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 |
|---|---|---|---|---|---|
in Preferences/Advanced/enable style sheets has no effect. i thought this option should disable any styles on any page, but it simply does nothing. something like this, *** <link href="/opensa.css" rel="stylesheet" type="text/css"> *** <style> body { font-size: 50px } </style> *** if (document.getElementById) { document.write('<link rel=STYLESHEET'); should be simply ignored. testet on win98 build 2000031708
Turning off CSS in the Prefs menu actually does nothing. I turned it off and went to the following page:, where the following CSS code is used: <style> <!-- a{text-decoration:none} //--> </style> After reloading the page (after turning of CSS), the links still were not underlined. I even restarted Mozilla and had the same results. Build ID: 2000050508 Operating System: Win98, Intel Pentium II
Confirming. Gerv
M17 ...
ekrock, is it impt to be able to turn off for beta2.
David, Ian--does the CSS or HTML spec *require* that applications have a feature/pref enabling style sheets to be turned off? Pierre, Mark--how much work is it in the code to just turn off CSS? Possible reasons to mark nsbeta2+: 1) strong reason: if mandated by a W3C spec 2) another good reason: there may be some users with visual impairments such as colorblindness who find that a particular CSS-specified page color scheme makes it hard/impossible for them to read a particular page; for those users, the ability to turn off CSS would improve accessibility 3) weaker reason: backward compatibility of "degree of functionality control" with Nav4 I *suspect* we can enable this easily but need more info from our standards gurus about requirements and from engineering about LOE.
HTML 4.01, section 14.3.1, paragraph 7: # User agents SHOULD also allow users to disable the author's style # sheets entirely, in which case the user agent MUST not apply any # persistent or alternate style sheets.
From Ian's post opf the HTML spec it looks like it is optional (noting the SHOULD). We cannot just turn off CSS - nothing would work if we did that. We can, however, disable the author's stylesheet if we can identify it. The underlying support is there in the StyleSet and SyleSheet, however we need to hook up some plumbing to get the correct sheet(s) and disable them, and also to re-enable them. Probably not a huge amount of work (a few days?), but it doesn't look like it is essential. Note that for bug 38026 I need to implement something similar in the StyleSet (ability to enable/disable a QuirkMode style sheet) so I can generalize the implementation to support something like this (enable/disable *any* stylesheet, including author style sheets). Once that work is done, the preferences can make calls into the StyleSet to do the work.
[nsbeta2-] Make sure this has to do with link style sheets rather than default.
<tough_decision>Sigh. All right. (1) It's a SHOULD, not a MUST, in the HTML 4.01 spec. (2) IE5 Win doesn't seem to have this either. Marking FUTURE, helpwanted, and relnote as Mark clearly indicates this is a nontrivial enhancement, and we're out of time for enhancements. Unless I'm persuaded otherwise in the next few days, I'll file a bug to have the "disable style sheets" pref removed from the UI. </tough_decision>
> We cannot just turn off CSS - nothing would work if we did that. We > can, however, disable the author's stylesheet if we can identify it. Isn't that exactly what "...in which case the user agent MUST not apply any persistent or alternate style sheets" is addressing. It seems to me that this says, "if you have the option of turning off the author's style sheets, then you must not use another in its place".
jerrybaker, what I meant was that we must still apply the *user agent* style rules (in html.css and xul.css), so we cannot 'turn off style'. You are correct, however, in that we MUST not apply any author stylesheets, persistent or altermate, when we do implement thsi in the future.
over to ekrock to resummarize and/or this bug. I can do pref UI stuff, not clear what's going on here.
until we get help on this feature, should the Pref be pulled from the UI?
To clarify: 1) retitling this bug "should be able to enable/disable style sheets via a pref in UI", leaving as FUTURE, reassigning to attinasi 2) opening new, separate bug 39552 on mcafee to eliminate the enable/disable pref of the UI for nsbeta2 (and FCS)
Here's a quote from the W3C User Agent Accessibility Guidelines, checkpoint 4.12: "Allow the user to select from available author and user style sheets or to ignore them. *[Priority 1] *" This is a priority 1 checkpoint: "This checkpoint *must* be satisfied by user agents, otherwise one or more groups of users with disabilities will find it impossible to access the Web. Satisfying this checkpoint is a basic requirement for enabling some people to access the Web." There should be a way to disable (document) style sheets in Mozilla, preferably as a button or a menu-item. Perhaps a small button in the statusbar for disabling/enabling style sheets?
IMHO, it would be logical to include the disable option in the "Use Stylesheet" menu. For details, see and the discussion at bug 6782.
spam: adding mostfreq, not necessarily due to many dups, but because i run into this problem frequently (thus want to get it my queries easily).
Disable the author stylesheets? That's what XBL style bindings are for... Geek humor aside, Marc, this should be fairly easy to do if you can find a way to tell whether the PresContext (or whatever owning object we're in) belongs to the chrome or to the content (because we want to do this in the content area only, right?). Looking for "isChrome" in nsDocumentViewer.cpp or for "isContent" in nsFrameFrame.cpp, or just asking hyatt, should put you on the right track. If you find the trick before me, please drop a note in bug 31816. I think that this pref should be active only in HTML documents.
And XHTML documents. And MathML documents. And XUL documents. And documents that only have elements from those namespaces. I think it might be easier just to always have this pref available...
From Daivd Hyatt: ben says you need to know how to tell if you're in chrome... This info is on the docshell... you can see an example of the check in nsDocumentViewer.cpp where I check to see whether or not I want to use chrome or content user stylesheets.... nsCOMPtr<nsIDocShellTreeItem> docShell = (get it from whereever you are...) PRInt32 shellType; docShell->GetItemType(&shellType); PRBool isChrome = (shellType == nsIDocShellTreeItem::typeChrome);
I filled in bug 51690 (disable stylesheets (also style="" and <style>) via View|Use stylesheet). This brought me to the question: Does disable means that "Use stylesheet" is disabled or that we default to "None" if we load a page so the user can later use this menu to choose a style?
Removing mostfreq - this bug does not qualify for this keyword under the established criteria. Gerv
adding se-radar to status so that i can find this bug more easily. pls don't remove it [yet], thx.
I think it would be better to make this a main part of the stylesheet UI and remember the setting between windows and invocations.
Closer examination of the CSS1 specification indicates that this is a CSS1 full-support requirement too. (Section 7.) RELEASE NOTE ITEM: In this release it is not possible to totally disable author stylesheets. It is possible to use user stylesheets (see XXX) to achieve more fine-grained control over the styling of web pages, however.
I'm not sure what you mean by full-support, Ian, but in section 7 I read: This specification also recommends, but doesn't require, that a UA: - allows the reader to specify personal style sheets - allows individual style sheets to be turned on and off as indicating that it is optional, but recommended. By full-support do you mean that we implement all _recommendations_ as well as _requirements_? I agree that the release note item is a good idea, thanks for writing it.
Marc: Yes, full support as distinct from conformant support.
Nominating for mozilla 0.9. There have been a number of strongly negative comments about Netscape 6 on c.i.w.a.s because of the lack of this feature. Probably the safer way to implement this pref would be around the loading of stylesheets and parsing of style elements/attributes. However, this would still allow HTML presentational hints. Implementing this at the cascade level would also block those, I think (if we've implemented them correctly, although I suspect we may not in some cases). Would there be any unexpected consequences of doing that? Would we want 2 separate prefs?
CC'ed erik & momoi.
I'm thinking that we want to turn on or off individual stylesheets more than having a global 'use stylesheets' preference. That is what CSS1 recommends. Having a global pref could simply be a shortcut for always disabling all stylesheets, of course, but we would still benefit from a UI to toggle each stylesheet individually (similar to the Alternate Stylesheets UI?)
I don't see any reason for toggling stylesheets individually other than as described by the author with TITLEs. Allowing that discourages or encourages authors from using linked stylesheets versus STYLE elements for reasons other than the ones on which they should be basing that decision. It also discourages authors from writing modular stylesheets, since the author would have to worry about the effects of disabling part of the stylesheets but not all.
One reason to support disabling of individual stylesheet is the CSS1 specification. Section 7 says: This specification also recommends, but doesn't require, that a UA: - allows the reader to specify personal style sheets - allows individual style sheets to be turned on and off I guess we could argue that the spec is wrong, and I cannot find the same recommendation in the CSS2 specification. I don't personally care either way, so hopefully Eric can tell us what he thinks the product should support - enabling/disabling of all stylesheets, or per-stylesheet. Also, do we really want to suppress HTML presentational hints along with the stylesheets? I do not see why we would since from an author's perspective they are NOT stylesheets (even though we may implement some of them as style rules internally).
The argument for including nonpresentational hints in the "turn all stylesheets off" option is that a user who chooses to turn off all stylesheets (including persistent ones) probably can't use the page with the styles given, which may or may not be specified using stylesheets.
Agreed. Then what we really want is an option to 'turn off all style'. I doubt users want to be bothered with figuring out what parts of the page are implemented with stylesheets vs. HTML attributes and elements. So what then would be included in the presentational hints that we disable? Font sizes, font faces, font weight, underline, bold, italics, color, and background? Hey, why not just make a 'show as plain text' option! Seriously, that is pretty much what it would be, except that you would have images too, and borders.
A *per-stylesheet* disabling UI would be incredibly confusing and utterly useless for ordinary users. A classic "provide too much UI and complexity for the user to understand, thus providing no benefit"-type mistake. (Yes, I'm sure that a few developers might find such a beast handy for testing & QA during page development, but Mozilla/N6 are a browser application, not a sophisticated style sheet development tool. Let's leave authoring tool functionality to the authoring tool vendors.) A single "turn off style sheets" option is clearly the way to go. As for turning off presentational hints at the same time: let's be careful about reinterpreting what the standards say. First of all, by presentational hints, are you referring to hardcoded FONT FACE tags and the like? If so, we'd be in violation of the HTML spec if we ignored those tags as well when the user turned of style sheets, yes? After all, we'd be ignoring markup that, though deprecated, should be respected and is used by developers as a fallback for non-stylesheet browsers (and thus arguably should be preserved if style sheets are turned off in a style sheet-capable browser). My take: 1) the ability to turn on/off all style sheets (binary, global) is something that Netscape should invest its time in. 2) The ability to ignore presentational hints is a separate feature, an enhancement request, and honestly not a good use of Netscape resources at this time. My proposal: a) Let's have Marc limit himself to working on a binary "turn off style sheets" checkbox (or View menu item, or whatever--the point is it should be an all-or-nothing setting that turns off the application of CSS only) b) A separate enhancement request bug on the "turn off presentational hints" should be opened and reassigned to nobody@mozilla.org until someone not at Netscape takes this work on. Netscape developers should remain focused on stability, performance, and bug fixes for some time to come, not work on enhancements that will only be use to a tiny fraction of our user base if that.
From an accessibility standpoint, it might be useful to be able to switch off all style sheets except for the user style sheet.
I disagree with Eric Krock's comments above. Turning off all stylesheets is only a useful feature in that it allows the user to control the browser when the page author misbehaves. If it only works for style specified in CSS, it won't be very useful. Turning off the FONT tag does *not* break compliance with HTML 4.0. I also suspect that, from an implementation standpoint, turning off all author style is easier than turning off all CSS, since it can be implemented easily at the cascade level. Turning off all CSS (including STYLE elements and attributes) seems a bit more difficult.
What's the status here? :-) Marc, is this very much on your back burner, or are we going to get it for 0.9 or 1.0? Gerv
Still a back-burner issue, but my manager has just informed me that I need to start addressing the nominations... That should happen over the next few days.
Can't you filter external stylesheet out on HTTP level?
Add more keywords. We really _do_ need to do this for 1.0, and that means doing it for 0.9 if it's going to get any serious testing. Gerv
Adding CSS to the summary, may help people searching for this bug if they're looking for "CSS" rather than "style sheets"
*** Bug 107326 has been marked as a duplicate of this bug. ***
Taking this style bug off Marc's list.
Rather then a pref, which would be quite inaccessible when you simply want to disable style temporarily, this should be integrated into the current view->stylesheets menu. As far as prefs, the current ones that disable custom fonts/colors etc should simply apply to CSS as well as the traditional HTML <font> method, as users using those options are most likely doing so for permanent accessibility reasons, and don't really care if the moron web designer used CSS or <font> to set the page to be 6pt green text on a blue background. How about this for the menu: None # No stylesheets applied ------- # divider Default # Only persistant styles applied. Equivilent to current 'none' funky # Prefered sheet listed next, which would be selected at page load clean # Alternate stylesheets listed next, in order of referance on the very red # page (unless the spec says they should be listed in some other # order) Currently, when only a persistant stylesheet is active, 'None' is checked in the menu. As shown above, I suggest 'Default' be added, which is only the persistant styles applied. None actually meaning, 'no stylesheets', is alot more obvious than it meaning 'no alternate/prefered stylesheets', especially to people who haven't read the CSS and HTML specs.
> Default # Only persistant styles applied. Equivilent to current 'none' It doesn't make sense to call that "Default", since it's not the default. I wrote a proposal in the main alternate stylesheets UI bug a year or two ago with suggestions for how to do this.
Some history: It was decided in bug 6782 to have a no-author-level-styles option in the Use Style menu; this was filed as bug 51690, which was marked as a duplicate of this bug. Bug 51688 was filed to deal with the current "none" option--initially to change the wording until 51690 could be fixed.
Created attachment 64169 [details] IRC discussion about how to implement this, and other issues
Moving to Mozilla1.1. Engineers are overloaded with higher priority bugs.
Created attachment 68076 [details] [diff] [review] patch v0.1 This unfinished fix enables/disables author level styles. There are two outstanding issues: 1.) The refresh function needs to be called on *every* page load. I don't know how to do this. 2.) Switching around with CSS generated content images has weird results and sometimes crashes. Reproducible. Might have something to do with the DeviceContext calls made in SetPreferenceStyleRules that I'm not making, or something else I'm not yet aware of. I'm going to look into this; hopefully I'll find the problem. Also, I haven't tested it with framesets yet.
Bulk moving from Moz1.1 to future-P1. I will pull from this list when scheduling work post Mozilla1.0.
*** Bug 127464 has been marked as a duplicate of this bug. ***
Mass removing self from CC list.
Now I feel sumb because I have to add back. Sorry for the spam.
Assigning pierre's remaining Style System-related bugs to myself.
I notice that style sheet toggling can be done per page via a bookmarklet: Seems to work fine.
The bookmarklet doesn't disable non-CSS style hints.
*** Bug 180649 has been marked as a duplicate of this bug. ***
cc:ing Aaron Is this another accessibility win? -R
Sure, this would be nice for some visually impaired users if it was something that could be easily toggled. I'd like to see something like this on the pref toolbar from xul planet. Not a high priority compared to our other accessibility work, at least at the moment.
There are really two separate issues here: (a) being able to disable CSS (or for those of you who prefer to say it this way, use only the UA stylesheet) as a global user preference (b) being able to switch the style sheet off temporarily (View -> Use Style -> None or something) for such purposes as testing or reading badly-written pages. (a) could merely set the default, while still allowing the user to override it either way from the Use Style submenu.
I think having two switches, one global and one "local" will just confuse the user. Are they two interfaces to the same switch? Are they two separate settings--e.g. does one override the other? Which one? It's better, IMO, to have just one switch in the Use Style menu and remember its last setting between sessions. The disabling author style, btw, will be quite drastic, as it will not only disable all CSS, but most HTML formatting as well. I doubt its use as a global preference will be very common; forcing a color or font override is usually more useful.
Please clarify: 1. If the global setting overrode the local setting, what would the local setting do at all? 2. How would disabling the author style sheet disable HTML formatting?
> 1. If the global setting overrode the local setting, what would the local > setting do at all? "Obviously" the local setting overrides the global one, but you have to convey this model to the users, which is easier said than done. They don't need a separate global setting; why confuse them with one? > 2. How would disabling the author style sheet disable HTML formatting? Disabling author styles disables HTML formatting because HTML formatting is part of the author style level[1]. It is style assigned by the author, so it certainly belongs there. From a UE perspective, we should not make a distinction between <font color="#FF0000"> and <span style="color: #FF0000"> because the user doesn't care. Lime text on a Green background is hard to read whether it's specified with HTML attributes or CSS properties. [1] , specifically 6.4.1 and 6.4.4
Your link gives this line: "It is therefore important that the user agent give the user the ability to turn off the influence of a certain style sheet, e.g., through a pull-down menu." But 6.4.4 seems rather odd. Why should HTML presentation hints be at the beginning of the author style sheet, rather than treated as being in style="..." attributes? And can't a makeshift "author style sheet" be used to handle HTML presentation hints if the real author style sheet is disabled? As for your "UE perspective", I'm not totally sure what to say. But what is for certain is that there is sometimes the need to disable an author style sheet in order to read a badly coded page.
> Why should HTML presentation hints be at the beginning of > the author style sheet, rather than treated as being in attributes? So that author CSS can override HTML presentation hints. If I make links silver with <body link="silver">, I should be able to make some of them aqua with .navigationbar :link {color: aqua} > And can't a makeshift "author style sheet" be used to handle HTML presentation > hints if the real author style sheet is disabled? Technically, yes. But we don't want to do that because, as you say, "there is sometimes the need to disable an author style sheet in order to read a badly coded page." And there is no less a need to disable <font> and other presentation hints in order to read a page badly coded with HTML presentational hints. You *do not care* if a poor color combination was specified in HTML or CSS. You just want to disable it.
You misunderstand. I was actually thinking of bad CSS and JS rather than bad HTML. There are situations where a page is inaccessible, e.g. because it has used some combination of CSS and JS to show/hide content, and the code is somewhere broken or otherwise heavily reliant on having the right browser. Witness for example. OK, so this one would need a bit more than just switching off the author style sheet, but surely some sites would work if only explicit CSS declarations were ignored even if HTML presentation hints are allowed to shine through. That's what happened on browsers that predated CSS, didn't it?
> surely some sites would work if only explicit CSS declarations were ignored even > if HTML presentation hints are allowed to shine through. Certainly, but why give HTML presentation hints (which are deprecated, btw) such a stronger precedence than CSS? I argue that if the same site used CSS instead of HTML presentation hints, I should get the same result if I turn off author style. And you still have this whole problem with color contrast, etc, which should be handled the same in both HTML and CSS.
A side comment (to the last few): Should the DOM Style interfaces be disabled when the style is "switched off"? Or may be made read-only to not be modifiable by scripts.
DOM style is just inline style. If inline style is off, so is DOM style (it can be changed, but has no effect on rendering).
Re: fantasai Yes, but if on a given page it's only the CSS that's broken and not the HTML, why should the luser be forced to disable both?
Re: famtasai Yes, but if on a given page it's only the CSS that's broken and not the HTML, why should the luser be forced to disable both? HTML presentation hints in a CSS-formatted page are, after all, supposed to be for graceful degradation.
What if it is the HTML that is broken and not the CSS? What if one stylesheet of the two linked to a page is fine, but the second is not? In fact, what if one third of the fifth stylesheet is the problem, but the rest is not? And how should the user discover this? As far as the overwhelming majority of users are concerned, there's no difference between HTML hints and CSS hints.
> What if it is the HTML that is broken and not the CSS? Good question. But can you supply an example of such a page? >? > And how should the user discover this? That depends. But discovering the case I mentioned above would be perfectly straightforward given the option. > As far as the overwhelming majority of users are concerned, there's > no difference between HTML hints and CSS hints. I expect that the overwhelming majority of users also don't care about the difference between alternative stylesheet 1 and alternative stylesheet 2. So why shouldn't we give the handful who either are interested or need it the option of using no stylesheet at all?
>> What if it is the HTML that is broken and not the CSS? > > Good question. But can you supply an example of such a page? That's trivial. A page with <font size="1"> at the top. >>? GD? >> And how should the user discover this? > > That depends. But discovering the case I mentioned above would be > perfectly straightforward given the option. So you want the user to try various options until they think the rendering is ok? Come on. >> As far as the overwhelming majority of users are concerned, there's >> no difference between HTML hints and CSS hints. > > I expect that the overwhelming majority of users also don't care > about the difference between alternative stylesheet 1 and alternative > stylesheet 2. They don't know about the feature, maybe, and that is an argument for making it more visible on pages with alternates. However, users like playing with themes (just look at mobile phone users changing their login screens). I have yet to see a user say "I'd like to turn off half the styles on this page". > So why shouldn't we give the handful who either are > interested or need it the option of using no stylesheet at all [but leaving > the HTML hints in place]? Because every option we add reduces overall usability. I agree that we should have a feature to remove all the stylesheets, and according to the CSS spec, HTML hints count as being in a stylesheet.
> I agree that we should have a feature to remove all the stylesheets, > and according to the CSS spec, HTML hints count as being in a stylesheet. do you mean to include user style (userContent.css) when removing all stylesheets? i think we need to be careful of reducing accessibility. imagine someone challenged has gone to the trouble of making their web experience more accessible, and this feature nukes their style. as much as i don't like adding options either, i think we need one to keep user style persistent -- unless we're going to keep it always (which could be just as bad with a fubar user stylesheet).
Sorry, I meant author sheets. Yes, of course, user and UA stylesheets would stay enabled at all times.
Re: comment 81 > GD? Gracefully degrade. >? > Because every option we add reduces overall usability. How can a little extra item on the Use Style submenu possibly reduce the usability of the whole of Mozilla, regardless of whether the user actually uses the option?
>>? I completely agree with the request for the feature to disable all author styling. What I was diagreeing with is having the option to disable author styling done by CSS but _not_ disabling author styling done by HTML. >> Because every option we add reduces overall usability. > > How can a little extra item on the Use Style submenu possibly reduce the > usability of the whole of Mozilla, regardless of whether the user actually > uses the option? It's a basic fact of user interface design that every additional menu item increases the time required by the user to decide which menu item to pick.
I'd like to mention the two big reasons I see on why this is really a legitimate feature. 1) It's useful to advanced or disabled users, who have personal stylesheets. Try setting text or/and background color on the user side and see how many pages are now unreadable because they only set one or the other. 2) It's useful to developers (at least as much as JS or Java console) to make sure their page is logicially laid out (section headers should still be <h1>/etc regardless of how the page looks with style, and things like that). This is assuming 'None' also removes old HTML styling. <font> and the like. Otherwise it's not much use, at least for point (1), the more important of the two IMO. Also keep in mind this isn't adding a menu item, it's adding a sub-menu item, which is a big difference. I for one will be very sad to see the Mozilla-suite featureness attack the Firebird UI, but the style menu is one addition I look forward to. Heck, doesn't the spec require it?
BTW Opera 7.x has this feature: View | Style | User mode
*** Bug 215803 has been marked as a duplicate of this bug. ***
bz: Will your stylesheet loader work give us an easy way to do this? (Including disabling author styles in the markup, such as <font> or <hr color>.)
No, that's pretty orthogonal to this rfe...
*** Bug 233471 has been marked as a duplicate of this bug. ***
*** Bug 241139 has been marked as a duplicate of this bug. ***
Am I mistaken, or does Firefox already have this feature? When I visit sites that have stylesheets, I get a little selector widget in the left end of the status bar that lets you choose between "No Style", "Basic Style", and the author's stylesheet. Is that something that was implemented specifically in Firefox that didn't get backported to Mozilla? Or am I looking at something else?
> choose between "No Style", "Basic Style", and the author's stylesheet A vanilla firefox build (just downloaded today's nightly) has a slightly different widget without the "No Style" option, so sounds like you have some sort of extension installed (which doesn't do quite what we want to do, since it can't possibly disable presentational attributes....).
Yeah, "No Theme" is not there in a vanilla nightly (and again, doesn't do what we feel it should).
this is the 0416 nightly, and the only extension I have installed is UserAgent Switcher.
It depends on what page is being displayed (and whether it has any persistent sheets).
bz, if one were to implement this, what is the interface function the Use Style > None menu would call?
There isn't such a function yet. It'd have to be written.
We now have a menu option "use style". All we need to do is switch to an empty stylesheet, no?
Felix, please read David Baron's comments on this bug.
write the interface definition, please?
We haven't even quite decided what the function should do. Once we have an idea of that, we could try to write an interface definition.... (what interface to put it in? What should happen with subframes?)
I'm disabling Doc and PresHint. Should this option disable Override as well?
It probably should disable override in case we ever implement . I think override is currently used only by editor, though. If you were to add disable CSS UI to editor that would be a problem, but otherwise I don't think it would.
it should be possible to disable any HTML page provided styles and show the page without any single <STYLE > tag or style="" parameter.
Created attachment 152786 [details] [diff] [review] patch
nsIDOMDocumentStyle.idl claims it's frozen, as visible in your patch... that means you should probably not change it.
I'd have gone through some other interface, but adding that property has been planned in bug 200930, so I figured I might as well add it now.
Frozen means you can't change it. You need to add another interface that inherits from it and add to that instead. (This is often done by adding nsIDOMNS... to inherit from nsIDOM...)
(This also disables things like bgcolor="", <font>, etc, right?)
(See comment #105. Would I write a patch that didn't?)
Created attachment 153604 [details] [diff] [review] patch Added nsIDOM3DocumentStyle from bz's work on stylesheet switching interfaces
Comment on attachment 153604 [details] [diff] [review] patch >+ //Enable/Disable entire author style level (Doc & PresHint levels) >+ PRBool GetAuthorStyleDisabled(); >+ nsresult SetAuthorStyleDisabled(PRBool aStyleDisabled); This could just return void. > PRUint16 mBatching; > > unsigned mInShutdown : 1; >- unsigned mDirty : 7; // one dirty bit is used per sheet type >+ unsigned mAuthorStyleDisabled; >+ unsigned mDirty : 6; // one dirty bit is used per sheet type The default is 32 bits, so putting that in the middle there doesn't do what you intended, I don't think. That said, please don't change this to 6, even though it could be now, since I'm adding a 7th in bug 252578. You'll also have to merge the GatherRuleProcessors changes with bug 252578 if I land first -- and it would probably be simpler to use an early return i.e., after the Clear(), just return if mAuthorStyleDisabled and the type is one of the relevant types. (I'm saying that knowing what the changes in bug 252578 look like.) More later...
(In reply to comment #115) > (From update of attachment 153604 [details] [diff] [review]) > >+ //Enable/Disable entire author style level (Doc & PresHint levels) > >+ PRBool GetAuthorStyleDisabled(); > >+ nsresult SetAuthorStyleDisabled(PRBool aStyleDisabled); > > This could just return void. Actually, never mind.
Comment on attachment 153604 [details] [diff] [review] patch >+nsStyleSet::SetAuthorStyleDisabled(PRBool aStyleDisabled) >+{ >+ if (aStyleDisabled != (PRBool)mAuthorStyleDisabled) { Don't cast to PRBool; it doesn't help anything. >+/** >+ * The nsIDOM3DocumentStyle interface is an extension to the >+ * nsIDOMDocumentStyle interface. This interface exposes more ways to interact If it's an extension, shouldn't it be nsIDOMNSDocumentStyle? What happened to all the nsDocument changes in bz's patch in bug 200930? The preferredStyleSheet changes and the authorStyleDisabled stuff seem like two different things that should be reviewed separately. And the UI changes should probably be reviewed as a third patch (or third and fourth, if separate for the suite and Firefox). Any chance you could attach a new patch addressing these (and previous) comments to this bug, and a separate one to bug 200930 if that one needs updating? Other than that, the authorStyleDisabled part of this patch looks fine.
> If it's an extension, shouldn't it be nsIDOMNSDocumentStyle? I haven't got a clue. I don't know anything about APIs, I'm just copying what bz did in bug 200930. If there's something you want me to change about it, you need to explain it. > What happened to all the nsDocument changes in bz's patch in bug 200930? Most of those changes are for adding document.selectedStylesheetSet support and are therefore not relevant here. > The preferredStyleSheet changes and the authorStyleDisabled stuff seem like > two different things that should be reviewed separately. Although it adds a new interface, the preferredStylesheet code changes are small and they are necessary for a correct interface here. I don't see how separating out the patch will help, it's just more work afaics. As for not using bz's method of calling GetHeaderData to get the preferred style set, I don't think it would work. The preferred style sheet is not always set via HTTP headers. See If you want to spend more time pondering the preferredStylesheetSet interface, then I will file a new bug on it. But if you already know what the interface is going to be, I don't see any point. > And the UI changes should probably be reviewed as a third patch (or third and > fourth, if separate for the suite and Firefox). I will open a separate bug for the patch to Firefox trunk. The UI changes for the Mozilla Suite are necessary in this patch because there's no other way to test the changes! Besides, if the only way of doing that is for the user to make an API call, then /this/ bug is definitely not fixed and will need a second patch.
One other thing -- the JS changes make it look like you're removing the "Basic Page Style" option whenever there are preferred sets. This make sense, but if so, perhaps the name should be "Page Style" instead? Also, if you think the code would be simpler if that option were created by the function that fills the popup (and created only if there are no preferred/alternate sheets), then that might be better (and more symmetric, since we're already doing that, and having both that and display toggling might be confusing).
Comment on attachment 153604 [details] [diff] [review] patch >- <menupopup onpopupshowing="stylesheetFillPopup(this);" >- >- <menuitem label="&useStyleSheetPersistentOnly.label;" accesskey="&useStyleSheetPersistentOnly.accesskey;" type="radio"/> >+ <menuitem label="&useStyleSheetNone.label;" accesskey="&useStyleSheetNone.accesskey;" oncommand="setStyleDisabled(true);" type="radio"/> I don't like you putting oncommand attribute on your dynamic menuitems. Please add event.preventBubble(); here instead. >+ <menuitem label="&useStyleSheetPersistentOnly.label;" accesskey="&useStyleSheetPersistentOnly.accesskey;" >+ >-. >+ if (window.content.document.preferredStylesheetSet) { >+ itemPersistentOnly.style.display = "none"; >+ } >+ else { >+ itemPersistentOnly.style.display = ""; >+ } We have to use .hidden = <boolean> here to play nicely with the Mac whose menubar doesn't use CSS, although in general we like to use attributes and stylesheets (.hidden = true; invokes a style rule in xul.css) rather than inline style. > function stylesheetSwitchAll(frameset, title) { >+ setStyleDisabled(false); This is a recursive function so this isn't a good place to add code. As you'll be moving the oncommand handler back to the menupopup you could add it there. Additionally I would have thought that enabling style after instead of before selecting the stylesheet would reduce the amount of style resolving. > if (!title || stylesheetInFrame(frameset, title)) { > stylesheetSwitchFrame(frameset, title); > } > for (var i = 0; i < frameset.frames.length; i++) { > stylesheetSwitchAll(frameset.frames[i], title); > } > }
(In reply to comment #120) > >-. It's just a rename of the same thing to be more consistent with other parts of the code.
Created attachment 154923 [details] [diff] [review] patch
Comment on attachment 154923 [details] [diff] [review] patch >Index: mozilla/content/base/src/nsStyleSet.h > unsigned mInShutdown : 1; >- unsigned mDirty : 7; // one dirty bit is used per sheet type >+ unsigned mAuthorStyleDisabled: 1; >+ unsigned mDirty : 6; // one dirty bit is used per sheet type We need 7 bits here, so you can't use 6. >Index: mozilla/content/base/src/nsStyleSet.cpp > nsresult > nsStyleSet::GatherRuleProcessors(sheetType aType) > { > mRuleProcessors[aType] = nsnull; >+ if (mAuthorStyleDisabled && (aType == eDocSheet || aType == ePresHintSheet)) { >+ //don't regather if this level is disabled >+ return NS_OK; >+ } You need to check eHTMLPresHintSheet and eStyleAttrSheet as well. >; >+ } >+ else { >+ mDirty |= 1 << eDocSheet; >+ mDirty |= 1 << ePresHintSheet; >+ } >+ } >+ return NS_OK; >+} Likewise here. Perhaps it's worth having an array: static const nsStyleSet::sheetType authorTypes = { ePresHintSheet, eHTMLPresHintSheet, eDocSheet, eStyleAttrSheet }; and iterating through that array in both these places, e.g. (for the first): // don't regather if author style is disabled if (mAuthorStyleDisabled) for (const nsStyleSet::sheetType *type = authorTypes, *type_end = authorTypes + NS_ARRAY_LENGTH(authorTypes); type < type_end; ++type) if (*type == aType) return NS_OK; although perhaps it's not worth it for just 4 entries. (I wonder which one generates less code.) >Index: mozilla/dom/public/idl/stylesheets/nsIDOMNSDocumentStyle.idl >+ * The nsIDOM3DocumentStyle interface is an extension to the The comment should match the name. With those changes, sr=dbaron.
Created attachment 154939 [details] [diff] [review] patch
Created attachment 154942 [details] [diff] [review] patch
Comment on attachment 154942 [details] [diff] [review] patch I was surprised that turning all style off also affected mapped attributes. Anyway, I was originally unsure how this was supposed to work, but now I see that "None" means no CSS at all while "Default Style" means that there were no named regular stylesheets.
Comment on attachment 154942 [details] [diff] [review] patch >Index: mozilla/content/base/src/nsStyleSet.h >- unsigned mDirty : 7; // one dirty bit is used per sheet type >+ unsigned mAuthorStyleDisabled: 1; >+ unsigned mDirty : 14; // one dirty bit is used per sheet type Just leave it at 7, since that shows what we need. >Index: mozilla/content/base/src/nsStyleSet.cpp >; >+ rv = GatherRuleProcessors(eHTMLPresHintSheet); >+ if (NS_FAILED(rv)) return rv; >+ rv = GatherRuleProcessors(eHTMLPresHintSheet); >+ if (NS_FAILED(rv)) return rv; >+ } >+ else { >+ mDirty |= 1 << eDocSheet; >+ mDirty |= 1 << ePresHintSheet; >+ mDirty |= 1 << eHTMLPresHintSheet; >+ mDirty |= 1 << eStyleAttrSheet; >+ } >+ } >+ return NS_OK; I just realized a way to simplify this a good bit: if (aStyleDisabled != mAuthorStyleDisabled) { mAuthorStyleDisabled = aStyleDisabled; BeginUpdate(); mDirty |= 1 << eDocSheet | 1 << ePresHintSheet | 1 << eHTMLPresHintSheet | 1 << eStyleAttrSheet; EndUpdate(); } return NS_OK; With that, sr=dbaron.
... except that the return value from EndUpdate should be propagated, i.e., |nsresult rv = NS_OK;| at the start of the function, |rv = EndUpdate();| instead of just |EndUpdate();|, and |return rv;| instead of |return NS_OK;|.
Created attachment 155203 [details] [diff] [review] final patch
(In reply to comment #118) > As for not using bz's method of calling GetHeaderData to get the preferred style > set, I don't think it would work. The preferred style sheet is not always set > via HTTP headers. But the headerDefaultStyle header data is always set to the preferred style sheet. If it didn't work, you need to file a bug. There was no need for GetPreferredSheet on the CSS loader IMHO. The license on nsIDOMNSDocumentStyle.idl references the NPL, please use the MPL/GPL/LGPL boilerplate () when adding new files.
The error came out by build of Camino. Mac OS X 10.3.4 make[7]: Entering directory `/Users/sek/Documents/mozilla-current/camino/mozilla/dom/public/idl/stylesheets' /Users/sek/Documents/mozilla-current/camino/mozilla/config/nsinstall -L /Users/sek/Documents/mozilla-current/camino/mozilla/dom/public/idl/stylesheets -m 644 nsIDOMLinkStyle.idl ../../../../dist/idl /Users/sek/Documents/mozilla-current/camino/mozilla/config/nsinstall -L /Users/sek/Documents/mozilla-current/camino/mozilla/dom/public/idl/stylesheets -m 644 _xpidlgen/nsIDOMLinkStyle.h ../../../../dist/include/dom /usr/bin/perl -I../../../../config ../../../../config/build-list.pl ../../../../dist/include/dom/.headerlist nsIDOMLinkStyle.h make[7]: *** No rule to make target `nsIDOMNSDocumentStyle.idl', needed by `export'. Stop. make[7]: Leaving directory `/Users/sek/Documents/mozilla-current/camino/mozilla/dom/public/idl/stylesheets' make[6]: *** [export] Error 2
If the defaultStyle header *is* set by the configuration of <link> elements, /then/ I'd probably have to file a bug. <link> elements shouldn't set HTTP headers. And if they are, then we're probably violating HTML 4. #." How would we implement that if a default style set with a LINK element gets treated the same as a meta tag with an HTTP header?
They are not treated the same, but they all set the headerDefaultStyle header data. There could very well be bugs there, that still doesn't justify GetPreferredSheet on the CSS loader. If our existing API really is broken you did nothing to fix it, you just added another API to get the same bad value.
-> bug 254445 marking this fixed. Tinderbox is in flames because cvs-mirror is out of sync with cvs.
It looks like nsIMarkupDocumentViewer was changed without modifying the UUID of the interface. Sure, it's a private interface, but you never know if some wacky extension or embedder may be using this interface for some random reason. Better to always modify interface UUIDs when modifying interfaces. Otherwise, you give those who need to use this interface no hope of doing so across browser versions.
(In reply to comment #135) > It looks like nsIMarkupDocumentViewer was changed without modifying the UUID of > the interface. I just checked in a patch to change the uuid. unfortunately alpha3 was released with the old UUID, but ah well, it's only an alpha.
*** Bug 264859 has been marked as a duplicate of this bug. ***
while netscape4.8 is able to show html pages when offline (lacking the css which points to a net adress) if you disable the css use, Mozilla 2005013106 is not, regardless if you choose View-Use Style-None or not.
So why was this _experimental_ interface added to SDK_XPIDLSRCS? And given that I need to change it if I'm going to reasonably implement the WHATWG proposal for this stuff, where do we go from here? I'm tempted to move it out of SDK_XPIDLSRCS, frankly. Except I suspect that's not kosher. :(
Yikes. I suppose if you have to, you can just leave it and not implement it anymore. Although not being able to use the name anymore is annoying.
So the current WHATWG proposal would just extend this interface. I suppose I could create nsIDOMNSDocumentStyle2 and inherit from nsIDOMNSDocumentStyle...
I'd call it nsIDOMNSDocumentStyleSets over nsIDOMNSDocumentStyle2
(In reply to comment #142) > I'd call it nsIDOMNSDocumentStyleSets over nsIDOMNSDocumentStyle2 Agreed ! Please, please don't run into the MS way of numbering new interfaces...
> I'd call it nsIDOMNSDocumentStyleSets over nsIDOMNSDocumentStyle2 How would someone looking at the WHATWG spec (where the interface is DocumentStyle) find that? I don't like the numbering that much, but it's the only sane choice when the DOM or WHATWG folks add stuff to interfaces that are already frozen. Note the discussion in mozilla.dev.platform, btw. I'm still tempted to just move this interface back out of SDK_XPIDLSRCS.
The interface name only affects C++ consumers at least. We've been using numbering for other DOM interfaces (e.g., nsIDOM3Node anyone?).
nsIDOMWindow2 is probably a better example of my point than nsIDOM3Node fwiw. | https://bugzilla.mozilla.org/show_bug.cgi?id=32372 | CC-MAIN-2017-26 | refinedweb | 7,728 | 63.49 |
Helmut Eller <address@hidden> writes: > Hi, > > I read your post about non-blocking open-network-stream in the web > archive of the emacs-devel list and would like to make some comments. > I write to you directly because I'm not subscribed and I have the > impression the list is "For Developers Only". > Thanks a lot for your feedback. I've copied my response to the list. > I tried the code a bit and I noticed that the sentinel is sometimes > not invoked with "run" when the connections completes successfully but > is closed shortly afterwards by the peer. The sentinel was sometimes > invoked sometimes not. The scenario was very simple: a server > accepted the connection and wrote "hello" to the socket and closed the > connection. Emacs executed this: > > (open-network-stream "nb" "x.x" "localhost" 34567 > nil > (lambda (s msg) > (with-current-buffer (process-buffer s) > (insert msg "\n") > (when (equal "failed" msg) > (message "deleting %S" s) > (delete-process s)))) > t) > This seems to be related to the problem you describe below: reading the process output before checking for the completion of the connect. I'll look into it. > You wrote: > > [...] > > The initial process-state is `connecting' which changes to `open' > > or `failed' depending on whether the connect succeeded or failed. > > Notice that the sentinel string for `open' is "run". > > You could modify status_message to return something more meaningful. > Preferably the symbol 'open. > Yes, I considered doing that. However, I didn't know whether existing code may depend on the current behaviour, and although I couldn't find any in CVS, I decided against changing it. > [...] > > + /* Number of bits set in connect_wait_mask. */ > > + int num_pending_connects; > > + > > Any reason to make this non-static? No. I just forgot it. > > [...] > > ! non_blocking = (NILP (non_blocking) ? Qnil : Qt); > > ! #ifdef NON_BLOCKING_CONNECT > > ! is_non_blocking = !NILP (non_blocking); > > ! #else > > ! is_non_blocking = 0; > > ! #endif > > Wouldn't non_blocking_p be a more lispy name? :-) Yes - but is_non_blocking is not a lisp object :-) > > [...] > > --- 1948,1971 ---- > > turn_on_atimers (1); > > > > if (ret == 0 || xerrno == EISCONN) > > ! { > > ! is_non_blocking = 0; > > ! /* The unwind-protect will be discarded afterwards. > > ! Likewise for immediate_quit. */ > > ! break; > > ! } > > Why do you set is_non_blocking to 0? I can see no later use. For > documentation? It is defensive programming -- in case it ever becomes necessary to test on it later in the code, it contains the proper value. > > > ! > > ! #ifdef NON_BLOCKING_CONNECT > > ! #ifdef EINPROGRESS > > ! if (is_non_blocking && xerrno == EINPROGRESS) > > ! break; > > ! #else > > ! #ifdef EWOULDBLOCK > > ! if (is_non_blocking && xerrno == EWOULDBLOCK) > > break; > > + #endif > > + #endif > > What does it mean when connect returns EWOULDBLOCK? My man page > doesn't mention it. > Neither does mine -- but I saw some references on the Web which mentions this as one of the possible error codes from a non-blocking connect. So I included the test in case EINPROGRESS is not defined. > [...] > > --- 2176,2202 ---- > [...] > > ! if (!NILP (non_blocking)) > > ! { > > ! XPROCESS (proc)->status = Qconnecting; > > ! if (!FD_ISSET (inch, &connect_wait_mask)) > > ! { > > ! FD_SET (inch, &connect_wait_mask); > > ! num_pending_connects++; > > ! } > > ! } > > Why is if(!FD_ISET...) necessary? Because num_pending_connects would be updated incorrectly if it is already set. Defensive programming... > > [...] > > + #ifdef NON_BLOCKING_CONNECT > > + if (check_connect && FD_ISSET (channel, &Connecting)) > > + { > > Isn't it possible that channel becomes readable and writable at the > same time? If yes, wouldn't that mean that read_process_output (and > hence the filter) was already called before we get here? It seems you are right. Maybe the easiest fix would be for read_process_output to just return 0 if the process state is Qconnecting. I'll look into that. > > > + struct Lisp_Process *p; > > + struct sockaddr pname; > > + socklen_t pnamelen = sizeof(pname); > > + > > + FD_CLR (channel, &connect_wait_mask); > > + if (--num_pending_connects < 0) > > + abort (); > > + > > + proc = chan_process[channel]; > > + if (NILP (proc)) > > + continue; > > Is it safe to decrement num_pending_connects even if proc is nil? > > [...] Yes, because we only get here if channel is in the Connecting mask which is a subset of connect_wait_mask. Whether there really is a corresponding process doesn't matter. (there should be one, but I'm playing safe here -- cleaning up the connect_wait_mask in any case). > > + > > + p = XPROCESS (proc); > > + XSETINT (p->tick, ++process_tick); > > + > > + /* If connection failed, getpeername fails */ > > + if (getpeername(channel, &pname, &pnamelen) < 0) > > + { > > + /* Preserve status of processes already terminated. */ > > + p->status = Qfailed; > > + deactivate_process (proc); > > + } > > + else > > It would be nice if the error message (obtained with getsockopt > (channel, SOL_SCOKET, SO_ERROR ...)) would be passed to the sentinel. > That would be reasonable. I'll look into that. > A minor note: open-network-stream contains a large chunk of duplicated > code (starting from "/* Kernel bugs (on Ultrix..." to > "report_file_error ("connection failed...))). This are about 70 lines; > should they be in a separate function? Maybe, or the #ifdefs could be rearranged to avoid the duplication. I'll take a look. -- Kim F. Storm <address@hidden> | http://lists.gnu.org/archive/html/emacs-devel/2002-02/msg00718.html | CC-MAIN-2016-36 | refinedweb | 746 | 58.89 |
MVC architecture
what is the difference between MVC1 & MVC2 in Java?
sivapurammani
- Jul 10th, 2013
MVC(Model-View-Controller) :: This type of architecture makes our code to be reusable and separation of code. View :: Which presents the modal data, example if we are presenting any tabular data or c...
Prasad MN
- Mar 11th, 2013
MVC1: Its a model view Controller architecture 1 that means all the presentation logic and business logic is mixed up. If any modification is required on its impact on the logic. Difficult .......
Adding Method in Java
Hi I have interface in that interface 3 methods are there , after some days client said that,i want to add one more method in that interface ,so how can add 4 method so that the implemented class did not affect, Thanks Kalins Naik
sivapurammani
- Jul 4th, 2013
If we implement any new method in Interface then by default that method is public and abstract, So the classes which are implementing that interface should implement that method that is one way in whi...
akii
- Apr 30th, 2013
Make a class abstract in this class you do not need to implement all methods of interface ....
toString function
What is the default value for toString() in java? Explain me with an example?
sivapurammani
- Jul 10th, 2013
Default value is String representation of any Object. "java class Student { int rollNo; String name; public Student(int rollNo, String name){ this.rollNo = rollNo; this.name = n...
Nikhil
- Feb 21st, 2013
If toString() method is not overriden, it will return
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
This is Object version of this method.
Synchronization in Java
When We should use Synchronization in Java and when we should not?
sivapurammani
- Dec 16th, 2013
In simple terms we can say only one thread can act on selected resource(method or variable). Understanding the above sentence is as follows:: For example we are booking any ticket in a particular bu...
Yeswanth
- Dec 6th, 2013
If you want to allow only one thread at a time to access block of code or method then we will go for synchronization.Code
- public synchronized
- void singleProcess() {
- // Insert code here
- }
Why do we write String args[] in main of the program?
muskan
- Jul 29th, 2013
We have to write String args[] in main to run a program, because JVM(java virtual machine) can only recognize the main with string array as parameter, as starting method or a point.
Gajavelli shiva krishna
- Jul 18th, 2013
We write in string args[] in main in Java because string args[] means it allows string of array objects
what is the difference between abstract class & Final class
Manjunath_7_89
- Mar 25th, 2016
Abstract Class
1. Could be Inherited.
2. Couldnt instatiated.
3. Could add few more methods.
4. Incomplete class
Final Class
1. Final version of Class
2. Couldnt be inherited.
3. Could be instantiated.
4. Couldnt add any more methods.
baban
- Feb 11th, 2016
Abstract class cannot create object but final class create a object
abstract class which have must a subclassed but final class which have no subclass...
Is java a fully object oriented programming or not? if not why?
Read Best Answer
Editorial / Best AnswerKanikaKG
- Member Since Jul-2008 | Aug 3rd, 2008
Amit Kumar
- May 21st, 2018
Sorry, I am completely agree that java is a pure object oriented language. First of all answer me one question , what do you mean by object oriented programming ? object oriented programming is a conc...
parthkd
- Mar 1st, 2018
No, Java is not pure object oriented language because java supports primitive data type so java is not a pure OOP language. A pure language is totally based on object and classes so Java is not a pure object oriented language.
What is the purpose of garbage collection
The purpose of garbage collection is to identify and discard objects that are no longerneeded by a program so that their resources may be reclaimed and reused.
sivapurammani
- Dec 17th, 2013
In simple terms we can say garbage collector removes the unreferenced objects from the memory. In general the memory should have some limitation. In JVM for accomplishing tasks we create objects and ...
pardeep131085
- Aug 21st, 2013
garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means th...
What is the difference between static and non-static variables
A static variable is associated with the class as a whole rather than with specific instancesof a class. Non-static variables take on unique values with each object instance.
sivapurammani
- Dec 17th, 2013
Static variables are class variables, we can access these variables using class name and the variable value remains same for all the objects. Generally we can use these static variables as constants f...
Arvindanathan
- Dec 3rd, 2013
"c //feel it by doing package com.practise; public class StaticStringDemo { static String strObject1; String strObject2; public static void main(String args[]) { StaticStr... | http://www.geekinterview.com/user_answers/698758 | CC-MAIN-2019-22 | refinedweb | 835 | 62.68 |
Arduino Forum
>
Topics
>
Education and Teaching
>
sending mail using arduino uno wifi rev2
Print
Go Down
Pages:
[1]
Topic: sending mail using arduino uno wifi rev2
(Read 332 times)
previous topic
-
next topic
MohamadMohamad
Newbie
Posts: 4
Karma: 0
[add]
sending mail using arduino uno wifi rev2
Apr 15, 2019, 05:36 pm
hello
i am trying to send data in a mail using arduino uno wifi rev2, i tried this program but it doesn't work.
the arduino is already connected to the wifi.
could you check the following program and tell me what i have to change or any suggestions ?
thanks.
#include <WiFiNINA.h>
#include <SPI.h>
char from [] = "arduinounowifirev2@yahoo.com"; // email of sender
char password [] = "xxxxxxxxx"; // email password
char to [] = "xxxxxxxxxxx";
char sub [] = "Results";
String from_base64 = ("YXJkdWlub3Vub3dpZmlyZXYyQHlhaG9vLmNvbQ=="); // email of sender in base64
String password_base64 = ("xxxxxxxxxx"); // email password in base64
const String host [] = "pop.mail.yahoo.com";
const String port [] = "995";
wifi.connect ( host , port );
if (wifi.connect(host, port)) {
Serial.println ( " access to server " );
wifi.println("EHLO kltan");
wifi.println(F("250"));
wifi.println("AUTH LOGIN");
wifi.println(F("334 YXJkdWlub3Vub3dpZmlyZXYyQGhvdG1haWwuY29t"));
wifi.println (from_base64);
wifi.println(F("334 bWhhbWFkMTIz"));
wifi.println ( password_base64 );
wifi.println ( F ("235"));
char mailfrom [20] = "MAIL FROM:<";
strcat ( mailfrom , from );
strcat ( mailfrom , ">" );
wifi.println ( mailfrom );
wifi.println (F ("250"));
char mailto [20] = "RCPT TO:<";
strcat ( mailto , to );
strcat ( mailto , ">" );
wifi.println ( mailto );
wifi.println ( F ("250"));
wifi.println ( "DATA" );
wifi.println ( F ("354"));
char efrom [50] = "FROM: ";
strcat ( efrom , from );
strcat ( efrom , " " );
strcat ( efrom , "<" );
strcat ( efrom , from );
strcat ( efrom , ">" );
wifi.println ( efrom );
char eto [50] = "TO: ";
strcat ( eto , to );
strcat ( eto , " " );
strcat ( eto , "<" );
strcat ( eto , to );
strcat ( eto , ">" );
wifi.println ( eto );
char subject [50] = "SUBJECT: ";
strcat ( subject , sub );
wifi.println ( subject );
wifi.println ( "\r\n" );
wifi.println ("welcome to Arduino, we will count the results and send them each 5 min. ");
wifi.println ( "\r\n" );
wifi.println ( "QUIT" );
}else{
Serial.println ( " couldn't access to server " );
}
pert
Brattain Member
Posts: 19,311
Karma: 1988
[add]
Re: sending mail using arduino uno wifi rev2
#1
Apr 16, 2019, 06:21 am
Is that your full sketch?
Please use code tags when you post code or warning/error messages. To do this, click the
</>
button on the forum toolbar, then
paste
the text you want to be in the code tags. Finally, move the cursor out of the code tags before adding any additional text you don't want to be in the code tags. If your browser doesn't show the posting toolbar, then you can manually add the code tags like this:
[code]
// your code is here
[/code]
The reason for doing this is that, without code tags, the forum software can interpret parts of your code as markup, leading to confusion, wasted time, and a reduced chance for you to get help with your problem. This will also make it easier for us to read your code and to copy it to the IDE or editor.
Using code tags and other important information is explained in the
"How to use this forum" post
. Please read it.
Print
Go Up
Pages:
[1] | https://forum.arduino.cc/index.php?topic=610270.0 | CC-MAIN-2019-30 | refinedweb | 520 | 76.22 |
Django views – time to create!
Time to get rid of the bug we created in the last chapter! :)
A view is a place where we put the "logic" of our application. It will request information from the
model you created before and pass it to a
template. We'll create a template in the next chapter. Views are just Python functions that are a little bit more complicated than the ones we wrote in the Introduction to Python chapter.
Views are placed in the
views.py file. We will add our views to the
blog/views.py file.
blog/views.py
OK, let's open up this file and see what's in there:
blog/views.py
from django.shortcuts import render # Create your views here.
Not too much stuff here yet.
Remember that lines starting with
# are comments – this means that those lines won't be run by Python.
The simplest view can look like this:
blog/views.py
def post_list(request): return render(request, 'blog/post_list.html', {})
As you can see, we created a function (
def) called
post_list that takes
request and
return a function
render that will render (put together) our template
blog/post_list.html.
Save the file, go to and see what we've got.
Another error! Read what's going on now:
This shows that the server is running again, at least, but it still doesn't look right, does it? Don't worry, it's just an error page, nothing to be scared of! Just like the error messages in the console, these are actually pretty useful. You can read that the TemplateDoesNotExist. Let's fix this bug and create a template in the next chapter!
Learn more about Django views by reading the official documentation: | https://tutorial.djangogirls.org/en/django_views/ | CC-MAIN-2017-34 | refinedweb | 292 | 85.08 |
baked 0.2.1
Import order detection
guidelines.
Example::
[baked] zamboni $ p ~/sandboxes/baked/baked.py lib/video/ffmpeg.py -p
lib/video/ffmpeg.py:9: order wrong for check_output, subprocess, VideoBase
--- /Users/andy/sandboxes/zamboni/lib/video/ffmpeg.py 2014-05-23 16:11:56.000000000 -0700
+++ /var/folders/15/3crpnr7j4sj75xynpsqkqbr00000gp/T/tmpXvc_Ml.py 2014-05-23 16:12:11.000000000 -0700
@@ -1,14 +1,14 @@
import logging
+import logging
import re
import tempfile
from django.conf import settings
+from django_statsd.clients import statsd
from tower import ugettext as _
-from django_statsd.clients import statsd
from .utils import check_output, subprocess, VideoBase
-import logging
Notice that it detected that `logging` should be up at the top and
`django_statsd` with the 3rd party imports.
Usage::
baked.py [filename] [filename..]
Filename can be a glob. Or multiple filenames. For example::
baked.py apps/*.py mkt/*.py
Baked will also accept files being piped to it, for example::
git diff-index HEAD^ --name-only | baked
Baked loads a confg file as JSON. It will look in the following places for the file:
* in the current and parent directories of the file being checked for
``.baked``
* the current directory for ``.baked``
* the users profile directory for ``.baked``
For an example see:
The config file contains:
* *order*: the list of orders of import ``blocks``. This allows you to group your imports into categories.
* *fallback*: if a category is not found for lib, what should it fall back to, for most this will be ``local``.
* *from_order*: a dictionary of sections with a boolean value for each section. If the value is false, then baked will not care that an ``import`` came before ``from``. Default is true for each category.
* *modules*: a dictionary of categories and a list of modules. This allows baked to put each module in the category.
If you'd like to exclude an import from baked add the comment ``#NOQA``.
Guidelines:
With one exception, we ignore that imports should be ordered ``CONSTANT``,
``Class``, ``var``. Just sort by alpha, case insensitive. That's easier for
everyone to parse.
Config params:
* ``-i`` change the file in place, but note that it doesn't fix the order of
imports on the same line, for example: ``from foo import XX, bar`` is raised
as a warning, but the order of ``XX`` and ``bar`` is not fixed.
* ``-p``: print the diff that baked has calculated
Changes
-------
0.2.1: lower case import names, so ``import StringIO`` comes after ``import
os`` for example
0.2: Is a backwards incompatible change, it focuses on generating diffs which
is a lot easier to read than some rules. For imports statements on one
line which are out of order, it still prints the import order and
doesn't try to fix it up.
- Author: Andy McKay
- License: BSD
- Categories
- Package Index Owner: andymckay
- DOAP record: baked-0.2.1.xml | https://pypi.python.org/pypi/baked/0.2.1 | CC-MAIN-2017-39 | refinedweb | 478 | 68.67 |
Getting Associated Icons Using C#
Posted by Parvez Ahmad Hakim on October 22nd, 2003
How to Use the SHGetFileInfo Function to Get the Icons That Are Associated with Files in Visual C# .NET
Summary
This step-by-step article describes how to use the SHGetFileInfo function to get the icons that are associated with files.
Create a Windows Forms Application
- Start Microsoft Visual Studio .NET.
- On the File menu, point to New, and then click Project.
- In the New Project dialog box, click Visual C# Projects under Project Types, and then click Windows Application under Templates.
- In the Name box, type GetIconSample.
Use the SHGetFileInfo Function
- Add the following code in the Form1.cs file at the end of the USING statements:
- Add the following code at the beginning of the GetIconSample namespace:
- Add the following code in the Form1 class after the PRIVATE statements:
- Add a listView control, a button control, and an imageList control to the form. The default names are listView1, button1, and imageList1, respectively.
- In the Properties window of button1, set the button text to Select a File, and then add the following code in the button1_click event:
using System.Runtime.InteropServices;
; };); }
private int nIndex = 0;
IntPtr hImgSmall; //the handle to the system image list IntPtr hImgLarge; //the handle to the system image list string fName; // 'the file name to get icon from SHFILEINFO shinfo = new SHFILEINFO(); OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\temp\\"; openFileDialog1.Filter = "All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true ; listView1.SmallImageList = imageList1; listView1.LargeImageList = imageList1; if(openFileDialog1.ShowDialog() == DialogResult.OK) { fName = openFileDialog1.FileName; //Use this to get the small Icon hImgSmall = Win32.SHGetFileInfo(fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON); //Use this to get the large Icon //hImgLarge = SHGetFileInfo(fName, 0, //ref shinfo, (uint)Marshal.SizeOf(shinfo), //Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON); //The icon is returned in the hIcon member of the shinfo //struct System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon); imageList1.Images.Add(myIcon); //Add file name and icon to listview listView1.Items.Add(fName, nIndex++); }
Run the Project
- Compile the project: On the Build menu, click Build Solution.
- Press F5 to run the project.
- Click Select a File, and then select a file in the Open dialog box. The name of the file and the icon that is associated with the file appear in the ListView control.
it dosent workPosted by eran65 on 01/29/2011 08:03pm
I HATE U MORE THEN LIFE ITSELFReply
You MUSE use DestroyIcon() function after extracting an iconPosted by nigor on 04/14/2005 02:39pm
This seems copied from by LRaiz on 03/24/2005 11:17am
This article seems to be a cut and paste of
IMPORTANTPosted by parvezhakim12 on 12/12/2004 12:19pm
This also belongs to Microsoft MSDN magzine. The idea of showing it here is to free developers from searching up the MSDN, and many changes have been made to that article where ever possible. This article is belongs to Microsoft and i do not have any intention to get involved in some legal problems, misuse it or distribute it. Parvez AhmadReply
Get File IconPosted by chandra.mohan on 10/05/2004 06:27am
How to Use the SHGetFileInfo Function to Get the Icons That Are Associated with Files in Visual C# .NET Compact Framework ( in PocketPC, SmartPhone, and WinCE Devices )Reply
And what if ...Posted by Legacy on 11/04/2003 12:00am
Originally posted by: Rob
How to check if the image list already contains the image/icon associated with the file selected?
Reply | http://www.codeguru.com/csharp/csharp/cs_misc/icons/article.php/c4261/Getting-Associated-Icons-Using-C.htm | CC-MAIN-2014-10 | refinedweb | 597 | 55.95 |
Import a library and all its dependencies on lib folder
Hi ,
I would like to use queues to communicate between my threads with this library :
However, this library need
collections.dequeand
uasynio.core.
1 from collections.deque import deque 2 from uasyncio.core import sleep
I went to the micropython-lib github repository, I downloaded
collection.dequeand paste the source file into the lib folder.
I think I'm not importing libraries correctly because I need to modify the line
from collections.deque import dequeto
from collections import deque
I tried to do the same thing with the
uasyncio.coremodule but it also needs the
loggingmodule.
I thing it should have a way to install a module and all its dependencies at the same time right?
I can't imagine the only way is to manually import all the dependencies.
Thank you in advance.
@livius
Hi thought an apt-get like or pip-like system would exist ^^.
I know that when I use pip for installing new modules there is a requires.txt file to download all the needed dependencies.
When I download the module on pypi.python the folder architecture is the following one:
micropython-uasyncio.core-1.0/ micropython_uasyncio.core.egg-info/ PKG-INFO requires.txt uasyncio/ core.py test.py test2.py
So because of this architecture I thought there would have a way to use the requires.txt file to recover all the dependencies.
Maybe I'm dreaming ^^
If it doesn't exist it's not a big deal, I'll just use the classic way ;-)
@Arkaik
Downloading whole repository?
How do you imagine that it will be automagically?
I know that this is not the same but:
Same with web page - you save it and it have link to other site. If it will automatically download all linked pages and all linked pages linked in linked pages - you will be attempting to download whole internet ;-)
Hi @livius, no I don't have it in the lib folder.
I could put it in this folder but I imagine a situation where the module logging (or another one, whatever) also needs dependencies, I'll need to dowload them too.
And if its dependencies also need other dependencies it will be a pain in the *** to import all of them independently, even more if I need to modify the way they are imported.
That's why I'm asking if there is a faster/easier way to import a module and all its dependencies? | https://forum.pycom.io/topic/1214/import-a-library-and-all-its-dependencies-on-lib-folder | CC-MAIN-2017-34 | refinedweb | 416 | 65.62 |
Play 1.1 — Release notes
You can read about the bugs fixed in Play 1.1 on the road map page. This page highlights the most important changes.
Migrating from Play 1.0.x
Migrating from Play 1.0.x is pretty straightforward. There are no changes to the application layout, so the same application will run on Play 1.0.3.2 or Play 1.1. However if you use any external modules in your application, you may have to use more recent versions that are compatible with Play 1.1. Check the corresponding module pages.
- Some APIs have been removed in Play 1.1, after having been deprecated for a long time, but most of the public API is the same. If you have compilation errors that you don’t know how to solve, ask on the Google group.
- Plugin order has been changed. If you have a specific plugin that need to run before or after a default one, perhaps you will need to change its index.
- In play.libs.IO, a lot of methods that used to throw checked exceptions are now throwing runtime exceptions. If you were catching the exception you may need to change the exception class or stop catching it.
- In production mode, the database is no longer automatically updated when the model changes. If you want this behavior, add this line to your your application.conf:
jpa.ddl = update
New headless test runner
As you know, the Play test runner requires a browser to run application tests. This is because of the Selenium test support, which makes it possible to really test your application running in a browser.
However, for continuous integration, it’s sometimes difficult to automatically run a real browser on the integration server. So, since this release, Play embeds a stand-alone headless browser based on HtmlUnit.
When you run tests with
play auto-test, this browser will be used.
Note that the headless browser try to behave like Internet Explorer 8. It’s a good thing because as most developers use and test locally on a real browser like Firefox or Webkit, it allows to check obvious JavaScript compatibility issues on the integration platform.
New HTTP server based on JBoss Netty
The Play 1.1 release uses JBoss Netty instead of Apache Mina as HTTP server. This should not change anything for your application, and the performance of the HTTP layer be the same as before. However, this fixes some small HTTP bugs that affected Play 1.0.x.
This new HTTP server will allow us the support more advanced HTTP features soon, such as WebSockets.
Updated core libraries and improved naming
As Play framework is a full-stack framework it directly embeds the required Java libraries. All of these libraries have been updated, including the new Hibernate 3.5.x release that provides JPA 2 support.
We have also adopted a better naming conventions for embedded libraries. If you look in the
framework/lib directory you can now see what the exact version of each library is.
New database-agnostic play.db.Model API
Play 1.1 introduces a new play.db.Model API. This API is not intended to be used directly by applications, but it provides a generic datastore interface that can be implemented by module’s creator to provide integration with any kind of datastore (including NoSQL based ones).
This means that in Play 1.1, JPA support is totally decoupled from the core framework. It is still a default plugin, and is activated automatically if it detects any @Entity class, but some features such as CRUD and Fixtures no longer directly depend on JPA. These components can work with any module that provides an implementation ok play.db.Model, such as the play-morphia module for MongoDB.
Scala language support
The core framework internals have been refactored to work with the Scala language. The Scala module provides complete integration for Scala with the Play framework.
Native Glassfish deployment support
Play has now a native container for the Glassfish application server. This means that by adding the Play container to any Glassfish server you can deploy any existing Play application on it.
The Glassfish container is hosted at, and should be soon available directly in the Glassfish
contrib repository.
Because Glassfish allows to run several applications simultaneously, you can now run several Play applications in a single JVM.
Note that this is different from packaging your application as a WAR file. The Play container for Glassfish runs applications natively: it doesn’t use a Servlet container, and does not require that you package your application in a particular way.
Virtual hosting in routes
The
routes file now supports Host matching. this can be useful if action parameters must be extracted from the host parameter. For example, for a SAAS application, you could use:
GET {client}.mysoftware.com/ Application.index
and then automatically retrieve the
client value as for any other request parameter:
public static void index(String client) { … }
When using the
@@{…} notation (absolute reverse routing) in a template, the host will be used if provided by the corresponding route. This can be useful in several situations.
For example, if you want to use a content distribution network to distribute your static assets in production, you could write a
routes file like this:
#{if play.Play.mode.isDev()} GET /public/ staticDir:public #{/} #{else} GET assets.myapp.com/ staticDir:public #{/}
And in your templates:
<img src="@@{'/public/images/logo.png'}">
This will be reversed as in DEV mode, and in PROD mode.
Support.
New powerful async WS library
The
play.libs.WS library allow your Play application to behaves like a web client. In this release we have introduced a new asynchronous implementation based on AsyncHttpClient. This new implementation provides new
xxxAsync methods that allow you to fetch remote resources asynchronously.
When combined with the
waitFor(…) feature, you can use this to build high performance non-blocking applications that mash-up existing applications:
public static void mirrorFeed() throws Exception { if (request.isNew) { Future<HttpResponse> feed = WS.url( "" ).getAsync(); request.args.put("futureFeed", feed); waitFor(feed); } else { HttpResponse res = ( (Future<HttpResponse>)request.args.get("futureFeed") ).get() renderXml(res.getXml()); } }
OAuth support
There is now a
play.libs.OAuth library that provides OAuth protocol support. OAuth is an open protocol to allow secure API authorization in a simple and standard method from web applications.
A new
twitter-oauth sample application demonstrates the API usage by connecting securely to the twitter API.
HTTPS support
The built-in server now supports the HTTPS protocol. You can of course use it in production if you want. 1024 > host.key openssl req -new -x509 -nodes -sha1 -days 365 -key host.key > host.cert.
New Cache features
There are two new features that enable easier cache integration for actions and templates. First you can easily cache the result of an action by adding the
@play.cache.CacheFor annotation. This is very useful for pseudo static pages.
@CacheFor("1h") public static void index() { render(); }
Second, there is now a new
#{cache} tag that allows to easily cache template fragments:
<h1>Very complex home page to build</h1> #{cache 'home-' + connectedUser.email, for:'15min'} … #{/cache}
These new features use the same cache implementation as the standard Play cache.
WAR archives are fully precompiled
The
play precompile command now really compile your applications to static Java bytecode. This means that you can distribute a Play application fully-compiled, and that you can remove all
app/ source files, including templates.
All WAR files generated by the
play war command are now automatically precompiled.
By default, when you run an application the standard way, Play will always check the application source code to detect changes. If you don’t care about this step and you want to start your application from precompiled classes, you can specify the
precompiled=true system property:
play start myApp -Dprecompiled=true
Global route arguments
The new
play.mvc.Controller.routeArgs scope allow to define arguments that will be used globally for any reverse routing during the request. For example, if you have a common parameter for a lot of routes:
GET /{lang}/ Application.index GET /{lang}/users Application.users GET /{lang}/items Application.items
You can omit the
lang parameter for each action, and manage it in a single
@Before filter:
@Before static setLang(String lang) { Lang.set(lang); routeArgs.put("lang", lang); }
By adding the
lang argument to the
routeArgs scope, it will automatically be used for reverse routing, even if not specified:
<a href="@{Application.users()}">Users list</a>
will be, for example, reversed as:
<a href="/fr/users">Users list</a>
More flexibility to write custom commands
Module creators now have more flexibility to write custom Python commands. A
commands.py file contributed by a module can hook into any existing built-in command. Also, commands contributed by modules are now listed by the
play help command.
Other small features
There are also some small new features as well as 230 fixed bugs, including:
- support for namespaces in the
play.libs.XPathlibrary
- support of the
nevervalue in Jobs scheduling
- mime type to serve static resources can be defined in
application.conf
- helpers for cross-domain XHR in
play.mvc.Http.Response
- support for HTTPOnly cookies
- new command
play checkto check for new Play framework releases. | https://www.playframework.com/documentation/1.5.x/releases/release1.1.x/releasenotes-1.1 | CC-MAIN-2021-21 | refinedweb | 1,555 | 56.76 |
Running systems library as Cloud Function.systems (4), gcf (1), cloud (3)
I was chatting with my friend Bobby Powers, and he mentioned a systems dynamics app he’s been hacking on. That conversation inspired me to want to finish a project I’ve been neglecting, which is explosing systems as an HTTP endpoint running within a Google Cloud Function.
The rough goals of this exercise were: (1) expose
systems via an HTTP API,
(2) run it as a function, aka serverless, to minimize maintenance and cost,
(3) the development workflow should be very simple since I’ll otherwise forget how it works when I periodically forget about it,
(4) it should be extensible for me to add a JavaScript GUI that calls into the API at some later point.
These goals have been accomplished, although it was a bit trickier than I expected.
I already had the Google Cloud SDK installed, so I skipped over that bit. Next I moved on to create a new Git repository:
cd sys-app git init
Initially it was just three files. The first was an HTTP function at
sys-app/functions/run-model/main.py:
def hello_get(request): return 'Hello World!'
The second was in that same directory at
sys-app/functions/run-model/requirements.txt and
specified the only Python library dependency:
systems==0.1.0
The final file was a build configuration for Cloud Build:
steps: - name: 'gcr.io/cloud-builders/gcloud' args: ['functions', 'deploy', 'run_model', '--trigger-http', '--runtime', 'python37' ] dir: 'functions/run-model'
Then created a new private repository on Github and sync the local repo up:
git remote add origin git@github.com:lethain/sys-app.git git push -u origin master
Then I updated Cloud Source Repositories on GCP to mirror over
lethain/sys-app.
I could have also just connected to the repository directly on Github instead of mirroring it over,
but for whatever reason I sort of prefer mirroring over and then getting to operate on it directly
within Cloud Source as it’s a bit more decoupled.
Started following the steps to do automatic builds.
First enabled
Cloud Build, then created a build trigger firing on all deploys on
sys-app to
master branch.
As a caveat, I know it says Github is the source, but the source I selected was the Cloud Source mirror. As best I can tell, this is just a weird UI bug.
The penultimate step was granting Cloud Function deploy permissions to Cloud Builder as its documented here. I initially missed this step, and honestly found it a bit confusing even following the directions word for word, but I eventually got it (I debugged by continuing on with next steps and futzed around until it all worked).
At this point, I committed another change to the
sys-app repository and deployed it, and viola,
the build trigger fired, the function was created, and it all worked.
In full transparency, I got stuck here for some time, with everything seeming to work, with new versions of the function getting created on each deploy, but the code it ran never getting updated at all. I had created that function through the UI, and there just wasn’t much useful context in the logs to say why it wasn’t updating, so I went ahead and deleted it and relied on the cloud build configuration to create and update a new function, at which point it worked properly.
I’m able to verify the function through the
gcloud CLI:
gcloud functions call run_model \ --data '{"definition": "a > b @ 1"}' \ --project=PROJECT
Alternatively, I can also call it over HTTP in Python:
import requests definition = """[a] > b @ 5 b > c @ 4""" resp = requests.post('', json={'definition': definition}) print(resp.content.decode("utf-8"))
I’m now able to modify
sys-app, push the new commit, and the function updates automatically behind the scenes,
which was pretty much the original goal.
Unlike with my GKE experiments, I was able to get this deployment flow without creating any sort
of services to handle scheduling upgrades after builds completed or whatnot, which is quite nice.
(Looking at the
kubectl cloud builder,
I bet I could figure out a way to do continuous deployments to k8s without a service monitoring the build pub-sub queue,
I’m not sure if this is new functionality or if I just missed it last time.)
If I were going to be developing with this workflow frequently,
my next step would be to figure out how to run tests in a blocking fashion on each build, but it doesn’t
seem like there is a good way to do that for Python (they’re missing
pip as a cloud-builder,
so I think I’d need to setup a Dockerfile to use for testing, which is totally fine, but not something I’m particularly excited for).
Altogether, there is a great user experience just over the hill from what GCP is offering.
Imagine how delightful this user experience would be if after I created a new Cloud Function I could select
a checkbox and it would automatically deploy each time I changed it in the Cloud Source repository? Imagine further yet
if I could include a
test.py that would automatically run before attempting to deploy an update?
You absolutely can build all of this yourself, but why should each user need to add this glue? This is why platforms like netlify are cropping up despite the cloud vendors having all the right components underneath. This evolution reminds me a bit of AWS' attempt to move downstream into the personal VM market with Amazon Lightsail, executing a few years too late on what other hosting providers like Slicehost and now Digital Ocean have realized some users want.
A good reminder for all of us that we should take a few hours each quarter and integrate our products from scratch and see what the rough edges are. | https://lethain.com/systems-lib-as-cloud-function/ | CC-MAIN-2021-21 | refinedweb | 994 | 54.97 |
Threading example
Hi all, am developing a Wipy multisensor, I want to have a PIR sensor running on a background thread pinging an MQTT message when it registers motion, whilst performing other periodic sensor readings on the main thread (or vice-versa I suppose). Does anyone have a good example of this?
Cheers
Robin
This post is deleted!
@robmarkcole
no, your link is for pyboard
here you have example from docs
from machine import Pin def pin_handler(arg): print("got an interrupt in pin %s" % (arg.id())) p_in = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP) p_in.callback(Pin.IRQ_FALLING | Pin.IRQ_RISING, pin_handler)
for pycom doc is here
@bucknall Hi Alex, thanks for the advice, you are referring to
? If you know of any examples that could get me started that would be a great help, as this appears quite advanced.
Cheers
Hi @robmarkcole,
Would using an interrupt on the PIR sensor pin be a potential solution? You could then run your main code loop and have your MQTT message sent any time that the interrupt is triggered? | https://forum.pycom.io/topic/1301/threading-example | CC-MAIN-2018-39 | refinedweb | 178 | 61.36 |
NAME | SYNOPSIS | DESCRIPTION | ATTRIBUTES | SEE ALSO
#include <sys/stream.h>
#include <sys/vuid_event. The user will need to change the state to VUID_FIRM_EVENT mode in order to initiate mouse protocol conversion to Firm events. This can be accomplished by the following code:
int format; format = VUID_FIRM_EVENT; ioctl(fd, VUIDSFORMAT, &format);
The user.
The messages coming in. There are two valid ioctl options processed by the vuidmice modules VUIDGFORMAT and VUIDSFORMAT. then this option is non-operational. It is not possible to set the state back to VUID_NATIVE once the state becomes VUID_FIRM_EVENT. To disable message processing, pop the STREAMS module out by calling ioctl(fd, 1I_POP, vuid*).
The write queue of the module is flushed of all its data messages and the message is passed downstream.
See attributes(5) for descriptions of the following attributes:
STREAMS Programming Guide
NAME | SYNOPSIS | DESCRIPTION | ATTRIBUTES | SEE ALSO | http://docs.oracle.com/cd/E19683-01/817-0685/6mgfgvajk/index.html | CC-MAIN-2015-14 | refinedweb | 144 | 58.79 |
I've been working on an alternative method to virtual pointers to achieving runtime polymorphism, with increased space efficiency being the primary concern. While this was simple enough, I found that when inlining was brought into consideration, my method was unable to benefit fully due to functions containing switch statements being refused inlining. While this doesn't amount to much of a speed difference in this simple test, I sought to improve upon it and came up with a method involving what I believe is called 'macro magic', which incidentally happens to offer a noticable speed advantage over virtual pointers in many cases.
What I'm asking for is info on any flaws which could limit its use.
Code:#include <iostream> #include <time> using namespace std; // This next bit is the macro that serves as a 'solution' to the non-inlining function(s?) containing switches. #define FUNC(ob) { \ switch(ob->get_type()) { \ case 1: \ ob->m1::koo(); \ break; \ case 2: \ reinterpret_cast <m2 *> (ob)->m2::koo(); \ break; \ } \ } // This determines the version of program compiled. Define MACROS for the macro version, or don't define it for the fuction-calling version. //#define MACROS class v1 { // The v-type classes use virtual pointers for runtime polymorphism. public: int i; int j; inline virtual void foo() { i = 4; } }; class v2 : public v1 { public: inline virtual void foo() { j = 6; } }; class m1 { // The m-types use my alternative method for runtime polymorphism. protected: int type; public: int k; int l; inline m1() { type = 1; } inline void goo(); inline void koo() { k = 3; } int get_type() { return type; } }; class m2 : public m1 { public: inline m2() { type = 2; } inline void goo(); inline void koo() { l = 5; } }; inline void m1::goo() { switch(type) { case 1: this->m1::koo(); break; case 2: reinterpret_cast <m2 *> (this)->m2::koo(); break; } } inline void m2::goo() { switch(type) { case 1: this->m1::koo(); break; case 2: reinterpret_cast <m2 *> (this)->m2::koo(); break; } } int main() { v1 ob1; v2 ob2; m1 ob3; m2 ob4; v1 *ptr1 = &ob1; v1 *ptr2 = &ob2; m1 *ptr3 = &ob3; m1 *ptr4 = &ob4; clock_t first1; clock_t first2; clock_t hold1; clock_t hold2; clock_t hold3; clock_t hold4; first1 = clock(); for(int i=0;i<10000000;++i) ptr1->foo(); first2 = clock(); hold1 = (first2 - first1); // Place a breakpoint here and start stepping through the assembly instructions to compare differences. first1 = clock(); for(int i=0;i<10000000;++i) ptr2->foo(); first2 = clock(); hold2 = (first2 - first1); #ifdef MACROS first1 = clock(); for(int i=0;i<10000000;++i) FUNC(ptr3); first2 = clock(); hold3 = (first2 - first1); first1 = clock(); for(int i=0;i<10000000;++i) FUNC(ptr4); first2 = clock(); hold4 = (first2 - first1); #else first1 = clock(); for(int i=0;i<10000000;++i) ptr3->goo(); first2 = clock(); hold3 = (first2 - first1); first1 = clock(); for(int i=0;i<10000000;++i) ptr4->goo(); first2 = clock(); hold4 = (first2 - first1); #endif cout << hold1 << '\n' << hold2 << '\n' << hold3 << '\n' << hold4 << '\n'; return 0; }
P.S. I know something about the lack of type safety and the possible problem of programmer logic (which could be helped by thinking of the macro as a global function call rather than a member function). However since I may not fully understand the potential effects, posts about them would not be considered...unwelcome/unnecessary/redundant. | http://cboard.cprogramming.com/cplusplus-programming/74814-request-peer-review.html | CC-MAIN-2015-06 | refinedweb | 533 | 52.16 |
Django comes with a high-level sitemap-generating framework that makes creating sitemap XML files easy.
A sitemap is an XML file on your website.
To install the sitemap app, follow these steps:
(Note: The sitemap application doesn’t install any database tables. The only reason it needs to go into INSTALLED_APPS is so that the Loader() template loader can find the default templates.)
To activate sitemap generation on your Django site, add this line to your URLconf:
from django.contrib.sitemaps.views import sitemap url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'):
A Sitemap class can define the following methods/attributes:
Required. A method that returns a list of objects. The framework doesn’t care what type of objects they are; all that matters is that these objects get passed to the location(), lastmod(), changefreq() and priority() methods.:
If location isn’t provided, the framework will call the get_absolute_url() method on each object as returned by items().
To specify a protocol other than 'http', use protocol.().
If all items in a sitemap have a lastmod, the sitemap generated by views.sitemap() will have a Last-Modified header equal to the latest lastmod. You can activate the ConditionalGetMiddleware to make Django respond appropriately to requests with an If-Modified-Since header which will prevent sending the sitemap if it hasn’t changed..
Optional.
This attribute defines the protocol ('http' or 'https') of the URLs in the sitemap. If it isn’t set, the protocol with which the sitemap was requested is used. If the sitemap is built outside the context of a request, the default is 'http'.
Optional.
This attribute defines the maximum number of URLs included on each page of the sitemap. Its value should not exceed the default value of 50000, which is the upper limit allowed in the Sitemaps protocol.
Optional.
A boolean attribute that defines if the URLs of this sitemap should be generated using all of your LANGUAGES. The default is False.
The sitemap framework provides a convenience class for a common case:
The django.contrib.sitemaps.GenericSitemap class allows you to create a sitemap by passing it a dictionary which has to contain at least a queryset entry. This queryset will be used to generate the items of the sitemap..
Here’s an example of a URLconf using GenericSitemap:
from django.conf.urls import url from django.contrib.sitemaps import GenericSitemap from django.contrib.sitemaps.views import sitemap from blog.models import Entry info_dict = { 'queryset': Entry.objects.all(), 'date_field': 'pub_date', } urlpatterns = [ # some generic view using info_dict # ... # the sitemap url(r'^sitemap\.xml$', sitemap, {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}}, name='django.contrib.sitemaps.views.sitemap'), ]
Often you want the search engine crawlers to index views which are neither object detail pages nor flatpages. The solution is to explicitly list URL names for these views in items and call reverse() in the location method of the sitemap. For example:
# sitemaps.py from django.contrib import sitemaps from django.core.urlresolvers import reverse class StaticViewSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'daily' def items(self): return ['main', 'about', 'license'] def location(self, item): return reverse(item) # urls.py from django.conf.urls import url from django.contrib.sitemaps.views import sitemap from .sitemaps import StaticViewSitemap from . import views sitemaps = { 'static': StaticViewSitemap, } urlpatterns = [ url(r'^$', views.main, name='main'), url(r'^about/$', views.about, name='about'), url(r'^license/$', views.license, name='license'), # ... url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap') ]
The sitemap framework also has the ability to create a sitemap index that references individual sitemap files, one per each section defined in your sitemaps dictionary. The only differences in usage are:
Here’s what the relevant URLconf lines would look like for the example above:
from django.contrib.sitemaps import views urlpatterns = [ url(r'^sitemap\.xml$', views.index, {'sitemaps': sitemaps}), url(r'^sitemap-(?P<section>.+)\.xml$', views.
If you’re not using the vanilla sitemap view – for example, if it’s wrapped with a caching decorator – you must name your sitemap view and pass sitemap_url_name to the index view:
from django.contrib.sitemaps import views as sitemaps_views from django.views.decorators.cache import cache_page urlpatterns = [ url(r'^sitemap\.xml$', cache_page(86400)(sitemaps_views.index), {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}), url(r'^sitemap-(?P<section>.+)\.xml$', cache_page(86400)(sitemaps_views.sitemap), {'sitemaps': sitemaps}, name='sitemaps'), ]
If you wish to use a different template for each sitemap or sitemap index available on your site, you may specify it by passing a template_name parameter to the sitemap and index views via the URLconf:
from django.contrib.sitemaps import views urlpatterns = [ url(r'^custom-sitemap\.xml$', views.index, { 'sitemaps': sitemaps, 'template_name': 'custom_sitemap.html' }), url(r'^custom-sitemap-(?P<section>.+)\.xml$', views.sitemap, { 'sitemaps': sitemaps, 'template_name': 'custom_sitemap.html' }), ]
These views return TemplateResponse instances which allow you to easily customize the response data before rendering. For more details, see the TemplateResponse documentation.
When customizing the templates for the index() and sitemap() views, you can rely on the following context variables.
The variable urlset is a list of URLs that should appear in the sitemap. Each URL exposes attributes as defined in the Sitemap class:
The item attribute has been added for each URL to allow more flexible customization of the templates, such as Google news sitemaps. Assuming Sitemap’s items() would return a list of items with publication_data and a tags field something like this would generate a Google News compatible sitemap:
<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="" xmlns: {% spaceless %} {% for url in urlset %} <url> <loc>{{ url.location }}</loc> {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %} {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %} {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %} <news:news> {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %} {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %} </news:news> </url> {% endfor %} {% endspaceless %} </urlset>
You may want to “ping” Google when your sitemap changes, to let it know to reindex your site. The sitemaps framework provides a function to do just that: django.contrib.sitemaps.ping_google().(). | http://djbook.ru/rel1.9/ref/contrib/sitemaps.html | CC-MAIN-2016-50 | refinedweb | 1,025 | 52.15 |
Is there a way to send email from Spotfire on a button click?
i am looking for an option to send email form a button click in spotfire text area using iron python
(or)
can we implement same with the help of iron python and Automation Services.
import clr
clr.AddReference("Microsoft.Office.Interop.Outlook")
from System.Runtime.InteropServices import Marshal
mail= Marshal.GetActiveObject("Outlook.Application").CreateItem(0)
mail.Recipients.Add("abc@xyz.com")
mail.Subject = "subject here"
mail.Body = "body here"
mail.Send();
the above code is to send email , it is working fine within spotfire Client but not in web player.please help me out
Thanks in Advance
+ Add a Comment | https://community.tibco.com/questions/there-way-send-email-spotfire-button-click | CC-MAIN-2021-04 | refinedweb | 113 | 61.12 |
Email is an old and proven technology and integrating with email is very important, especially if you target businesses. Unfortunately building email applications has been a major pain until recently. In this post I will explore my venture into building email support for Wedoist using a modern framework like Lamson.
The problem with building email applications is that the email tools are as old as email itself (from the 1970's). Fortunately for us, in the recent times there has been a major contribution in this field by Zed Shaw. He has created a modern framework for building email applications called Lamson.
Wedoist is a project management tool and I think it would be super useful to add status updates or tasks via email. For example, if you get an error report via email you can delegate it by forwarding it to the proper project.
What I wanted to implement are following emails:
All of these have been implemented, so let's take a look how they were done, how it can be done and why Lamson is a great way to do it.
No, it's not hard, but building your own SMTP server is just the first step, just like coding a HTTP server is just a tiny part of implementing a web application.
To show how easy it is here is a very simple non-blocking SMTP server built in Python:
import smtpd
import asyncore
class MailDummy(smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
print mailfrom
if __name__ == '__main__':
server = MailDummy(('0.0.0.0', 25), None)
asyncore.loop()
Lamson does a lot more than just being a SMTP server. It's a framework for building kickass email applications.
Lamson provides following tools:
So basically Lamson provides the same tools for building email-applications as the tools we use to build web-applications. It's pretty neat. Let's take a look at my Wedoist code to see how Lamson code feels like.
The first step is to implement a handler. For status updates this is done from app/handlers/status_updates.py and the code looks like this:
@route("status.(project_id)@(host)", project_id="[0-9]+")
@stateless
def STATUS(message, project_id=None, host=None):
project_id = long(project_id)
user = _resolve_user(project_id, message, host)
if not user:
return
try:
project = ProjectsApi().get(project_id)
subject, body = parse_subject_body(message)
if subject:
item = StatusesApi().add(project.id, subject)
if body:
'status',
item.id,
body)
signals.send_signal('email_status', item)
except PermissionError as p_err:
_send_permission_error(project_id, message, p_err)
except ModelError as m_err:
_send_model_error(project_id, message, m_err)
Decorators are used to tell that status[project_id]@wedoist.net should be routed to this function. It's quite elegant and much more readable than your average email code.
As I mature as a developer I find testing more and more important, especially in a language like Python. Lamson supports unit-testing and makes it trivial. Here is how one of the tests for status[project_id]@wedoist.net looks like:
def test_unknown_user():
assert len(ItemsApi().getActive(PROJECT.inbox_list)) == 0
helpers.say('[email protected],
INBOX_EMAIL,
'Some random rambling',
'Body body',
except_reply='noreply')
assert len(ItemsApi().getActive(PROJECT.inbox_list)) == 0
It's neat and a very nice way to develop email-applications.
I highly recommend using Lamson. I basically built Wedoist's email support in one day - it is in production now and you can check it out.
Happy hacking :-) | http://amix.dk/blog/post/19608 | CC-MAIN-2014-42 | refinedweb | 561 | 57.77 |
Solution :
Let's try to build a 'bad' solution first. By 'bad', I mean the approach may not be the most optimal but will return correct results every time. One such approach is to list down all possible substrings and count the unique letters in each of them and then take their sum. This approach is perfectly reasonable approach but why it is not optimal ?
For e.g. let our string S be represented as a n-tuple of letters :
[x0, x1, ..., xn-1], where each xi belongs to one of the letters from A to Z.
Then the number of possible sub-strings is = 0.5*n*(n-1) = O(n2), because the number of sub-strings of length 1 is 'n', the number of sub-strings of length 2 = n-1 and so on. Thus :
n + (n-1) + (n-2) + ... + 1 = 0.5*n*(n-1) = O(n2)
For each such substring, we count the number of unique letters. For a string of length 'd', the complexity of counting unique letters is O(d). Thus the total time complexity for all possible sub-strings is given by the sum :
S = 1*n + 2*(n-1) + 3*(n-2) + ... + n*1
The maximum value in the above summation, occurs for sub-strings of length n/2, which is (n/2)2 = O(n2).
Thus S <= n*(n/2)2 = O(n3).
Thus the above approach has an asymptotic run-time complexity of O(n3). Too bad for such a reasonable solution !!!
Can we do better than that ? Where can we optimize ? Can we somehow use dynamic programming technique to compute number of unique letters for each sub-string, so that each computation takes a constant O(1) time complexity instead of O(d) as seen earlier ?
Let us denote a sub-string 'xixi+1...xj' as [i, j].
Note that once we have computed the value of UNIQ([i, j]) for the sub-string [i, j], then in order to compute the unique letters for the sub-string [i, j + 1], we can use the fact that on addition of the extra letter 'xj+1' to the sub-string [i, j], the value of UNIQ([i, j]) can either increase, decrease or remain the same. i.e.
UNIQ([i, j + 1]) = UNIQ([i, j]) + 1, if the letter 'xj+1' is never seen in the sub-string [i, j]
UNIQ([i, j + 1]) = UNIQ([i, j]) - 1, if the letter 'xj+1' is seen once in the sub-string [i, j]
UNIQ([i, j + 1]) = UNIQ([i, j]) if the letter 'xj+1' is seen more than once in the sub-string [i, j], because they already cancel out.
Let us define an array H[i], which returns the last seen position of the character at index 'i'. If the character is not seen before index 'i', then H[i] = -1. Let's take an example.
Consider the sub-string 'ABCDBCB', then H[0]=H[1]=H[2]=H[3]=-1 because the first 4 letters 'ABCD' are unique and thus they do not occur anywhere before. But H[4]=1, because the letter at index 4, which is 'B' was also present at index 1, similarly H[5]=2 and H[6]=4, because last seen position of letter 'B' was at index 4 in the string. Using this data structure, we can determine UNIQ([i, j + 1]) from UNIQ([i, j]) in constant time.
i.e. if H[j+1] < i, then the letter 'xj+1' is never seen in the sub-string [i, j], and thus UNIQ([i, j + 1]) = UNIQ([i, j]) + 1
But if H[j+1] >= i, there are two possibilities, one that the letter 'xj+1' is seen only once in the sub-string [i, j] or it is seen more than once. To verify whether it is seen more than once in the sub-string [i, j], just check whether H[H[j+1]] < i or not.
If H[j+1] >= i and H[H[j+1]] < i, then the letter 'xj+1' is seen only once in the sub-string [i, j], and thus UNIQ([i, j + 1]) = UNIQ([i, j]) - 1, else UNIQ([i, j + 1]) = UNIQ([i, j])
Now for each sub-string, the time complexity for UNIQ is O(1), achieved through dynamic programming. Thus the total time complexity is :
S = n + (n-1) + (n-2) + ... + 1 = O(n2), instead of O(n3) by the earlier approach.
Can we still do better ? Let's try.
Observe that we can break down the summation of the unique letters for all sub-strings as the summation of unique letters for all sub-strings ending with each of the letters, i.e. assuming that our string is 'x0x1x2', then the summation of unique letters for all sub-strings is given by :
Q = UNIQ(x0) + UNIQ(x1) + UNIQ(x2) + UNIQ(x0x1) + UNIQ(x1x2) + UNIQ(x0x1x2)
Let G(xi) be the summation of unique letters for sub-strings ending with the letter at the i-th position :
G(x0) = UNIQ(x0)
G(x1) = UNIQ(x1) + UNIQ(x0x1)
G(x2) = UNIQ(x2) + UNIQ(x1x2) + UNIQ(x0x1x2)
Then we can write Q = G(x0) + G(x1) + G(x2).
Observe that each G(xi) is obtained by adding 'xi' at the end of each of the sub-strings in G(xi-1) and then taking the UNIQ function over each, plus a fixed term UNIQ(xi) which is anyway equals to 1.
Let's assume that we have computed all G's till G(xi-1) and we need to compute G(xi). Now if 'xi' has never been seen in [0, i - 1], then addition of 'xi' to each of the sub-strings in G(xi-1), i.e.
[0, i - 1], [1, i - 1], [2, i - 1], ..., [i - 1, i - 1]
will contribute an additional factor of 1 for each of the terms, i.e. UNIQ([0, i]) = UNIQ([0, i - 1]) + 1, UNIQ([1, i]) = UNIQ([1, i - 1]) + 1, and so on.
Thus in such a case : G(xi) = G(xi-1) + i + 1, because there are i terms in G(xi-1) and +1 due to UNIQ(xi).
What if 'xi' is already present in [0, i - 1] ? Then as seen earlier, there could be two scenarios :
- 'xi' is seen only once in [0, i - 1]
- 'xi' is seen more than once in [0, i - 1]
The first case is valid if H[i] >=0 and H[H[i]] = -1 and the second case is valid if both H[i] >=0 and H[H[i]] >= 0.
Assuming the first case is true, let p = H[i], then addition of 'xi' to each of the sub-strings :
[p + 1, i - 1], [p + 2, i - 1], [p + 3, i - 1], ..., [i - 1, i - 1]
contributes an addition of +1 similar to before because 'xi' is never seen after the index 'p' according to the definition of H. The number of such terms is (i - p - 1).
For the remaining terms, i.e.
[0, i - 1], [1, i - 1], [2, i - 1], ..., [p, i - 1]
Addition of 'xi', will decrease the number of unique letters by 1, because now 'xi' is not unique anymore. The number of such terms is (p + 1).
Thus in such a case :
G(xi) = G(xi-1) + (i - p - 1)*1 + (p + 1)*(-1) + 1 = G(xi-1) + i - 2p - 1
Assuming the second case is true, i.e. both H[i] >=0 and H[H[i]] >= 0, let :
p = H[i] and q = H[H[i]] = H[p], thus quite obviously q < p.
In such a case, the terms contributing +1 remains the same as the above case and the number of such terms is (i - p - 1). For the terms contributing (-1), now instead of all substrings starting from 0th index, we will have only the sub-strings starting from the (q+1)th index, i.e. The terms contributing (-1) are :
[q + 1, i - 1], [q + 2, i - 1], [q + 3, i - 1], ..., [p, i - 1]
The number of such terms is (p - q).
Now, for the remaining terms, i.e.
[0, i - 1], [1, i - 1], [2, i - 1], ..., [q, i - 1]
They do not contribute anything at all on addition of 'xi', because 'xi' is already a non-unique in [0, i - 1]. The number of such terms is (q + 1). Thus we can write the expression for G(xi) as :
G(xi) = G(xi-1) + (i - p - 1)*1 + (p - q)*(-1) + (q + 1)*0 + 1 = G(xi-1) + i - 2p + q
Thus now instead of enumerating all possible sub-strings, we can use dynamic programming to derive G(xi) from G(xi-1) in constant time O(1) and then we can compute UNIQ([0, n - 1]) in linear time as :
UNIQ([0, n - 1]) = G(x0) + G(x1) + G(x2) + ... + G(xn-1).
Although the logic described above looks a bit complicated (especially given that we are doing two levels of dynamic programming), but the Python code turns out to be surprisingly easy.
import collections class Solution(object): def uniqueLetterString(self, S): if len(S) == 0: return 0 chr_pos_before, last_char_pos = [-1]*len(S), collections.defaultdict(int) for idx in range(len(S)): char = S[idx] if char in last_char_pos: chr_pos_before[idx] = last_char_pos[char] last_char_pos[char] = idx else: last_char_pos[char] = idx unique, res = [0]*len(S), 0 for end in range(len(S)): if end == 0: unique[end] = 1 else: count = unique[end - 1] last_pos = chr_pos_before[end] if last_pos == -1: count += end else: if chr_pos_before[last_pos] >= 0: last_last_pos = chr_pos_before[last_pos] count += end - 2 * last_pos + last_last_pos else: count += end - 2 * last_pos - 1 unique[end] = count res += unique[end] return res
The run-time complexity of the above code is O(n), where n is the length of the original string.
Categories: PROBLEM SOLVING
Tags: Dynamic Programming, Leetcode, Unique Letters | http://www.stokastik.in/leetcode-unique-letters/ | CC-MAIN-2018-47 | refinedweb | 1,657 | 75.74 |
Network.
In addition to locating resolvers, the NAPTR provides for other
naming systems to be grandfathered into the URN world, provides
independence between the name assignment system and the resolution
protocol system, and allows multiple services (Name to Location, Name
to Description, Name to Resource, ...) to be offered. In conjunction
with the SRV RR, the NAPTR record allows those services to be
replicated for the purposes of fault tolerance and load balancing.
Introduction:
=============
Uniform Resource Locators have been a significant advance in
retrieving Internet-accessible resources. However, their brittle
nature over time has been recognized for several years. The Uniform
Resource Identifier working group proposed the development of Uniform
Resource Names DNS to locate "resolvers" that can
provide information on individual resources, potentially including
the resource itself. To accomplish this, we "rewrite" the URI into a
domain name following the rules provided in NAPTR records. Rewrite
rules provide considerable power, which is important when trying to
meet the goals listed above. However, collections of rules can become
difficult to understand. To lessen this problem, the NAPTR rules are
*always* applied to the original URI, *never* to the output of
previous rules.
Locating a resolver through the rewrite procedure may take multiple
steps, but the beginning is always the same. The start of the URI is
scanned to extract its colon-delimited prefix. (For URNs, the prefix
is always "urn:" and we extract the following colon-delimited
namespace identifier [3]). NAPTR resolution begins by taking the
extracted string, appending the well-known suffix ".urn.net", and
querying the DNS for NAPTR records at that domain name. Based on the
results of this query, zero or more additional DNS queries may be
needed to locate resolvers for the URI. The details of the
conversation between the client and the resolver thus located are
outside the bounds of this draft. Three brief examples of this
procedure are given in the next section.
The NAPTR RR provides the level of indirection needed to keep the
naming system independent of the resolution system, its protocols,
and services. Coupled with the new SRV resource record proposal[4]
there is also the potential for replicating the resolver on multiple
hosts, overcoming some of the most significant problems of URLs. This
is an important and subtle point. Not only do the NAPTR and SRV
records allow us to replicate the resource, we can replicate the
resolvers that know about the replicated resource. Preventing a
single point of failure at the resolver level is a significant
benefit. Separating the resolution procedure from the way names are
constructed has additional benefits. Different resolution procedures
can be used over time, and resolution procedures that are determined
to be useful can be extended to deal with additional namespaces.
Caveats
=======
The NAPTR proposal is the first resolution procedure to be considered
by the URN-WG. There are several concerns about the proposal which
have motivated the group to recommend it for publication as an
Experimental rather than a standards-track RFC.
First, URN resolution is new to the IETF and we wish to gain
operational experience before recommending any procedure for the
standards track. Second, the NAPTR proposal is based on DNS and
consequently inherits concerns about security and administration. The
recent advancement of the DNSSEC and secure update drafts to Proposed
Standard reduce these concerns, but we wish to experiment with those
new capabilities in the context of URN administration. A third area
of concern is the potential for a noticeable impact on the DNS. We
believe that the proposal makes appropriate use of caching and
additional information, but it is best to go slow where the potential
for impact on a core system like the DNS is concerned. Fourth, the
rewrite rules in the NAPTR proposal are based on regular expressions.
Since regular expressions are difficult for humans to construct
correctly, concerns exist about the usability and maintainability of
the rules. This is especially true where international character sets
are concerned. Finally, the URN-WG is developing a requirements
document for URN Resolution Services[15], but that document is not
complete. That document needs to precede any resolution service
proposals on the standards track.
Terminology
===========
"Must" or "Shall" - Software that does not behave in the manner that
this document says it must is not conformant to this
document.
"Should" - Software that does not follow the behavior that this
document says it should may still be conformant, but is
probably broken in some fundamental way.
"May" - Implementations may or may not provide the described
behavior, while still remaining conformant to this
document.
Brief overview and examples of the NAPTR RR:
============================================
A detailed description of the NAPTR RR will be given later, but to
give a flavor for the proposal we first give a simple description of
the record and three examples of its use.
The key fields in the NAPTR RR are order, preference, service, flags,
regexp, and replacement:
* The order field specifies the order in which records MUST be
processed when multiple NAPTR records are returned in response to a
single query. A naming authority may have delegated a portion of
its namespace to another agency. Evaluating the NAPTR records in
the correct order is necessary for delegation to work properly.
* The preference field specifies the order in which records SHOULD be
processed when multiple NAPTR records have the same value of
"order". This field lets a service provider specify the order in
which resolvers are contacted, so that more capable machines are
contacted in preference to less capable ones.
* The service field specifies the resolution protocol and resolution
service(s) that will be available if the rewrite specified by the
regexp or replacement fields is applied. Resolution protocols are
the protocols used to talk with a resolver. They will be specified
in other documents, such as [5]. Resolution services are operations
such as N2R (URN to Resource), N2L (URN to URL), N2C (URN to URC),
etc. These will be discussed in the URN Resolution Services
document[6], and their behavior in a particular resolution protocol
will be given in the specification for that protocol (see [5] for a
concrete example).
* The flags field contains modifiers that affect what happens in the
next DNS lookup, typically for optimizing the process. Flags may
also affect the interpretation of the other fields in the record,
therefore, clients MUST skip NAPTR records which contain an unknown
flag value.
* The regexp field is one of two fields used for the rewrite rules,
and is the core concept of the NAPTR record. The regexp field is a
String containing a sed-like substitution expression. (The actual
grammar for the substitution expressions is given later in this
draft). The substitution expression is applied to the original URN
to determine the next domain name to be queried. The regexp field
should be used when the domain name to be generated is conditional
on information in the URI. If the next domain name is always known,
which is anticipated to be a common occurrence, the replacement
field should be used instead.
* The replacement field is the other field that may be used for the
rewrite rule. It is an optimization of the rewrite process for the
case where the next domain name is fixed instead of being
conditional on the content of the URI. The replacement field is a
domain name (subject to compression if a DNS sender knows that a
given recipient is able to decompress names in this RR type's RDATA
field). If the rewrite is more complex than a simple substitution
of a domain name, the replacement field should be set to . and the
regexp field used.
Note that the client applies all the substitutions and performs all
lookups, they are not performed in the DNS servers. Note also that it
is the belief of the developers of this document that regexps should
rarely be used. The replacement field seems adequate for the vast
majority of situations. Regexps are only necessary when portions of a
namespace are to be delegated to different resolvers. Finally, note
that the regexp and replacement fields are, at present, mutually
exclusive. However, developers of client software should be aware
that a new flag might be defined which requires values in both
fields.
Example 1
---------, "duns", is extracted from
the URN, prepended to urn.net, and the NAPTRs for duns.urn.net looked
up. It might return records of the form:
duns.urn.net
;; order pref flags service regexp replacement
IN NAPTR 100 10 "s" "dunslink+N2L+N2C" "" dunslink.udp.isi.dandb.com
IN NAPTR 100 20 "s" "rcds+N2C" "" rcds.udp.isi.dandb.com
IN NAPTR 100 30 "s" "http+N2L+N2C+N2R" "" http.tcp.isi.dandb.com
The order field contains equal values, indicating that no name
delegation order has to be followed. The preference field indicates
that the provider would like clients to use the special dunslink
protocol, followed by the RCDS protocol, and that HTTP is offered as
a last resort. All the records specify the "s" flag, which will be
explained momentarily. The service fields say that if we speak
dunslink, we will be able to issue either the N2L or N2C requests to
obtain a URL or a URC (description) of the resource. The Resource
Cataloging and Distribution Service (RCDS)[7] could be used to get a
URC for the resource, while HTTP could be used to get a URL, URC, or
the resource itself. All the records supply the next domain name to
query, none of them need to be rewritten with the aid of regular
expressions.
The general case might require multiple NAPTR rewrites to locate a
resolver, but eventually we will come to the "terminal NAPTR". Once
we have the terminal NAPTR, our next probe into the DNS will be for a
SRV or A record instead of another NAPTR. Rather than probing for a
non-existent NAPTR record to terminate the loop, the flags field is
used to indicate a terminal lookup. If it has a value of "s", the
next lookup should be for SRV RRs, "a" denotes that A records should
sought. A "p" flag is also provided to indicate that the next action
is Protocol-specific, but that looking up another NAPTR will not be
part of it.
Since our example RR specified the "s" flag, it was terminal.
Assuming our client does not know the dunslink protocol, our next
action is to lookup SRV RRs for rcds.udp.isi.dandb.com, which will
tell us hosts that can provide the necessary resolution service. That
lookup might return:
;; Pref Weight Port Target
rcds.udp.isi.dandb.com IN SRV 0 0 1000 defduns.isi proposal [8]. This is a significant optimization. In
conjunction with a long TTL for *.urn.net the zone files. For one
thing, the administrator should supply the trailing '.' character on
any FQDNs.
Example 2
---------
Consider a URN namespace based on MIME Content-Ids. The URN might
look like this:
urn:cid:199606121851.1@mordred.gatech.edu
(Note that this example is chosen for pedagogical purposes, and does
not conform to the recently-approved CID URL scheme.)
The first step in the resolution process is to find out about the CID
namespace. The namespace identifier, cid, is extracted from the URN,
prepended to urn.net, and the NAPTR for cid.urn.net looked up. It
might return records of the form:
cid.urn.net
;; order pref flags service regexp replacement
IN NAPTR 100 10 "" "" "/urn:cid:.+@([^\.]+\.)(.*)$/\2/i" .
We have only one NAPTR response, so ordering the responses is not a
problem. The replacement field is empty, so we check the regexp
field and use the pattern provided there.:
lookup(query=NAPTR, "gatech.edu").:
gatech.edu IN NAPTR
;; order pref flags service regexp replacement
IN NAPTR 100 50 "s" "z3950+N2L+N2C" "" z3950.tcp.gatech.edu
IN NAPTR 100 50 "s" "rcds+N2C" "" rcds.udp.gatech.edu
IN NAPTR 100 50 "s" "http+N2L+N2C+N2R" "" http
seperating the domain name components. Since '\' is the escape
character, literal occurances of a backslash must be escaped by
another backslash. For the case of the cid.urn.net record above, the
regular expression entered into the zone file should be
"/urn:cid:.+@([^\\.]+\\.)(.*)$/\\2/i". When the client code actually
receives the record, the pattern will have been converted to
"/urn:cid:.+@([^.]+\.)(.*)$/\2/i".
Example 3
---------
Even if URN systems were in place now, there would still be a
tremendous number of URLs. It should be possible to develop a URN
resolution system that can also provide location independence for
those URLs. This is related to the requirement in [1] to:
We extract the prefix, "http", and lookup NAPTR records for
http.urn.net. This might return a record of the form
http.urn.net+L2R" "" http.tcp.foo.com
IN NAPTR 100 100 "s" "ftp+L2R" ""
Looking up SRV records for http.tcp.foo.com would return information
on the hosts that foo.com has designated to be its mirror sites. The
client can then pick one for the user.
NAPTR RR Format
===============
The format of the NAPTR RR is given below. The DNS type code for
NAPTR is 35.
Domain TTL Class Order Preference Flags Service Regexp
Replacement
where:
Domain
The domain name this resource record refers to.
TTL
Standard DNS Time To Live field
Class
Standard DNS meaning
Order
A 16-bit integer specifying the order in which the NAPTR
records MUST be processed to ensure correct delegation of
portions of the namespace over time. Low numbers are processed
before high numbers, and once a NAPTR is found that "matches"
a URN, the client MUST NOT consider any NAPTRs with a higher
value for order.
Preference
A 16-bit integer which.
Flags
A String giving flags to control aspects of the rewriting and
interpretation of the fields in the record. Flags are single
characters from the set [A-Z0-9]. The case of the alphabetic
characters is not significant.
At this time only three flags, "S", "A", and "P", are defined.
"S" means that the next lookup should be for SRV records
instead of NAPTR records. "A" means that the next lookup
should be for A records. The "P" flag says that the remainder
of the resolution shall be carried out in a Protocol-specific
fashion, and we should not do any more DNS queries.
The remaining alphabetic flags are reserved. The numeric flags
may be used for local experimentation. The S, A, and P flags
are all mutually exclusive, and resolution libraries MAY
signal an error if more than one is given. (Experimental code
and code for assisting in the creation of NAPTRs would be more
likely to signal such an error than a client such as a
browser). We anticipate URN.
Service
Specifies the resolution service(s) available down this
rewrite path. It may also specify the particular protocol that
is used to talk with a resolver. 822[9]):
service_field = [ [protocol] *("+" rs)]
protocol = ALPHA *31ALPHANUM
rs = ALPHA *31ALPHANUM
// The protocol and rs fields are limited to 32
// characters and must start with an alphabetic.
// The current set of "known" strings are:
// protocol = "rcds" / "thttp" / "hdl" / "rwhois" / "z3950"
// rs = "N2L" / "N2Ls" / "N2R" / "N2Rs" / "N2C"
// / "N2Ns" / "L2R" / "L2Ns" / "L2Ls" / "L2C"
i.e. an optional protocol specification followed by 0 or more
resolution services. Each resolution service is indicated by
an initial '+' character.
Note that the empty string is also a valid service field. This
will typically be seen at the top levels of a namespace, when
it is impossible to know what services and protocols will be
offered by a particular publisher within that name space.
At this time the known protocols are rcds[7], hdl[10] (binary,
UDP-based protocols), thttp[5] (a textual, TCP-based
protocol), rwhois[11] (textual, UDP or TCP based), and
Z39.50[12] (binary, TCP-based). More will be allowed later.
The names of the protocols must be formed from the characters
[a-Z0-9]. Case of the characters is not significant.
The service requests currently allowed will be described in
more detail in [6], but in brief they are:
N2L - Given a URN, return a URL
N2Ls - Given a URN, return a set of URLs
N2R - Given a URN, return an instance of the resource.
N2Rs - Given a URN, return multiple instances of the
resource, typically encoded using
multipart/alternative.
N2C - Given a URN, return a collection of meta-
information on the named resource. The format of
this response is the subject of another document.
N2Ns - Given a URN, return all URNs that are also
identifers for the resource.
L2R - Given a URL, return the resource.
L2Ns - Given a URL, return all the URNs that are
identifiers for the resource.
L2Ls - Given a URL, return all the URLs for instances of
of the same resource.
L2C - Given a URL, return a description of the
resource.
The actual format of the service request and response will be
determined by the resolution protocol, and is the subject for
other documents (e.g. [5]). Protocols need not offer all
services. The labels for service requests shall be formed from
the set of characters [A-Z0-9]. The case of the alphabetic
characters is not significant.
Regexp
A STRING containing a substitution expression that is applied
to the original URI in order to construct the next domain name
to lookup. The grammar of the substitution expression is given
in the next section.
Replacement
The next NAME to query for NAPTR, SRV, or A records depending
on the value of the flags field. As mentioned above, this may
be compressed.
Substitution Expression Grammar:
================================
The content of the regexp field is a substitution expression. True
sed(1) substitution expressions are not appropriate for use in this
application for a variety of reasons, (see [13], section
2.8.4)
repl = dns_str / backref / repl dns_str / repl backref
dns_str = 1*DNS_CHAR
backref = "\" 1POS_DIGIT
flags = "i"
DNS_CHAR = "-" / "0" / ... / "9" / "a" / ... / "z" / "A" / ... / "Z"
POS_DIGIT = "1" / "2" / ... / "9" ; 0 is not an allowed backref
value domain name (see RFC-1123 [14]).
The result of applying the substitution expression to the original
URI MUST result in a string that obeys the syntax for DNS host names
[14]. Since it is possible for the regexp field to be improperly
specified, such that a non-conforming host name can be constructed,
client software SHOULD verify that the result is a legal host.
Advice to domain administrators:
================================
Beware of regular expressions. Not only are they a. We anticipate that urn.net
will be the heaviest user of regexps. Only when delegating portions
of namespaces should the typical domain administrator need to use
regexps.
On a related note, beware of interactions with the shell when
manipulating regexps from the command line. Since '\' is a common
escape character in shells, there is a good chance that when you
think you are saying "\\" you are actually saying "\". Similar
caveats apply to characters such as
The "a" flag allows the next lookup to be for A records rather than
SRV records. Since there is no place for a port specification in the
NAPTR record, when the "A" flag is used the specified protocol must
be running on its default port.
The URN Sytnax.
Usage
=====
For the edification of implementers, pseudocode for a client routine
using NAPTRs is given below. This code is provided merely as a
convience,.net
sprintf(key, "%s.urn.net",.
}
die with an "unable to find a host" error;
}
Notes:
======
- A client MUST process multiple NAPTR records in the order
specified by the "order" field, it MUST NOT simply use the first
record that provides a known protocol and service combination.
-".
(A match is defined as:
1) The NAPTR provides a replacement domain name
or
2) The regular expression matches the URN
)
-.
- If the lookup after a rewrite fails, clients are strongly
encouraged to report a failure, rather than backing up to pursue
other rewrite paths.
- When a namespace is to be delegated among a set of resolvers,
regexps must be used. Each regexp appears in a separate NAPTR
RR. Administrators should do as little delegation as possible,
because of limitations on the size of DNS responses.
- Note that SRV RRs impose additional requirements on clients..
References:
===========
[1] Sollins, Karen and Larry Masinter, "Functional Requirements
for Uniform Resource Names", RFC-1737, Dec. 1994.
[2] The URN Implementors, Uniform Resource Names: A Progress Report,, D-Lib Magazine,
February 1996.
[3] Moats, Ryan, "URN Syntax", RFC-2141, May 1997.
[4] Gulbrandsen, A. and P. Vixie, "A DNS RR for specifying
the location of services (DNS SRV)", RFC-2052, October 1996.
[5] Daniel, Jr., Ron, "A Trivial Convention for using HTTP in URN
Resolution", RFC-2169, June 1997.
[6] URN-WG, "URN Resolution Services", Work in Progress.
[7] Moore, Keith, Shirley Browne, Jason Cox, and Jonathan Gettler,
Resource Cataloging and Distribution System, Technical Report
CS-97-346, University of Tennessee, Knoxville, December 1996
[8] Paul Vixie, personal communication.
[9] Crocker, Dave H. "Standard for the Format of ARPA Internet Text
Messages", RFC-822, August 1982.
[10] Orth, Charles and Bill Arms; Handle Resolution Protocol
Specification,
[11] Williamson, S., M. Kosters, D. Blacka, J. Singh, K. Zeilstra,
"Referral Whois Protocol (RWhois)", RFC-2167, June 1997.
[12] Information Retrieval (Z39.50): Application Service Definition
and Protocol Specification, ANSI/NISO Z39.50-1995, July 1995.
[13] IEEE Standard for Information Technology - Portable Operating
System Interface (POSIX) - Part 2: Shell and Utilities (Vol. 1);
IEEE Std 1003.2-1992; The Institute of Electrical and
Electronics Engineers; New York; 1993. ISBN:1-55937-255-9
[14] Braden, R., "Requirements for Internet Hosts - Application and
and Support", RFC-1123, Oct. 1989.
[15] Sollins, Karen, "Requirements and a Framework for URN Resolution
Systems", November 1996, Work in Progress.
Security Considerations
=======================
The use of "urn.net" as the registry for URN.
Author Contact Information:
===========================
Ron Daniel
Los Alamos National Laboratory
MS B287
Los Alamos, NM, USA, 87545
voice: +1 505 665 0597
Michael Mealling
Network Solutions
505 Huntmar Park Drive
Herndon, VA 22070
voice: (703) 742-0400
URL: | http://www.faqs.org/rfcs/rfc2168.html | CC-MAIN-2019-09 | refinedweb | 3,663 | 55.64 |
I have a 37,000+ picture & video library with many keyword tags that I have managed for years with Photoshop Elements. I'm investigating upgrading to Lightroom, but am having problems importing my Elements 12 catalog into Lightroom 2015.9.
I started a Lightroom free trial, installed the application using the Creative Cloud application, and was automatically prompted to import my Elements 12 catalog when the application started. When I click "Import" on the prompt screen, I get a Step 1 (of 3) dialog box and it appears the import process starts. When the Step 1 process reaches about 8%, the dialog box disappears and nothing further happens. The import seems to have aborted mid-process. No pictures are imported.
I tried uninstalling the application and reinstalling it, but the exact same thing happened while attempting to import the Elements 12 catalog.
Any ideas?
Hi Jim-Cincinnati,
You need to check the minimum system requirements for Lightroom CC 2015 and check if it's compatible with your machine or not?
Also, you can refer the below tutorial to import your Photoshop element's catalog to Lightroom.
How to import photos from Photoshop Elements, other Lightroom catalogs, or apps such as iPhoto in Lightroom
Let us know if that helps.
Regards,
Mohit
Mohit -- Thanks for taking the time to answer, but your suggestions are the
most basic things to check, and the first things I checked, when I
originally had the problem over a month ago. The fact that the Elements
import process dies without any messages or error handling means there is a
high probability that there is a problem with your software.
I ended up loading the catalog manually by first using the "save metadata
to file" option in Elements for all 37,000+ pictures, then importing them
into Lightroom. I had to recreate all the tags for my video files in
Lightroom.
So I don't need any more help at this point since I already completed the
time consuming, manual process to load my catalog. I suspect you still
have a problem with your software. If you decide to investigate this
further, a clue I can give you is that I had several file formats that were
supported by Elements that would not import into Lightroom. Possibly the
Lightroom process just died when it encountered these files. There were
approximately 100 files out of the 37,000+ that worked perfectly in
Elements that I was not able to load into Lightroom.
Jim
On Tue, May 9, 2017 at 6:05 AM, Mohit Goyal <forums_noreply@adobe.com> | https://forums.adobe.com/thread/2298254 | CC-MAIN-2018-05 | refinedweb | 429 | 59.84 |
2020 Jul Tutorials, Overviews
All (87) | Events (3) | News, Education (7) | Opinions (16) | Top Stories, Tweets (9) | Tutorials, Overviews (52)
- Fuzzy Joins in Python with d6tjoin - Jul 31, 2020.Combining different data sources is a time suck! d6tjoin is a python library that lets you join pandas dataframes quickly and efficiently.
-.
- Scaling Computer Vision Models with Dataflow - Jul 31, 2020.Scaling Machine Learning models is hard and expensive. We will shortly introduce the Google Cloud service Dataflow, and how it can be used to run predictions on millions of images in a serverless way.
Awesome Machine Learning and AI Courses - Jul 30, 2020.Check out this list of awesome, free machine learning and artificial intelligence courses with video lectures.
-.
- 5 Big Trends in Data Analytics - Jul 30, 2020.Data analytics is the process by which data is deconstructed and examined for useful patterns and trends. Here we explore five trends making data analytics even more useful.
- A Tour of End-to-End Machine Learning Platforms - Jul 29, 2020.An end-to-end machine learning platform needs a holistic approach. If you’re interested in learning more about a few well-known ML platforms, you’ve come to the right place!
First Steps of a Data Science Project - Jul 29, 2020.Many data science projects are launched with good intentions, but fail to deliver because the correct process is not understood. To achieve good performance and results in this work, the first steps must include clearly defining goals and outcomes, collecting data, and preparing and exploring the data. This is all about solving problems, which requires a systematic process.
- Why You Should Get Google’s New Machine Learning Certificate - Jul 29, 2020.Google is offering a new ML Engineer certificate, geared towards professionals who want to display their competency in topics like distributed model training and scaling to production. Is it worth it?
- 5 Fantastic Natural Language Processing Books - Jul 28, 2020.This curated collection of 5 natural language processing books attempts to cover a number of different aspects of the field, balancing the practical and the theoretical. Check out these 5 fantastic selections now in order to improve your NLP skills..
- Building a Content-Based Book Recommendation Engine - Jul 28, 2020.In this blog, we will see how we can build a simple content-based recommender system using Goodreads data.
- Deep Learning for Signal Processing: What You Need to Know - Jul 27, 2020.Signal Processing is a branch of electrical engineering that models and analyzes data representations of physical events. It is at the core of the digital world. And now, signal processing is starting to make some waves in deep learning.
Computational Linear Algebra for Coders: The Free Course - Jul 27, 2020.Interested in learning more about computational linear algebra? Check out this free course from fast.ai, structured with a top-down teaching method, and solidify your understanding of an important set of machine learning-related concepts.
- Labelling Data Using Snorkel - Jul 24, 2020.In this tutorial, we walk through the process of using Snorkel to generate labels for an unlabelled dataset. We will provide you examples of basic Snorkel components by guiding you through a real clinical application of Snorkel.
Easy Guide To Data Preprocessing In Python - Jul 24, 2020.Preprocessing data for machine learning models is a core general skill for any Data Scientist or Machine Learning Engineer. Follow this guide using Pandas and Scikit-learn to improve your techniques and make sure your data leads to the best possible outcome.
- Better Blog Post Analysis with googleAnalyticsR - Jul 24, 2020.In this post, we'll walk through using googleAnalyticsR for better blog post analysis, so you can do my better blog post analysis for yourself!
- Powerful CSV processing with kdb+ - Jul 23, 2020.This article provides a glimpse into the available tools to work with CSV files and describes how kdb+ and its query language q raise CSV processing to a new level of performance and simplicity.
-.
-.
- Before Probability Distributions - Jul 16, 2020.Why do we use probability distributions, and why do they matter?
-.
-.
- Building a REST API with Tensorflow Serving (Part 1) - Jul 15, 2020.Part one of a tutorial to teach you how to build a REST API around functions or saved models created in Tensorflow. With Tensorflow Serving and Docker, defining endpoint URLs and sending HTTP requests is simple.
- Clustering Uber Rideshare Data - Jul 14, 2020.This blog discusses clustering the Uber ridesharing dataset, with a focus on interpretation and understanding the concepts in the real world.
-.
- Auto Rotate Images Using Deep Learning - Jul 14, 2020.Follow these 5 simple steps to auto rotate images and get the right angle in human photos using computer vision.
- Foundations of Data Science: The Free eBook - Jul 13, 2020.As has become tradition on KDnuggets, let's start a new week with a new eBook. This time we check out a survey style text with a variety of topics, Foundations of Data Science.
-.
- PyTorch LSTM: Text Generation Tutorial, by Domas Bitvinskas - Jul 13, 2020.Key element of LSTM is the ability to work with sequences and its gating mechanism.
- 5 Things You Don’t Know About PyCaret - Jul 9, 2020.In comparison with the other open source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with a few words only.
-.
- Pull and Analyze Financial Data Using a Simple Python Package - Jul 9, 2020.We demonstrate a simple Python script/package to help you pull financial data (all the important metrics and ratios that you can think of) and plot them.
- Spam Filter in Python: Naive Bayes from Scratch - Jul 8, 2020.In this blog post, learn how to build a spam filter using Python and the multinomial Naive Bayes algorithm, with a goal of classifying messages with a greater than 80% accuracy.
- Some Things Uber Learned from Running Machine Learning at Scale - Jul 7, 2020.Uber machine learning runtime Michelangelo has been in operation for a few years. What has the Uber team learned?
A Complete Guide To Survival Analysis In Python, part 1 - Jul 7, 2020.
- PyTorch for Deep Learning: The Free eBook - Jul 7, 2020.For this week's free eBook, check out the newly released Deep Learning with PyTorch from Manning, made freely available via PyTorch's website for a limited time. Grab it now!
A Layman’s Guide to Data Science. Part 3: Data Science Workflow - Jul 6, 2020.Learn and appreciate the typical workflow for a data science project, including data preparation (extraction, cleaning, and understanding), analysis (modeling), reflection (finding new paths), and communication of the results to others..
Deploy Machine Learning Pipeline on AWS Fargate - Jul 3, 2020.A step-by-step beginner’s guide to containerize and deploy ML pipeline serverless on AWS Fargate.
-.
Feature Engineering in SQL and Python: A Hybrid Approach - Jul 2, 2020.Set up your workstation, reduce workplace clutter, maintain a clean namespace, and effortlessly keep your dataset up-to-date.
Getting Started with TensorFlow 2 - Jul 2, 2020.Learn about the latest version of TensorFlow with this hands-on walk-through of implementing a classification problem with deep learning, how to plot it, and how to improve its results.
- PyTorch Multi-GPU Metrics Library and More in New PyTorch Lightning Release - Jul 2, 2020.PyTorch Lightning, a very light-weight structure for PyTorch, recently released version 0.8.1, a major milestone. With incredible user adoption and growth, they are continuing to build tools to easily do AI research.
Speed up your Numpy and Pandas with NumExpr Package - Jul 1, 2020.We show how to significantly speed up your mathematical calculations in Numpy and Pandas using a small library.
- Data Cleaning: The secret ingredient to the success of any Data Science Project - Jul 1, 2020.With an uncleaned dataset, no matter what type of algorithm you try, you will never get accurate results. That is why data scientists spend a considerable amount of time on data cleaning. | https://www.kdnuggets.com/2020/07/tutorials.html | CC-MAIN-2022-27 | refinedweb | 1,336 | 56.96 |
.
For the scope of this introductory blog post, we are going to demonstrate how to start a new project using Storybook to get familiar with its platform and mechanics stemming from the "Storybook-Driven Development" practices that we have developed at Auth0 within the Customer Success Infrastructure team.
In a previous blog post, we created the foundation of our project by setting up a component library. If you have been following along you may continue to build upon where we left. Otherwise, feel free to clone the Marvel Bank app repo and checkout the
A-Tale-of-Reusability-Part-1 branch which includes all the work that we've done in the first part.
git clone cd marvel-bank-app/ git checkout A-Tale-of-Reusability-Part-1
Let's start by learning how we can setup Storybook in a brand-new
create-react-app project.
Thrilling news: the next chapter for @storybookjs with full-time maintenance and a bigger team. I'm over the moon! pic.twitter.com/T1JJfzNGp6— shilman (@mshilman) July 23, 2018
Setting Up Storybook
There are two options available to us for adding Storybook: we can install the platform globally or we can start the platform locally. Which installation path should we take?
Our colleague, Matt Machuga, an Engineering Lead in our R&D Team, suggests that "CLI tools that are not project specific are good candidates for global installation." In practice, Matt tries to "scope everything else into local. So the version being used is kept recorded and installed via
npm install."
We have different options for installing Storybook: a global install, an install using
npx, and a local manual install. I'll explore those options with you and let you decide which one is right for you. However, I do recommend that you walk with me through the local manual install as it let us learn a great deal about how Storybook works.
Install
@storybook/react Globally
To install and run Storybook from your shell follow these quick steps:
In the shell, make sure that your project directory your current working directory,
marvel-app.
Next, install
@storybook/cliglobally:
npm i -g @storybook/cli
Above, we used a few
npmargument shortcuts.
istands for
installand
-gstands for the flag
--global.
Restart your shell. You can do that by closing the existing window or tab and opening a new one.
Finally, with
marvel-appagain as your current working directory, run the
getstorybookcommand to have the Storybook CLI scaffold all the necessary files and folders to work with Storybook in your project. These include the
.storybookfolder under the root project and the
storiesfolder under the
srcfolder.
Let's see how this can be done without a global install using
npx.
Install
@storybook/react Using
npx
We can emulate the same behavior of the global installation of Storybook but without the actual global installation. If you have
npm >= 5.2 installed in your system, you have
npx available!
In the shell, make sure that your project directory your current working directory,
marvel-app.
Run the
getstorybookcommand using
npx:
npx @storybook/cli getstorybook
npx downloads and executes the binary on the fly. The Storybook CLI will run and create all the necessary files and folder in your project just as in the previous section. This method is the fastest way to get up and running!
"npx lets us run one-off invocations of CLI tools available in the npm registry without local installation."
Now, let's explore what the Storybook creators call the "slow start", the local manual installation of Storybook. Through that process, we'll learn how the folders and files installed by the Storybook CLI work.
Install @storybook/react manually
In the shell, let's run the following command:
npm:
npm i -D @storybook/react
Another
npmargument shortcut.
-Dstands for
--save-dev.
Storybook NPM Script
After
@storybook/react has finished its installation. We need to add the following
script to
package.json to run Storybook:
"storybook": "start-storybook -p 9001 -c .storybook"
{ ", "storybook": "start-storybook -p 9001 -c .storybook", "start-react": "react-scripts start", "start": "npm-run-all -p watch-css start-react", "build-react": "react-scripts build", "build": "npm-run-all -s build-css build-react", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "devDependencies": { "@storybook/react": "^3.4.8" } }
Create A Storybook Configuration File
As explained in the Storybook docs, the platform is flexible and can be configured in different ways. We can control that configuration through a config directory. In our
storybook
npm script, we added a
-c option followed by
.storybook which tells Storybook to look for configuration options in the
.storybook hidden folder.
Having our project root folder as the current working directory, let's go ahead and create that folder:
macOS/Linux/Windows:
mkdir .storybook
Next, we need to create a
config.js file inside
.storybook to hold the configuration. Let's start it with the following code:
// .storybook/config.js import { configure } from "@storybook/react"; function loadStories() { require("../src/stories/index.js"); // You can require as many stories as you need. } configure(loadStories, module);
Storybook works in a similar way to testing tools. The
config.js loads the
configure method, which takes as argument a function called
loadStories and a
module.
loadStories will have stories defined on its body. A story describes the single state of a component. We want to write a story for each state a component will have.
Stories are similar to how
itmethods run tests in testing libraries like Jest.
We are going to write and load the stories from
../src/stories/index.js which will be under the root folder. Let's create such folder and file to write our first story. Under the
src folder let's create a
stories subfolder and then create an
index.js file inside it.
.storybookis used solely for configuration files. Do not put your
storiesfolder inside this hidden folder.
Writing a Story in Storybook
Open the recently created
index.js under
src/stories and populate it with the following code:
// src/stories/index.js import React from "react"; import { storiesOf } from "@storybook/react";
So far, there's not much going on. We import
React and a
storiesOf method that will help us create stories for a component. We need that component. Let's import
Button here:
// src/stories/index.js import React from "react"; import { storiesOf } from "@storybook/react"; import Button from "../../src/features/common/Button";
Storybook has a declarative language. What we are going to do next is to tell it that we want stories of
Button:
// src/stories/index.js import React from "react"; import { storiesOf } from "@storybook/react"; import Button from "../../src/features/common/Button"; storiesOf("Button", module);
If we were thinking in terms of an actual book, this is the book's binding and cover. We need to fill it with pages full of stories. We do that declarative too using the
add method:
// src/stories/index.js import React from "react"; import { storiesOf } from "@storybook/react"; import Button from "../../src/features/common/Button"; storiesOf("Button", module).add("with text", () => ( <Button label={`Continue`} /> ));
add acts like adding a chapter to a book that has a story. We want to give each chapter a title. In this case, we are creating a story titled
with text.
add takes as argument the story title and a function that renders the component being staged.
We have the foundation of writing a story. It's time to see if everything is working by running Storybook.
"Similar to testing, Storybook uses declarative language to let us write stories that define the expected presentation and behavior of our components."
Running Storybook
In the shell, run the following command:
npm:
npm run storybook
If everything runs successfully, we will see this message in the shell:
info Storybook started on =>
Let's open that URL, in the browser. Let it load... and there we have it in its full glory: our own Storybook!
Right now it's pretty basic but this is a great start!
This is a good time to make another commit to address the integration of Storybook:
git status git add . git commit -m "Integrate Storybook"
Integrating CSS with Storybook
To communicate the presentation and state of the
Button component, we need to add styling to it. Under
src/features/common, let's create
Button.scss and populate it with the following code:
// src/features/common/Button.scss @import "../../styles/theme"; .Button { display: flex; flex-direction: row; justify-content: center; align-items: center; height: 40px; width: 160px; border: 2px solid $blue; border-radius: 60px; font-family: $primary-font; font-size: 16px; color: $blue; letter-spacing: 1.27px; text-align: center; text-transform: uppercase; }
Next, let's import that stylesheet into
Button.js and add
Button as a
className for the
Button component:
import React from "react"; import "./Button.css"; const Button = props => <div className="Button">{props.label}</div>; export default Button;
Let's save our work. We should see now how Storybook has refreshed the board and shows the updated component with styling applied:
Just like with
create-react-app, we can make changes to the structure, content, or style of a component and they will be updated in Storybook. Let's change the background, font color and border of
Button to see this in action:
// src/features/common/Button.scss @import "../../styles/theme"; .Button { display: flex; flex-direction: row; justify-content: center; align-items: center; background: $green; height: 40px; width: 160px; border-radius: 60px; font-family: $primary-font; font-size: 16px; color: white; letter-spacing: 1.27px; text-align: center; text-transform: uppercase; }
Let's save our work again and observe the changes:
Style changes are well integrated into our workflow. It's truly amazing that we can preview our components this way without having to run our application. We can develop our component in isolation and then use them in the app whenever we want.
"Just like with `create-react-app`, we can make changes to the structure, content, or style of a React component and it will be updated in Storybook! We can visualize our components without running our app."
As discussed before,
Button has three different presentations. The best way to organize that would be through CSS classes and props.
We want the
Button component to know:
- Its active state:
active/
disabled
- Its style state:
fill/
no-fill
Let's update
Button.scss with classes that represent these states:
// src/features/common/Button.scss @import "../../styles/theme"; .Button { display: flex; flex-direction: row; justify-content: center; align-items: center; height: 40px; width: 160px; border-radius: 60px; font-family: $primary-font; font-size: 16px; letter-spacing: 1.27px; text-align: center; text-transform: uppercase; } .active { } .disabled { border: 2px solid $color-text-lighter; color: $color-text-lighter; letter-spacing: 1.64px; } .fill { background: $green; box-shadow: 0 6px 8px 0 rgba(103, 194, 172, 0.5); color: $white; letter-spacing: 1.61px; } .no-fill { border: 2px solid $blue; color: $blue; letter-spacing: 1.27px; }
Let's briefly review what we are doing here since it's important how this impacts component staging in Storybook:
.Buttonhas all the style properties shared by all instances of
Button.
.activeis not in use right now but it could be used to provide unique properties to an active button.
.disabledhas the style properties for any instance of
Buttonthat becomes disabled.
filland
no-fillapply distinct styling to an active button.
We need to integrate this style logic into our component logic as follows:
// src/features/common/Button.js import React from "react"; import "./Button.css"; const Button = props => ( <div className={`Button ${ props.active ? props.fill ? `active fill` : `active no-fill` : `disabled` }`} > {props.label} </div> ); export default Button;
Using a combination of ternary operators we process the state of the button. If
props.active is true, we check if
props.fill is true or not and apply the corresponding class to the component. If
props.active is false, there are no extra decisions to make and we apply the default
disabled class.
To see this in action, let's create new stories in our Storybook!
Creating Multiple Stories for a Component in Storybook
Let's head to
src/stories/index.js and remove the current story that we have defined there,
with text, as it isn't telling too much of a story:
// stories/index.js import React from "react"; import { storiesOf } from "@storybook/react"; import Button from "../../src/features/common/Button"; storiesOf("Button", module);
Next, let's add three new stories that clearly define the three presentations that we want
Button to have depending on different state flags:
// stories/index.js import React from "react"; import { storiesOf } from "@storybook/react"; import Button from "../../src/features/common/Button"; storiesOf("Button", module) .add("active with fill", () => ( <Button label={`continue`} fill={true} active={true} /> )) .add("active with no fill", () => ( <Button label={`sign up`} fill={false} active={true} /> )) .add("disabled", () => <Button label={`continue`} active={false} />);
Let's save our work and we'll see Storybook update to show the three new stories under
Button:
Each story renders an isolated instance of
Button whose presentation depends on the
props values that are passed to it. This is where we can see the value proposition of Storybook at play.
Without Storybook, we would need to add
Button in our app somewhere and test its rendering by passing it different props. We would then need to remove the component. What if we need to change the structure or style of the component? We'd need to start that process all over again.
With Storybook, a component and all of its different states can be staged in a centralized location. What we see in Storybook will be seen in all the areas of the application that use the component, giving us confidence that we'll have presentational consistency throughout our application.
Let's click around the different stories and see how the component changes on each one. The UI Kit graphic definition of the user interface button is now alive in code.
"Button active with fill":
"Button active with no fill":
"Button disabled":
We have a solid
Button component that communicates its state clearly through its presentation. Let's go ahead and commit these changes:
git status git add . git commit -m "Add three states to Button component"
Next Steps
We have just barely scratched the surface of what can be done with Storybook! There's a lot more we can do with this amazing tool to make the creation, testing, and documentation of React components much faster. Storybook is also a highly configurable tool that relies on add-ons to boost its offerings.
At Auth0, different teams are making extensive use of Storybook in their React development and design processes. We are converging designers and developers into a Design Systems team that is letting us iterate faster and develop better products for our cherished customers.
Feel free to grab the source code of the project we have created so far from the Marvel Bank App GitHub repo.. | https://auth0.com/blog/building-a-component-library-with-react-and-storybook/ | CC-MAIN-2020-45 | refinedweb | 2,498 | 57.16 |
1. Unit Testing
Now that you've had a little experience writing tests,
we'll introduce you to a test harness called
unittest that make tests more convenient.
To use
unittest,
you write a separate Python file that defines a series of classes,
where each class is derived from the
unittest.TestCase class,
and has a
test() method that uses
assert
to verify something.
Then you call
unittest.main().
This will automatically run all of your tests
and produce a report on any failures.
A simple example should help to make this more clear:
from unittest import TestCase, main class TestAddition(TestCase): def test(self): assert 1 + 1 == 2, "addition produced an incorrect result" class TestSubtraction(TestCase): def test(self): assert 5 - 4 == 2, "subtraction produced an incorrect result" class TestMultiplication(TestCase): def test(self): assert 2 * 2 == 4, "multiplication produced an incorrect result" class TestDivision(TestCase): def test(self): assert 3 / 0 == 1, "division produced an incorrect result" main()
Here's what you'll see if you run the above script:
.E.F ====================================================================== ERROR: test (__main__.TestDivision) ---------------------------------------------------------------------- Traceback (most recent call last): File "arith.py", line 17, in test assert 3 / 0 == 1, "division produced an incorrect result" ZeroDivisionError: integer division or modulo by zero ====================================================================== FAIL: test (__main__.TestSubtraction) ---------------------------------------------------------------------- Traceback (most recent call last): File "arith.py", line 9, in test assert 5 - 4 == 2, "subtraction produced an incorrect result" AssertionError: subtraction produced an incorrect result ---------------------------------------------------------------------- Ran 4 tests in 0.003s FAILED (failures=1, errors=1)
The first line of output is a summary of the tests that succeeded or failed. It shows a dot for success, then an E for error, then a dot for success, then an F for failure, corresponding to the four tests in alphabetical order (TestAddition, then TestDivision, then TestMultiplication, then TestSubtraction). Then there are more detailed reports on any tests that didn't succeed.
Notice the distinction between a failure (an assertion failed, which generally means that some expression produced an unexpected result) and an error (an error occurred while trying to perform the test).
A couple of notes about this:
- You can put as many assertions as you like in a single test method. The ability to group the tests under classes is provided just to help you organize your tests.
- If you want some preparations to take place before the actual test, you can put the preparatory work into a method called
setUp(). Then, you can derive test classes from other test classes, so they can share the same
setUp()method without you having to write the setup code twice.
- There are many more ways to use
unittestif you want to do fancier things. For now, we're sticking to the straightforward way.
Q1.
Find your partner for the last homework assignment.
Pick just one or two tests from your test suite,
and convert them over to use
unittest.
The result should be a script that imports both
unittest
and the appropriate date module,
then defines a class or two derived from
unittest.TestCase,
and finally calls
unittest.main().
Call me over to show me your work.
Do not work on Q1 past 5:10 pm. If it's after 5:10 pm, move on.
I'll be asking you to use the
unittest style
when you submit the tests for your projects.
2. XML
Here we'll just do a brief introduction to the XML facilities in Python. Again, you can go much deeper into this if you want, but this might help you get started.
Python provides a package called
xml.
A package is a collection of modules.
We'll talk more about packages later,
but the main point is just that you can use dots to form a path
to a module within a package.
The
xml package contains a small implementation
of the "XML Document Object Model" (the "DOM") in the module
xml.dom.minidom.
This module can parse XML into a corresponding tree-like data structure in memory. Here's an example:
>>>>> top = xml.dom.minidom.parseString(doc) >>> top.childNodes [<DOM Element: spam at 136293436>] >>> n = top.childNodes[0] >>> n.childNodes [<DOM Text node "ick">, <DOM Element: eggs at 136658772>] >>> n.childNodes[0] <DOM Text node "ick"> >>> n.childNodes[0].data u'ick' >>> n.childNodes[1] <DOM Element: eggs at 136658772> >>> n.childNodes[1].childNodes [<DOM Text node "yum">] >>> n.childNodes[1].childNodes[0].data u'yum' >>> n.getElementsByTagName('spam') [] >>> top.getElementsByTagName('spam') [<DOM Element: spam at 136293436>] >>> top.getElementsByTagName('eggs') [<DOM Element: eggs at 136658772>] >>>
As you can see, each node in the tree has an attribute called
childNodes that lists its children.
You can walk your way down to the nodes a level at a time,
by asking successive nodes for their children,
or you can collect all the nodes for a particular tag
using the
getElementsByTagName() method,
which searches an entire subtree.
Text can be extracted from text nodes using the
data attribute.
For nodes representing tags, the tag name is available
in the
tagName attribute.
The tag attributes can be obtained by looking at the node's
attributes attribute,
which retrieves something similar to a dictionary:
>>> enode = _[0] >>> enode.attributes <xml.dom.minidom.NamedNodeMap instance at 0x8252e74> >>> enode.attributes.keys() [u'type'] >>> enode.attributes['type'] <xml.dom.minidom.Attr instance at 0x825421c> >>> enode.attributes['type'].value u'scrambled' >>>
The little
u that appears
in front of the strings indicates that the strings use Unicode,
a standard for encoding strings containing characters
from all the world's languages.
XML is officially specified to use Unicode for all of its text.
The
parseString() routine
is only good if you have an entire XML document in a string.
Alternatively, you can parse an open stream (such as the one produced
by
urllib.urlopen) using
xml.dom.minidom.parse().
That's probably what you will want to use for the following exercise.
Q2.
The URL
provides an XML document describing the current headlines at Slashdot.
Have a look at this document to see what tags are used to mark the headlines.
Using
urllib and
xml.dom.minidom together,
parse the Slashdot XML into a document object.
Then use
getElementsByTagName
to extract the headline titles as a list of strings.
(I'm not asking you to write a program;
just play around in the interpreter
until you've extracted the titles, and send me a transcript.)
Do not work on Q2 past 5:30 pm. If it's after 5:30 pm, move on.
3. Tkinter
This is just a brief look at Tkinter, the GUI toolkit that comes bundled with Python. We'll look at this more in depth next week, but i wanted to give you a chance to play with it first..
If you have any questions about these exercises or the
assignment, feel free to send me e-mail at
bc
zesty
ca. | http://zesty.ca/bc/explore-08.html | CC-MAIN-2017-13 | refinedweb | 1,142 | 64.81 |
Problem
You have a string containing a number in scientific notation, and you want to store the number's value in a double variable.
Solution
The most direct way to parse a scientific notation number is by using the C++ library's built-in stringstream class declared in , as you can see in Example 3-7.
Example 3-7. Parsing a number in scientific notation
#include #include #include!
Discussion
The stringstream class is, not surprisingly, a string that behaves like a stream. It is declared in . If you need to parse a string that contains a number in scientific notation (see also Recipe 3.2), a stringstream will do the job nicely. The standard stream classes already "know" how to parse numbers, so don't waste your time reimplementing this logic if you don't have to.
In Example 3-7, I wrote the simple function sciToDub that takes a string parameter and returns the double it contains, if it is valid. Within sciToDub, I use the stringstream as follows:
stringstream ss(str); // Construct from a string double d = 0; ss >> d; if (ss.fail( )) { string s = "Unable to format "; s += str; s += " as a number!"; throw (s); } return (d);
The most important part here is that all you have to do is use the right-shift operator (>>) to read from the string stream into a double, just as you would read from cin.
Well, that's not all you have to do. If there's a value in the stringstream that can't be written to the variable on the right side of the >> operator, the fail bit is set on the stream. You can check this bit using the fail member function (this is actually a member function of basic_ios, which is a superclass of stringstream). Additionally, the variable on the righthand side of the >> operator is unchanged if the operation fails.
In the interest of being generic, however, you can avoid having to write separate versions of sciToDub for ints, floats, doubles, and whatever else you want to convert to by writing a function template. Consider this new version:
template T strToNum(const string& str) { stringstream ss(str); T tmp; ss >> tmp; if (ss.fail( )) { string s = "Unable to format "; s += str; s += " as a number!"; throw (s); } return (tmp); }
Now, if you want to convert a string to a numeric type, you can do it like this:
double d = strToNum("7.0"); float f = strToNum("7.0"); int i = strToNum("7.0");
You can also make the type of character a template parameter, but that's straightforward to do, so I'll leave it as an exercise for you.
See Also
Recipe 3.2 | http://flylib.com/books/en/2.131.1/parsing_a_string_containing_a_number_in_scientific_notation.html | CC-MAIN-2018-05 | refinedweb | 448 | 70.63 |
SSL_rstate_string, SSL_rstate_string_long - get textual description of
state of an SSL object during read operation
#include <openssl/ssl.h>
const char *SSL_rstate_string(SSL *ssl);
const char *SSL_rstate_string_long(SSL *ssl);
SSL_rstate_string() returns a 2 letter string indicating the
current read state of the SSL object ssl.
SSL_rstate_string()
SSL_rstate_string_long() returns a string indicating the
current read state of the SSL object ssl.
SSL_rstate_string_long()
When performing a read operation, the SSL/TLS engine must parse the record,
consisting of header and body. When working in a blocking environment,
SSL_rstate_string[_long]() should always return ``RD''/``read done''.
This function should only seldom be needed in applications.
SSL_rstate_string() and SSL_rstate_string_long()
can return the following values:
The header of the record is being evaluated.
The body of the record is being evaluated.
The record has been completely processed.
The read state is unknown. This should never happen.
ssl(3) | http://www.openssl.org/docs/ssl/SSL_rstate_string.html | crawl-001 | refinedweb | 142 | 59.09 |
26 February 2013 17:39 [Source: ICIS news]
HOUSTON (ICIS)--?xml:namespace>
Year on year, January 2013’s sales were about 28.9% higher than 339,000 in the same month last year, the department said in its monthly residential sales report.
The median sales price of new homes sold in January 2013 was $226,400, with the average sale price at $286,300, the department said. A 4.1-month supply of homes – 150,000 – was available for sale at the end of the month.
."
Housing construction.
While the construction of new single-family homes is the principal consumer sector for chemicals and resins, improving sales of existing homes helps drive demand for new housing by taking previously owned residences off | http://www.icis.com/Articles/2013/02/26/9644630/month-on-month-us-new-home-sales-jump-by-15.6-in-january.html | CC-MAIN-2014-52 | refinedweb | 122 | 61.36 |
Has anyone here worked on a multi-label classification problem using ULMFiT. Any pointers?
Multilabel Classification with ULMFiT
Sure.
- Language Model works as is … so nothing needs to change there.
- For the classifier, a number of changes will be required (see below)
First, the datatype for your labels will need to be a
np.float32 rather than an
np.int64. Look at the pytorch docs for
binary_crossentropy to better understand why and what is going on.
Second. the shape of your target values will need to be a numpy array such as
(num_of_labels,). So, if you are trying to predict 5 labels, it is
(5,)
Third, your classifier needs to know how many labels you are trying to predict, and also predict that many values. For example, here is how I create my model to predict 8 labels:
m = get_rnn_classifer(bptt, max_seq=20*70, n_class=8, n_tok=vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1, layers=[em_sz*3, 50, 8], drops=[drops[4], 0.1], dropouti=drops[0], wdrop=drops[1], dropoute=drops[2], dropouth=drops[3])
Fourth, you’ll need to use
F.binary_cross_entropy as your loss function (this i discussed at length in the course)
Fifth, you have several options to put your predicted values in the format you want … what I did was create another
nn.Module and append that to the head of the sequential model you get from the code above. The code looks like this:
class MultiLabelClassifier(nn.Module): def __init__(self, y_range=None): super().__init__() self.y_range = y_range def forward(self, input): x, raw_outputs, outputs = input x = F.sigmoid(x) if (self.y_range): x = x * (self.y_range[1] - self.y_range[0]) x = x + self.y_range[0] return x, raw_outputs, outputs learner = RNN_Learner(md, TextModel(to_gpu(m)), opt_fn=opt_fn) learner.reg_fn = partial(seq2seq_reg, alpha=2, beta=1) learner.clip = 25. learner.crit = F.binary_cross_entropy learner.model.add_module('2', MultiLabelClassifier())
Sixth, use
pdb.set_trace() everywhere to learn what is going on
This is perfect, thank you!
A question, though: I was under the impression that the argument ,
n_class refers to the number of classes for any given label (and not the number of labels). Is that incorrect?
Further, the function definition of
get_rnn_classifer() does not appear to be utilising this argument at all …
def get_rnn_classifer(bptt, max_seq, n_class, n_tok, emb_sz, n_hid, n_layers, pad_token, layers, drops, bidir=False, dropouth=0.3, dropouti=0.5, dropoute=0.1, wdrop=0.5): rnn_enc = MultiBatchRNN(bptt, max_seq, n_tok, emb_sz, n_hid, n_layers, pad_token=pad_token, bidir=bidir, dropouth=dropouth, dropouti=dropouti, dropoute=dropoute, wdrop=wdrop) return SequentialRNN(rnn_enc, PoolingLinearClassifier(layers, drops))
So I’m led to believe that whatever
n_class we pass to the function is irrelevant, what goes into
layers is what is important. However, I am not sure if
layers=[em_sz*3, 50, 8] is going to give you predictions over 8 labels or 8 classes.
Thank you for the solution. How is the evaluation accuracy calculated in this case? I get errors as the accuracy function in fastai simply argmaxes the predictions which leads to one output column of labels. For my case, the labels are quite structured so I tweaked the accuracy function to average the accuracy after comparing the argmaxes of the specific columns I want, but this doesn’t generalize to all multi-label cases. Anyway, my problem is with the accuracy score printout during evaluation phase while the binary cross entropy loss seems to work nicely for training. How did you deal with this problem?
ULMFiT for tag recommendation system for newspaper articles
Seconding @chiayewken. Setting
learner.metrics = [acccuracy] throws the following TypeError:
File "/home/guest/.pyenv/versions/3.6.1/lib/python3.6/site-packages/fastai/metrics.py", line 10, in accuracy return (preds==targs).float().mean() File "/home/guest/.pyenv/ TypeError: eq received an invalid combination of arguments - got (torch.cuda.FloatTensor), but expected one of: * (int value)
I’m currently doing this by setting
learner.metrics = [accuracy_thresh(0.5)]. And it seems about right.
See metrics.py for details.
You want to use multi_accuracy rather than just accuracy since you have multiple labels. I don’t have access to my computer so I can’t verify this, but I think you’ll find something helpful in either metrics.py or evaluation.py.
Use pdb.set_trace to see what is getting passed into the accuracy function as is and you’ll see why you are getting this error.
Thank you!
Hi,
I wonder if someone has a complete notebook to share for Multi-label classification using fastai.text. I will really appreciate as I can’t figure out how to do this. I fix one thing and then get stuck in another thing. This will be very useful for newbies. Thanks
Hi Everyone,
I am facing out of memory issue in Multi-label Classification using fastai library. I think I am making some mistakes that cause this error because this error arises even if I reduce the batch size to a very low 2. I am running this on AWS Instance that has a GPU with 12GB memory. The data set that I am using is not big either. I have uploaded the data and notebook to dropbox, which can be downloaded from this link. I will be very thankful if someone can help and comment what are the mistakes. This will be super useful for many users that are using wonderful fastai library.
Thanks
## Vaccines Classification import warnings warnings.filterwarnings("ignore") from fastai.text import * import html BOS = 'xbos' # beginning-of-sentence tag FLD = 'xfld' # data field tag PATH=Path('data/vaccines/') torch.cuda.is_available() CLAS_PATH=Path(PATH/'vaccines_clas') #CLAS_PATH.mkdir(exist_ok=True) LM_PATH=Path(PATH/'vaccines_lm') ## Classifier trn_clas = np.load(CLAS_PATH/'tmp'/'trn_ids.npy') val_clas = np.load(CLAS_PATH/'tmp'/'val_ids.npy') itos = pickle.load(open(CLAS_PATH/'tmp'/'itos.pkl', 'rb')) #These are single-label data, with the labels in 0s and 1s form. trn_labels = np.squeeze(np.load(CLAS_PATH/'tmp'/'trn_labels.npy')) val_labels = np.squeeze(np.load(CLAS_PATH/'tmp'/'val_labels.npy')) #Creating multi-labels just for testing purpose trn_labels1 = np.array([trn_labels, trn_labels,trn_labels,trn_labels,trn_labels,trn_labels,trn_labels]) trn_labels1 = trn_labels1.transpose() val_labels1 = np.array([val_labels, val_labels,val_labels,val_labels,val_labels,val_labels,val_labels]) val_labels1 = val_labels1.transpose() val_labels1.shape em_sz,nh,nl = 400,1150,3 wd = 1e-7 bptt = 30 bs = 24 opt_fn = partial(optim.Adam, betas=(0.8, 0.99)) vs = 60004#len(itos) 60004 min_lbl = trn_labels1.min() trn_labels1 -= min_lbl val_labels1 -= min_lbl c=7#int(trn_labels.max())+1 trn_ds = TextDataset(trn_clas, trn_labels1) val_ds = TextDataset(val_clas, val_labels1)=3, pad_idx=1, sampler=trn_samp) val_dl = DataLoader(val_ds, bs, transpose=True, num_workers=3, pad_idx=1, sampler=val_samp) md = ModelData(PATH, trn_dl, val_dl) dps =)) learn = RNN_Learner(md, TextModel(to_gpu(m)), opt_fn=opt_fn) learn.reg_fn = partial(seq2seq_reg, alpha=2, beta=1) learn.clip=25. learn.metrics = [accuracy_thresh(0.5)]]) len(itos) # This is language model previously trained on data learn.load_encoder('V_lm_enc_last_ft') wd = 1e-7 #learn.freeze_to(-1) #Memory error even with very small batch size (bs) and bptt learn.fit(lrs/10, 1, wds=wd, cycle_len=1, use_clr=(8,3))
I’m unsure how the training data should be stored. Typically, we create a “train” folder, and for each class, we create a folder with its name (e.g. “positive” or “negative”), and that folder is filled with examples of that class. We could continue that structure here, but then you would only ask the model to predict on one label at a time, and it’d never learn to output multiple labels. Even if it tried to output multiple labels, it’d be penalized because the structure is such that it only ever sees one label at a time.
How do we translate this structure of data to the multilabel scenario?
Multi-label classification is different from traditional way of keeping label data in corresponding label folders. It is discussed in fastai lesson 3 for images but I am trying to do it for text. Other people probably have done this but I have problem. Hopefully someone may help.
As I asked the question, I realized that was probably the case. I’ll go ahead and rewatch the video (it’s been awhile) and update you if I have success.
The only difference is that instead of a single label column, you have multiple label columns (where the value is 0 or 1). Other than that, everything is the same.
I understand that, but my question was specifically directed at how we access our stored training data, not how do we structure it once we have it loaded. The storage structure in the ULMFit lecture doesn’t lend itself to multilabel classification, but @zubair1.shah reminded me that previous lectures might help with finding the appropriate structure.
It looks like the major difference in data processing comes in at the get_texts method. It assumes that each text only has one associated label, so we need to overhaul that in order to read in multi-label appropriately. @wgpubs, is this correct? And in a previous reply, you mentioned needing to have a column for each possible label, marked with a 0 or 1. However, in past fastai multi-label case studies, we’ve put all the labels into one column. Clarification here would be appreciated. If this is the case, it’d be great if you could edit your original post with some tips on preprocessing, since the imdb notebook assumes your data comes in a particular format.
You don’t need to overhaul it. I’m seeing two scenarios, based on your questions:
- The data are in a single csv with one text column, and one (or more) label columns.
- The data are in text files, stored in subfolders based on their class.
The workflow in the imdb notebook moves data from scenario 2 to scenario 1. Scenario 1 is the standard. The get_texts function takes a slice of columns as labels, based on the
n_labels parameter, and for each row in the dataframe, loops through that number of columns. What you get in the case of a single label is a n-dimensional column vector with the label, where n is the number of data instances (or the batch size, if you’re in a training loop). In the multi-label case, you get a
n x m matrix, where n is, again, either the number of data instances or the batch size, and m is the number of labels. The values in this matrix are usually 1 or 0.
Here’s a snippet that shows how you could move from a dataset that looks like this:
To this:
text_labels = [f'Label {n+1}' for n in range(12)] for index, row in trn_df.iterrows(): for c in text_labels: c_val = row[c] if isinstance(c_val, str): trn_df.loc[index, c_val] = 1 # print(c_val)
where
c_val tracks the column names seen in the second screenshot. Note the values in the row are
0.0 and
1.0. The
1.0 values are set by
trn_df.loc[index, c_val] = 1, while the
0.0 values are set by
clean_train_df.fillna(0), since the resulting values there are
NaN.
Note that, to fit with the standard set in
get_texts, the line
clean_train_df = trn_df[['Text'] + classes] should instead be
clean_train_df = clean_train_df[classes + ['Text']], which follows the convention:
['labels', 'text'].
To use
clean_train_df as the classification dataset in the state I show in the second screenshot, I set
n_labels to 27 (the number of labels), which got me a
3900x27-dimensional
trn_labels vector. | https://forums.fast.ai/t/multilabel-classification-with-ulmfit/19809 | CC-MAIN-2020-05 | refinedweb | 1,914 | 57.77 |
I am currently a programming student and am attempting to learn some Flash/Action Script in my spare time for fun. I have been familierizing myself with the language and it's application using Flash. I have started to make a simple game to implement what I have learned so far and have run into a snag.
What I am doing is instantiating a fist image, increasing its height and width to simulate it coming towards the screen as a punch(yes I know lame but it's a start
import fl.transitions.Tween; import fl.transitions.easing.*; var fist = new Fist; fist.x = 50; fist.y = 50; addChild(fist); var fistTween:Tween = new Tween(fist,"width",None.easeNone,50,100,2,true); var fistTween2:Tween=new Tween(fist,"height",None.easeNone,50,100,2,true); removeChild(fist);
I would of course wrap most of that up in a punch method. Could anyone advise me on how I could make the line to remove the child not run until after the animation completes? Any info would be appreciated, thanks much! | http://www.dreamincode.net/forums/topic/148546-adding-child-creating-a-tween-and-removing-the-child/ | CC-MAIN-2016-07 | refinedweb | 180 | 67.35 |
I found the below given code on this very useful link:
First I think I have to include non-standard windows.h header file. I have questions about the bold statements. For example, system() is a function call and arguments are system dependent. In windows the command to clear the screen is system("cls") but the argument used to clear the screen in Linux would be different (I have been told this).
What is "HANDLE hOut"? If it were a function call then it would have parentheses after it? Is it some kind of declaration such as the one "float x, y,..."?
I understand these three bold lines are related. What is "hOut = GetStdHandle(STD_OUTPUT_HANDLE)"? It has a look of a assignment statement such as "Mean = x+y/2".
Then what about "SetConsoleTextAttribute(hOut, FOREGROUND_RED)"? It has a look of a function because it has parentheses and there are arguments within.
It would be really kind of you if you could help me with these queries. Thanks for your help and time. Please don't forget I'm a beginner, so please keep things simple.
Regards
Jackson
#include <windows.h> #include <iostream.h> int main() { [b] HANDLE hOut; hOut = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hOut, FOREGROUND_RED); [/b] cout << "This text is red." << endl; SetConsoleTextAttribute(hOut, FOREGROUND_GREEN); cout << "This text is green." << endl; SetConsoleTextAttribute(hOut, FOREGROUND_BLUE); cout << "This text is blue." << endl; return 0; } | http://forum.codecall.net/topic/63170-how-c-really-works-internally/ | crawl-003 | refinedweb | 231 | 69.99 |
¤ Home » Programming » C Tutorial » Preprocessor Directive in C
In the previous posts, in all C programs you would have noticed that the first line is written as
#include <stdio.h>. In programs where we used mathematical calculations, we had two such include directives, as below:
Although those two lines look like program statements, they are not part of a function body and do not end with a semicolon, as program statements must. Instead, they start with a hash sign (#), and are called preprocessor directives. While program statements are instructions to the computer, a preprocessor directive, is an instruction to the compiler itself. A part of the compiler, called the preprocessor, deals with these directives before it begins the real compilation process.
The preprocessor directive #include tells the compiler to insert another text file (known as header file) into your C source code file. In fact, the #include directive is replaced by the contents of the file indicated, before compilation begins. The filenames stdio.h and math.h are examples of header files. These header files contain definitions of standard C utility programs and without these declarations the compiler will not allow the usage of functions that are defined in these files. For instance, commonly used standard input and output functions such as getchar, putchar, scanf and printf, etc. are defined in the stdio.h file. Thus reference to any such function inside the program requires the corresponding header file to be included using #include preprocessor directive. The symbols < and >, that enclose the header filename indicates that the header file is located under the default include directory of the C compiler.
Thus, you can build your own library of functions that are put in files with .h extension and place them in the default include directory of your C compiler, and thereby enhance the functionality of C. Alternatively, you can place such include files in the same directory as your C program and include the file as below:
By using quotes instead of angle-brackets, you are telling the preprocessor to first look for the file in the same directory as your C program. If the file is not found there, the preprocessor will look for it in the default include directory.
Another type of preprocessor that we have seen being used in previous posts, is #define. This preprocessor directive can be used to define constants in C. For example, when you add a define directive in your program as below:
Before the compilation begins, all occurrences of PI occurring in the C program, after the above directive, are replaced with the value 3.14.
You can even use #define to define a function (referred as macros). See an example below:
With the above define directive in place, you can have a C statement as:
In the above, wherever getmax(a,b) is used, the preprocessor will replace it with a>b?a:b. So the second statement above will become as below, before compilation:
Elements of the C Language - Identifiers, Keywords, Data types and Data objects
Elements of the C language - Operators and Expressions
The C Language - An Introduction
Data Input and Output functions. | http://www.how2lab.com/programming/c/preprocessor-directives.php | CC-MAIN-2018-51 | refinedweb | 524 | 50.67 |
memcached_prepend man page
memcached_prepend — Appending to or Prepending to data on the server
Appending or Prepending to data on the server
Synopsis
#include <libmemcached/memcached.h>)
Compile and link with -lmemcached
Description the main value. Many sub libraries make use of this field, so in most cases users should avoid making use of it.
memcached_prepend() places a segment of data before the last piece of data stored. Currently expiration and key are not used in the server.
memcached_append() places a segment of data at the end of the last piece of data stored. Currently expiration and key are not used in the server.
memcached_prepend_by_key() and memcached_append_by_key() methods both behave in a similar method as the non key methods. The difference is that they use their group_key parameter to map objects to particular servers.
If you are looking for performance, memcached_set() with non-blocking IO is the fastest way to store data on the server.
All of the above functions are testsed with the MEMCACHED_BEHAVIOR_USE_UDP behavior enabled. However, when using these operations with this behavior on, there are limits to the size of the payload being sent to the server. The reason for these limits is that the Memcached Server does not allow multi-datagram requests and the current server implementation sets a datagram size to 1400 bytes. Due to protocol overhead, the actual limit of the user supplied data is less than 1400 bytes and depends on the protocol in use as, well as the operation being executed. When running with the binary protocol, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, the size of the key,value, flags and expiry combined may not exceed 1368 bytes. When running with the ASCII protocol, the exact limit fluctuates depending on which function is being executed and whether the function is a cas operation or not. For non-cas ASCII set operations, there are at least 1335 bytes available to split among the key, key_prefix, and value; for cas ASCII operations there are at least 1318 bytes available to split among the key, key_prefix and value. If the total size of the command, including overhead, exceeds 1400 bytes, a MEMCACHED_WRITE_FAILURE will be returned.
Return
All methods return a value of type memcached_return_t. On success the value will be MEMCACHED_SUCCESS. Use memcached_strerror() to translate this value to a printable string.
To find out more information please check:
See Also
memcached(1) libmemached(3) memcached_strerror(3) memcached_set(3) memcached_add(3) memcached_cas(3) memcached_replace(3)
Author
Brian Aker
2011-2013, Brian Aker DataDifferential,
Referenced By
libmemcached(3), memcached_add(3), memcached_add_by_key(3), memcached_cas(3), memcached_cas_by_key(3), memcached_replace(3), memcached_replace_by_key(3), memcached_set(3), memcached_set_by_key(3). | https://www.mankier.com/3/memcached_prepend | CC-MAIN-2018-30 | refinedweb | 431 | 52.7 |
Storing passwords securely should be imperative for any credible engineer. Plain text passwords are extremely insecure - you shouldn't even bother considering storing them a plain format. It's enough that someone gains view privileges on a database for an entire userbase to be compromised.
Passwords must be stored in a database in a secure, yet manageable way.
You should always assume that your database will be compromised and take all necessary precautions to prevent anyone, who could get hold of your data, from exploiting it in any way possible. That is especially true for databases that store users' login credentials or other sensitive data. Additionally - it's a question of ethical conduct. If a user signs up for your website - should you be able to find their password ad verbatim? Passwords are oftentimes used on multiple websites, contain personal information and/or could expose a side of the user that they wouldn't like to put out publicly. Neither you nor a malicious actor should be able to read a plain-text password at any point. This is why websites can't email you your password when you forget it - they don't know it. You have to reset it.
Hashing passwords is a cheap, secure and standard procedure that keeps passwords safe from both a webmaster and malicious actors.
To prevent anyone from blatantly exploiting login credentials, you should always hash passwords before storing them in a database. That is the simplest, yet most effective way to prevent the unauthorized use of passwords stored in your database. Even if someone gets a hold of users' login credentials, that information can't be used in any shape or form, since the format is unreadable for humans, and hard to crack computationally.
In this guide, we'll explain how to hash your passwords in Python using BCrypt. We'll cover what hashing is, how hashes are compared, how "salting" works and how hashing even makes passwords secure.
In its most basic form, hashing refers to converting one string to another (which is also called a hash) using a hash function. Regardless of the size of an input string, the hash will have a fixed size which is predefined in a hashing algorithm itself. The goal is that the hash doesn't look anything like the input string and that any change in the input string produces a change in the hash. Additionally - hashing functions hash input in a one-way fashion. It's not a round trip and a hashed password cannot be unhashed. The only way to check whether an input password matches the one in the database is to hash the input password as well, and then compare the hashes. This way, we don't need to know what the actual password is to ascertain whether it's matching the one in the database or not.
Note: In this guide, we'll use the term "hashing function" for a mathematical function used to calculate the fixed-size hash based on the input string (popular hashing functions include SHA256, SHA1, MD5, CRC32, BCrypt etc.). A "hashing algorithm" refers to the whole process of hashing, including not only a hashing function used but many more parameters that can be altered during the process of hashing.
<p><img src=" alt="how salting works during password hashing" class="lozad" data-</p>
Every time you put something such as
"myPwd" into the hashing algorithm you'll get the same exact output. But, if you change
"myPwd" even a bit, the output will be changed beyond recognition.
That ensures that even similar input strings produce completely different hashes. If similar passwords produced the same hashes - cracking one simple password could lead to creating a lookup table for other characters. On the other hand, since the same input always yields the same output, a hashing is pretty predictable.
Predictability is easily exploitable.
If someone knows what hashing function was used to hash a certain password (and there isn't a large list of hash functions in use), they can crack it by guessing all possible passwords, hashing them with the same hashing function, and comparing obtained hashes to the hash of the password that they want to crack. This type of attack is called a brute-force attack and the attack used to work extremely well for simple passwords, such as
password123,
12345678, etc.
The easiest way to prevent brute-force attacks is to use a hashing function that is relatively slow to compute. That way the brute-force attack would take so much time to compute all possible hashes, that it's not even worth trying to perform.
Additionally, most web applications have built-in "timeouts" after a certain number of incorrect passwords were input, making brute-force guessing unviable if someone's trying to brute-force a password through a controlled UI, though, this doesn't hold if someone obtains a local copy of a hashed password.
As cryptography, price per computation and technology advance - just choosing a proper hashing function isn't quite enough to secure passwords stored in a database. In some cases, even a great hashing function can't prevent an attack. Therefore, it's advised to take additional precautions to make cracking stored passwords even more difficult. The problem with hashing is that the output (i.e. hash) is always the same for the same input. That makes hashing predictable, thus vulnerable. You can solve that by passing an additional random string alongside the input string when performing hashing. That will ensure that the hashing no longer produces the same output every time it gets the same string as the input. That fixed-length pseudorandom string passed alongside the input string when performing hashing is called salt. Every time you want to store a password in a database, a new, random, salt will be created and passed alongside the password to the hashing function. Consequently, even if two users have the same password, its record in a database will be totally different.
Remember that adding a single character to the end of a string before hashing changes the hash completely. The salt used to generate a password is stored separately, and added to any new input that's to be hashed and compared to the stored hash in the database, ensuring that even with the addition of random elements - the user can log in using their respective password. The point of salting isn't to make it much more computationally unviable to crack a single password - it's to prevent finding similarities between hashed strings, and to prevent an attacker from cracking multiple passwords if they're the same. Through salting - extremely computationally expensive operations are localized to a single instance and have to be repeated for every password in the database, stopping a cascade of broken security. Thankfully - the entirety of this logic is typically abstracted away by security frameworks and modules that we can readily use in code.
BCrypt is a password hashing algorithm, designed with all security precautions we've mentioned in mind. It is used as the default password hashing algorithm in OpenBSD, an open-source security-focused operating system, and is the most widely supported hashing algorithm to date. BCrypt is considered to be fairly secure. Its hashing function is based on the Blowfish (cipher) algorithm, implements salting and adaptive computation speed. Adaptive speed refers to the ability to increase the complexity of calculating hash value, which future proofs the algorithm. It keeps being slow enough to prevent brute-force attacks no matter the increasing computing speed of the hardware. BCrypt is widely supported and implemented in most mainstream languages. There publicly available implementations for Java, JavaScript, C, C++, C#, Go, Perl, PHP, etc. In this guide, we'll cover the Python implementation of the BCrypt algorithm.
The
bcrypt module on PyPi offers a great implementation of BCrypt that we can easily install via
pip:
$ pip install bcrypt
Note:
To make sure that all required dependencies are installed, the official documentation advises you to run the following commands based on your operating system of choice.
<strong>For Debian and Ubuntu:</strong>
$ sudo apt-get install build-essential libffi-dev python-dev
For Fedora and RHEL-derivatives:
$ sudo yum install gcc libffi-devel python-devel
For Alpine:
$ apk add --update musl-dev gcc libffi-dev
After you've installed BCrypt using
pip, you can import it to your project:
import bcrypt
To hash your password using BCrypt, you must convert it to the array of bytes first. To achieve that, we can use the
encode() method of the
string class! It will encode the string version of the password you want to hash into a byte array, given a certain encoding type, and make it possible to hash using BCrypt.
Let's take
'MyPassWord' as the example password to illustrate the usage of BCrypt:
pwd = 'MyPassWord' bytePwd = password.encode('utf-8')
The
encode() method takes a string in some encoding (e.g. ASCII, UTF-8, etc.) and converts it to a corresponding array of bytes. That byte-array formed of a string is called a b-string.
Note: In the previous example,
pwdis a string and
bytePwdis a byte-array. But if you print both variables, the only visible difference is that the
bytePwdhas
bas a prefix before its value -
b'myPassword'. Thence the name of that type of byte-array - a b-string.
Finally, you can hash the encoded password using BCrypt:
# Generate salt mySalt = bcrypt.gensalt() # Hash password hash = bcrypt.hashpw(bytePwd, mySalt)
As you can see, the method used for hashing in BCrypt is
hashpw(). It takes two arguments, the b-string representation of a password and a salt. Obviously, you can manually create a salt, but it's definitely recommended to use the
gensalt()method instead. It's a BCrypt method created specifically for creating salt in a cryptographically secure fashion.
Note: Adaptive computation speed in BCrypt is achieved by setting a number of iterations needed to create a salt. That value is passed as the argument of the
gensalt()method. The default value is 12, meaning that BCrypt uses 212 (4096) iterations to generate a salt. By increasing the value of that argument, you increase the number of iterations used to generate a salt, and by extension, the time needed to compute the hash.
Now, the
hashis storing the hashed version of the password
pwd. The
hashshould look somewhat similar to:
b'$2b$12$1XCXpgmbzURJvo.bA5m58OSE4qhe6pukgSRMrxI9aNSlePy06FuTi'
Not very similar to the original password, right? But if you compare the
hash to the original password using BCrypt's
checkpw() method, it returns a
True value!
Note: The
checkpw()method is designed for validating hashed passwords. It hashes the new input password, adds the salt it automatically tracks, and then compares the results.
Let's check whether the literal-text
passwordis a valid password for the new
hashwe've just created:
print(bcrypt.checkpw(password, hash)) # Output: True
As we've seen in the previous example, the input to BCrypt is a password (up to 72 bytes) and a salt (with the associated number of iterations) and the output is the 24-byte hash.
Let's examine the following illustration to get a grasp of how BCrypt constructs the produced hash:
This illustration shows a hashing of the password,
'MyPassword', therefore it illustrates hashing from the previous section.
As we've discussed before, every time you call the
gensalt() method, it produces a new fixed-size byte-array (represented by a b-string). In this example, the
gensalt() method produced the output marked as
salt in the illustration. Let's decompose the
salt section and explain each individual subsection.
The
salt has three subsections divided by the
$ sign:
2b- the newest version of the BCrypt algorithm.
gensalt()method representing the number of iterations used to compute a salt. If no argument is passed, the default value is 12, therefore 212 iterations are used to compute a salt.
After that, BCrypt sticks the
salt together with the hashed value of
MyPassword and thus creates the final
hash of the
MyPassword.
Note: The hashed value of
MyPassword(or any other password) refers to a radix-64 encoding of the first 23 bytes of the 24-byte hash. It is represented by 31 characters.
<h3 id="conclusion">Conclusion</h3>
After reading this article you will have a solid understanding of how to use a BCrypt to hash a password before storing it into a database. To put things into a perspective, we've explained basic terminology in a general sense and then illustrated the process of hashing a password on the example of BCrypt.Reference: stackabuse.com | https://www.codevelop.art/hashing-passwords-in-python-with-bcrypt.html | CC-MAIN-2022-40 | refinedweb | 2,112 | 60.55 |
Abstract
This module implements types which encapsulate an optional value.
A value of type Option[T] either contains a value x (represented as some(x)) or is empty (none(T)).
This can be useful when you have a value that can be present or not. The absence of a value is often represented by nil, but it is not always available, nor is it always a good solution.
Tutorial
Let's start with an example: a procedure that finds the index of a character in a string.
import options proc find(haystack: string, needle: char): Option[int] = for i, c in haystack: if c == needle: return some(i) return none(int) # This line is actually optional, # because the default is empty
try: assert("abc".find('c').get() == 2) # Immediately extract the value except UnpackError: # If there is no value assert false # This will not be reached, because the value is present
The get operation demonstrated above returns the underlying value, or raises UnpackError if there is no value. There is another option for obtaining the value: unsafeGet, but you must only use it when you are absolutely sure the value is present (e.g. after checking isSome). If you do not care about the tiny overhead that get causes, you should simply never use unsafeGet.
How to deal with an absence of a value:
let result = "team".find('i') # Nothing was found, so the result is `none`. assert(result == none(int)) # It has no value: assert(result.isNone) try: echo result.get() assert(false) # This will not be reached except UnpackError: # Because an exception is raised discard
Types
Option[T] = object when T is SomePointer: val else: val has
- An optional type that stores its value and state separately in a boolean. Source Edit
UnpackError = ref object of ValueError
- Source Edit
Procs
proc some[T](val: T): Option[T]
- Returns a Option that has this value. Source Edit
proc option[T](val: T): Option[T]
- Can be used to convert a pointer type to an option type. It converts nil to the none-option. Source Edit
proc none(T: typedesc): Option[T]
- Returns an Option for this type that has no value. Source Edit
proc none[T](): Option[T]
- Alias for none(T). Source Edit
proc isSome[T](self: Option[T]): bool {...}{.inline.}
- unequals operator. This is a shorthand for not (x == y). Source Edit
proc isNone[T](self: Option[T]): bool {...}{.inline.}
- Source Edit
proc unsafeGet[T](self: Option[T]): T
- Returns the value of a some. Behavior is undefined for none. Source Edit
proc get[T](self: Option[T]): T
- Returns contents of the Option. If it is none, then an exception is thrown. Source Edit
proc get[T](self: Option[T]; otherwise: T): T
- Returns the contents of this option or otherwise if the option is none. Source Edit
proc get[T](self: var Option[T]): var T
- Returns contents of the Option. If it is none, then an exception is thrown. Source Edit
proc map[T](self: Option[T]; callback: proc (input: T))
- Applies a callback to the value in this Option Source Edit
proc map[T, R](self: Option[T]; callback: proc (input: T): R): Option[R]
- Applies a callback to the value in this Option and returns an option containing the new value. If this option is None, None will be returned Source Edit
proc flatten[A](self: Option[Option[A]]): Option[A]
- Remove one level of structure in a nested Option. Source Edit
proc flatMap[A, B](self: Option[A]; callback: proc (input: A): Option[B]): Option[B]
- Applies a callback to the value in this Option and returns an option containing the new value. If this option is None, None will be returned. Similar to map, with the difference that the callback returns an Option, not a raw value. This allows multiple procs with a signature of A -> Option[B] (including A = B) to be chained together. Source Edit
proc filter[T](self: Option[T]; callback: proc (input: T): bool): Option[T]
- Applies a callback to the value in this Option. If the callback returns true, the option is returned as a Some. If it returns false, it is returned as a None. Source Edit
proc `==`(a, b: Option): bool
- Returns true if both Option``s are ``none, or if they have equal values Source Edit
proc `$`[T](self: Option[T]): string
- Get the string representation of this option. If the option has a value, the result will be Some(x) where x is the string representation of the contained value. If the option does not have a value, the result will be None[T] where T is the name of the type contained in the option. Source Edit | https://nim-lang.org/docs/options.html | CC-MAIN-2018-51 | refinedweb | 787 | 62.78 |
Hackathon Project: Viewing Datadog metrics in Minecraft
Datadog recently held an internal hackathon. We run these about twice a year across the organization. Each team hacks on the project of their choice for 2 days. Projects vary from process improvement, to new feature ideas, or just plain old fun hacks.
At Datadog we see and gather metrics everywhere by using Datadog to monitor our applications and infrastructure. So our team thought it’d be fun to come up with creative solutions to “where can we display metrics?”.
We decided to see if we could build a way to display Datadog graphs and dashboards inside the world of Minecraft. We know engineers are often gamers too, and while we do not expect our customers to monitor their production environments in Minecraft, we thought showing metrics inside the game world might help you get more game time while on-call.
Our goal with this was:
- Programmatically access Minecraft elements. More precisely being able to create, remove and query information about blocks.
- Programmatically retrieve real-time data from Datadog.
- Glue it all together to read data from Datadog and pump it into Minecraft.
Control Minecraft
The first step was to control Minecraft via Python. We picked Python because we use it heavily at Datadog and are familiar with the language. It also has lots of existing libraries and documentation to make Minecraft interactions straightforward. One way to do this was to use Raspberry Juice, which implements a subset of the Minecraft API; and PI Edition, a Minecraft server for Raspberry PI. We set this up on our laptops rather than installing dedicated PI boxes for this hack as it offered improved build times and performance. Once we had set up a dedicated server using Raspberry Juice, we simply had to import the Python library py3minepi and we were all set with a development environment.
Interacting with this environment (creating blocks) via Python code was as simple as:
import mcpi.minecraft as minecraft import mcpi.block as block mc = minecraft.Minecraft.create("127.0.0.1") mc.setBlock(10, 10, 10, block.STONE.id)
Once you can do this, you can do anything… The power of Python unleashed in Minecraft.
Access Datadog data
To access data from Datadog we installed the Datadog Python library and followed the API reference.
from datadog import initialize, api Import time options = { 'api_key':'01234abc01234abc', 'app_key':'0123456789abcdef0123456789abcdef' } initialize(**options) now = int(time.time()) data = datadog.api.Metric.query(start=now - 300, end=now, query="avg:system.cpu.idle{*}")
Once we were able to both query data and draw objects, it was rather trivial to integrate the two pieces. We also started to implement some monitors, which would shine red when in alert mode, and resume to green in normal mode.
Challenges
Configuration
We rapidly found out we would need to describe our world with configuration files rather than rely on data mixed in function calls. So we set up some basic YAML files containing information such as:
- Where a graph should be (size, position, orientation, …)
- How a graph should look (colors, transparency, …)
- What data it should display (metrics to get, time span, …)
Here is a sample YAML configuration file, representing a dashboard with CPU usage and a monitor alert :
- graph2: type: wall query: "avg:system.cpu.idle{*}" pos1: x: 81 y: 40 z: 170 pos2: x: 92 y: 55 z: 170 layout: "xy" border: true - monitor_status: type: monitor_status monitor_id: 660012 pos1: x: 81 y: 56 z: 170 pos2: x: 86 y: 61 z: 170
A complete dashboard, displaying several metrics, the two dark squares represent monitors. Everything is updated in real-time.
Persistence
Another problem was that Minecraft is by nature persistent. That is once you create an object it lives on. Our graphs on the other hand change frequently as the data changes. More challenges was that as we iterated on the project our failed attempts to make graphs would populate the world with random cubes and and be cumbersome to navigate or clean up. To ease this pain we wrote vacuum functions to clean anything we drew.
Displaying data
It feels awkward to draw graphs without being able to rely on JS and CSS as we do on the web. However as long as the data could be simplified to “one row of data”, we were able to build methods that would display the metrics from Datadog in a reasonably viewable manner. At some point, displaying large graphs would saturate the data pipeline, so we had to implement caching to save bandwidth. Interestingly enough, implement caching, saving bandwidth, is typically what we do in our daily job, as engineering for performance is commonplace at Datadog.
How fun was this?
The first four hours were spent trying to set up the environment, and connecting various components together. It has the charm of random hacking – trying to find your way in technologies you usually ignore (ie Minecraft). Which is fun. Then we had up to 20 hours to play around like kids, build walls, view them, explore, destroy, rebuild, and try again. Is there anything more enjoyable than hacking for pure fun?
See it in action!
To view your own metrics in Minecraft, fork the repository on Github.
Want to join us for our next hackathon? Datadog is hiring! Learn more on our careers site or email us a description of your favorite hackathon project. | https://www.datadoghq.com/blog/engineering/hackathon-project-viewing-datadog-metrics-in-minecraft/ | CC-MAIN-2017-51 | refinedweb | 895 | 63.49 |
Eric W. Biederman wrote:> Pavel Emelyanov <xemul@openvz.org> writes:> >> I could use the struct net pointer values (obtained with sprintf(id, "%p", net))>> instead, but exporting internal kernel addresses seemed even uglier.> > Agreed.> >>> Can you try this approach by capturing a struct pid instead of an id>>> in a new global namespace? >> This is a bad approach. When task, that created the namespace dies, his>> pid is removed from the pidmap and can be reused, so we can get another>> net with the same id.> > It takes a little updating of how we use pids. The easiest method> is to add an extra counter. So we know when someone besides the hash> chains is using the pid as an id. However it might make sense to actually> have a net namespace pointer in the pid.No, please, no. I'm strongly opposed to making pids provide identificationfor anything we need in the kernel.>> This net's id is not supposed to be used to address any net in the kernel.>> And I see no problems with migration - you can change the net's id safely>> during checkpoint/restart - tasks will always see this one via the /proc/net>> symlink, which is dynamic.> > So you are really talking about a hidden id. There are just enough> ways for something like that to slip out I'm not especially> comfortable with the idea.> > I really think we need something clean that we can live with, and be> proud of. However we implement the enhancement to /proc/net this has> to be maintained for decades.> > Eric> | http://lkml.org/lkml/2008/3/3/41 | CC-MAIN-2016-18 | refinedweb | 264 | 73.27 |
Uncyclopedia talk:Projects
From Uncyclopedia, the content-free encyclopedia
edit UnWhoniverse
I was wondering whether the UnWhoniverse is possible. No I didn't mean the UnUniverse. I meant the UnWhoniverse, a project dedicated to Doctor Who comedy.
If that is not possible, is a Sci-Fi comedy project possible?
Thank you to all who answer. —The preceding unsigned comment was added by 98.67.111.202 (talk • contribs)
- I cannot imagine that even a single page in this direction will be original comedy writing but instead probably fan-fiction. There are plenty of websites for this, including one within Wikia, but not us. I cannot imagine this concept meriting its own project and namespace. And I cannot imagine wanting to do the legwork for a person who has not registered as an Uncyclopedian nor figured out the correct way to post to a talk page. Spıke
21:45 20-Mar-17
- I'm sorry about not correctly posting to this page, but although I have not registered, I may post and edit on this wikia, and would be happy to take on the work of managing this idea. I do suppose though, that you have a point. Thank you for answering.--98.67.111.202 22:10, March 20, 2017 (UTC)
- There, you figured it out! Now, what usually happens is that an Uncyclopedian doesn't just create a page but declares that he can't be creative under our cover story and needs his own space to work in. For instance, he can't just write an UnNews but needs a sub-genre of "articles that seem to be written by Rush Limbaugh" because he wants to make fun of Rush Limbaugh. We figure out how to fit it in and still look like a news page, he writes a couple, and is never heard from again. Now, if you picked a user name, you would have a userspace and you could create anything within that. Spıke
22:44 20-Mar-17
edit UnVoyage
This is something that'd be fun, a parody of travel guides. I think this was made on the fork, but not on the spoon. MyOwnBadSelf (talk) 10:47, April 18, 2017 (UTC) | http://uncyclopedia.wikia.com/wiki/Uncyclopedia_talk:Projects | CC-MAIN-2017-39 | refinedweb | 368 | 71.85 |
Hey,
I'm trying to concatenate strings with const chars (letters in the double quotes). I've tried using the + way, the sprintf, and strcat. None work... An example piece below...
***not my actual code, it's just extremely similar to it******not my actual code, it's just extremely similar to it***Code:#include <iostream> #include <string> using namespace std; int main ( int argc, char *argv[]) { string word1 = "this is a string"; string word2; word2 = "hello" + word1 + "\n"; return 0; }
That's what I'm trying to do... can anyone help (i don't want to use c-strings)
Thanks in advance,
Guitarist809 | http://cboard.cprogramming.com/cplusplus-programming/96964-string-concat.html | CC-MAIN-2014-35 | refinedweb | 104 | 69.52 |
Damon Payne
MySQL is a decent product. I've been very critical of it in the past, but it has been evolving nicely. It's probably the most popular open source database and plays nicely with .NET due to a solid ADO.Net provider. What's been lacking up to this point, though, is LINQ to SQL support, and more recently a provider for the Entity Framework. The EF has gotten a lot of flak, but I for one like it for the most part and I think it will hugely speed up a lot of database-heavy development. Sure, you need to write some extension methods to get around the lack of foresight for how change-tracking would work in ASP.Net applications, but once you've cracked that nut (and grokking aggregates with Entity SQL) you can go back to happily writing LINQ queries.
I have been watching the MySQL forums for a while. The MySQL team had said during the Beta of VS2008 SP1 that there would be something we could test "real soon". This was followed by months of radio silence. Recently, silence was finally broken by the lead developer that September 30th was the date. MySQL subsequently set up a webcast to demonstrate the new functionality. Today, the day of the webcast, it seems that registered participants got messages saying that November 4th was the new date. Unbelievable. See:
When I was in consulting, we had a tongue-in-cheek (yet very true) rule about deadlines. If the deadline was to be pushed back, it could only be pushed back by the amount of time remaining until the delivery date. If you have 3 weeks until the deadline, you can only move the deadline out 3 weeks. If it's due tomorrow, you can only push it out one day. You do not wait until it's due today and push it back a month. I'm sure there's a reason, but it's just bad form. People are on the edge of their seats over this feature. This isn't how open source is supposed to:
As promised, my next task was to make any changes needed to prepare the app so far for working with the RC0 Silverlight release.
The first thing I noticed is that when I tried to run the application I was presented with “Get Silverlight”. I figured the version # had changed, but it was actually the type attribute of the object tag:
<object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/DamonPayne.HTLayout.xap"/>
<param name="onerror" value="onSilverlightError" />
<param name="background" value="white" />
<a href="" style="text-decoration: none;">
<img src="" alt="Get Microsoft Silverlight" style="border-style: none"/>
</a>
</object>
Note the type is now “application/x-silverlight-2”.
The next error I noticed was a seemingly uncatchable error that percolated all the way up to the onSilverlightError JavaScript function.
“Can not set ItemTemplate and DisplayMemberPath simultaneously.”
Looking at the XAML, this makes sense.
<ListBox x:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="{Binding Name}"
This makes sense, it just didn’t cause an error before. I’m setting DisplayMemberPath in XAML, which is then not used since I’ve provided the entire ItemTemplate. It would be useful if the error told me which XAML file the error is in, but this is a small project so far and future Silverlight developers will be starting out with Silverlight 2 Release.
At this point I thought I’d better do a Clean Solution just to be safe, and sure enough this turned up another issue. At some point, my DesignSurface.HitTest method (required by IDropTarget) disappeared. The Clean Solution found this out for me. Looking back through my code snapshots taken at the end of each article, it’s been gone for quite some time. This behavior from VS2008/Silverlight Tools is just not ok. This was my last breaking change though. UIElement.HitTest is gone, replaced with a method in VisualTreeHelper:
public IEnumerable<UIElement> HitTest(Point p)
{
return VisualTreeHelper.FindElementsInHostCoordinates(p, LayoutRoot);
}
I find now that my Selection code is absolutely broken, but that was under repair anyway.
Source code: Because the code was in a state of flux pending the selection/sizing updates, the next source code will be at the end of AGT[12].
You have probably seen that Silverlight RC 0 is now available:
I was in the middle of writing AGT[11] and got sick, requiring a 16 hour sleeping spree, and I'm still not over it. AGT[11] also represented some frustrating material, so it was going slow. Figuring out the Silverlight Layout-->Measure-->Clip-->Render process well enough to acheive my next goal is turning out to be challenging. I'll preface it with some recommended reading. At any rate, the material for AGT[11] will now become AGT[12]. The articles and the live demo are immediately switching over to use Silverlight RC0 before I accumulate any more breaking changes or write code to Measure behavior that changes. Some of the solutions I was pursuing just became private/internal/sealed as of yesterday.
Recommended reading:
I have contacted my Federal representatives today to let them know I am firmly against the proposed $700 billion bailout proposal. You should do the.
Now that we’ve got things on the surface, we need to think about selecting, moving, editing, and resizing them. It makes sense for Selection to come first.
Selection is slightly more complicated than it sounds. In a tool like VS2008 or Visio things could be added or removed from the selection in several ways:
· Clicking on a component
· Control+Click on multiple components to select and deselect
· Shift+Click to add contiguous components to the selection
· Click and draw a rectangle, selecting components within the bounds of said rectangle.
Since I’m extending the olive branch to the dozens and dozens of unfortunate Mac users in the world, I’ll have to make any gesture code I write smart enough to not use any normal keys that are missing from the Mac, such as: Control, Window Key, Right-click Key, Pause/Break, up arrow, and the letter Q.
Back in the Dark Ages when I was writing code to host the WinForms 2 design surface, I think my selection service implementation was quite a few lines of code. While I still like the idea of a selection service, I’m not going to go look at the old code and corrupt my pure thoughts. First, let’s create a cross platform Keyboard service:
public class CrossPlatformKeyboardService : IKeyboardService
{
/// <summary>
/// Control key, or open-apple on the Mac "platform"
/// </summary>
public bool ControlKeyDown
get
{
return ( Test(ModifierKeys.Control) || Test(ModifierKeys.Apple));
}
}
public bool AltKeyDown
get { return Test(ModifierKeys.Alt); }
public bool ShiftDown
get { return Test(ModifierKeys.Shift); }
protected bool Test(ModifierKeys target)
return target == (target & Keyboard.Modifiers);
Next I’ll define what I expect the interface for a selection service to be.
public interface ISelectionService : IService
void SetSelectedControls(IList<IDesignableControl> selection);
IList<IDesignableControl> GetSelection();
int SelectionCount { get; }
IDesignableControl PrimarySelection { get; }
event EventHandler SelectionChanged;
}
In WinForms, adding to the ISelectionService can optionally come with a parameter of type “SelectionType”, which is a discriminator for things like adding to a selection vs. starting a new selection. I’d rather leave those details behind the ISelectionService wherever possible. You will also note that I am using a plain old .Net event here and not something from EventAggregator. I feel this is highly appropriate in this case. The EventAggregator exists so that components can respond to interesting events without referencing each other, but selection events are specific to this Service, and components that need ISelectionService will magically receive it from the container. Now I can start working on a default ISelectionService implementation, with a dependency on IKeyboardService.
We need to take another step before Selection can make sense. The WinForms designer has the notion of an ISite, where an ISite is an adapter between a designed component and its designer. Once sited, the component can request various things of its container. While not quite what I’m about to do, it’s a point for interested users to research. I will explain this concept further in the next article. I have created a UserControl called DesignSite. DesignSite contains a border whose thickness is set to zero by default. Inside DefaultDesignTypeCreator I shove the real IDesignableControl inside my DesignSite and let DesignSite handle the selection code when the real IDesignableControl is clicked on.
The Site mentioned above wires up selection by resolving the ISelectionService. Here, then, is the selection service implementation.
public class DefaultSelectionService : ISelectionService
public DefaultSelectionService()
_selection = new List<IDesignableControl>();
public IKeyboardService KBService { get; set; }
private List<IDesignableControl> _selection;
public void Select(System.Collections.Generic.IList<IDesignableControl> incoming)
if (!KBService.ControlKeyDown)
_selection.Clear();
_selection.AddRange(incoming);
OnSelectionChanged();
else
foreach (IDesignableControl idc in incoming)
{
if (!_selection.Contains(idc))
{
_selection.Add(idc);
}
OnSelectionChanged();
}
}
public System.Collections.Generic.IList<IDesignableControl> GetSelection()
return _selection;
public int SelectionCount
get { return _selection.Count; }
public IDesignableControl PrimarySelection
return _selection[0];
public event EventHandler SelectionChanged;
protected void OnSelectionChanged()
if (null != SelectionChanged)
SelectionChanged(this, EventArgs.Empty);
Much simpler and shorter than I remember the WinForms implementation I remember. We’ll see if I eat crow for saying so later. Here is my site-style selection with a single component selected.
Shown here with multiple components selected by holding in Control or Open Apple:
You will note I don’t have any little “knobs” on the corners or anything. I like how this looks better with a solid border and a gradient brush. As we saw with Couch v1, perhaps my taste in visual appeal should not be trusted. Speaking of couches, I have a chair now too. You can take a look at my freshly painted Red Chair in the live demo. Live demo….?
Ever since being enlightened by Generics (the answer to everything) using the (cast) bothers me. Casting using “as” bothers me more. For this reason, I don’t know why the whole DependencyProperty framework deals with getting and setting of values as Object. When I ported some code from Silverlight 2 beta 1 to beta 2, some of it was broken because I was using SetValue(Canvas.Left, 3) when in fact Canvas.Left wanted to be of type double and some auto-conversion was lost in the move to beta 2. This error only pops up at runtime since SetValue takes type Object. At least I can save myself some casting here and there by adding another extension method:
public static T GetValue<T>(this DependencyObject d, DependencyProperty p)
return (T)d.GetValue(p);
Which allows glorious code like:
double left = SiteBorder.GetValue<double>(Canvas.LeftProperty);
It isn’t much but I’ll take it.
I have created a live demo at ; obviously this is a work in progress but feedback is welcome.
I have a pretty good idea how I’m going to do resizing, that will come next. After that I will do multi-select by drawing a rectangle and then Moving. After moving works I will have to think of how I want object editing to work, some kind of Property Grid I’m sure. From there, I’ll have to take stock of where I’m at, review my goals, and decide what to do next.
Source code:DamonPayne.AGT[10].zip (1.28 MB):
Since this is a Silverlight application I thought I should spend some time making it look good. I hit my frustration limit in a very short period of time and what you see here is as far as I got. I am guessing Styling is not entirely baked in Silverlight 2 beta 2, or else doing a complete control template is really the way to go.
My first issue was with fonts. I downloaded a copy of the Trajan Regular font. Ever since Klipsch started using Trajan pro in the Palladium branding I’ve been digging the Trajan font family. At any rate, it seems that Silverlight is very picky about using extra fonts, be they set from a style or per control. Worse, it’s very difficult to track down where the issue might be. I have three primary tools available to me for Silverlight debugging: Blend 2.5 June CTP, VS2008 SP1, and running the application for inspection. Debugging is not fun when all three tools show different output, check out the ToolboxView:
Blend shows the correct font and color. VS2008 shows the correct nothing. Runtime shows the correct color but not font. I’ve tried obvious things like double checking relative paths and so forth. At this point I’m admitting defeat and moving on. At least my bad taste and visual look stolen from Klipschcorner’s CSS is better than black and grey. Right? Let’s skip to the punchline, here is what the application looks like now:
I tricked a visual designer into making me a better purple couch. This person happens to be an extreme Adobe fanboy, to the degree that they didn’t believe me when I said there were other drawing programs for both vector and raster graphics. The Adobe fans are easily worse than the Mac fans. At any rate, that sure looks like a couch, at least. It’s rather large in relation to the design surface, but we’ll fix that with resizification later.
I haven’t really thought of what all I want to include in the example HT Layout program, but I figured some speakers would be nice. I’m getting slightly better at drawing some things in Blend: these speakers look better than my original couch. If you’re not familiar with horn-loaded speakers you’ll have to trust me that the white horn shape is actually a reasonable caricature.
I’ll refactor later as I get to read more about the control templating and style creation. I think the app is starting to look like a real program, and we’re still less than 1000 lines of code. The next articles are not written yet, but the next step is to implement functionality that allows me to move, resize, and otherwise Transform things once they are on the designer surface. As it turns out, this is a very interesting problem for all sorts of reasons. I’m not breaking my Reality Blogging pledge, but remember I’ve done this in WinForms before, and I recall things like “selection” being more complex than it sounds: . Once selection is implemented moving and resizing come free in WinForms, and I’ve got to build those from scratch now. I’m sure I’ll be spending some time in traffic this week and I’ll spend many mental cycles thinking about the interactions.
Source Code:DamonPayne.AGT[9].zip (1.26 MB)
This article and AGT[8] were written with Windows Live Writer, after Larry talked me into trying it. So far, I really like the idea, but the implementation could be better. I typically write my articles in Word 2007, since I may be working on one for days or weeks. Cut 'n pasting out of Word into the DasBlog FreeTextBox just works. Sure, it generates the ugliest HTML you've ever seen, but it looks like code in both IE7 and FF3. Copy/pasting out of VS2008 into Live Writer looks like this:
ToolboxItem speakItem = new ToolboxItem("Tower speaker", "This is a generic 2-way tower speaker with horn-loaded mid & high range", typeof(HornSpeaker)); Toolbox.AddItem(speakItem, "Audio");
Copy/pasting out of MS Word 2007 into Live Writer looks like this, using the "keep formatting" option.
ToolboxItem speakItem = new ToolboxItem("Tower speaker", "This is a generic 2-way tower speaker with horn-loaded mid & high range", typeof(HornSpeaker));
Toolbox.AddItem(speakItem, "Audio");
It's not bad, but it insists on inserting some extra spaces between lines. I've also been uploading a .zip file of the source code as it stands at the end of each article, and I find no way to do this from Live Writer - perhaps that's not supported by the blogger API. I do like it inserting & uploading images for me.
For complex articles, I'll still be copy/pasting from Word, but for a free program I do rather like Live Writer.:
Part 8 in a 50 part series begins...
It’s time to try dragging something out of the Toolbox and onto the DesignSurface.
We start dragging by wiring up events inside the ToolboxCategoryControl. We’ve already established a mechanism for making sure only one ToolboxItem is ever selected, and that the ToolboxView owns the ToolboxCategoryControl. We define a normal local dragstart event:
void cat_DragStart(object sender, EventArgs e)
ToolboxItem tbi = SelectedItem;//Will already be populated from event wireup
DragDropManager.BeginDrag(tbi);
I have implemented the cleverly named DefaultDragDropManager in the DamonPayne.AGT.Design.Services namespace to handle the task. The first thing DDDM does is obtain a drag-time representation of the Control visual. This is one of the places where we start diverging more and more from how VS2008 works and looks today. While I’m not ready for the Visual Refactoring stage yet, we can clearly do better than a tiny mouse cursor with a “+” next to it. This is what IDragTypeCreator is for: to provide a pluggable mechanism for building a better representation of what you’re dragging around than a mouse cursor. I created a special DragContainer control for this purpose in DamonPayne.AGT.Design.Controls. Here is the entire DefaultDragTypeCreator.CreateDragRepresentation method:
public Control CreateDragRepresentation(Type t)
//Default behavior:
DragContainer dc = new DragContainer();
Control c = (Control)Activator.CreateInstance(t);
//Thanks to for scaling code
//TODO, extension method for uniform scale size?
double originaltWidth = c.Width;
double originalHeight = c.Height;
double uniformScaleAmount = Math.Min(MAX_DIMENSION / originaltWidth, MAX_DIMENSION / originalHeight);
ScaleTransform st = new ScaleTransform();
st.ScaleX = uniformScaleAmount;
st.ScaleY = uniformScaleAmount;
c.RenderTransform = st;
c.InvalidateMeasure();
c.UpdateLayout();
//TODO: why couldn't I force this to recalc size here after setting render transform?
double estimatedNewWidth = c.Width * uniformScaleAmount;
double estimatedNewHeight = c.Height * uniformScaleAmount;
double left = (dc.Width / 2.0D) - (estimatedNewWidth / 2.0D);
double top = (dc.Height / 2.0D) - (estimatedNewHeight / 2.0D);
c.SetValue(Canvas.LeftProperty, left);
c.SetValue(Canvas.TopProperty, top);
dc.LayoutRoot.Children.Add(c);
dc.Opacity = .65D;
dc.LayoutRoot.Opacity = .65D;
return dc;
I am basically creating an instance of whatever Type I was given, which ultimately came from ToolboxItem.Type. Then I scale the instance down to where it will fit in my DragContainer and return the DragContainer. With this in hand, DefaultDragDropManager wires up the mouse events for dragging around: basically when mouse left button goes up we do a hit check to see if there is an IDropTarget registered with us that would be under the current mouse position. With the events set, we add the DragContainer control to the root visual of the Silverlight application.
The next thing I need to actually implement is the DesignSurface control, implementing IDropTarget. This needs to be added into the IRegionManager way back when the ToolboxView and MessageConsole are created. I’ve resized the whole Page such that I can fit a 480x640 gray DesignSurface in there. You can now see me take my drag-time couch representation over to the design surface:
As soon as I got into developing the drop part, I realized I was in the Silverlight world, thinking like a WinForms developer. Silverlight has built in hit test code already and I don’t need to do anything with Bounds. The IDropTarget interface is thefore modified to use UIElement.HitTest(Point), so the EndDrag method can now do this:
public virtual void EndDrag(MouseButtonEventArgs e)
RegionManager.TopLevelContainer.Children.Remove(_dragRepresentation);
_dragRepresentation = null;
foreach (IDropTarget target in _dropTargets)
if (target.IsHitTestVisible)
IEnumerable<UIElement> elements = target.HitTest(_mousePos);
if (elements.GetEnumerator().MoveNext())//hit test succeed
IDesignableControl ctrl = DesignCreator.CreateInstance(_draggingType);
target.OnDrop(ctrl);
_draggingType = null;
As soon as we enter OnDrop, the design time representation is worthless and we throw it away. We’ll either be building the real control the surface or simply cleaning up. I believe in the last article I described the interaction as the DesignSurface calling the creation method from OnDrop, but it makes more sense to put it here now. For now, the IDesignTypeCreator simply instantiates the appropriate Type. DesignSurface.OnDrop is incredibly simple for now:
public void OnDrop(IDesignableControl dc)
dc.Visual.SetValue(Canvas.LeftProperty, _localMousePos.X);
dc.Visual.SetValue(Canvas.TopProperty, _localMousePos.Y);
LayoutRoot.Children.Add(dc.Visual);
Success! Here’s the very nice looking purple couch on the design surface.
Clearly there is tons of work to be done still, but I was shocked when I actually ran metrics: this just a little over 500 lines of code so far!
Source code: DamonPayne.AGT[7].zip (613.16 KB)
Theme by Mads Kristensen
Damon Payne is a Microsoft MVP specializing in Smart Client solution architecture.
Tweetses by damonpayne
Get notified when a new post is published. | http://www.damonpayne.com/2008/09/default.aspx | CC-MAIN-2014-52 | refinedweb | 3,515 | 55.95 |
Imagine the following entities:
@Entity public class Car { @Id @GeneratedValue private long id; private String manufacturer; private String model; @OneToMany(mappedBy = "car") private Set<Tire> tires = new HashSet<>(); // Getters & setters } @Entity public class Tire { @Id @GeneratedValue private long id; @ManyToOne @JoinColumn(name = "car_id") private Car car; // Getters & setters }
I create a new
Car and add some new
Tires to it. Then I try to save that car using the
save() method of a
JpaRepository<Car, Long>. The car gets persisted but not the tires. I already tried to add
cascade = CascadeType.PERSIST to the
@OneToMany annotation, but it had no effect. So how can I store the tires? | http://www.howtobuildsoftware.com/index.php/how-do/iR7/java-spring-jpa-spring-data-jpa-how-to-store-an-entity-together-with-its-relations | CC-MAIN-2017-43 | refinedweb | 108 | 54.02 |
Data collected over a certain period of time is called Time-series data. These data points are usually collected at adjacent intervals and have some correlation with the target. There are certain datasets that contain columns with date, month or days that are important for making predictions like sales datasets, stock price prediction etc. But the problem here is how to use the time-series data and convert them into a format the machine can understand? Python made this process a lot simpler by introducing a package called Darts.
In this article, we will learn about Darts, implement this over a time-series dataset.
Introduction to Darts
For a number of datasets, forecasting the time-series columns plays an important role in the decision making process for the model. Unit8.co developed a library to make the forecasting of time-series easy called darts. The idea behind this was to make darts as simple to use as sklearn for time-series. Darts attempts to smooth the overall process of using time series in machine learning.
The basic principles of darts are:
- There are two types of models in darts :
Regression models: these predict the output based on a set of input time-series.
Forecasting models: these predict a future output based on past values.
- They have a class called TimeSeries which is immutable like strings.
- The TimeSeries class can either one single dimensional or multi-dimensional. Some models like neural networks need multiple dimensions while other simple models work with just 1 dimension.
- Methods like fit() and predict() are unified across all models from neural networks to ARIMA.
Implementation of darts on time-series data
Darts is open-source and can be installed with the pip command. To install darts use:
pip install u8darts
Dataset
Next, choose any time-series dataset of your choice. I have selected the monthly production of beer in Australia dataset. To download this click here. Let us now load the dataset and import the libraries needed.
from google.colab import drive
drive.mount('/content/gdrive/')
import pandas as pd
from darts import TimeSeries
beer_data = pd.read_csv('/content/gdrive/My Drive/beer.csv')
beer_data.head()
The dataset contains two columns- the month with the year and the beer production in that time period.
Train-test split
Let us now use the TimeSeries class and split the data into train and test. We will use a method called from_dataframe for doing this and pass column names in the method. Then, we will split the data based on the time period. The dataset has around 477 columns, so I chose the 275th time period to make the split (1978-10).
get_data = TimeSeries.from_dataframe(beer_data, 'Month', 'Monthly beer production')
traindata, testdata = get_data.split_before(pd.Timestamp('1978-10'))
Modelling
Training of the model is very simple with darts. An exponential smoothing model is used here to fit the data. Similar to sklearn, fit() method is used to fit the dataset.
from darts.models import ExponentialSmoothing
beer_model = ExponentialSmoothing()
beer_model.fit(traindata)
This completes the training part. Let us now make predictions and plot the graph
prediction = beer_model.predict(len(test))
print("predicted" ,prediction[:5])
print("actual",test[:5])
import matplotlib.pyplot as plt
get_data.plot(label='actual')
prediction.plot(label='predict', lw=3)
plt.legend()
Here the monthly values after 1978 are forecasted due to the model exponential smoothing. It shows the time-series predictions with good accuracy.
Darts can also be used in neural networks, multivariate models and clustering models.
Conclusion
In this article, we saw how to use the darts library to forecast time-series problems with just a few simple lines of code. The library is fast and saves time when compared to the Pandas library. The library also contains options for backtesting, regression models and even automatically select models. It is a great way to handle time-series datasets.. | https://analyticsindiamag.com/hands-on-guide-to-darts-a-python-tool-for-time-series-forecasting/ | CC-MAIN-2020-45 | refinedweb | 642 | 58.28 |
As usual while waiting for the next release - don't forget to check the nightly builds in the forum.
But, by experience, I know that when a project become too big it's very difficult to add new features.
So you have given up on using a real C++ parser that builds a full AST? One like Elsa or ANTLRC++.
I know this is going to come on strong, but I have no faith in a custom built C++ parser providing any better level of functionality than the current pluggin. Instead of spending hundreds of hours reinventing the wheel we should port Elsa (some small linux dependent pieces exist), or get the ANTLR passed parser working. Then we can do a whole lot more than just code completion. Elsa at least builds a full AST out of all possible c++ code including the stl headers, so it has full namespace and template support. It has a prebuilt visitor based system for pulling information out of the AST, so you can gather all the information you need.
Now you could integrate the Elsa or ANTLR passed parser as your "cxxparser", but I don't think you need to go through all the extra work of building a parser smart enough to filter out that information. I think the above listed parsers might keep the comments in the AST, and If they do, then it will save you a lot of work, they also don't care about extra preprocessor tokens. Of course you could always use ucpp, or wave to preprocess everything for you. | http://forums.codeblocks.org/index.php?topic=2494.msg19797 | CC-MAIN-2019-43 | refinedweb | 263 | 74.93 |
write our item first as it depends on nothing else. As you should already know the item stores the data and paints it on the screen. One item has an exact position on the globe as longitude, latitude and altitude. The item we will write shows a text at the specific position.
We will now look at the header file to see what functions we have to implement.
TutorialItem.h
// This is to prevent this header to be included multiple times
class QFont;
namespace Marble {
class TutorialItem : public AbstractDataPluginItem {
Q_OBJECT public: TutorialItem( QObject *parent ); ~TutorialItem(); // Returns the item type of the item. QString itemType() const; // Returns true if the item is paintable bool initialized(); // Here the item gets painted void paint( GeoPainter *painter, ViewportParams *viewport, const QString& renderPos, GeoSceneLayer * layer = 0 ); bool operator<( const AbstractDataPluginItem *other ) const; // The text we want to show on the map QString text() const; void setText( const QString& text ); private: QString m_text; static QFont s_font;
};
}
As you have probably seen, it will be very easy to implement this as we have only one function (paint()) besides some getters and setters.
Let's have a look at the implementation.
TutorialItem.cpp
// Self
// Marble
// Qt
using namespace Marble;
// That's the font we will use to paint. QFont TutorialItem::s_font = QFont( "Sans Serif", 8 );
TutorialItem::TutorialItem( QObject *parent )
: AbstractDataPluginItem( parent )
{
// The size of an item without a text is 0 setSize( QSize( 0, 0 ) );
}
TutorialItem::~TutorialItem() { }
QString TutorialItem::itemType() const {
// Our itemType: return "tutorialItem";
}
bool TutorialItem::initialized() {
// The item is initialized if it has a text if ( m_text.isEmpty() ) return false; else return true;
}
bool TutorialItem::operator<( const AbstractDataPluginItem *other ) const {
// That's not a very nice priority estimation, you'll hopefully find // a better one for your plugin. return this->id() < other->id();
}
QString TutorialItem::text() const {
return m_text;
}
void TutorialItem::setText( const QString& text ) {
// On a text change our size may also change, so we have to set the new // item size. Marble needs to know how large an item is to find the correct // bounding rect. The given position will always be in the middle of the // item for now. QFontMetrics metrics( s_font ); setSize( metrics.size( 0, text ) ); m_text = text;
}
void TutorialItem::paint( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos, GeoSceneLayer * layer )
{
Q_UNUSED( renderPos ) Q_UNUSED( layer ) // Save the old painter state. painter->save(); // We want to paint a black string. painter->setPen( QPen( QColor( Qt::black ) ) ); // We will use our standard font. painter->setFont( s_font ); // Draw the text into the given rect. painter->drawText( QRect( QPoint( 0, 0 ), size() ), 0, m_text ); // Restore the old painter state. painter->restore();
}
// This is needed for all QObjects (see MOC)
Wasn't that easy? Continue with the next section.
We will continue developing the core component, the model. Let's first look at the header file:
TutorialModel.h );
};
}
You see that we have to implement the function getAdditionalItems(). getAdditionalItems() is called when the viewport has been changed significantly, so new items have to be generated. Let's continue with the interesting part, the implementation:
// Self
// Plugin
//; } // We will only create one item in our first tutorial. // Every item has to get an id. We have to check if the item already exists. if ( !itemExists( "tutorial1" ) ) { // If it does not exists, create it GeoDataCoordinates coor( 10.22 * DEG2RAD, 54.4 * DEG2RAD ); // The parent of the new item is this object TutorialItem *item = new TutorialItem( this ); item->setCoordinate( coor ); item->setTarget( "earth" ); item->setId( "tutorial1" ); item->setText( "Hello World!" ); // Add the item to the list of items, so it will be displayed addItemToList( item ); }
} | https://techbase.kde.org/index.php?title=Projects/Marble/OnlineServices&diff=43653&oldid=43643 | CC-MAIN-2015-27 | refinedweb | 594 | 54.32 |
span8
span4
span8
span4
I have created a shared resource directory (named PROJ) based on this article.
I'm using it in a (type: text) private parameter (named SHAREDRESOURCE_PROJ) as I would do with an FME parameter :
$(FME_SHAREDRESOURCE_PROJ)\Templates
And I access that parameter from a number of scripted private parameters like this:
import fme templateA = fme.macroValues[‘SHAREDRESOURCE_PROJ’] + '/templateA.ini' return templateA
When executing my workspace from FME Server it throws the error ' failed to evaluate Python script'.
If I replace $(FME_SHAREDRESOURCE_PROJ) with the actual path to the folder it works so the problem is the resource directory parameter, but I don't want to use the hardcoded path.
What am I doing wrong?
Since you've tagged your question with FME Server 2018, I would definitely recommend that you create the resource connection in the GUI. The document you linked to is for FME Server 2016 and should not be used for FME Server 2018.
That said, you need to use the complete name in the scripted parameters etc, for example:
A = fme.macroValues['FME_SHAREDRESOURCE_PROJ']
There is more information on the subject here:
I don't know why that document is not in the Administrator's Guide anymore. It does work and that way you don't have to provide a network directory as it uses the default location of the Resources folder.
Apart from that, it works if I use the resource connection as you say but that's not what I want to do.
I want to use a private parameter pointing to a folder in my resource connection, and then use that private parameter inside another (actually a number of) private parameter. That's what's giving me an error.
The reason to do it like this is because the folder name inside the resource connection may change and otherwise I'd have to change it in all parameters accessing that folder. This way it's just a change in one parameter.
Why do you mention FME_SHAREDRESOURCE_PROJ and SHAREDRESOURCE_PROJ, which one did you define?
You need to reference the value from the Name column when you defined the resource connection:
I defined the resource directly in the FME Server configuration file (FMEServerDir>Server\fmeServerConfig.txt) with the name FME_SHAREDRESOURCE_PROJ:
SHAREDRESOURCE_TYPE_8=FILE SHAREDRESOURCE_NAME_8=FME_SHAREDRESOURCE_PROJ SHAREDRESOURCE_DISPLAYNAME_8=PROJ SHAREDRESOURCE_DESCRIPTION_8=This shared resource is the project data directory SHAREDRESOURCE_ISMIGRATABLE_8=true SHAREDRESOURCE_DIR_8=C:/ProgramData/Safe Software/FME Server///resources/proj/ SHAREDRESOURCE_SECURITY_DEFAULT_ROLES_8=fmeadmin SHAREDRESOURCE_SECURITY_DEFAULT_OWNER_8=admin
SHAREDRESOURCE_PROJ is the name of the private parameter. It could be simply PROJ or whatever. If that's confusing let me change my example:
PROJ private parameter:
$(FME_SHAREDRESOURCE_PROJ)\Templates
Scripted private parameter:
import fme templateA = fme.macroValues[‘PROJ’] + '/templateA.ini' return templateA
Answers Answers and Comments
11 People are following this question.
Create a Private Parameter Value From Attribute Value 1 Answer
FME Hub Transformer Issues 3 Answers
Python Custom Transformer Bug using fme.macroValue 2 Answers
Problem with custom coordinate system: "inverse calculation failed to converge" and some changes to MyCoordSysDef.fme are ignored by FME 2 Answers
Is there / or how do I create a workspace that can change a private parameter [string] in other (different) workspaces? 1 Answer | https://knowledge.safe.com/questions/84087/accesing-fme-server-custom-shared-resources-from-a.html | CC-MAIN-2020-16 | refinedweb | 525 | 50.97 |
Hello,In practice there is no syntactical difference between function arguments that are T and those that are Function0[T]. This makes it difficult for a human to understand if an argument is evaluated more than once. I would like to change that, although I am not sure of the best way.
T
Function0[T]
A trivial solution is be rid of by-name syntax.
f(arg)
becomes
f(() => arg)
Another solution would be to require special syntax for by-name parameters. An example would be to require =>, so that
=>
f(=> arg)
This would make it so that Function0[T] and Function1[Unit, T] have different surface syntax. => arg and arg would type differently, and so the compiler can help find problems when the author meant one versus another.
Function1[Unit, T]
=> arg
arg
Additionally,
val x: Function0[Int] = 3
val x: Function0[Int] = => 3
This example makes me think my first idea is better, but it's only because () would break up the two =s. I don't think Function0 is often used this way. However, there is an upside!
()
=
val x = => 3
would be inferred as a Function0.
Please respond with any other ideas or criticisms!
Thanks,Jeff
Hey @shawjef3, thanks for opening a discussion around this.
Generally, I don't think this is a huge problem.
I think by-name parameters are useful as they are -- they are syntactic sugar for Function0. I am not aware of any evaluation semantics difference between the two. The syntactic changes you propose would make the use of by-name parameters difficult and clunky, which contradicts the idea of having syntactic sugar for the use of parameterless functions.
Function0
However, I think there's some room for improvement.
As by-name parameters is not a common concept in other programming languages, Scala developers have to learn it when they bump into it (it's difficult to guess what they are from just seeing it in the wild). If by-name parameters semantics are not intuitive, it's an education problem -- something that we should address in the docs and Scala learning material.
I guess this refers to the fact that by-name parameters are executed every time there is a reference to it from the method body. I had a casual discussion with @odersky to consider changing it so that by-name parameters are only executed once. However, I do not remember what Martin told me in response, so I cannot clarify whether that is possible or not. This change seems to go against the real semantics of named parameters. However, I think that changing the semantics would be better than what you propose. Do you agree?
However, I am aware of several places that depend on these semantics of by-name. For example, I remember seeing some Scala standard library code relying on this. Breaking this code is something that, if done, has to be done with care, and probably in a major version of Scala (2.13.x or Dotty).
Honestly, the cure feels far worse than the disease on this one. While I can see the objection in principle, in practice I don't recall ever encountering it, and by-name usage is sufficiently common (and useful for keeping call-site code clean) that I would strongly object to making it wordier.
@jvican's idea of changing the use-side to (effectively) treat the result as a lazy val, to avoid double-calls, is intriguing; that would reify in the language what I generally think of as good practice anyway. I'm curious how much code depends on multiple executions of the call-by-name function.
The thing is, with the current semantics you can always do
def foo(f: => Unit) = {
lazy val f0 = f
???
}
If you turn it around this gets a bit cleaner, but code that requires reevaluation becomes impossible without making the calls look like foo(() => ???). In that case I prefer cleaner calls over cleaner definition.By-name parameters in Scala are mostly about clean callsites anyway. Otherwise you could always use normal functions.
foo(() => ???)
@shawjef3 Thanks for pointing out that this isn't clear. I will update the documentation accordingly in the next week:
Hello,
I think the idea was not so much enabling the implementer to have itevaluate only once, but to have a guarantee for the caller that it is onlyevaluated once.
Best, Oliver
One more or less implies the other, I guess. In what @jvican was saying anyway.
My intent is not to change the semantics of by-name parameters, but to require by-name parameters be explicitly Function0[T].
In fact, after this discussion, I should change the focus of my original post.
The real problem, as I see it, is automatic conversion from T to Function0[T]. It is done silently whenever a Function0 is required. Some explicit syntax should be required, just as it is for, say, Function[Unit, T].
Function[Unit, T]
But that problem doesn't exist, as far as I know.
scala> def foo(a: Function0[Int]) = a()
foo: (a: () => Int)Int
scala> foo(42)
<console>:13: error: type mismatch;
found : Int(42)
required: () => Int
foo(42)
^
I thought that by-name parameters were Function0. I guess they're a different beast, which is even more confusing.
Something that is evaluated when used should really be a Function, and not a value. So I suppose there needs to be yet another type, something like ByName[T], which has the syntax sugar => T.
ByName[T]
=> T
Under the hood they are implemented as Function0. I think what you actually meant was probably "remove by-name parameters".
I think you're right, Jasper-M. If by-name parameters were removed, they could be replaced by explicit Function0s, and => could be introduced as syntax for Function0.
I'm nut sure if suggested solution suits well to the scala language, but I encounter the described problem regularly. Not too often though. It arises when I study a library from its usage documentation instead of scaladocs. In certain cases order of evaluation matters much. So I go to REPL, create simple example and test if the library function uses call-by-name semantics. It would be great to distinguish call-by-name without constructing test examples or looking inside the source code. And it would be equally miserable to lost nice DSL syntax method_name { } to create Future, Try and so on.
method_name { }
casper - if the DSL syntax became something like method_name => { } is that okay? It looks awkward because we're not used to it, but it shows you that the parameter is a Function0.
method_name => { }
This variant is definitely no ok, because it reserved for closure over method_name variable.
method_name
This came up on chat recently somewhere. If f(A) is overloaded with f(=> A), there is no syntax for explicitly selecting the by-name version. (Maybe the overload ought to be disallowed.)
The question posed here could be expressed the other way: explicit syntax to ensure eval-once semantics.
Instead of f(launch()), something with a lazy val as Jasper-M pointed out. f(lazy launch()) would say eval at most once no matter how f is defined.
Other syntaxes where people want something evaluated in a handy scope and order are early definitions and leading midstream assignment in for comprehensions.
for (lazy x = launch()) f(x) or for (lazy x = launch() ; ok <- f(x)) yield ok
or without the lazy for exactly-once.
som-snytt, how about if ‘lazy’ became syntax for creating a Function0, and we remove by-name parameters?
val x = lazy {}
f(x) //calls Function0[A] variant, i.e. by-name overload
vs
val x = {}
f(x) //calls A variant, i.e. concrete overload
where {} is some block that returns an A.
On second thought, “lazy” probably isn’t the best keyword, since it implies that the block will be evaluated only once. Anyone disagree or have another idea?
Maybe “thunk”, if we want to be Haskell-ey.
“Thunk” isn’t any better, since they’re only evaluated once.
How about “yield”? A “yield” without a “for” would be a Function0.
val x = yield println("hi") | https://contributors.scala-lang.org/t/pre-sip-ideas-for-by-name-exlicit-syntax-for-caller/873 | CC-MAIN-2017-43 | refinedweb | 1,361 | 64.91 |
.Net technical interview questions for 2+ years
I would like to share my interview questions in the technical round for candidates with 2+ years experience .Net, as this was the second round of my interview i was asked some tricky questions which i would like to share.
The following are the technical questions asked in the Interview
1.When we write a sql query "Select 1.2" and run it in the sql query builder then what is the output we get ?
2.What is the sequence of pageloads when master page is used ?
Ans : the squence in which the pages get load when master pages are used is
Load(Page)--->Load(Master)--->LoadComplete(Page)
3.When we instantiate a class variable then what are the default properties or methods we can access through that variable other than class members and class methods ?
For Example
public class Myclass()
{
public string Name;
Public string age;
}
static void main()
{
Myclass mc = new Myclass();
mc. //--->now here what are the default methods which we can access apart for the members of class i.e, Name,Age .
}
4.What is Client ID and Unique ID in master pages and where is it used ?
5.What is the significance of "Intergrated security = true" in a connection string ?
6.What is the difference in throwing exceptions using ex.message and throw ?
Finally few more questions were asked on Javascript.
It is a good guide.Thank you.It helped me a lot. | http://www.dotnetspider.com/resources/43714-Net-technical-interview-questions-years.aspx | CC-MAIN-2017-04 | refinedweb | 245 | 74.79 |
In which topic/lesson is the
import.math covered? I think I either have a gap in my notes or I just haven’t covered it for some reason.
Import.math topic - where is it?
In which topic/lesson is the
1 Like
It might come up before the Modules unit, but for sure it is also covered in that unit.
It won’t be written like that, at any length.
import math
All imports should occur at the start of the script (top lines).
We access that namespace by module name dot method name:
math.sqrt() PI = math.pi
Note that
math.pi is a constant, not a method, so we do not invoke it.
Python 2.x Mathematical functions
Python 3.x Mathematical functions
2 Likes | https://discuss.codecademy.com/t/import-math-topic-where-is-it/393273 | CC-MAIN-2019-47 | refinedweb | 128 | 78.45 |
28 October 2011 07:03 [Source: ICIS news]
GUANGZHOU (ICIS)--PetroChina announced on Friday that it has signed an agreement with the stakeholders of South Oil Exploration and Development to buy out the company for yuan (CNY) 1.67bn ($263m).
Under the agreement signed on 27 October, PetroChina will buy a 95% stake held by CNPC Exploration and Development (CNPC E&D) for CNY1.58bn and CNPC Central Asia's 5% stake for CNY83m, PetroChina said in a statement on its website.
The parties aim to close the deal before 31 December 2011, it said.
PetroChina said the acquisition will help it integrate and better manage its upstream exploration operations.
South Oil engages primarily in oil and gas exploration in south ?xml:namespace>
CNPC E&D, CNPC Central Asia and PetroChina are subsidiaries of China National Petroleum Corp (CNPC).
($1 = CNY6.36)
For more on PetroChina, | http://www.icis.com/Articles/2011/10/28/9503609/petrochina-to-buy-out-south-oil-exploration-and-development.html | CC-MAIN-2014-52 | refinedweb | 146 | 62.58 |
Hello all,
I work for a small, private university in a 95% windows environment. Of our around 500 machines, we have probably 30 or so Macs, used primarily in our Art department. (Cliche, I know). We currently authenticate in AD on all machines, our macs included. Other than user authentication, we have little administrative control over these machines.
We're installing ten new Mac's in a Design lab we're building and I was wondering if there would be a benefit of setting up a Mac OS server so we can centrally manage this new lab, as well as other faculty machines.
We have little actual Mac knowledge, but definitely willing to learn. Any advice would help!
Thanks!
Cris Crane
11 Replies
I am in the same boat as you. God damn Art department and their iMacs. Always a god damn issue. I dont hear a peep from the Windows users in the same department.
But anywho, I am going to be making the recommendation to grab a mac mini and load the server OS onto it to manage the items.
David,
That would be the hope, yes. This is a semi-public classroom that would have open lab hours, ergo, free use. Unlike our faculty, which don't usually have issues (that they tell us about, at least), these would be student used, and probably more prone to issues.
Bringing the other machines under the fold w/ updates, or being able to add iOS devices, would be an added perk.
Cris
I would actually recommend this option instead of adding a Mac server. We can from a Mac and Windows split environment which was a nightmare until we switched to ExtremeZ-IP which solved 99% of our share and permission issues. Now we are just dealing with the fact that the artist keeping creating larger and larger files which is chewing through our storage. Adding a Mac server in a Windows AD environment really doesn't add anything besides complexity.
A Mac Mini would be an inexpensive addition for you for Management. Are all the devices on Mavericks or Yosemite? The old Workgroup Manager was used for the 10.8 and below. New ones are managed via Profile Manager
You actually don't really need a Mac Mini. You just download the Server App on a Yosemite computer and poof, it's a server
The Acronis product seems limited, and based on my reading of the OP's post, doesn't help as it only does stuff with fileshares.
Actually it really is not limited. Also as I mentioned in my second post Acronis Advanced allows you to manage the security, apps, users etc without adding a Mac server that will cause more headaches then it is worth.
We have two Mac labs and a handful in our Library. We also purchased a Mac Server about 3 years ago.
Honestly, we don't want it anymore. It really doesn't do a whole lot for us. We have mostly used it for a Network Time Machine (Synology does that) and Apple Remote Desktop (ScreenConnect does that).
It is by far the most finicky server on campus. I have to reboot it at least once a week. I am about to go Office Space on this thing.
I setup the imaging process from it when I first set it up, but it really didn't work that great .Way more temperamental than WDS. Ultimately I just ended up using Time Machine and a USB 3.0 drive. Was way faster.
I am sure there is more to leverage, but if you aren't super Mac-centric the workflows don't really make any sense (in my opinion). To me unless you are a serious Mac-head and building a Mac-centric network, you don't get a whole lot of bang-for-your-buck.
Just an opinion.
We have a similar environment. We added a Mac server and use it for:
- Caching Service (think WSUS for everything Apple, but its hands-off)
- DeployStudio (how we deploy OS X images)
- ARD (we use it to wake Macs, and install software or run Unix commands)
We had other lofty ideas, but in the end this is all we use. Everything else is done on Windows servers.
The minimal cost of a server will help if you want to do the basics as suggested by jason jackson
All the stuff he mentions is excellent and vital (especially deploy studio which is awesome)
But if you want proper control you need something like JAMF casper (probably not cost effective for a limited number of Macs) or use Centrify which gives you GPO like controls from inside AD with no schema changes required | https://community.spiceworks.com/topic/1081767-benefits-of-adding-a-mac-os-x-server-to-our-current-ad-environment | CC-MAIN-2020-50 | refinedweb | 789 | 72.26 |
Change background of div based on value of div
change background color using javascript function
javascript onclick change background color of div
change background color on button click in javascript
javascript program to change background color using array
javascript get background color
javascript change font color based on value
toggle background color javascript
Trying to get this javascript to read the value of the div "flow-hold" and change the background color based on the value.
I have a div named flow hold with a value of 132 for example, that I would like to see green because it is less than the 200 threshold. If the value exceeds the threshold, I would like it to be red.
<div class="flow-hold">132</div> <script type="text/javascript"> $('.flow-hold'), function(){ if($(this).val()>=200){ $('.flow-hold').css({"background-color":"red"}); } else { $('.flow-hold').css({"background-color":"green"}); } }); </script>
try this simple and easy:
$('.flow-hold').each(function() { if (parseInt($(this).text()) >= 200) { $(this).css("background-color","red"); } else { $(this).css("background-color","green"); } });
HTML DOM Style backgroundColor Property, the background color. Look at CSS Color Values for a complete list of possible color values Set a background color of a specific <div> element: document. JavaScript - Change Div Background Using Javascript - Free JavaScript Tutorials, Help, Tips, Tricks, and More. JavaScript - Change Div Background Using Javascript - AllWebDevHelp.com Close Window
If you want to do it on page load you could use your Back-End technology to assign a CSS class with demanded color according to the threshold.
For example, in PHP it would be:
<div class="flow-hold <?=($threshold>=200)?'bg-red':'bg-green'?>">132</div>
In your CSS file:
bg-red{ background-color: red; } bg-green:{ background-color: green; }
However, if you want to do it on client-side, you have to allocate an exact action to it, for instance:
<div class="flow-hold">132</div> <script type="text/javascript"> $('.flow-hold').on('hover', function(){ if($(this).val()>=200){ $('.flow-hold').css({"background-color":"red"}); } else { $('.flow-hold').css({"background-color":"green"}); } }); </script>
CSS Backgrounds, The opacity property specifies the opacity/transparency of an element. It can take a value from 0.0 - 1.0. The lower value, the more transparent: opacity 1. I want to change the background of my main div depending on the time of day. Right now this code works for two time of day, day and night but it only works on the "body" tag not on a div.
actually your problem are the accessors that you are using. check that if you use
JQuery and get the items by class you will get an
array with all the divs containing that
class.
so here you have a working example of what you wanted to achieve taking into account what I told before.
NOTE: your code doesn't run by itself, next time please fix it. NOTE2: note that I didn't do a lot of changes and it started to work.
function changeBackground() { let div = $('.flow-hold')[0]; if (div.innerText >= 200) { $('.flow-hold').css({ "background-color": "red" }); } else { $('.flow-hold').css({ "background-color": "green" }); } } changeBackground();
<script src=""></script> <div class="flow-hold">132</div>
Show Hide DIV Based on Dropdown Selection in jQuery, How to show and hide div elements based on dropdown selection in jQuery a select box using the jQuery change() method in combination with the show() and hide() methods. The div boxes in this example are hidden by default using the CSS display property which value is set to none . .green{ background: #228B22; } I am trying to make my basket button have a circular div background turn blue after an item is added to the basket, so far the add to basket function is working perfectly with ajax I just can't somehow toggle background from none to display based on for example if the basket has 1 or more items the background needs to be blue and if the basket
You can use the script below:
$(document).ready(function(){ var value = parseInt($('.flow-hold').html()); if(value >= 200){ $('.flow-hold').css("background-color","red"); } else { $('.flow-hold').css("background-color","green"); } });
How to Change the Background Color of a Web Page Using , You can easily change the background color of a webpage i.e. the <body> element or any other element dynamically by using its style property in JavaScript.
I believe you intended to use the
.each( function ) jQuery method, where the function should only handle one element at a time, so it shouldn't lookup
$('.flow-hold') again, since there can be more than one element with that class.
You should also use the
.text() method, not the
.val() method.
$('.flow-hold').each(function() { if ($(this).text() >= 200) { $(this).css({"background-color":"red"}); } else { $(this).css({"background-color":"green"}); } });
Since you are setting the same property in both cases, you can also use the implicit looping of the
.css( propertyName, function ) method:
$('.flow-hold').css("background-color", function() { return ($(this).text() >= 200 ? "red" : "green"); });
How to change an element color based on value of the color picker , How to convert an Object {} to an Array [] of key-value pairs in JavaScript? To change the color of our element based on the value of color picker we have to use onclick() event of the element and change its CSS background-color: black;. have a table displayed by a web Part with a td section having a class ms-vb2 and inside that td there is a div. Now i want to make the background color changing the color of the td based on the value of containing div - jQuery Forum
jQuery Change CSS Dynamically, Change Specific CSS Element You may wish to just extend a style based upon it's current value. Common Background CSS Changes. Re: dynamically setting the css value Jul 18, 2009 01:58 AM | nb123 | LINK anzer,i wud not know the theme in advance,to create the theme file accordingly,also in my case its not practical to have numerous files per login in my case.So,My goal is to read the color scheme for a given user from database and be able to assign it to style elements
javascript Change div color based on controller value, I would create a method on your controller to expose the color value to the page in lieu of a complicated IF() or CASE() statement written directly in the page. How to Show and Hide div elements using radio buttons? In order to display data/content of a specific element by selecting the particular radio button in jQuery we can use the following two methods: hide() methods: This method is used to hiding the syntax or the element of html that you want to hide.
Use CSS to change the style of each row depending on the content , Display element B if element A's attribute is empty; 3. Display and style elements depending on their value. 1. Display background:lightgrey } .no_grades{ okey, Suppose you want to change your div styling by some condition like below: [code]if($condition==1){ $style='style="background: blue;"'; }else{ $style='style
- How is the value of "flow-hold" being changed? If it's coming from the server this way, just assign a class to it that gives the desired background color.
- Your JavaScript is invalid, it has unbalanced
()parenthesis. Error is around
, function(). Did you intend to write
.each(function()?
- @Philip Are you really asking how to write an
else if? Or chaining ternary operators? Really?!? ---
txt < 100 ? "green" : txt < 200 ? "yellow" : "red" | http://thetopsites.net/article/50458919.shtml | CC-MAIN-2020-45 | refinedweb | 1,264 | 63.09 |
I've been working on connecting my ESP8266 to AWS IoT over SSL. I've managed to overcome all the obstacles related to certificates and my code 'works'. The only issue is that the initial connection initialization takes about 30 seconds. As my use case is to send a single measurement to the broker, go to deep sleep, and send it again, the MQTT connection is re-established every time.
I tested the same solution against a local mosquitto, without SSL and it works like a charm. (Un)fortunately, AWS only allows TLS connections.
My code is very simple:
Code: Select all
from umqtt.simple import MQTTClient # Read cert and private key files certificate = ... private_key = ... mqtt_client = MQTTClient( client_id=mqtt_client_id, server=mqtt_host, port=8883, ssl=True, ssl_params={ "cert": certificate, "key": private_key } ) print('Connecting to AWS IoT Core...') mqtt_client.connect() client.publish('foo', 'bar', qos=1)
Does anyone have suggestions on how to improve this? | https://forum.micropython.org/viewtopic.php?f=16&t=9443 | CC-MAIN-2021-04 | refinedweb | 153 | 57.37 |
Anemic Domain ModelArash Bijanzadeh Mar 9, 2008 7:47 PM
This question is not directly related to Seam. But because the Seam generated source code uses this anti-pattern. I wanted to ask it here and hopefully get some feed back to illuminate my brain in this matter.
If I understand the pattern correctly it emphasize to put domain related logic in the Domain Objects.
So my POJOs will be more than just getter-setter and some hibernate validation logic.
On the other hand pattern says that I should not put my business logic in the domain classes.
When I think about it, the difference between business logic and domain logic gets completely blurry. After all, all the logic we got, even in the DB layer is related to the business!
On the other hand I have this feeling that putting the for example validation logic inside the domain objects feels good. But considering the fact that we - as in Seam - put all our database related operations in other layer, and some of the logic needs these kind of functionality ( ie. a record validity is based on the some conditions on other records); then I will end up with having recursive dependency between my Domain Layer and my DAL.
Any thought on this
1. Re: Anemic Domain ModelGavin King Mar 10, 2008 5:31 AM (in response to Arash Bijanzadeh)
I think you should stop thinking about somebody's buzzwordy
patternsand
anti-patternsand start thinking about where you should write code in order to end up with a truly powerful and re-usable domain model.
What I usually do is put business logic that uses only the state of the entity and its related entities on the entity. Application logic that calls external APIs (entity managers, services, etc) does not belong on the domain model, since it is usually not part of my model of the business domain, and is by nature much less reusable than the domain model.
But the main thing is to be practical and stop paying too much attention to lame
patternstalk.
2. Re: Anemic Domain ModelAlex Savitsky Mar 10, 2008 2:42 PM (in response to Arash Bijanzadeh)
Gavin King wrote on Mar 10, 2008 05:31 AM:
Application logic that calls external APIs (entity managers, services, etc) does not belong on the domain model, since it is usually not part of my model of the business domain
Sometimes it is - say, a business rule could dictate the removal of some child collection elements based on a change in (not deletion of!) parent element. Since removing a child element from collection doesn't trigger its deletion from the DB, there are only two options left - either to move the whole rule into the
Application logic that calls external APIspart and out of the domain model, or to expose the EM to the entity beans, DDD-style. I opted for the latter approach, adding
protected static EntityManager getEntityManager() { return (EntityManager) Component.getInstance("entityManager"); }
to the base entity class. It's ugly and hardcoded, but it works.
3. Re: Anemic Domain ModelKeith Naas Mar 10, 2008 4:16 PM (in response to Arash Bijanzadeh)
Or, you could use JPA cascades to cascade the delete or use the Hibernate extensions for Cascaded if you also need orphan delete :)
Using the entityManager directly inside of the domain model seems like a dangerous use of it.
4. Re: Anemic Domain ModelAlex Savitsky Mar 10, 2008 5:32 PM (in response to Arash Bijanzadeh)
Keith Naas wrote on Mar 10, 2008 04:16 PM:
Or, you could use JPA cascades to cascade the delete or use the Hibernate extensions for Cascaded if you also need orphan delete :)
Last time I checked, cascading delete could only work on parent object deletion. My case is a cascading delete triggered by an UPDATE of parent object.
5. Re: Anemic Domain ModelKeith Naas Mar 10, 2008 5:47 PM (in response to Arash Bijanzadeh)
Nope.
Directly from the docs - hibenate has been this way for as long as I've used it.
DELETE_ORPHAN applies only to @OneToMany associations, and indicates that the delete()/remove() operation should be applied to any child object that is removed from the association. In other words, if a child is dereferenced by a persistent parent and if DELETE_ORPHAN is used, the "orphaned" child is deleted.
6. Re: Anemic Domain ModelFrancisco Peredo Mar 10, 2008 6:03 PM (in response to Arash Bijanzadeh)
Hi!
Perhaps what you need is not POJO persistence... (or at least not
onlyPOJO persistence, but something that also gives you bussines objects...
Something like EOF
is the closest thing I know that works with that style of programming might be Apache Cayenne (I wonder if it will be possible to integrate it with Seam when the version with JPA support is completed). Another possible option (but for .NET) could be ECO.
On the other hand, while programming gets very
object oriented and elegantsometimes it also makes it too easy to make really bad decisions performance wise... (it is also interesting to note that none of this project are AFAIK as
community successfulas Hibernate)
I see a lot of potential to avoid anemic domain models in LINQ, I think many if this
anemia problemswill dissapear when the LINQ support for NHibernate gets finished... and Java programmers (like us) get so envious of what can be done with LINQ+NHiberante in C# that somehow something like LINQ for NHibernate will get ported in to Java and included in the next JPA release...
Then we will have almost-really-true transparent persistence... In the mean time, I really enjoy working with hibernate...
7. Re: Anemic Domain ModelAlex Savitsky Mar 10, 2008 6:08 PM (in response to Arash Bijanzadeh)
Oh, sorry, I see it now - thanks. I usually try to avoid using provider-specific extensions, but this feature might be worth deviating from JPA core.
Still, I'm not convinced that all domain-related logic could be coded up without referencing the EM. Say, I do have an example, where a creation of an entity M triggers creation of a number of child entities S, and there should be one S created for each record in yet another table W... well, I don't see how this could be done without a ref to EM, short of passing a list of W's to the constructor...
8. Re: Anemic Domain ModelKeith Naas Mar 10, 2008 6:40 PM (in response to Arash Bijanzadeh)
Chapter 5. Entity listeners and Callback methods
As per avoiding provider-specific extensions, the architect in me agrees with you, but the pragmatist in me says: don't reinvent the wheel. Some of the extensions are actually supported by other JPA implementations, they just never made it into the spec.
Real world example of avoiding extensions:
Hibernate has a lovely set of classes for doing complex Criteria. We can create really complex dynamic queries with minimal code. JPA doesn't have a lot of this functionality (e.g. Restrictions) so we decided to code up a bunch of standards based stuff that in the end look much like Hibernate Restrictions. In hindsight, it was a waste of our time. We could have had the whole thing done in 1/10 the time and spent that extra time working on additional functionality. In addition, how likely are we to ever deploy that application to another JPA implementation? The only reason would be if Hibernate were to disappear, and if that were to happen, we would have much bigger fish to fry than having non standard code bases.
9. Re: Anemic Domain ModelArash Bijanzadeh Mar 10, 2008 6:58 PM (in response to Arash Bijanzadeh)
INHO entity Listener or another service class does not make any difference here; we are still dealing with the anemic domain classes.
On the other hand if I want to have a reference to EM in domain objects, why not write the whole persistence methods inside the same class? Why do need another class?
10. Re: Anemic Domain ModelAlex Savitsky Mar 10, 2008 7:42 PM (in response to Arash Bijanzadeh)
Except that EntityListener doesn't have any more references to EM than an entity itself does, either, so we're back to square one - service locators and such... | https://developer.jboss.org/thread/180807 | CC-MAIN-2018-17 | refinedweb | 1,385 | 56.79 |
Sometimes you get a chance to combine helping out your family with a nice hobby project..
In this case my father in law was looking for a lighting system for his bird breeding cages. A daylight simulation system to be exact. He asked me to take a look at a website which sells such systems, since he wanted to know what he needed to order. After a quick look at those websites and seeing their pricing.. I convinced my father in-law I would develop and install the system myself.. He would get his lighting, I would have a new hobby project!
Daylight-simulation systems
The requirements for a daylight simulation system are simple: lights should gradually (say in 20 minutes) increase to a set high intensity in the morning, stay at that intensity during the day, gradually decrease to a set lower intensity in the evening, and stay at the low intensity during the night.
Other ‘non-functional’ requirements of such systems: the light should not flicker (this is stressful for the birds), the dimming should be smooth (again related to stress), the system should be reliable..
This instructable describes how I built this system based on an Arduino, some N-channel NPN transistors, a real time clock, a character LCD and some cheap LEDs from eBay.
A sidenote: The birds are only in the cages for breeding, the remainder of the year they are in an outside bird sanctuary. So no animals were harmed for making this instructable!
I’ve submitted this project to the 123D Circuits Contest and the 2014 makerlympics (both pending approval). So if you like this project: please vote for it! Thanks!
Step 1: Bill of materials
The base of the system is an Arduino Duemillenova. I think a Uno should work just fine. If you are considering to use a Leonardo or Mega: the code sets special registers in the Arduino.. these might be different for these boards!
furthermore the system uses:
- an Arduino experimenting cape
- a 16×4 character LCD (HD44780)
- an I2C serial display adapter (or just get a serial LCD)
- BD135 transistors (any NPN N-channel will do. Power MosFets would be even better)
- a 7809 9v voltage regulator (12v to 9v for the Arduino)
- A ds1302 RTC module
- some capacitors and resistors
- Cool white LED modules (12v led strips will also do)
- an auto-reset fuse ( or normal fuse if you like)
- Some switches (if you want to switch off unused cages). I used:
- a 12v power supply (over dimensions). I used a 3.5A supply for 18 x 4 LEDs (total +- 18 watts)
- A case: I used a Fibox TAM201610
I think everything combined including shipping cost about 85 euro’s
All items were sourced online from dealextreme, eBay, Conrad etc.. but any electronics store would do.
A note on ‘daylight’ LEDs
According to bird breeder forums and stores: birds need special daylight LEDs. Maybe this is true (I do not want to start a religious discussion), but to me such definitions feel a bit like high-end audio discussions…
I’ve seen special birdkeeper websites showing off ‘home developed’ LED units for which the CE marking is of the ‘China Export’ type. A quick search on eBay revealed that the advertised LEDs (which are sold at special discount prices of 5 EUR per unit) very much resemble ‘Cool White store lighting’ LED chains sold for around 10USD / 20 units. Therefore I feel that at least some of the advise is a sneaky way to overprice the LEDs.
Step 2: Power the Arduino and LEDs
A schematic of supplying power to the arduino via a voltage regulator IC. Note that the same power supply can directly be used to power the LEDs without a voltage regulator.
Note that since the number of available components is still a bit limited, the 9v battery represents a power supply ( > 9v) and the PNP transistor represents a 7809 voltage regulator IC. The schematic view gives the clearest representation.
Be sure to use a power supply which can easily supply the the current you need to drive all your LEDs. I started out with a 12V / 2A power supply from some equipment that I no longer had. This seemed OK in the beginning, but resulted in a lower brightness and an unreadable LCD after about a day of testing!
Step 3: LED dimming
Dimming/fading of leds is the key part of the daylight simulation system. Leds can be faded by supplying a PWM signal instead of a DC signal. An example of this is known to most arduino owners: The ‘fade’ example. The only thing you need for this is a simple LED and a resistor to limit the current through the circuit.
The same code can be used for fading a LED strip instead of a single LED. When powering or fading a LED strip, the voltage or the current that can be supplied by an Arduino pin are no longer sufficient. Therefore an n-channel NPN transistor is introduced. A very common transistor for this is the BD135. The current that can be supplied by this LED is limited (the TO220 type I used for this can supply a maximum of 1A). If more power is needed, a Power MOSFET can be used.
An example circuit is shown below:
Here a 9V battery is used to power a led which is controlled by an Arduino. Here, the 9v battery represents any type of external power supply. Note that a 10k external puldown resistor is used to keep the signal low until the arduino supplies a signal on Pin 9. Also, in case you are powering a LED strip, the current limiting resistors are already integrated in the strip itself and can be left out.
The above example does not take into account two things:
- The relation between the pulse width and the (perceived) LED brightness is not linear, but logarithmic (or at least: logarithmic is a good enough approximation)
- The default PWM frequency is rather low, this might disturb the birds if they’re in this light all day
Google is your friend, and there are a lot of topics covering fast PWM and logarithmic LUTs for arduino, so you don’t have to re-invent the wheel. My main source of inspiration:…
So here’s some example code which uses a logarithmic LUT and fast PWM on pin 9:
Note that this works on my duemillanova clone, and might not work on Arduino mega, due, leonardo etc.
<p>/* BirdLight</p><p>Example of a 12bit logarithmic LUT & Fast PWM for gently increasing / decreasing brightness during day to night and night to day transitions. </p><p>Code mostly retrieved from: <a href="">....</a> </p><p>Copyright 2013 - Patrick Bronneberg */ /*-----( Configuration )-----*/ const double Night_Level = 5.0; const double Day_Level = 99.0; const int LED_PWM_PIN = 9; // the pin that the fading LEDs are attached to</p><p>/*-----( Declare Constants )-----*/ const int PWMMax = 4095; // Set maximum brightness for PWM // Define a logarithmic LUT for PWM dimming const int PWMLut[] = {0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,9,9,9,10,11, 13,15,16,17,19,21,23,25,26,27,29,31,32,33,35,37,39,41,43,45,47,49,51,53,55,57, 60,63,66,69,71,74,77,80,84,88,91,94,98,102,106,110,114,118,123,128,133,138,143, 148,154,160,166,172,179,185,192,199,207,214,222,230,239,248,257,266,276,286,296, 306,317,329,341,353,366,379,392,406,421,436,451,466,483,500,518,536,555,574,595, 616,638,661,684,707,732,757,784,811,840,869,900,931,964,997,1032,1067,1105,1144, 1184,1224,1267,1311,1357,1404,1453,1503,1555,1609,1665,1722,1782,1843,1907,1973, 2042,2112,2185,2260,2339,2419,2503,2589,2679,2771,2867,2965,3069,3174,3284,3397, 3514,3629,3761,3905,4024,4079,4094}; //Define the size of the lut: note that integers are 16bits so 2 bytes const int lutSize = sizeof(PWMLut)/2;</p><p>/*-----( Declare global variables )-----*/ int ledBrightnessLevel = 0; int dayLevel = 0; int nightLevel = 0; boolean isDay = true;</p><p>void setup() { //Initialize the LED PWM pinMode(LED_PWM_PIN,OUTPUT); TCCR1A = (1 << COM1A1) | (1 << WGM11); // Enable Fast PWM on OC1A (Pin 9) TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10); // Mode 14 Fast PWM/ (TOP = ICR1), pre-scale = 1 ICR1 = PWMMax; //Set the TOP value for 12-bit PWM // Calculate levels from configured percentages dayLevel = LutPercentageToLevel(Day_Level); nightLevel = LutPercentageToLevel(Night_Level); }</p><p>void loop() { if (isDay) { //Decrease led brightness until we reach night level if (ChangeLedBrightness(nightLevel, -1)) { isDay = false; } } else { //Increase led brightness until we reach day level if (ChangeLedBrightness(dayLevel, -1)) { isDay = true; } } }</p><p>double LutLevelToPercentage(int lutLevel) { return lutLevel*100.0/lutSize; }</p><p>int LutPercentageToLevel(double lutPercentage) { return (int)((lutSize/100.0)*lutPercentage); }</p><p>boolean ChangeLedBrightness(int finishedLevel, int ledFadeAmount) { // set the current brightness analogWrite(LED_PWM_PIN, PWMLut[ledBrightnessLevel]); </p><p> // change the brightness for next time through the loop: ledBrightnessLevel = ledBrightnessLevel + ledFadeAmount;</p><p> //Check if dimming is finished if ((ledFadeAmount > 0 && ledBrightnessLevel >= finishedLevel) || (ledFadeAmount < 0 && ledBrightnessLevel <= finishedLevel) ) { //Finished! return true; } //Not yet finished return false; }</p>
Step 4: Adding the display
I had a 20×4 HD44780 character display lying around which I bought for less than 1 Euro on a clearance. I wanted to use this in this project, but did not want to lose 10pins of my arduino just for driving the LCD.
To overcome this issue, I used an I2C backpack for the display. This is basically an adapter which drives all pins of the LCD but only costs you 2 pins + 5V & ground on your arduino. As stated in the Bill of Materials, these backpacks can be bought for less than 3 dollars on the internet.
The downside of using such a device is that the standard Arduino character LCD library doesn’t work, and you have to browse on the internet for a while until you find a suiting replacement. The replacement I used is:F Malpartida’s NewLiquidCrystal library. which works great, so many thanks to F Malpartida of electroFUN LTD!
Unfortunately it took me 2 evenings to get the display up & running with the backpack. So watch out for the following issues
For more detail: Bird cage LED daylight simulation system | https://duino4projects.com/bird-cage-led-daylight-simulation-system/ | CC-MAIN-2021-43 | refinedweb | 1,747 | 57.3 |
Log:
Update to 0.11021
Upstream changes:
0.11021 2015-01-29
* Fix Oracle producer generating an unnecessary / at the end in case there
are no triggers
* Skip HTML tests if CGI is not installed (RT#98027)
* Fix JSON and YAML tests if the defaults have been tweaked (RT#98824)
* Fixes for parsing and producing identifiers and values that need
quoting and escaping for SQLite, MySQL, PostgreSQL, SQLServer and
Oracle (RT#90700, RT#31034)
* Add support for ALTER TABLE ... ADD CONSTRAINT to Oracle parser
* Add trigger support to Oracle parser (RT#62927)
* Fix erroneous PostgreSQL floating point type translations (RT#99725)
* Remove executable bit from Parser/JSON.pm (RT#100532)
* Update the Free Software Foundation's address (RT#100531)
* Provide default index names for SQLite (GH#45)
* Fix SQLite diffing on perl 5.8.1
* Fix multi-column indexes in Parser::DBI::PostgreSQL
* Fix array data types in Parser::PostgreSQL (GH#49)
* Fix multidimensional sizes in Parser::PostgreSQL.11020
Upstream changes:
0.11020 2014-09-02
* Fix test failure if Test::PostgreSQL is installed but not working
0.11019 2014-09-02
* Add Json and hstore types to Pg Parser (cloudinstustrie)
* Fix DROP TABLE in SQL Server Producer
* Fix Pg DBI parser test (Dagfinn Ilmari Mannsker)
* Remove spurious warnings (Matt Phillips, Wallace Reis)
* Fix MySQL producer for columns with scalar ref in 'ON UPDATE' (Wallace Reis)
* Fix handling of views in MySQL DBI parser
* Fix handling of renamed fields in SQLite diff (Peter Mottram)
* Check numeric equality of default values in numeric-type fields (Wallace Reis)
* Fix handling of renamed fields in renamed tables in Pg diff (Peter Mottram)
0.11018 2013-10-31
* Revert "Fix AUTOINCREMENT in SQLite"
0.11017 2013-10-30
* Apply quotes to fix tables that are reserved words, DBI::SQLServer (Jonathan \
C. Otsuka)
* Add DECIMAL_DIGITS to field size for scale info, DBI::SQLServer (Jonathan C. \
Otsuka)
* De-linkify XML namespace in docs (RT#81838)
* Allow both single and double quotes for values in MySQL parser
* Fix diff for altering two things per column - add ; at the end
* Call all diff methods in list context (it can be merged later)
* Fix Pg diff issue with drop constraint on primary keys
* SQLite support for SET NULL, SET DEFAULT and NO ACTION in FK clauses
* Clean up properly after Parser::DBI::PostgreSQL tests
* Fix typos in error messages
* Add SQL_TINYINT and SQL_BIGINT to the type map in
SQL::Translator::Schema::Field
* Add JSON parser and producer (Jon Jensen)
* Clean up TTSchema doc some (Gavin Shelley)
* Fix AUTOINCREMENT in SQLite (Rafael Porres Molina). | http://pkgsrc.se/databases/p5-SQL-Translator | CC-MAIN-2017-13 | refinedweb | 424 | 50.6 |
View Questions and Answers by Category
Advertisements
I have been assigned a work to read big text file and extract the data and save into database. The file size is in many GBs. We have studied the memory requirement of the application and the memory available for the Java program. For Java program max memory assigned is also a limit.
So, we have decided to read the text file line by line and the extract the data line by line. Reading the file line by line will also increase the performance of the application.
Earlier our company was using the text file for saving the data through an application developed in C++. Now we have given a job for extracting the data and save into database. Give use you kind advice and let's know how to read a large text file line by line in java?
Thanks
Hi,
The only good solution to read big text file is to read the file line by line in your Java program. Reading the file line by line will make your application much faster. The application will use less memory and work even on the computer having less amount of memory.
Since reading the file line by line is the only best method for reading a big file, developers are searching for 'Java read file line by line' on google and other search engines. Many programmers are finding difficult if they starts writing the code to read the file in one go and then process one line at a time. If you try to read a big file in memory then it your application will throw java out of memory error exception. So, it's clear that the best method of reading a big file is to read the text file line by line and then process the data.
Furthermore reading file line by line is the fastest way to read the file. It's also very easy to write code for reading the file line by line.
Here is the code example from our website:
// Open the file FileInputStream fstream = new FileInputStream("textfile System.out.println (strLine); } //Close the input stream in.close();
The above code opens the files and then uses the BufferedReader class to read the file line by line and then prints the data on console. In your real program you can process the line data and then save into database. You can also use the FileReader and BufferedReader classes to read the file line by line. Here is the code example:
import java.io.*; public class ReadFileFileReader { public static void main(String[] args) { System.out.println("Example of reading file line by line!"); System.out.println("through FileReader and BufferedReader classes"); try{ BufferedReader br = new BufferedReader(new FileReader("log.txt")); String line; while ((line = br.readLine()) != null) { // process the line. System.out.println(line); } br.close(); }catch(Exception e){ System.out.println("Error:" + e.getMessage()); } } }
Above code example uses the FileReader and BufferedReader classes to read a text file line by line and then prints the content on console.
Thanks
Hi,
Here is video tutorial of writing and testing code for reading a text file line by line.
Thanks
Thanks for good explanation.
Code discussed above can the used to read the data from a text file much faster. Above code is very easy to understandable also. After reading one line of data you can use the data and process it according to your business needs. You can also save the data into relational database if you are converting your legacy data.
Thanks
Hi, Another very important thing is the proper exception handling of the application. You should update the above code for proper exception handling and closing the resources properly.
You should properly catch all the exception of the application. For example
br.close(); throws the IOException, it must be properly handled.
You must also properly handle the FileNotFound exception, this exception is thrown by the FileReader's constructor. So, proper exception handling is very important.
Thanks
Hi,
Check this tutorial: How to read big file line by line in java?
Thanks
Hello,
The BufferedReader class is very convenient class reading the data from the resource. This helps the programmers to develop the code for reading the data very conveniently. The BufferedReader class provides a method called readLine(), which reads one line at a time from the input stream. The readLine() method returns a String.
Read more at Java Read File Line by Line - Java Tutorial.
Thanks
Hi,
There is another way to read the file line by line using the Scanner class of Java API. Read more at Line by Line reading from a file using Scanner Class.
Thanks
Hi,
All the above examples are good. You can view more tutorials at Java file examples and tutorials on Rose India website in Files Handling section.
Java API also provides classes and interfaces for reading and writing to the .properties files. Check the tutorial How to read properties file in Java.
Thanks | http://www.roseindia.net/answers/viewqa/Java-Beginners/30359-How-to-read-a-large-text-file-line-by-line-in-java-.html | CC-MAIN-2014-52 | refinedweb | 836 | 65.32 |
Did you know you can use C# to control the general-purpose I/O (GPIO) pins on your Raspberry Pi? Learn how to write a .NET app to drive an LED with this tutorial.
Wiring the Circuit
The electronics for this project will consist of a current-limiting resistor connected to a single LED in series. consider the following schematic.
Though it doesn't really matter in this simple circuit, it is good practice to connect the resistor to the anode (+) of the LED. The anode is the long leg of the LED. In my case, I am using a 470Ω resistor. If you use a lower resistance (e.g. 47Ω), your LED will be brighter. If you use a resistor with a larger resistance value (e.g. 1kΩ), your LED will be dimmer. If you don't use a resistor at all, your LED might burn out!
Connect the resistor to a GPIO pin and connect the cathode (-) of the LED to any available ground (GND) pin on your Raspberry Pi. For an overview of a Raspberry Pi's GPIO pins, review the documentation. I am using GPIO24 (pin 18) and ground pin 20.
Making LED Blink with .NET
If you have not already installed .NET on your Raspberry Pi, you will need to do that first. If you have Visual Studio Code installed on your Raspberry Pi, you can write your .NET code directly from there. I will be writing the code on my desktop computer using Visual Studio, and then I will deploy the final project to the Raspberry Pi.
Create a new Console Application targeting .NET 5.0 or later. To interface with I/O pins on your device, you must install the System.Device.Gpio Nuget Package. From the Nuget Package Manager Console, run the following command.
Install-Package System.Device.Gpio
Let's take a moment to walk through the following code. The first thing you might notice is that this program is relying on top-level statements. This is a new feature in C# 9.0 that allows you to omit a lot of boilerplate code in simple console applications and utilities.); while (true) { controller.Write(ledPin, PinValue.High); Thread.Sleep(ledOnTime); controller.Write(ledPin, PinValue.Low); Thread.Sleep(ledOffTime); }
Start by importing the requisite namespaces, including
System.Device.Gpio. Next, declare some variables that you will use when setting up and using your
GpioController. If you are driving your LED through a different pin besides GPIO24, be sure to change the value of the variable
ledPin. In this example, the LED will be on for 1 second and off for half a second.
Notice the
using keyword when declaring the
GpioController variable. A using declaration ensures the compiler properly disposes of the declared variable once the controlling scope ends. Prior to C# 8.0, you would have manually declared the scope for the disposable variable as follows.
using (GpioController controller = new()) { ... }
In our example, since the
controller has been declared in an implicit Main() method that consists of an infinite loop, it will never be disposed while the program is running. Let's add some code to make sure make sure to properly dispose of the controller if a user closes the console application using the Ctrl-c keyboard shortcut.
Console.CancelKeyPress += (s, e) => { controller.Dispose(); };
We already configured the controller to treat
ledPin (pin 24) as an output. This will allow our program to drive the value of the pin high or low depending on whether we want the LED to be on or off. The
while loop of our .NET app simple drives the pin HIGH to turn the LED on, waits 1000ms, then drives the pin LOW to turn the LED off and waits 500ms. Your final program should look similar to the following.); Console.CancelKeyPress += (s, e) => { controller.Dispose(); }; while (true) { controller.Write(ledPin, PinValue.High); Thread.Sleep(ledOnTime); controller.Write(ledPin, PinValue.Low); Thread.Sleep(ledOffTime); }
You are now ready to publish your program as a self-contained application targeting linux-arm. Once you push the file to your Raspberry Pi and launch it, your LED should begin to blink. If you need help setting up SSH on your Raspberry Pi or configuring publishing options in Visual Studio, see the Visual Studio, SSH, Raspberry Pi tutorial.
The Bottom Line
If your IoT application requires the capabilities of a full computer on a single board instead of a simple microcontroller, a Raspberry Pi is a good option. In this tutorial, you learned how to use the
System.Device.Gpio package to interact with GPIO pins on a Raspberry Pi. You connected a simple LED circuit to a Raspberry Pi and wrote a .NET 5 program to make the LED flash. Once you master the fundamentals of building IOT apps for the Raspberry Pi, | https://wellsb.com/csharp/iot/raspberry-pi-gpio-csharp-led/ | CC-MAIN-2022-21 | refinedweb | 805 | 67.15 |
our lecture on NumPy, we learned one method to improve speed and efficiency in numerical work.
That method, called vectorization, involved sending array processing operations in batch to efficient low-level code.
This clever idea dates back to Matlab, which uses it extensively.
Unfortunately, vectorization is limited and has several weaknesses.
One weakness is that it is highly memory-intensive.
Another problem is that only some algorithms can be vectorized.
In the last few years, a new Python library called Numba has appeared that solves many of these problems.
It does so through something called just in time (JIT) compilation.
JIT compilation is effective in many numerical settings and can generate extremely fast, efficient code.
It can also do other tricks such as facilitate multithreading (a form of parallelization well suited to numerical work).
The Need for Speed¶
To understand what Numba does and why, we need some background knowledge.
Let’s start by thinking about higher-level languages, such as Python.
These languages are optimized for humans.
This means that the programmer can leave many details to the runtime environment
- specifying variable types
- memory allocation/deallocation, etc.
The upside is that, compared to low-level languages, Python is typically faster to write, less error-prone and easier to debug.
The downside is that Python is harder to optimize — that is, turn into fast machine code — than languages like C or Fortran.
Indeed, the standard implementation of Python (called CPython) cannot match the speed of compiled languages such as C or Fortran.
Does that mean that we should just switch to C or Fortran for everything?
The answer is no, no and one hundred times no.
High productivity languages should be chosen over high-speed languages for the great majority of scientific computing tasks.
This is because
- Of any given program, relatively few lines are ever going to be time-critical.
- For those lines of code that are time-critical, we can achieve C-like speed using a combination of NumPy and Numba.
This lecture provides a guide.
a, b = 10, 10 a + b
20
Even for this simple operation, the Python interpreter has a fair bit of work to do.
For example, in the statement
a + b, the interpreter has to know which
operation to invoke.
If
a and
b are strings, then
a + b requires string concatenation
a, b = 'foo', 'bar' a + b
'foobar'
If
a and
b are lists, then
a + b requires list concatenation
a, b = ['foo'], ['bar'] a + b
['foo', 'bar']
(We say that the operator
+ is overloaded — its action depends on the
type of the objects on which it acts)
As a result, Python must check the type of the objects and then call the correct operation.
This involves substantial overheads.
#include <stdio.h> int main(void) { int i; int sum = 0; for (i = 1; i <= 10; i++) { sum = sum + i; } printf("sum = %d\n", sum); return 0; }
The variables
i and
sum are explicitly declared to be integers.
Hence, the meaning of addition here is completely unambiguous.
Summing with Compiled Code¶
In C or Fortran, these integers would typically be stored in an array, which is a simple data structure for storing homogeneous data.
Such an array is stored in a single contiguous block of memory
- In modern computers, memory addresses are allocated to each byte (one byte = 8 bits).
- For example, a 64 bit integer is stored in 8 bytes of memory.
- An array of $ n $ such integers occupies $ 8n $ consecutive memory slots.
Moreover, the compiler is made aware of the data type by the programmer.
- In this case 64 bit integers
Hence, each successive data point can be accessed by shifting forward in memory space by a known and fixed amount.
- In this case 8 bytes
Summing in Pure Python¶
Python tries to replicate these ideas to some degree.
For example, in the standard Python implementation (CPython), list elements are placed in memory locations that are in a sense contiguous.
However, these list elements are more like pointers to data rather than actual data.
Hence, there is still overhead involved in accessing the data values themselves.
This is a considerable drag on speed.
In fact, it’s generally true that memory traffic is a major culprit when it comes to slow execution.
Let’s look at some ways around these problems.
import random import numpy as np import quantecon as qe
Now let’s try this non-vectorized code
qe.util.tic() # Start timing n = 1_000_000 sum = 0 for i in range(n): x = random.uniform(0, 1) sum += x**2 qe.util.toc() # End timing
TOC: Elapsed: 0:00:0.47
0.4725649356842041
Now compare this vectorized code
qe.util.tic() n = 1_000_000 x = np.random.uniform(0, 1, n) np.sum(x**2) qe.util.toc()
TOC: Elapsed: 0:00:0.02
0.02841973304748535
The second code block — which achieves the same thing as the first — runs much faster.
The reason is that in the second implementation we have broken the loop down into three basic operations
- draw
nuniforms
- square them
- sum them
These are sent as batch operators to optimized machine code.
Apart from minor overheads associated with sending data back and forth, the result is C or Fortran-like speed.
When we run batch operations on arrays like this, we say that the code is vectorized.
Vectorized code is typically fast and efficient.
It is also surprisingly flexible, in the sense that many operations can be vectorized.
The next section illustrates this point.
np.cos(1.0)
0.5403023058681398
np.cos(np.linspace(0, 1, 3))
array([1. , 0.87758256, 0.54030231])
By exploiting ufuncs, many operations can be vectorized.
For example, consider the problem of maximizing a function $ f $ of two variables $ (x,y) $ over the square $ [-a, a] \times [-a, a] $.
For $ f $ and $ a $ let’s choose$$ f(x,y) = \frac{\cos(x^2 + y^2)}{1 + x^2 + y^2} \quad \text{and} \quad a = 3 $$
Here’s a plot of $ f $
import matplotlib.pyplot as plt %matplotlib inline from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib import cm def f(x, y): return np.cos(x**2 + y**2) / (1 + x**2 + y**2) xgrid = np.linspace(-3, 3, 50) ygrid = xgrid x, y = np.meshgrid(xgrid, ygrid) fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, projection='3d') ax.plot_surface(x, y, f(x, y), rstride=2, cstride=2, cmap=cm.jet, alpha=0.7, linewidth=0.25) ax.set_zlim(-0.5, 1.0) plt.show()
To maximize it, we’re going to use a naive grid search:
- Evaluate $ f $ for all $ (x,y) $ in a grid on the square.
- Return the maximum of observed values.
Here’s a non-vectorized version that uses Python loops
def f(x, y): return np.cos(x**2 + y**2) / (1 + x**2 + y**2) grid = np.linspace(-3, 3, 1000) m = -np.inf qe.tic() for x in grid: for y in grid: z = f(x, y) if z > m: m = z qe.toc()
TOC: Elapsed: 0:00:3.06
3.0612900257110596
And here’s a vectorized version
def f(x, y): return np.cos(x**2 + y**2) / (1 + x**2 + y**2) grid = np.linspace(-3, 3, 1000) x, y = np.meshgrid(grid, grid) qe.tic() np.max(f(x, y)) qe.toc()
TOC: Elapsed: 0:00:0.00
0.0075800418853759766
Pros and Cons of Vectorization¶
At its best, vectorization yields fast, simple code.
However, it’s not without disadvantages.
One issue is that it can be highly memory-intensive.
For example, the vectorized maximization routine above is far more memory intensive than the non-vectorized version that preceded it.
Another issue is that not all algorithms can be vectorized.
In these kinds of settings, we need to go back to loops.
Fortunately, there are nice ways to speed up Python loops.
Numba¶
One exciting development in this direction is Numba.
Numba aims to automatically compile functions to native machine code instructions on the fly.
The process isn’t flawless, since Numba needs to infer type information on all variables to generate pure machine instructions.
Such inference isn’t possible in every setting.
But for simple routines, Numba infers types very well.
Moreover, the “hot loops” at the heart of our code that we need to speed up are often such simple routines.
Prerequisites¶
If you followed our set up instructions, then Numba should be installed.
Make sure you have the latest version of Anaconda by running
conda update anaconda from a terminal (Mac, Linux) / Anaconda command prompt (Windows).
An Example¶
Let’s consider some problems that are difficult to vectorize.
One is generating the trajectory of a difference equation given an initial condition.
Let’s take the difference equation to be the quadratic map$$ x_{t+1} = 4 x_t (1 - x_t) $$
Here’s the plot of a typical trajectory, starting from $ x_0 = 0.1 $, with $ t $ on the x-axis
def qm(x0, n): x = np.empty(n+1) x[0] = x0 for t in range(n): x[t+1] = 4 * x[t] * (1 - x[t]) return x x = qm(0.1, 250) fig, ax = plt.subplots(figsize=(10, 6)) ax.plot(x, 'b-', lw=2, alpha=0.8) ax.set_xlabel('time', fontsize=16) plt.show()
To speed this up using Numba is trivial using Numba’s
jit function
from numba import jit qm_numba = jit(qm) # qm_numba is now a 'compiled' version of qm
Let’s time and compare identical function calls across these two versions:
qe.util.tic() qm(0.1, int(10**5)) time1 = qe.util.toc()
TOC: Elapsed: 0:00:0.07
qe.util.tic() qm_numba(0.1, int(10**5)) time2 = qe.util.toc()
TOC: Elapsed: 0:00:0.08
qe.util.tic() qm_numba(0.1, int(10**5)) time2 = qe.util.toc()
TOC: Elapsed: 0:00:0.00
time1 / time2 # Calculate speed gain
204.36588459099556
That’s a speed increase of two orders of magnitude!
Your mileage will of course vary depending on hardware and so on.
Nonetheless, two orders of magnitude is huge relative to how simple and clear the implementation is.
@jit def qm(x0, n): x = np.empty(n+1) x[0] = x0 for t in range(n): x[t+1] = 4 * x[t] * (1 - x[t]) return x
This is equivalent to
qm = jit(qm).
How and When it Works¶
Numba attempts to generate fast machine code using the infrastructure provided by the LLVM Project.
It does this by inferring type information on the fly.
As you can imagine, this is easier for simple Python objects (simple scalar data types, such as floats, integers, etc.).
Numba also plays well with NumPy arrays, which it treats as typed memory regions.
In an ideal setting, Numba can infer all necessary type information.
This allows it to generate native machine code, without having to call the Python runtime environment.
In such a setting, Numba will be on par with machine code from low-level languages.
When Numba cannot infer all type information, some Python objects are given generic
object status, and some code is generated using the Python runtime.
In this second setting, Numba typically provides only minor speed gains — or none at all.
Hence, it’s prudent when using Numba to focus on speeding up small, time-critical snippets of code.
This will give you much better performance than blanketing your Python programs with
@jit statements.
a = 1 @jit def add_x(x): return a + x print(add_x(10))
11
a = 2 print(add_x(10))
11
Notice that changing the global had no effect on the value returned by the function.
When Numba compiles machine code for functions, it treats global variables as constants to ensure type stability.
Numba for Vectorization¶
Numba can also be used to create custom ufuncs with the @vectorize decorator.
To illustrate the advantage of using Numba to vectorize a function, we return to a maximization problem discussed above
from numba import vectorize @vectorize def f_vec(x, y): return np.cos(x**2 + y**2) / (1 + x**2 + y**2) grid = np.linspace(-3, 3, 1000) x, y = np.meshgrid(grid, grid) np.max(f_vec(x, y)) # Run once to compile qe.tic() np.max(f_vec(x, y)) qe.toc()
TOC: Elapsed: 0:00:0.02
0.0283660888671875
This is faster than our vectorized version using NumPy’s ufuncs.
Why should that be? After all, anything vectorized with NumPy will be running in fast C or Fortran code.
The reason is that it’s much less memory-intensive.
For example, when NumPy computes
np.cos(x**2 + y**2) it first creates the
intermediate arrays
x**2 and
y**2, then it creates the array
np.cos(x**2 + y**2).
In our
@vectorize version using Numba, the entire operator is reduced to a
single vectorized process and none of these intermediate arrays are created.
We can gain further speed improvements using Numba’s automatic parallelization
feature by specifying
target='parallel'.
In this case, we need to specify the types of our inputs and outputs
@vectorize('float64(float64, float64)', target='parallel') def f_vec(x, y): return np.cos(x**2 + y**2) / (1 + x**2 + y**2) np.max(f_vec(x, y)) # Run once to compile qe.tic() np.max(f_vec(x, y)) qe.toc()
TOC: Elapsed: 0:00:0.00
0.0026471614837646484
This is a striking speed up with very little effort. | https://lectures.quantecon.org/py/numba.html | CC-MAIN-2019-35 | refinedweb | 2,234 | 67.15 |
Mixup didn’t help much in my case. Validation error stayed pretty the same (even worse for a bit, but maybe it can be slightly better after some finetuning).
Here’s what I did:
First of all I’ve preprocessed the data (normalized, categorized and fill missing if needed). Then I took a model and fed it all my dataframes (train and validation sets) to embedding layers only (so I’ve got embeddings output for all the data). Then I’ve concat these values with cont values. So to this moment I had a bunch of floats for each row of data (cat values numericalized and cont as is). This is what our NN (apart from embeddings) really gets as input. Then I’ve blended (interpolated) all the values (all independent variables are floats now and my dependent variable is a number, not a class).
def interp(var1, var2, alpha):
lam = np.random.beta(alpha, alpha)
return lam*var1 + (1.-lam)*var2
Now I can pretend that these floats are just a bunch of cont values and try to teach NN in a normal way (without preprocessing (!)).
The last step is to validate models with validation set (fed through embedding as well)
I’ve already had a function that makes all the preprocess and outputs the ‘real model input’. I’ve made it for Random Forrest with embedding case (RF vs NN) in
And… As I said I’ve got an error slightly worse than initial model (trained in a normal way).
As for clarity my dataset consists of only about 10 000 rows.
It has 53 category and 26 continuous variables.
And my task is regression, not classification. | https://forums.fast.ai/t/tabulardata-mixup/52011?page=2 | CC-MAIN-2022-27 | refinedweb | 279 | 63.29 |
Asked by:
Windows.Gaming reference
Question
Hi,
I am following the below youtube video:
It has instructions on how to add the Windows.Gaming reference to my project although it is not working for me.
I go into Add References, although under Universal Windows section it just says "No references were found in the Universal Windows SDK"
Am I missing something, do I need to install anything additional. I have Windows 10 SDK (10.0.18362.0) installed, I thought that would be all that was needed.
I am using Visual Studio 2019 and the application is for C# Windows Form Application.
Any help would be appreciated.
Thanks
All replies
Hi JayWeb,
Welcome to MSND forum.
According to your description, please try to open visual studio installer -> download "Universal Windows Platform Development" workload. And please work in Win10 environment.
If there is update information, please feel free to contact us. Windows SDK is enough, but it isn't obvious what you need to do.
If you are writing a desktop application and you want to get access to one of the objects that are available for desktop application then, as you know, no references to the Windows Runtime are added.
It is possible to add a reference using the following steps.
1) Go through the initial steps for adding a reference to your project.
2) Select Browse at the bottom on the left side.
3) Click the Browse button. The open window that appears is filtered for expected file types (.dll, .ocx and the like)
so change the file type filter to All Files (*.*)
4) Go to the path where the Windows SDK is installed (defaults to %ProgramFiles%\Windows Kits or %ProgramFiles(x86)%\Windows Kits) and go to 10\UnionMetadata\<sdk version> subdirectory. The path that it is installed to by default is shown in the screenshots above.
5) Select the file Windows.winmd and click the Add button. This will show the Reference Manager window with this file added and selected.
Now you are able to access the entire UWP namespace. So Windows.Gaming is obviously available.
This is a signature. Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.
- Proposed as answer by Lance Li-MSFTMicrosoft contingent staff Friday, August 2, 2019 3:32 AM
Hi JayWeb,
Any update for this issue? I've checked the tutorial and get the same issue like you.
So I assume the cause of the issue is the tutorial is a bit out-of-date, it may apply to VS2015 in earlier windows OS using earlier Windows SDK, but it just not work for the latest VS2019 in current Windows OS after some many new updates.
>>Am I missing something, do I need to install anything additional.
It seems that the tutorial is not supported for your current development environment. Then I suggest you can do what Darran suggests, it's a real working approach for your current situation I think.
So I proposed it as answer since I've checked this approach in Winform app, it really works for this situation. You can follow his answer to solve this issue.
In addition: Don't worry about if it's a better way to manually add reference to Windows.winmd. I've confirmed with one engineer more experienced in UWP and Xbox topic, and get the hint from him, so it should work and hope it helps:)
Sincerely Lance Li-MSFTMicrosoft contingent staff Friday, August 2, 2019 3:45 AM | https://social.msdn.microsoft.com/Forums/vstudio/en-US/cb3d494b-d893-4191-a2b8-c2352f521b03/windowsgaming-reference?forum=visualstudiogeneral | CC-MAIN-2019-47 | refinedweb | 622 | 65.52 |
Chaining asynchronous functions is a common problem across languages. JavaScript
has
Promise to deal with this, Elm has
Task, and the list goes on.
However, many real-world problems are more complex than straightforward linear
chaining. To solve this, many languages have introduced special syntactic sugar
over their chaining API.
Pseudocode
We want to measure how long an HTTP request takes. To do so, we check the time before and after the request completes and calculate the difference. In pseudocode we could say:
get the current time THEN get the user data via HTTP THEN get the current time THEN calculate the difference between the start time and end time
Elm
In Elm, both HTTP requests and getting the current time are async operations. We
can chain them with
Task.andThen. However, things are not as straightforward
as the pseudocode made it seem.
Time.now |> Task.andThen (\before -> getUserDataViaHttp) |> Task.andThen (\_ -> Time.now) |> Task.andThen (\after -> -- ??? -- no access to the before time -- in this lambda )
This is awkward because we need both
before and
after at the end of the
pipeline, but
andThen only has access to the result of the operation
immediately previous.
To get around this, we can start nesting the lambdas so the result of each step is always in scope for all the following steps. It’s really ugly but it gets the job done 😬.
timeUserRequest : Task Http.Error Int timeUserRequest = Time.now |> Task.andThen (\before -> getUserDataViaHttp |> Task.andThen (\_ -> Time.now |> Task.andThen (\after -> Task.succeed (after - before) ) ) )
Haskell
Like Elm, Haskell has a function that can be used to chain async operations (the
operator
=<<). To get around the nested lambdas we saw in the Elm example,
Haskell introduces some syntactic sugar:
do notation.
do before <- getCurrentTime _ <- getUserDataViaHttp after <- getCurrentTime return (after - before)
This desugars into a bunch of chained
=<< calls in nested lambdas. The sugared
version is much nicer to read though!
Scala
Like Elm and Haskell, Scala also has a function that can chain async operations
(theirs is called
flatMap). Like Haskell, it has a syntactic sugar for those
nested lambdas. It’s called a
for comprehension and it’s visually
really similar to Haskell’s
do notation.
for { before <- getCurrentTime _ <- getUserDataViaHttp after <- getCurrentTime } yield (after - before)
JavaScript
Like all the other languages here, JavaScript has a method for chaining async
operations (
Promise.prototype.then). It also has some syntactic sugar
(
async/await) that makes non-linear chains cleaner. If you squint a bit,
you’ll see it’s very similar to both Haskell’s
do notation and Scala’s
for
comprehensions.
Note that while getting the current time can be done syncronously in JavaScript, I’m using a function that returns a promise here so the example is similar to the ones we looked at in other languages.
const timeUserRequest = async () => { const before = await getCurrentTimeAsync() await getUserDataViaHttp() const after = await getCurrentTimeAsync() return (after - before) };
Chaining elsewhere
While chaining with
then is promise-specific in JavaScript, the other
languages examined in this article use their chaining functions for many other
constructs - not just for async operations.
For Haskell and Scala, that means that their syntactic sugar notations can be
used for all chainable structures. If you work with these languages you will
encounter the
do /
for sugar everywhere from IO operations to null-checking,
to JSON parsing. | https://thoughtbot.com/blog/chaining-events-like-a-boss | CC-MAIN-2019-47 | refinedweb | 557 | 63.7 |
In this article, we will discuss some of the essential Flask Extensions. These extensions are convenient and easy to use. So let’s look into them !!
Why do we need Flask extensions?
As we know, Flask is a micro-web framework since its core functions only include Werkzueg based WSGI, routing, and Jinja2-based Template Engine.
It can also support cookies and sessions and front-end features like JSON, static files, etc.
But this is not enough to build Full-scale Secure web applications. This is where the Flask Extensions come into the picture. With Flask-Extensions, we can perform many more tasks using the Flask framework.
There are many Flask-Extensions available. We will now look at some of the most used Flask-Extensions
Some Important Flask-Extensions
Some of the Most used Flask extensions are:
These Extensions are Python Modules, which extends the functionalities of Flask Application. Hence we can install them just like a Python library using the pip utility.
The syntax to install a Flask-Extension “flask-foo” would be:
pip install flask-foo #pip install flask-Sqlalchemy #pip install flask-wtf #pip install flask-mail #pip install flask-login #pip install flask-debugtoolbar #pip install flask-sijax
The import is also similar to the way we import a python library:
from flask_foo import <Class>, <function>...
For Flask versions greater than 0.7, you can also import extensions via flask.ext.
The syntax is:
from flask.ext import foo #sqlalchemy, login .....
You can get an error if your compatibility module is not active. To activate it, use the code:
import flaskext_compat flaskext_compat.activate() from flask.ext import foo
Once we activate it, we can use flask.ext in same way as before.
References:
- Flask SQLAlchemy:
- Flask WT Forms:
- Flask Mail:
- Flask Login:
- Flask DebugToolBar:
- Flask Sijax:
Conclusion
That’s it, guys! This was the last article in the Flask Tutorial series. Do check out our other Flask tutorials to know more about Flask.
Happy Coding !! | https://www.askpython.com/python-modules/flask/flask-extensions | CC-MAIN-2021-31 | refinedweb | 329 | 67.55 |
Following this answer I tried to get the date for last Thursday of the current month. But my code doesn't get out of loop.
from datetime import datetime
from dateutil.relativedelta import relativedelta, TH
todayte = datetime.today()
cmon = todayte.month
nthu = todayte
while nthu.month == cmon:
nthu += relativedelta(weekday=TH(1))
#print nthu.strftime('%d%b%Y').upper()
Looking at the documentation of
relativedelta
Notice that if the calculated date is already
Monday, for example, using
(0, 1)or
(0, -1)won’t change the day.
If
nthu is already Thursday then adding
TH(1) or
TH(-1) won't have any effect but result in the same date and that's why your loop is running infinitely.
I will assume maximum 5 weeks in a month and do it like following:
todayte = datetime.today() cmon = todayte.month for i in range(1, 6): t = todayte + relativedelta(weekday=TH(i)) if t.month != cmon: # since t is exceeded we need last one which we can get by subtracting -2 since it is already a Thursday. t = t + relativedelta(weekday=TH(-2)) break | https://codedump.io/share/wjeQC8cUw0Yi/1/get-the-last-thursday-of-the-current-month-using-python | CC-MAIN-2017-04 | refinedweb | 183 | 68.87 |
November 01, 2017Andrea Muttoni
We are happy to announce that lock control and query capabilities, previously launched in the US and the UK, are now also available to developers in Germany and Austria.
Developers targeting devices with locking behavior can now enable customers to issue a voice command such as "Alexa, lock the front door" (in German: "Alexa, schließe die Eingangstür ab."), or "Alexa, is the front door locked?" (in German: "Alexa, ist die Eingangstür abgeschlossen?").
The feature is currently supported with the Innogy hub in Germany with locks from Yale.
The Smart Home Skill API simplifies development efforts as everything is managed through the Alexa.ConnectedHome.Query namespace.
To get started, see the documentation on lock control and query.
To learn more about developing a smart home skill check out these resources:
Publish your skill in the Alexa Skills Store, and earn perks like an Amazon Echo Dot or an Alexa dev shirt. Check back every month for new promotions in Germany, UK, and the US. | https://developer.amazon.com/blogs/alexa/post/f679579b-f786-42ed-ae54-cf004e31ce02/alexa-is-the-front-door-locked-lock-control-and-query-for-smart-home-skills-now-available-in-germany-and-austria | CC-MAIN-2020-16 | refinedweb | 167 | 61.36 |
Python Scikit-learn: Create a Pie plot to get the frequency of the three species of the Iris data
Python Machine learning Iris Visualization: Exercise-3 with Solution
Write a Python program to create a Pie plot to get the frequency of the three species of the Iris data.
Sample Solution:
Python Code:
import pandas as pd import matplotlib.pyplot as plt iris = pd.read_csv("iris.csv") ax=plt.subplots(1,1,figsize=(10,8)) iris['Species'].value_counts().plot.pie(explode=[0.1,0.1,0.1],autopct='%1.1f%%',shadow=True,figsize=(10,8)) plt.title("Iris Species %") plt.show()
Output:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to create a Bar plot to get the frequency of the three species of the Iris data.
Next: Write a Python program to create a graph to find relationship between the sepal length and | https://www.w3resource.com/machine-learning/scikit-learn/iris/python-machine-learning-scikit-learn-iris-visualization-exercise-3.php | CC-MAIN-2021-17 | refinedweb | 158 | 55.84 |
In Python you indicate whether a function/method is private by naming it so that it starts with an _ underscore like this:
def _thisIsPrivate(): return 'a' def thisIsPublic(): return 'b'
It means that if you have these two functions in a file called
dummy.py and you do something like this:
>>> from dummy import * >>> thisIsPublic() 'a' >>> _thisIsPrivate() Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name '_thisIsPrivate' is not defined
Seems fair doesn't it. Now is there such similar naming convention and functionality in Javascript?
In many of my javascript files there will be functions with the same naming convention as Python so that I can remember which functions might be used from outside and which are only relevant inside the module's scope. But that's just me and I don't think it has an actual effect other than my personal naming convention taste.
The reason I'm asking is that I want to improve my slimmer with the new
--hardcore option. Last month I added that if you switch on
--hardcore it renames all parameters to functions from something like
document_node to
_1 and
formname to
_2. Now I want to do something similar to the functionnames too. So imagine going from:
function addParameters(param1, param2) { return _fixParameter(param1) + _fixParameter(param2); } function subtractParameters(param1, param2) { return _fixParameter(param1) - _fixParameter(param2); } function _fixParameter(param) { return param.toUpperCase(); }
to this much more whitespace efficient result:
function addParameters(_0,_1){return _a(_0)+_a(_1);} function subtractParameters(_0,_1){return _a(_0)-_a(_1);} function _a(_0){return _0.toUpperCase();}
That's a bandwidth save of 123 bytes 45%!
maybe have different 'hardcore' modes? --hardcore=1 would change local names and argument names, but --hardcore=2 would slim _ named functions. Or you could allow custom regexes for the functions to allow slimming.
Since JavaScript has no notion of a module, there is can be no "private" functions as used in your Python example (which aren't that private either: "from dummy import _thisIsPrivate; _thisIsPrivate()"). And I've never really seen functions beginning with underscores outside of OO-like programming (where technically private functions are possible:).
As for your slimmer: what about simply testing for the existence of a function of the slimmed name first? And for inspiration, you might want to have a look at other products with the same functionality ().
That's a very interesting read. I figured what one can do is to relabel all functions that are repeated by generating new code in the slimmer. So if you start with this code::
function parseSomething(z) {
...
}
function foo(x, y) {
return parseSomething(x) + parseSomething(y);
}
Then this can be revamped to this::
function A(z) {
...
}
function foo(x, y) {
return A(x) + A(y);
}
var parseSomething=A;
Not a big saving, but at least something. | http://www.peterbe.com/plog/private-functions-javascript | CC-MAIN-2015-06 | refinedweb | 473 | 53.41 |
Transforms (Direct3D 9)
The part of Direct3D that pushes geometry through the fixed function geometry pipeline is the transform engine. It locates the model and viewer in the world, projects vertices for display on the screen, and clips vertices to the viewport. The transform engine also performs lighting computations to determine diffuse and specular components at each vertex.
The geometry pipeline takes vertices as input. The transform engine applies the world, view, and projection transforms to the vertices, clips the result, and passes everything to the rasterizer.
At the head of the pipeline, a model's vertices are declared relative to a local coordinate system. This is a local origin and an orientation. This orientation of coordinates is often referred to as model space, and individual coordinates are called model coordinates.
The first stage of the geometry pipeline transforms a model's vertices from their local coordinate system to a coordinate system that is used by all the objects in a scene. The process of reorienting the vertices is called the world transform. This new orientation is commonly referred to as world space, and each vertex in world space is declared using world coordinates.
In the next stage, the vertices that describe your 3D world are oriented with respect to a camera. That is, your application chooses a point-of-view for the scene, and world space coordinates are relocated and rotated around the camera's view, turning world space into camera space. This is the view transform.
The next stage is the projection transform. In this part of the pipeline, objects are usually scaled with relation to their distance from the viewer in order to give the illusion of depth to a scene; close objects are made to appear larger than distant objects, and so on. For simplicity, this documentation refers to the space in which vertices exist after the projection transform as projection space. Some graphics books might refer to projection space as post-perspective homogeneous space. Not all projection transforms scale the size of objects in a scene. A projection such as this is sometimes called an affine or orthogonal projection.
In the final part of the pipeline, any vertices that will not be visible on the screen are removed, so that the rasterizer doesn't take the time to calculate the colors and shading for something that will never be seen. This process is called clipping. After clipping, the remaining vertices are scaled according to the viewport parameters and converted into screen coordinates. The resulting vertices, seen on the screen when the scene is rasterized, exist in screen space.
Transforms are used to convert object geometry from one coordinate space to another. Direct3D uses matrices to perform 3D transforms. This section explains how matrices create 3D transforms, describes some common uses for transforms, and details how you can combine matrices to produce a single matrix that encompasses multiple transforms.
- World Transform (Direct3D 9) - convert from model space to world space
- View Transform (Direct3D 9) - convert from world space to view space
- Projection Transform (Direct3D 9) - convert from view space to projection space
Matrix Transforms
In applications that work with 3D graphics, you can use geometrical transforms to do the following:
- Express the location of an object relative to another object.
- Rotate and size objects.
- Change viewing positions, directions, and perspectives.
You can transform any point (x,y,z) into another point (x', y', z') by using a 4x4 matrix, as shown in the following equation.
Perform the following equations on (x, y, z) and the matrix to produce the point (x', y', z').
The most common transforms are translation, rotation, and scaling. You can combine the matrices that produce these effects into a single matrix to calculate several transforms at once. For example, you can build a single matrix to translate and rotate a series of points.
Matrices are written in row-column order. A matrix that evenly scales vertices along each axis, known as uniform scaling, is represented by the following matrix using mathematical notation.
In C++, Direct3D declares matrices as a two-dimensional array, using the D3DMATRIX structure. The following example shows how to initialize a D3DMATRIX structure to act as a uniform scaling matrix.
Translate
The following equation translates the point (x, y, z) to a new point (x', y', z').
You can manually create a translation matrix in C++. The following example shows the source code for a function that creates a matrix to translate vertices.
For convenience, the D3DX utility library supplies the D3DXMatrixTranslation function.
Scale
The following equation scales the point (x, y, z) by arbitrary values in the x-, y-, and z-directions to a new point (x', y', z').
Rotate
The transforms described here are for left-handed coordinate systems, and so may be different from transform matrices that you have seen elsewhere.
The following equation rotates the point (x, y, z) around the x-axis, producing a new point (x', y', z').
The following equation rotates the point around the y-axis.
The following equation rotates the point around the z-axis.
In these example matrices, the Greek letter theta stands for the angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.
In a C++ application, use the D3DXMatrixRotationX, D3DXMatrixRotationY, and D3DXMatrixRotationZ functions supplied by the D3DX utility library to create rotation matrices. The following is the code for the D3DXMatrixRotationX function.
D3DXMATRIX* WINAPI D3DXMatrixRotationX ( D3DXMATRIX *pOut, float angle ) { #if DBG if(!pOut) return NULL; #endif float sin, cos; sincosf(angle, &sin, &cos); // Determine sin and cos of angle pOut->_11 = 1.0f; pOut->_12 = 0.0f; pOut->_13 = 0.0f; pOut->_14 = 0.0f; pOut->_21 = 0.0f; pOut->_22 = cos; pOut->_23 = sin; pOut->_24 = 0.0f; pOut->_31 = 0.0f; pOut->_32 = -sin; pOut->_33 = cos; pOut->_34 = 0.0f; pOut->_41 = 0.0f; pOut->_42 = 0.0f; pOut->_43 = 0.0f; pOut->_44 = 1.0f; return pOut; }
Concatenating Matrices
One advantage of using matrices is that you can combine the effects of two or more matrices by multiplying them. This means that, to rotate a model and then translate it to some location, you don't need to apply two matrices. Instead, you multiply the rotation and translation matrices to produce a composite matrix that contains all their effects. This process, called matrix concatenation, can be written with the following equation.
In this equation, C is the composite matrix being created, and M1 through Mn are the individual matrices. In most cases, only two or three matrices are concatenated, but there is no limit.
Use the D3DXMatrixMultiply function to perform matrix multiplication.
The order in which the matrix multiplication is performed is crucial. The preceding formula reflects the left-to-right rule of matrix concatenation. That is, the visible effects of the matrices that you use to create a composite matrix occur in left-to-right order. A typical world matrix is shown in the following example. Imagine that you are creating the world matrix for a stereotypical flying saucer. You would probably want to spin the flying saucer around its center - the y-axis of model space - and translate it to some other location in your scene. To accomplish this effect, you first create a rotation matrix, and then multiply it by a translation matrix, as shown in the following equation.
In this formula, Ry is a matrix for rotation about the y-axis, and Tw is a translation to some position in world coordinates.
The order in which you multiply the matrices is important because, unlike multiplying two scalar values, matrix multiplication is not commutative. Multiplying the matrices in the opposite order has the visual effect of translating the flying saucer to its world space position, and then rotating it around the world origin.
No matter what type of matrix you are creating, remember the left-to-right rule to ensure that you achieve the expected effects.
Build date: 11/22/2012 | http://msdn.microsoft.com/en-us/library/windows/desktop/bb206269(v=vs.85).aspx | CC-MAIN-2013-20 | refinedweb | 1,330 | 56.05 |
simple source code is
Post your Comment
Sum of a Number using Swing
Sum of a Number using Swing
In this section, you will learn how to sum of a number
using swing...;);
Step: Create a file "Calculate.java"
to sum of a number using
Java swing
Java swing how to create simple addition program using java swing... JLabel("Enter first number: ");
final JTextField text1=new JTextField(20);
JLabel lab2=new JLabel("Enter second number: ");
final JTextField text2=new
insert data into mysql databse using swing
insert data into mysql databse using swing
Blockquote
hi,
here is my code,
i want code for store data into mysql database when click on submit...);
linfo14=new JLabel("ROOM NUMBER ALLOTED");
linfo14.setBounds(10,200,150,30
Swing |
Color Effect On Image |
Login Form in Swing |
Sum
of a Number... Component
Java Swing Tutorial Section - II
Limiting
Values in Number... Using Java Swing |
Noise Image in Graphics in Java Swing |
Event
prime number
prime number get one number and check the number prime or not using if statement
Java Check Prime Number
prime number
prime number check prime number using if statement
Java Check Prime Number
prime number
prime number HI!I want a java program that accepts a number from user and displays whether it is a prime number or not using BufferedReader
Swing Applet Example in java
Java - Swing Applet Example in java
Introduction
In this section we will show you about using swing in an applet. In this example,
you will see that how resources of swing
Lost Using Swing Components
Lost Using Swing Components Hello, I sound like every other newbie but I desperately need help. I have to write an application for the WebBuy Company that allows a user to compose the three parts of a complete email message
creation of table using a Java swing
creation of table using a Java swing how to create a table dynamically in Java swing
need help - Swing AWT
as well.
Must read a set of 10 correct answers, using a JOptionPane dislog box....
The program must then ask the user to: "Please enter the number of students".
Therafter... answers with answer in the answer array. keep count of the number of answers
swing/awt - Swing AWT
swing/awt How to create richtexteditor using swings...?I'm very much new to swings....It's urgent.....Thank u...
hello
read this book you get idea;
JFC Swing Tutorial, The: A Guide to Constructing GUIs, Second
Reading .doc file using swing
Reading .doc file using swing Sir,
Could U Please Tell me the Way To Read .doc file in java using swing,with code
swing sms
swing sms HOW TO SEND SMS MESSAGE FROM SWING USING SQL DATABASE
Using swing - Java Beginners
Using swing How can one use inheritance and polymophism while developing GUI of this question.
Develop an application that allows a student to open an account. The account may be a savings account or a current account
Swing paint - Swing AWT
Swing paint hi,
i want to print something on window using swing applet..
m doing dis..
protected void paintComponent(Graphics g... the Swing Applet, use html file with the following code:
Java Applet Demo
java swing
java swing view the book details using swing
JFileChooser - Swing AWT
JFileChooser Hi,iam using jfilechooser to select a directory....now the prob is iam able to open only the files in the directory....actually i have... number of files............so now if I select the data directory it should read
random number
random number Please
How do I generate a program that gives me random integer from 115 to 250? Using java.util.random.
Thank you very much!
Hi Friend,
Try the following code:
import java.util.*;
public final
java swing
java swing add two integer variables and display the sum of them using java swing
swing with jdbc - Swing AWT
swing with jdbc Hi, i m developing the desktop application using swing.i want to use table structure for that.also its DB specific application. i have some problems with swing using jdbc.
1. the values entered in table
how to give validation using javascript in swing
how to give validation using javascript in swing how to give validation using javascript in swing....... can somebody give code for username and password validation using javscript and swing
swing - Swing AWT
swing hi..please help me to retrieve image using histogram of that image Hi Friend,
Please clarify your problem.Do you want to create a histogram by retrieving the data from the database and save the histogram
simple source code is
Post your Comment | http://www.roseindia.net/discussion/22688-Sum-of-a-Number-using-Swing.html | CC-MAIN-2015-27 | refinedweb | 771 | 60.75 |
Modern React Context has been with us for a while but I still see a lot of confusion about how to use it effectively.
@Swizec pic.twitter.com/vJQDVT9Ou1
— Wojtek (@pugson) December 30, 2018
A lot of people feel that no matter what, you still need some form of state management. Either an existing library or you end up building your own anyway.
Yes, sort of. But not in the way you think.
Redux and MobX have always used context behind the scenes. They’re familiar, you can use them right away, and your workflow doesn’t have to change. Congratz, you’re using React Context effectively.
Maybe you don’t like or need the complexity of Redux and MobX. Overhead, bundle sizes, indirection and separation of concerns way beyond what your tiny app needs. Lots of reasons.
That’s where modern React Context comes in.
Work with context directly
Here’s a video of mine explaining React Context in 2 minutes 👇
To use context effectively you need 3 things:
- A state object
- A way to change state from consumers
- A way to communicate state changes to your provider
That is all.
A state object is where you hold your state tree. Many ways to build one, I prefer plain JavaScript objects. A reducer-like approach is also popular.
Then you need some way to change said state. I like to use functions attached to the state object itself. That way anyone who has access to state also has the ability to change values. Functions are best. Think of them as actions.
Finally, you need a way for your Provider to know that state changed. This is important because React uses the same props-changed tree diffing algorithm to update context as it does for reconciliation and re-rendering.
JavaScript uses shallow object comparisons, so relying on component state is best. React comes with all necessary machinery built-in.
Here’s a bug you can run into if you’re not careful:
Even though we made a copy of
obj, their internal properties remained equal. The
pugson object is shared between both.
So if you’re passing deep properties into your context or your props, your app is going to break.
An example CodeSandbox
Okay, so you’re gonna need some state, a way to change it, and a way to communicate changes. Here’s what that would look like in code 👇
You can say hi to Pugson. Type into the input box and see what you’re typing right away.
It’s a little contrived, but that makes it easier to explain. There are a few moving pieces.
1. The Context itself
I like to define the context itself in its own file. You could have a file with multiple context definitions for different parts of your app.
This creates a convenient way for different components to share the same context via
import statements.
Create context and export its
Provider and
Consumer. Providers pass values down the tree of components, and consumers use them to do stuff.
2. The App component holds and provides state
Like I said, the simplest way to keep state that communicates changes is with component state. You should have a single source of truth for your entire app like always.
The
state object has both values and setters.
greeting is the string you’re typing with a default value of
"", and
setGreeting is the setter any component can use to change the greeting.
Since we’re using component state, the setter can call
setState and let React figure out the rest.
My favorite side-effect of this approach is that important parts of your code are close together. You can start thinking of your state as a state machine because states and their transitions are next to each other.
As your state grows in complexity, you might want to move this machinery out of
App.js into its own file. Just make sure your App component knows when something changes.
When rendering we use
Provide to pass this component state as a context value down to our entire component tree.
3. Consuming context state
Consuming your state is a matter of rendering a
and using the values it provides.
See how keeping the context definition in a separate file makes it more convenient to use?
We import the
Consumer, render it as the root of our
Greeting component, and pass-in a function as children. The good old render props approach but with children.
Since our context value is an object, we can destructure it right away and take out just what we need:
greeting. Then render as usual.
Whenever the
greeting value changes, our component will automatically re-render and show the new value.
4. Changing context state
Changing our
greeting value works in a similar way. We render a consumer, take out the setter, and pass it as a prop into a component that does the changes.
But there’s no way to access it outside of render, is there?
@swizec waiting for your expert answer. Maybe I’ve been doing unstated wrong the whole time
This also lets you solve the problem that you can’t access context value outside of the render method. It’s true, you cannot, and that’s why you pass them into child components and use it there.
Once more, we import that same shared context
Consumer, render, and use a function as children approach. This time, we take both the
greeting and
setGreeting out of our context value.
We pass those into the
Input component as
value and the
onChange callback. This allows
Input to be as complex or as simple as it wants, makes it a fully controlled component, and most importantly, it doesn’t rely on context.
A common foot-gun is to make your components so tied to context or state management that you can’t reuse them. Always a good idea to make your basic components rely on props alone.
Some modern context-based libraries
“But that’s an awful lot like re-inventing your own state management”, I hear you say.
Kind of? You’re using out-of-the-box React tools. No wheel reinventing required.
But yes, as complexity grows, you start moving this machinery out of your main component into its own files, and start running into a lot of similar problems as you would with building your own state management library.
When that happens, I recommend splitting your context into subcontexts. Have a new context with a new state object for every section of your app.
A form could have its own state and context, for example, use it to communicate between all the fields, then communicate its end result to the parent context. Much like nested redux reducers or something.
You can also make some of this stuff easier with modern state management libraries like Constate or Unstated.
I won’t go into detail on those, so here’s two videos:
What about hooks?
Yes, this approach works with hooks. Replace
with
useContext. Everything else stays the same.. | https://swizec.com/blog/react-context-effectively/swizec/8844 | CC-MAIN-2019-22 | refinedweb | 1,182 | 74.08 |
Writing Smart Contracts using Convector — a Fullstack JavaScript Framework
Writing smart contracts for any blockchain shouldn't be a hard thing to do. A blockchain developer is nothing more than a software developer, that knows a couple of special rules that apply in its code (checkout our quick intro to blockchain development for software developers). The biggest problem right now is having to learn a whole new programming language just to do one job. This slows down the adoption of the technology and thus the innovation of new developers entering the field.
That's why we created Convector, a Typescript (Javascript) framework for blockchain development systems. It's based on the MVC pattern, more specifically in the Model and Controller side.
We write all our code in Typescript, because it has proved us the flexibility and security of maintaining a big codebase and the utility to have models shared between the whole stack, between chaincode and server side to the browser, all in a single typed language. Since typescript compiles down to javascript, the packages can be imported in vanilla javascript projects, but we make a strong use of decorators and using them in vanilla might be complicated.
As a blockchain developer your main responsibility is to write and think about two things: What data do I want to store? What rules does this data need?
When you know what you want to store, the best idea is to start modeling the data, just like you do when programing a database. In Convector, writing a model is as easy as extending the ConvectorModel class.
class Product extends ConvectorModel<Product> {
@ReadOnly()
@Required()
type = 'io.worldsibu.example.product'; @Required()
@Validate(yup.string())
name: string; @Required()
@Validate(yup.number())
price: number; @Required()
@Validate(yup.string())
owner: string; @ReadOnly()
@Default(() => Date.now())
@Validate(yup.number())
created: number;
}
Even if you're not familiar with Typescript, it's pretty obvious what's going in here: you have a model called Product with a set of properties, each of them has some flags describing the rules the data has to follow. For example, ReadOnly is a modifier to not allow modifications after being set, Required makes sure the data complies with a certain schema validation (we support yup for now), Default/Required ensure at write time, that this property will have a value, either by providing one in code or by expecting the user to set one.
ConvectorModel provides an
id field, all the models have one, and it's the key being used to identify the instance of this model in the blockchain.
Convector is made in a modular way, we want to support not only Hyperledger Fabric, but all the possible blockchains out there! And models are not used in the chaincode codebase only, you'll probably want to use the same structure in your Nodejs server, your angular website or your react native application. For this reason the models are separated from the actual implementation layer that talks with the underlying storage layer. For write operations right now we have the FabricStorage and for querying data we have the CouchDBStorage. We have some more planned in the upcoming months, but the community is free to develop their own storage implementations.
Next thing you'll need is the set of rules and policies for your data. This is where the ConvectorController is useful.
@Controller('product')
class ProductCtrl extends ConvectorController { @Invokable()
async create(
@Param(Product) product: Product
) {
const _product = await Product.getOne(id); if (product.id === _product.id) {
throw new Error('Product ID already created');
} product.owner = this.sender; await product.save();
} @Invokable()
async transfer(
@Param(yup.string()) id: string,
@Param(yup.string()) to: string
) {
const product = await Product.getOne(id); if (product.owner !== this.sender) {
throw new Error('Only the owner can transfer the product');
} product.owner = to; await product.save();
}
}
Here we have a controller to manipulate our products in the blockchain. A single chaincode can be made of multiple controllers, so we need to register this controller using a name. In this case
product is our namespace.
Controllers are installed in a chaincode using NPM, so they must be valid node modules with a package.json file.
This Product controller is made up of two methods, one to create a new product and another one to transfer its ownership. Not all the methods in your controllers are invokable from the outside world, you can expose the ones you want by using Invokable and keep the rest private.
Convector offers a parameter validation using yup. We also support models as parameters and we cast the object for you.
In a controller method, throwing an error is the way to reject a transaction. If the sender doesn't not have the permissions to invoke the function, you simply throw and no changes will be committed.
Controllers, in the same way as models, are used outside the blockchain too. You want to be able to invoke methods from your nodejs or front-end application and you don't want to start creating custom wrappers of logic around something you already built and replicate the same functions with the same parameters everywhere! We got your back here. Convector is a full-stack framework and we auto-generate a client interface of your controller for you, so it can be used with any ConvectorAdapter.
Adapters follow the same principle as the Model Storage. We have a FabricAdapter capable to talk with the Fabric SDK and send transactions to multiple peers. We also offer a MockAdapter, useful for unit-tests and mock the blockchain behavior. We're planning more adapters to come, like services for Angular or components for React. If you're interested in a specific adapter, left your suggestions in our github issues.
Writing a smart contract is a really simple task, but the logic inside has to be verified and confirmed to be working. Unit tests are a essential feature of a blockchain framework and Convector is no different.
describe('ProductController' () => {
let adapter: MockControllerAdapter;
let productCtrl: ProductCtrl; beforeEach(async () => {
adapter = new MockControllerAdapter();
productCtrl = new ProductCtrl(adapter); await adapter.init([
{
version: '*',
controller: 'ProductCtrl',
name: '/path/to/controller-package'
}
]);
}); it('should create a product', async () => {
const productId = uuid(); await productCtrl.create(new Product({
id: productId,
name: 'OnePlus 6',
price 600
})); const product = await adapter.getById<Product>(productId); expect(product).to.exist;
expect(product.name).to.eq('OnePlus 6');
});
});
To execute the unit tests you don't need a full blockchain running. Since the logic inside controller has to be deterministic, unit testing the functions can be done using regular javascript testing tools like Mocha or Jasmine.
Finally, we offer some tools to make local development really easy. The dev-env contains two organizations with one peer each and one orderer. If you're not familiar with the Hyperledger Fabric concepts, this is pretty much all the infrastructure necessary to run a blockchain, but thanks to Convector you dodn't have to learn how to configure all that just to make a hello world.
Alongside with the dev-env, the chaincode manager is really helpful to package, install, update and invoke the chaincode in the dev-env, so you can now just focus on writing your amazing new project's code.
Conclusion
Writing smart contracts doesn't have to be a hard task or demand hours of reading technical books with complex math just to store some data in a blockchain. Convector helps you eliminating the distractions and put you on track to just write code.
If you're still curious about Convector, checkout our guide on how to write a full stack application, or checkout our repo, we're an open source project in case you want to contribute moving the blockchain development forward. | https://medium.com/covalentxhq/writing-smart-contracts-using-convector-a-fullstack-typescript-framework-e089da0f4ee1?readmore=1&source=user_profile---------4---------------------------- | CC-MAIN-2021-31 | refinedweb | 1,287 | 54.02 |
#include <wx/aui/auibook.h>
wxAuiNotebook is part of the wxAUI class framework, which represents a notebook control, managing multiple windows with associated tabs.
See also wxAUI Overview.
wx.
The default theme that is used is wxAuiDefaultTabArt, which provides a modern, glossy look and feel. The theme can be changed by calling wxAuiNotebook::SetArtProvider.
This class supports the following styles:
The following event handler macros redirect the events to member function handlers 'func' with prototypes like:
Event macros for events emitted by this class:
wxEVT_AUINOTEBOOK_PAGE_CLOSEevent.
wxEVT_AUINOTEBOOK_PAGE_CLOSEDevent.
wxEVT_AUINOTEBOOK_PAGE_CHANGEDevent.
wxEVT_AUINOTEBOOK_PAGE_CHANGINGevent. This event can be vetoed.
wxEVT_AUINOTEBOOK_BUTTONevent.
wxEVT_AUINOTEBOOK_BEGIN_DRAGevent.
wxEVT_AUINOTEBOOK_END_DRAGevent.
wxEVT_AUINOTEBOOK_DRAG_MOTIONevent.
wxEVT_AUINOTEBOOK_ALLOW_DNDevent. This event must be specially allowed.
wxEVT_AUINOTEBOOK_DRAG_DONEevent.
wxEVT_AUINOTEBOOK_TAB_MIDDLE_DOWNevent.
wxEVT_AUINOTEBOOK_TAB_MIDDLE_UPevent.
wxEVT_AUINOTEBOOK_TAB_RIGHT_DOWNevent.
wxEVT_AUINOTEBOOK_TAB_RIGHT_UPevent.
wxEVT_AUINOTEBOOK_BG_DCLICKevent.
Default ctor.
Constructor.
Creates a wxAuiNotebok control.
Adds a page.
If the select parameter is true, calling this will generate a page change event.
Adds a new page.
The page must have the book control itself as the parent and must not have been added to this control previously.
The call to this function may generate the page changing events.
Reimplemented from wxBookCtrlBase.
Sets the selection to the next or previous page.
Changes the selection for the given page, returning the previous selection.
This function behaves as SetSelection() but does not generate the page changing events.
See User Generated Events vs Programmatically Generated Events for more information.
Implements wxBookCtrlBase.
Creates the notebook window.
Deletes all pages.
Reimplemented from wxBookCtrlBase.
Deletes a page at the given index.
Calling this method will generate a page change event.
Reimplemented from wxBookCtrlBase.
Finds tab control associated with a given window and its tab index.
Returns active tab control for this notebook.
Returns the associated art provider.
Returns the currently selected page or NULL.
Returns the desired height of the notebook for the given page height.
Use this to fit the notebook to a given page size.
Returns the page specified by the given index.
Returns the tab bitmap for the page.
Returns the number of pages in the notebook.
Reimplemented from wxBookCtrlBase.
Returns the image index for the given page.
Implements wxBookCtrlBase.
Returns the page index for the specified window.
If the window is not found in the notebook, wxNOT_FOUND is returned.
Returns the tab label for the page.
Implements wxBookCtrlBase.
Returns the tooltip for the tab label of the page.
Returns the currently selected page.
Implements wxBookCtrlBase.
Returns tab control based on point coordinates inside the tab frame.
Returns the height of the tab control.
InsertPage() is similar to AddPage, but allows the ability to specify the insert location.
If the select parameter is true, calling this will generate a page change event.
Inserts a new page at the specified position.
Implements wxBookCtrlBase.
Removes a page, without deleting the window pointer.
Reimplemented from wxBookCtrlBase.
Sets the art provider to be used by the notebook.
Sets the font for measuring tab labels.
Sets the font for drawing unselected tab labels.
Sets the bitmap for the page.
To remove a bitmap from the tab caption, pass wxNullBitmap.
Sets the image index for the given page.
image is an index into the image list which was set with SetImageList().
Implements wxBookCtrlBase.
Sets the tab label for the page.
Implements wxBookCtrlBase.
Sets the tooltip displayed when hovering over the tab label of the page.
Sets the font for drawing selected tab labels.
Sets the page selection.
Calling this method will generate a page change event.
Implements wxBookCtrlBase.
Reimplemented in wxAuiMDIClientWindow. SetUniformBitmapSize().
Specifying -1 as the height will return the control to its default auto-sizing behaviour.
Ensure that all tabs have the same height, even if some of them don't have bitmaps.
Passing wxDefaultSize as size undoes the effect of a previous call to this function and instructs the control to use dynamic tab height.
Shows the window menu for the active tab control associated with this notebook, and returns true if a selection was made.. | https://docs.wxwidgets.org/trunk/classwx_aui_notebook.html | CC-MAIN-2021-17 | refinedweb | 640 | 52.97 |
Creates a new UDP socket.
Syntax
#include <prio.h> PRFileDesc* PR_NewUDPSocket(void);
Returns
The function returns one of the following values:
- Upon successful completion, a pointer to the
PRFileDescobject created for the newly opened UDP socket.
- If the creation of a new UDP socket failed,
NULL.
Description
UDP (User Datagram Protocol) is a connectionless, unreliable datagram protocol of the TCP/IP protocol suite. UDP datagrams may be lost or delivered in duplicates or out of sequence.
PR_NewUDPSocket creates a new UDP socket. The socket may be bound to a well-known port number with
PR_Bind. Datagrams can be sent with
PR_SendTo and received with
PR_RecvFrom. When the socket is no longer needed, it should be closed with a call to
PR_Close.
See Also
PR_NewUDPSocket is deprecated because it is hardcoded to create an IPv4 UDP socket. New code should use
PR_OpenUDPSocket instead, which allows the address family (IPv4 or IPv6) of the new UDP socket to be specified. | https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_NewUDPSocket | CC-MAIN-2017-09 | refinedweb | 158 | 66.94 |
The Visual Studio Team System “off-road” code coverage experience
John Cunningham, Developer Lead, Dynamic Analysis team, VSTS
Off-road – eh?
The Code Coverage collection and analysis portions of Team System, which my team is responsible for, had a particular design philosophy in mind for this version. That philosophy was to have a seamless integrated experience when working with the unit testing framework in Team System. That’s not to say you can’t use code coverage in whichever framework you deem necessary for your own purposes. This post shows the fundamentals of collecting coverage information and analyzing it in the Beta 2 bits of Team System.
Before going down this road, you should note that it would be a far better investment of your time is to integrate with the Team System testing framework. It’s designed with extensibility in mind and you’ll get a host of “free” test features, such as test selection and reporting.
All Wheel Drive please!
In our code coverage implementation there are three primary steps:
1) Instrumentation of the assemblies/binaries you want to collect code coverage from
2) Collecting that information while exercising your code
3) Analyzing that information afterwards
To instrument the exe/dll/assembly (I say that since .Net, mixed and native executable types are supported) we use the vsinstr.exe tool that comes with VSTS. You’ll find this tool in the following directory:
Microsoft Visual Studio 8\Team Tools\Performance Tools
Instrumenting an exe/dll/assembly for coverage is as simple an operation as:
vsintr -coverage myassembly.exe
Now that assembly has been backed-up, and myassembly.exe has some instrumentation code in it to allow coverage information to be collected. Before we go and exercise this code, we need to make sure the coverage monitor is running and ready to put results into a file. We do this like so:
start vsperfmon -coverage -output:mytestrun.coverage
You’ll now see that you have a command shell running the monitor, basically sitting there doing nothing. Now go ahead and exercise that code. Give it a good run around. Go for the burn. When you feel that you’ve given it the once-over, you need to tell the monitor that you are done for the day:
vsperfcmd -shutdown
This command will wait until your process (the one exercising your code) has exited.
And there you have it – a lovely .coverage file has been produced to give you an idea of how well you exercised that code. To load that file into VS for visualization, simply open the file mentioned in the “start vsperfmon” line above via the File->Open->File menu in VS. The code coverage results window will appear giving you a breakdown of your coverage. <insert favoured brass flourish>
Pimp my Ride!
I hear you cry, “JoC man, I need tighter control, I need all the gauges; give me the raw horsepower!” Well, yes, command line control may not cut it for whatever integration or harness you want to tie this up to. Let me talk a little about some of the assemblies that are shipped to add code coverage functionality that can be used to tie into your own mechanisms. Please note that assemblies and interfaces are the Beta2 versions and may change before the final release of Visual Studio Team System.
First off, there is the controlling mechanism available in:
Microsoft.VisualStudio.Coverage.Monitor.dll
This assembly allows all of the mechanisms described in the above instrumentation and collection phases. A small example piece of code that drives this like the example above would be: to call vsinstr.exe using
Process p = new Process();
StringBuilder sb = new StringBuilder(“/COVERAGE “);
sb.Append(“myassembly.exe”);
p.StartInfo.FileName = “vsinstr.exe”;
p.StartInfo.Arguments = sb.ToString();
p.Start();
p.WaitForExit();
// TODO: Look at);
}
}
}
Remember that this is how the API looks in Beta 2. If it changes in the final shipping version, I’ll announce it here so you have the heads-up, but sometimes we have to do that to fix bugs and issues. Obviously, people can extend that to whatever mechanisms they want, including hooking it up to some GUI for control or a script/test harness that they rolled themselves.
Next up in the “raw horsepower” assemblies is:
Microsoft.VisualStudio.Coverage.Analysis.dll
This assembly provides the raw smarts under the code coverage visualization hood in VSTS. Here’s how you can dump some XML for the covered lines in a coverage file collected above:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.CodeCoverage;
// You must”);
}
}
}
The XSD for the coverage dataset schema may also change slightly between now and the final shipped product. You can now operate with the DataSets we provide programmatically to do your own filtering or roll-ups, or you can flush the XML and work with it through some XSLTs to present and roll-up as needed. Team System will feature some aggregated reports for coverage, so you may find that any work you do here will be covered by what Team System does for you.
Destination reached
Hopefully, this has given people who want to go off-road with Code Coverage collection and analysis the guide to go do so, but I do want to re-emphasize what I said earlier in this post. For most folks the right way to get what you want is to integrate into the test framework in Team System. You get a lot more “free” features when doing this, such as reporting, run configurations, etc. To get more details on doing that, look at the white paper and samples included with the Team System extensibility SDK.
To quickly look at some code coverage on an ad-hoc basis, or where you just need to tie up to something else, off-roading can be fun however…
Although Beta2 is not available as yet, I decided to publish this article anyway. You can read…
Feel the love:
Various Team System News Items
Ian’s weekly review of the best of the blogs for the .Net developer week ending 17th April 2005
What can I say…I’m a big fan of hello…
I’ve pulled together all of the technical articles and walkthroughs from the various team member blogs…
Another day fille with a variety of issues across profiling, debugging and team system. First order…
PingBack from
This FAQ will collect the most common questions that are asked about the code coverage tool that is included… | https://blogs.msdn.microsoft.com/ms_joc/2005/04/08/the-visual-studio-team-system-off-road-code-coverage-experience/ | CC-MAIN-2017-09 | refinedweb | 1,101 | 51.89 |
Hello:
In general I’ve found Ruby 1.9.1 to be 2 times faster than 1.8.6 and
roughly the same speed as Python 2.8 which is great… thanks guys,
great job!
However, in one case, when using a regular expressions (posted here by
someone a long time ago) which I use to determine what numbers in
0…10000 are prime numbers, version 1.9.1 was at least 6.5 times slower
(1.8.6 = 67 secs, 1.9.1 = 457 secs).
The regular express is:
((("1" * self) =~ /^1$|^(11+?)\1+$/) == nil)
which I’ve used in different versions of my program running either on
its own or as part of an overloading function as follows:
Add an “is_prime?” method to the built-in numeric class
which returns true if the number is a prime number.
class Fixnum
def is_prime?
(((“1” * self) =~ /^1$|^(11+?)\1+$/) == nil)
end
end
I also have a version of the prime-number calculation program that which
doesn’t use the above regex (i.e. it uses a traditional brute force
approach instead) and it runs 2 times faster in 1.9.1. In 1.9.1 the
regex gets exponentially worse as the number being evaluated exceeding
1000.
Does anyone know why the regex in 1.9.1 is so much slower than 1.8.6?
Thank You,
Michael | https://www.ruby-forum.com/t/1-9-1-regex-6-5-times-slower-than-1-8-6-in-at-least-one-case/161171 | CC-MAIN-2021-39 | refinedweb | 228 | 86.81 |
Skeleventy gives you a rock solid foundation to build fast and accessible static websites. View the demo site.
Node
v10+
git clone
cdinto the project folder and run
npm install
npm run devTip: Eleventy has live reload baked in!
site/contains all the global data, templates and content
utilities/contains Eleventy helper
filtersand
transforms
index.mdfile
css/for compiled CSS
js/for compiled JavaScript
images/contains our site's images, an SVG icon sprite and a folder for meta images (OG, Twitter etc)
Laravel Mix gives us a nice API layer on top of Webpack. Skeleventy uses a simplistic set up, but you can take advantage of extending Mix with custom Webpack configurations, code splitting and plugins such as PostCSS, if you so wish.
You'll find the site's uncompiled SCSS and JS within
resources/ where Mix will be watching these directories for any changes. Tip: it's best to always restart the server when creating any new partials or folders
scss/is structured into opinionated sub folders
_config.scssfile is where you can change the site's colours and the utility classes generated by Gorko
I decided to remove Tailwind in favour of Gorko, purely for its simplicity and maintainability (especially for newer developers). Not having too much to begin with and adding in what you need, will lead to a simpler, more maintainable codebase. Gorko lets you add a sprinkle of reusable utility classes to help keep your code DRY. Credit to Andy Bell for making this handy little tool
utilities/contains any global utility/helper functions
modules/contains your site's actual JavaScript, all kept neat and tidy within their respective modular subfolders
main.jsusing
import '@modules/example-module'
webpack.mix.jsfile
Skeleventy doesn't have responsive images baked in, the main reason being: it's best using CDN. Check out this tutorial on setting up Eleventy with Cloudinary. | https://awesomeopensource.com/project/josephdyer/skeleventy | CC-MAIN-2021-31 | refinedweb | 313 | 51.89 |
TensorFlow.js Core APITensorFlow.js Core API
A part of the TensorFlow.js ecosystem, this repo hosts
@tensorflow/tfjs-core, the TensorFlow.js Core API, which provides low-level, hardware-accelerated linear algebra operations and an eager API for automatic differentiation.
Check out js.tensorflow.org for more information about the library, tutorials and API docs.
To keep track of issues we use the tensorflow/tfjs Github repo.
ImportingImporting
You can install TensorFlow.js via yarn or npm. We recommend using the @tensorflow/tfjs npm package, which gives you both this Core API and the higher-level Layers API:
import * as tf from '@tensorflow/tfjs'; // You have the Core API: tf.matMul(), tf.softmax(), ... // You also have Layers API: tf.model(), tf.layers.dense(), ...
On the other hand, if you care about the bundle size and you do not use the Layers API, you can import only the Core API:
import * as tfc from '@tensorflow/tfjs-core'; // You have the Core API: tfc.matMul(), tfc.softmax(), ... // No Layers API.
For info about development, check out DEVELOPMENT.md.
For more informationFor more information
Thanks BrowserStack for providing testing support. | https://javascript.ctolib.com/PAIR-code-deeplearnjs.html | CC-MAIN-2019-22 | refinedweb | 188 | 51.95 |
16 September 2010 19:16 [Source: ICIS news]
TORONTO (ICIS)--RAG-Stiftung, the majority owner of Germany-based specialty chemicals major Evonik, is warning that an earlier-than-planned phase-out of the country's subsidised hard coal production could trigger its insolvency and collapse, a company spokesman said on Thursday.
The company warned of such a “worst-case scenario” in a letter to ?xml:namespace>
“An early coal phase-out would put pressure on RAG to sell off Evonik much faster, and such pressure would not be good,” Winkler added.
In its letter, RAG warned that a collapse would trigger “large-scale jobs cuts.”
Under the original plan, the phase-out is due to be completed by 2018, with a review set for 2012. However, the EU has been pressing
Michael Vassiliadis, head of
($1 = €0.77) | http://www.icis.com/Articles/2010/09/16/9394006/evonik-owner-rag-warns-of-collapse-as-eu-wants-coal-mines-closed.html | CC-MAIN-2015-11 | refinedweb | 138 | 58.92 |
20 November 2012 03:46 [Source: ICIS news]
SINGAPORE (ICIS)--Here is Tuesday’s midday ?xml:namespace>
CRUDE: WTI Jan $89.15/bbl, down 13 cents; BRENT Jan $111.71/bbl, up 1 cents/bbl
Crude futures were range-bound on Tuesday after large gains made in the previous day. Upside pressure, driven by an escalation of violence in Middle East and hopes of a resolution in the
NAPHTHA: $960.50-963.50/tonne CFR
Open-spec first-half January contracts rose in the morning, following overnight gains in crude futures.
BENZENE: $1,370-1,380/tonne FOB
Prices were higher on the back of stronger Brent crude futures from the previous day’s close. A deal for a February-loading cargo was done at $1,330/tonne FOB Korea, while January-loading lots were offered at $1,365-1,380/tonne FOB Korea against bids at $1,350-1,360/tonne FOB Korea. Discussions for December-loading lots were limited.
TOLUENE: $1,265-1,275/tonne FOB
Prices firmed in tandem with higher Brent crude futures from the previous day’s close. Bids for January-loading cargoes were at $1,255/tonne FOB
ETHYLENE: $1,200-1,250/tonne CFR NE Asia, stable
Some buyers shunned offers at $1,250/tonne CFR NE Asia and lowered their buying ideas to below $1,200/tonne CFR Taiwan for December-arrival cargoes, citing affordability issues given poor derivative market conditions.
PROPYLENE: $1,350-1,360/tonne CFR NE Asia, stable
Buying ideas for December cargoes were capped at $1,350/tonne CFR NE Asia, although sellers made offers at $1,360/tonne CFR NE Asia or | http://www.icis.com/Articles/2012/11/20/9615716/noon-snapshot-asia-markets-summary.html | CC-MAIN-2014-42 | refinedweb | 275 | 53.21 |
Ruby is a multi-paradigm programming language. It fully allows writing old-fashioned procedural code, but also provides many useful constructs and features from the functional world.
The majority of developers come to Ruby from the imperative world. They are used to making many local variables, changing their state and relying on implicit dependencies. Very quickly, it becomes clear that code can be much more expressive, using powerful idioms from functional languages. Ruby isn't a fully functional language by any means; functions are not first class citizens, evaluation flow is not lazy, pattern matching support is very limited, etc. But still, it is possible to write code in a functional way and garner many benefits as a result.
I'd like to start with a practical example. Let’s define a problem, try to solve it using both imperative and functional styles in Ruby and see what happens. Let me first point out that it’s very hard to come up with a good example that is concise and easily understandable and, at the same time, not too artificial, but I have done my best.
Problem definition: Write a function, which accepts a list of users with a full_name property and returns a string with users' names and birthdays sorted by distance from the current point in time. Birthdays of users can be obtained from an external system by using birthday method of BirthdayRegistry class. If multiple people are lucky enough to be born on the same day, the function should combine them together with a comma.
Example: Bob and Joe are both born on July 16, 1985, Maria celebrates her birthday on January 2, 1989, and Alice blows out her candles on October 25, 1989. The function should return "[Alice] - 1989-10-25; [Maria] - 1989-01-02; [Bob, Joe] - 1985-07-16" string.
Imperative implementation:
def birthday_sequence(users) result = '' hash = {} users.each do |user| birthday = BirthdayRegistry.birthday(:date, user) hash[birthday] ||= [] hash[birthday] << user end sorted = hash.sort_by { |birthday, _| (Date.today - birthday).abs } sorted.each do |birthday, celebrators| result << '[' names = [] celebrators.each { |user| names << user.full_name } names.sort! names[0..-2].each do |name| result << name result << ', ' end result << names.last + "] - #{birthday}; " end result[0..-3] end
As I mentioned earlier, this example is a bit artificial, but code similar to this can be easily found in an arbitrary Ruby project featuring several junior developers. My hope is that you, as the reader, will practice some patience with this example since it is only used for demonstration purposes of the article. | http://www.programmableweb.com/news/how-to-leverage-rubys-functional-programming-capability/how-to/2015/09/24 | CC-MAIN-2016-26 | refinedweb | 424 | 55.54 |
import "cmd/internal/bio"
Package bio implements common I/O abstractions used within the Go toolchain.
MustClose closes Closer c and calls log.Fatal if it returns a non-nil error.
MustWriter returns a Writer that wraps the provided Writer, except that it calls log.Fatal instead of returning a non-nil error.
Reader implements a seekable buffered io.Reader.
Open returns a Reader for the file named name.
Writer implements a seekable buffered io.Writer.
Create creates the file named name and returns a Writer for that file.
Package bio imports 4 packages (graph) and is imported by 12 packages. Updated 2019-03-15. Refresh now. Tools for package owners. | https://godoc.org/cmd/internal/bio | CC-MAIN-2019-13 | refinedweb | 111 | 62.24 |
The Java Specialists' Newsletter
Issue 071
2003-06-01
Category:
Language
Java version:
Subscribe
RSS Feed
Welcome to the 71st edition of The Java(tm) Specialists' Newsletter. We have a new country on our subscription list; please welcome the Faroe Islands (applause)! I had never heard of them, but then again, my knowledge of Geography has never been good. There is a nice website about these islands, you can have a look at. We are approaching 100 countries in our subscription list, and you can see whether your country is already in our count by looking on our web page under countries.
A few weeks ago, Alexander (Sascha) Hoeher sent me a piece he had written in German on method overloading. The writing was persuasive and interesting, so I asked Sascha if he could perhaps translate it into English so we could feature his ideas on this newsletter. The ideas were based on something that I had written about 2.5 years ago, on Depth-first Polymorphism, but Sascha added a dimension to the argument that I had missed. He asks whether perhaps overloading is harmful? I enjoyed both the German and the English version - I trust you will also. The format is a bit different to my usual newsletters, but I encourage you to spend the time reading through the prose and let use know what you think of this.
Alexander Hoeher is based in Weilheim near Munich, Germany. After getting into software development with C++, he found himself attracted to Java, seeing its simplicity as a necessary basis for architecting reliable complex systems. A Sun Certified Enterprise Architect by now, his ideas about object-oriented design have been strongly influenced by playing around with Eiffel and digging into UML literature (the latter resulting in an IBM UML certificate). His current interests comprise concurrent programming (formal process modeling), design patterns, and XML related topics. He is fond of juggling, monocycling, swimming, and a dedicated guitar-player..
What is overloading, once again? Same method name for different methods - sounds harmless enough!
Sure it's one of the first things Java programmers are confronted with when learning the language. You are told things like: Do not mix it up with overriding - remember, these things may look quite similar, but are altogether different concepts! Then your Java introduction goes on telling you about unique parameter lists, and after one and half pages you get the impression that this is something not so terribly hard to understand. [HK: I can vouch for this argument. In my Java courses, students commonly make this mistake.]
What is the value proposition of this seemingly simple feature?
Shorter interfaces, not bogged down by artificial, tiresome discriminators, and a bit of lexical structuring of your class text: Overloading allows you to indicate the conceptual identity of different methods, letting you stress common semantics across methods so that similarities become apparent at first sight. It's supposed to make your code more readable, and what regards server code - the code, where these method siblings are defined -, it really does.
There are many who like it. There is tons of code using what overloading has to offer. And of course, you cannot even escape it in Java, where you're simply forced to use it when you want to provide different initializers. It seems, overloading rules - a feature not only popular, but tightly integrated into some important programming languages, an open commitment of venereous language designers that surely does not fail to impress the masses. And, what is more: no performance penalty whatsoever...
Now, should we fully embrace overloading in our own code then? Should we use it wherever possible? This discussion shall present an attempt to put the technical facts investigated in-depth by a former edition of this newsletter into a usage perspective - a bit similar in spirit to the popular harping on pointers which you can find in every Java introduction. The seminal idea that overloading clashes with dynamic binding is taken from a discussion of overloading to be found in "Object-Oriented Software Construction" by Bertrand Meyer.
There is no reason to question that naming conventions to indicate conceptual interrelatedness of different methods will benefit the class text where these methods are defined. To adopt the convention of reusing the same method name, however, has unfortunate consequences on client code which can become quite unintuitive, to say the least.
Overloading with parameter lists of different length pose no problem for client code interpretation, as they openly disambiguate client calls at first sight. Things that could irritate you just will not compile. However, when overloaded methods with the same method name have parameter lists of the same length, and when the actual call arguments conform to more than one signature of these overloaded methods, it somehow gets a little hard to tell which methods are actually executed just looking on the client calls. In this situation, you experience the strange phenomenon that the methods being called are not independent of the reference types being used for the calls.
There are several problems related to this, but first let's take another look on the small code example presented in a former edition of this newsletter in order to really get a feel for what it's like when methods being called are not independent of the reference types being used for the calls.
A minimal modification allows us to focus on the ugly side of overloading: The program still tells us which method gets actually called, but on top of that also delivers rather strong comments when overloading is caught to harm our ability to reason about the client code without knowing the server classes.
Basically, we have two fixed instances, which will play always the same roles: one serving as call target, the other serving as argument. Now we mix and match several calls always to be executed on these same instances (always the same target object, always the same argument object) the only difference being the reference types through which these objects are accessed. And behold: Different methods are being called. If you are familiar with this simple setting, you may skip the program part to directly go on with the following discussion.
public class OverloadingTest { public abstract static class Top { public String f(Object o) { String whoAmI = "Top.f(Object)"; System.out.println(whoAmI); return whoAmI; } } public static class Sub extends Top { public String f(String s) { String whoAmI = "Middle.f(String)"; System.out.println(whoAmI); return whoAmI; } } public static void main(String[] args) { Sub sub = new Sub(); Top top = sub; String stringAsString = "someString"; Object stringAsObject = stringAsString; if (top.f(stringAsObject) == sub.f(stringAsString)) //if (top.f(stringAsObject) == sub.f(stringAsObject)) //if (top.f(stringAsString) == sub.f(stringAsString)) //if (top.f(stringAsString) == sub.f(stringAsObject)) //if (sub.f(stringAsString) == sub.f(stringAsObject)) //if (top.f(stringAsString) == top.f(stringAsObject)) { System.out.println("Hey, life is great!"); } else { System.out.println("Oh no!"); } } }
Can you tell what happens with activating each of the conditions?
Let us carefully go through the code.
And that's it.
The program shows, once again, that one thing to be aware of in connection with overloading is that it's all about reference types. This is as true for target reference types as it is for parameter reference types. For instance, the predicate "sub.f(stringAsObject) == sub.f(stringAsString)" will resolve to false in our setup because two different methods are executed. This dependence on reference types in connection with overloading may or may not be what you expected, but the question remains if this is a clean approach to object-oriented programming.
No doubt, this may puzzle many a brave programmer, as it is a result absolutely exclusive to overloaded methods. And, as the use of overloaded methods does not identify itself as such in the method call, the intuitive, but unfortunately wrong expectation might be that the predicate returns true, as it would be the case with any gentle non-overloaded method.
Honest, do we like this? No. Object-oriented programming, as we know it, is about objects, not about references. We expect objects to behave the way they are and not the way they are referenced. Objects do their thing regardless of the role the client assigns them. This is how it should be be, and we call this thing dynamic binding. It is not cosmetics, it is not just a feature, it is THE feature. It shapes the architecture of our systems, decoupling clients from servers.
Now, with overloading a second rule, reference type dependence, takes over, breaking the fundamental polymorphic equivalence property described above (that polymorphic assignments do not change the results of method calls as long as the code can be compiled). The choice of references in the client, which should be based on considerations like grouping and low coupling, suddenly has to take the demands of overloading into account. Overloaded server objects affect the design of client code. Cosmetics beat structure. Unlike overriding, overloading cannot just be applied in a server method definition act and end of the story. It is a feature you have to stay aware of in your clients whose specific referencing of server objects influences what functionality gets called in the end. While with dynamic binding alone the method to be executed is completely server-defined, overloading proves to be client-sensitive.
Now to the problems. An important issue closely connected to software quality is readability. Our ability to reason about the software text is essential for any kind of maintenance, and, as you might have guessed by the direction this discussion has taken by now, overloading affects readability of client code in a rather negative way. It is all very well to let the program run and after the surprise look at the server code and explain the strange things away (oh, of course, overloaded methods, you know...), but nevertheless it would be preferable by far to predict the behaviour, simple as it is, by simply (i.e. exclusively) examining the client. Show me the client class, tell me no overloading is involved, and I tell you: "Hey, life seems great!" I can reason about the result of the condition solely looking at the client class.
With overloading being introduced, or even with just the slightest chance of overloading being used (this includes all unknown Java code), this statement is impossible to make, because you cannot tell if the same server method gets called without examining the server sources. In our program, you would have to read three classes instead of one to know what's going on. So, use of overloading weakens the expressive power of client code as the polymorphic equivalence property cannot be relied upon.
Sometimes, of course, you are willing to dig into the server code because you want to find out the exact server method that gets called. But even then overloading significantly complicates things. Without overloading, you just work your way bottom up through the target's class hierarchy, and when you find a match, bingo, you're done! With unknown code or code known to use overloading, this can be only your second step. First you have to examine the class of the reference and find the matching method. Only then can you check the class hierarchy for overriding methods. The bad thing about this is probably not the additional step involved, but that you have to repeat this analysis for every different reference type, because results can vary. Thus, overloading complicates the analysis of client-server interaction.
There is also a psychological dimension to all this. The following will try to show that overloading is not a gentle, unobtrusive language feature, but, as it stands in conflict with other language features, late binding and inheritance, particularly prone to abuse. In other words, overloading is an open invitation for introducing conceptual errors. Think of novice programmers or programmers in a rush. Overloaded methods, coming with its own method selection rules, present an anomaly in the object-oriented landscape shaped by the presence of dynamic binding, and will surely go on to puzzle people, who will falsely think overloaded methods behave like "normal" methods, or mistake overloading for overriding just because the methods signatures involved in overloading look so similar.
In fact, such a mistake may be seen as expressing justified desires regarding object-oriented design. Hell, we'd sure like to see the overloaded methods in our example being handled as an instance of overriding! The parameters of our methods are related through inheritance, so inspired by other programming languages, it does not take great imagination to see the derived class define a method that overrides the inherited method. Of course, this is an additional twist adding a bit of vision to our discussion, and of course, we know that Java does not support such covariant method redefinition (restricting the parameter domain of the method): Most of us have learnt by now that Java allows only specification inheritance (overriding being only defined for methods with the same return and parameter types). But still. Do we not think, deep in our heart, that the subclass method with the more specific parameter should, in a better world maybe, be the one in charge, overriding the superclass method? Think about an Integer class inheriting from Number while redefining addition for integers only. Not allowed in Java, but still desirable (and a real feature in other languages such as Eiffel). Sure, overloading is not to be blamed for an incorrect understanding of inheritance in Java, but it clearly invites such fantasies (and the corresponding errors) when used in a context such as the presented one. And even if such interpretations are wrong - shouldn't they be right?
And then the poor integration of overloading and inheritance in Java, which is very misleading as well. Reference type dependence means that overloading is simply not developed to conceptual consistency in the context of inheritance. Guessing from experience with overloaded methods defined in one and the same class, we might expect the method with the best match in terms of formal parameter type and actual method argument to be called on the object. This does not happen, though. Java does not produce any kind of "flat form" for the object's class with all overloaded methods, inherited or not, appearing side by side in a list in order to allow the runtime to choose the most appropriate.
No, what technically happens, is, in my understanding, that the compiler takes the method symbol plus the parameter reference types of some method call and calculates a position in the method table of the target's reference type. So, choosing between overloaded methods is done compile-time, and it is restricted to the overloaded methods of one class: the class of the reference type. Overloaded methods defined in subclasses of the reference type are never called: Java ignores the exiled siblings although the whole thing looks so very similar to overriding.
With overloaded methods being defined in superclasses of the reference type, Java exhibits quite strange behaviour: While the server code can still be compiled, client code will break: Trying to make a method call where the compiler would have to choose between them, you get a compilation error, complaining that the call is ambiguous. Put the method into the reference type and all is well. Don't ask me why - just remember selection of overloaded methods is limited to the reference type class. I personally believe this further anomaly might is more a compiler issue than a language issue. If you find a logic explanation for this, other than that it helps to improve compilation performance, please let me know.
Once again (the last time): overloaded methods defined in subtypes of the target reference will not be taken into consideration as candidates for execution by the runtime. With the table position given in the bytecode, the runtime will only check if there are overriding methods (which will appear at the same position in the method tables of subclasses if they exist). So, the compiler cannot hunt them down, and the runtime does not want to.
A consequence of this is, disturbingly, that the place where non-overridden overloaded methods are defined in the class hierarchy is of essential importance what regards the selection of the method being actually called. To me, this sounds a little scary, or would you really want your class design to be influenced by the crippled demands of overloading? Summing up: Overloading is a static compile-time feature which does not integrate well with our expectations shaped by dynamic method lookup coming along with inheritance.
What else can we do to shoot the dead man? (Who is still alive enough to ruin our programs, of course.) Bertrand Meyer sees overloading as a violation of the "principle of non-deception: differences in semantics should be reflected by differences in the text of the software" (OOSC 94, Bertrand Meyer). But wait a second, isn't late binding another case where there is only one method symbol for different methods?
As I understand it, the difference between late binding and overloading can be pinned to the observation that late binding lets one method name to be the pointer to one operation contract (which then can be fulfilled by several different methods whose differences are nevertheless absolutely transparent to the client code), whereas overloading lets one method name to be the pointer for several method specifications whose differences can be experienced in the client code. In the scope of the client, there is no difference between polymorphic calls bound to different methods. The polymorphic call specification is all the client has to know about the call. Overloaded methods, on the other hand, need not share common semantics, to be more precise, a common contract, their pre- and postconditions potentially varying wildly. This is something the client always has to take into account: Overloaded methods can not be used interchangeably, as different methods just under the same hood they have to be treated according to their specific contracts. These contracts, however, are hidden behind the same name which makes them hard to identify.The same method name does not point to a common denominator, in this case, but only serves to disguise differences that have to be laboriously disambiguated lateron. The client has to stay aware of the method contract being pointed to by a complicated three component key for the method which, as we have seen, consists of target reference type, method name, and parameter reference types.
So what are my final words to the programmer who, after having read this article, wonders if he should try to use overloading now wherever possible or not? Keep going... And if you really, really want to use it, go on and do so, but only with different method names - this is a trick stolen from real experts that can improve your overloading a lot! :o)
Sascha
Language Articles
Related Java Course
Would you like to receive our monthly Java newsletter, with lots of interesting tips and tricks that will make you a better Java programmer? | http://www.javaspecialists.eu/archive/Issue071.html | CC-MAIN-2017-09 | refinedweb | 3,193 | 50.16 |
About ruby programs.
・ SET i a: Assign value a to variable i (i = 1, 2)
・ ADD a: Calculates the value of variable 1 + a and assigns the calculation result to variable 2
・ SUB a: Calculates the value of variable 1-a and assigns the calculation result to variable 2
The first line is given the number of instructions n.
The following n lines are given in the order in which n instructions are executed.
n
s_1
s_2
・
・
s_i is one of three strings:
・ SET i a
・ ADD a
・ SUB a
(i = 1, 2;a is an integer)
Each value is passed as a string from standard input. I was thinking about a program like this, but I can't help it and I'd like to ask you for advice on what went wrong.
Code
input_lines = gets.to_i
i = Array.new (2, 0)
def setf (a, b)
i [a-1] = b
end
def addf (a)
i [1] = i [0] + a
end
def subf (a)
i [1] = i [0]-a
end
input_lines.times do | n |
command = gets.chomp.split ('')
if command [0] =='SET'
setf (command [1] .to_i, command [2] .to_i)
elsif command [0] =='ADD'
addf (command [1] .to_i)
else
subf (command [1] .to_i)
end
end
puts i.join ('')
Error
Main.rb: 9: in
setf&apos ;: undefined local variable or methodi'for main: Object (NameError)
from Main.rb: 23: in
block in<main>'
from Main.rb: 20: intimes'
from Main.rb: 20: in `<main>'
- Answer # 1
Related articles
- about reverse sorting of ruby array elements (code problem)
- about file specification program
- i'm confused about how to write ruby on rails
- ruby - about conditional branching with def index
- ruby on rails - there is something i don't know about the association between models
- ruby on rails - about render
- about uninitialized constant in ruby on rails
- ruby on rails - about nested routing urls
- windows 10 - about the program named "program" running at the start
- about rewriting hash of ruby
- python - about the program for electronic bulletin board made by raspberry pi
- ruby - half a program does not run
- ruby on rails - about introducing bootstrap to rails
- ruby - about require in rspec of rails application
- about input in the form in ruby on rails
- ruby - about classes and modules in rails
- ruby - i learned about singular methods, but do you really have a chance to use them?
- ruby - about params required for login
- ruby - about authenticate
- about [ruby]include? method
-
Local variables are linked to the defined method, so the local variable
>icannot be referenced.
In this case, it is easy to changeThere is also a method called
ito
@ior
$i.
Or use a lambda expression or proc
.
Is it a mystery whether you need to input the number of commands
nin advance
case/
whenseems to be easier to see | https://www.tutorialfor.com/questions-100665.htm | CC-MAIN-2020-40 | refinedweb | 466 | 69.62 |
Diagnosing Hidden ODR Violations in Visual C++ (and fixing LNK2022)
Visual C++
Hi, my name is Andy Rich, and I’m a tester on the front-end compiler. Last time I posted here, I discussed several aspects of testing conformance in the C++ compiler, which is a large part of my job. Another large part of what I do is diagnosing bugs in the compiler. These come from a variety of sources, such as customer reports through Connect, regression testing, and new tests. But some of the most useful and critical bugs come from one of our largest customers: other developers in Microsoft. These developers are the most likely to be using our latest product, and are often doing some very complicated things with it (such as building Windows).
What I want to discuss today is a class of bug report that we get all the time, especially from internal customers. We see these reports because the user is convinced they’ve caught a compiler bug, and have contacted us for a fix. But I’m not going to discuss a compiler bug – because this class of bug report is always user error.
It is important that I warn you up front: some of the tricks that I am going to use – one compiler switch in particular – are UNDOCUMENTED and UNSUPPORTED. If you choose to make use of this option in the compiler, you do so at your own risk. We use this option all the time internally, but we have basically no testing for it, so there’s no telling what might happen if you use it. Still here? Great – let’s get on with it.
Spot the defect is a fun game we play in the compiler team. Someone sends out a snippet of code, and says “Spot the defect!” and then we all take potshots at the code, trying to determine where the bug is. (I used to play the same game with my DDJ subscription – the first thing I sought out every month was the PC-Lint Bug Of The Month advertisements.) Let’s play the same game – here’s your code, in three source files:
// a.h – share class definition (code has been corrected from original post)
#pragma once
class Test_A {
public:
Test_A(){ c = ‘X’; data = 0; }
~Test_A(){ if(data) delete [] data; }
char c;
char* data;
};
void Test_A_Loader(Test_A&);
// loader.cpp – loader defn.
#include <cstring> //for strcpy
#include “a.h”
void Test_A_Loader(Test_A& a) {
a.c = ‘p’;
a.data = new char[10];
strcpy(a.data, “3.14159”);
}
// main.cpp – main program
#include <stdio.h> // for printf
#include “a.h”
int main(){
Test_A a;
Test_A_Loader(a);
printf(“%c : %c %c %c %cn”, a.c,
a.data[0], a.data[1], a.data[2], a.data[3]);
}
If I told you this code was crashing, would you believe me? This is simplified, but accurately represents the same class of bugs I was whining about earlier. The astute reader will look to the title of the post for assistance, which is helpful, though it won’t be a big enough hint: knowing the dangers of ODR violations are key to understanding this problem. (I did say they’d be hidden ODR violations, didn’t I?)
The One-Definition Rule is defined in section 3.2 of the C++ Standard (ISO/IEC 14882:2003). Paraphrasing that rule: no single translation unit can have two definitions for the same variable, function, class type, etc. However, between two translation units, some things can have the same definition (as in the code sample above), provided they are the same in both translation units. Based on this reading, it doesn’t appear I’m breaking this rule in my code – in fact, based on what I’ve shown you, I haven’t. Because the spot-the-defect was a trick question of sorts: there appears to be no crash in the code I showed you.
This lie-through-omission is the same one that internal customers tell all the time: the class appears to be the same in both translation units, and yet one translation unit is treating it differently than the other. They’re left to assume that there’s a bug in the compiler that’s causing this. After a while in the compiler group, you learn to ask the right questions; and the right question, in this case, is: how is this program being built? Because in this case, that’s where the defect lies:
cl main.cpp /Zp2 /c
cl loader.cpp /Zp1 /c
link main.obj loader.obj
As soon as I see the /Zp switch (or I notice code that has a lot of #pragma pack’s), I start getting suspicious that I’m about to see an ODR violation. The issue is actually fairly simple, once you understand it – the problem is that it is rarely as obvious as this case – classes have lots of base classes, are embedded in other classes, and often only show issues when you move to another architecture (especially when moving from 32 to 64-bit, because pointer sizes change).
The defect is that the definition of Test_A is different between main.obj and loader.obj. So main creates the object with one view, and loader goes and stomps the data passed to it with its own understanding of Test_A, then that object is returned by-value to main.obj, which then tries to access an invalid pointer.
Main.obj’s understanding of Test_A:
class Test_A size(6):
+—
0 | c
| <alignment member> (size=1)
2 | data
+—
Loader.obj’s understanding of Test_A:
class Test_A size(5):
+—
0 | c
1 | data
+—
You can clearly see that the data pointer is not in the same place in both of these objects. This looks like a bug of the compiler, but the compiler is explicitly complying with the user’s request, and because the two compilands are compiled as separate entities, there’s no way the compiler could diagnose this. The linker can diagnose this in limited scenarios, especially under IJW. If you’ve gotten the boggling “inconsistent metadata” error (LNK2022), you’ve probably fallen victim to this issue.
Diagnosing and fixing these issues, once you’ve run into them, is the real challenge. The LNK2022 help page is especially informative, stating: “In this case, make sure that the type has an identical definition in all compilands.” (Which is harder to do – especially when packing throws a wrench in there.) The compiler has a switch that can help you do this, but (as I said before) that switch is undocumented and unsupported. It’s also fantastically helpful. That switch is /d1reportSingleClassLayoutXXX, where XXX performs substring matches against the class name. In fact, those helpful class layout tables above were created with that switch:
cl main.cpp /Zp2 /c /d1reportSingleClassLayoutTest_A
Using this switch in multiple compilands and then comparing the output is an unbelievably useful way to get to the bottom of these issues. It shows you exactly what the compiler believes to be the layout of that class – if these layouts differ at all, you’ve got potential bugs waiting to be found. The switch is more than just useful – it can be fun to inspect and see how things are laid out by the compiler.
One other helpful tip for getting to the bottom of these problems is to make use of #pragma pack(show), which you can put right before your object definition to see what the packing level is when the compiler hits that line.
Thanks for reading,
Andy | https://devblogs.microsoft.com/cppblog/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022/ | CC-MAIN-2020-34 | refinedweb | 1,258 | 70.33 |
Hi All,
I am stumped and I am hoping for some assistance. I am currently using ImageJ 1.51. I have a lot of math to do on a lot of images that are in sequences. I need to do the math and then save the sequences as individual images. Because of the number of separate sequences, I wrote a macro to do this.
The mathematics in the macro are correct (I checked them by hand and it is all correct), however, I cannot seem to save the sequences as individual images. I used the run("Image Sequence ...") command produced by the macro recorder.
After several iterations, I used the recorder to provide the commands to simply open a sequence and save it as separate images in another folder. It will not mean anything (pathwise), but here is the exact commands provided by the recorder:
run("Image Sequence...", "open=C:\Users\PSP_2\Desktop\20inchMach6\Run003\Ratio\Test7020_Run0003_Seq301_Image000.rat sort");run("Image Sequence... ", "format=FITS use save=C:\Users\PSP_2\Desktop\20inchMach6\Run003\Calibrated\Ratio0000.fits");
(This is just a copy and paste, so no line breaks or anything like that)
If I copy and paste those exact lines in a macro, it fails. The sequence will open correctly, but the second line (to save the images) is simply ignored. There is no error provided. It just does not execute the command.
Any assistance would be greatly appreciated.
Thanks in advance,Neal
Oh....one other thing. I selected to use the slice names as the filenames.
Good day Neal,
please have a look at the many example macros and guides to macro programming that can be accessed from here:
I'm sure you will find useful code that helps with your problem.
Have success
Herbie
Hi Herbie,
I appreciate the links. However, this really does not explain why I can copy the EXACT commands from the macro recorder into a macro and it does not function properly. Again, these were the only commands.
I guess if it comes down to it, I will have to change the macro to pull each slice individually and save it.
Thanks,Neal
Neal,
ImageJ tells me that the images, if they are to be saved by
run("Image Sequence... ", "format=FITS use save=/Users/me/Downloads/ScreenShots");
(I'm on a Mac) in a directory named "ScreenShots", they need to be in a stack.If they are in a stack, the images are save separately as desired.
HTH
When I opened them with the run("Image Sequence...") command it put the images in a stack.
Thank you for your responses. I will try and figure out what is going on. I saw on some other posts where people were saving images separately from a stack. Their command had a slightly different format. Maybe I will try that.
It is just strange that using the exact command from the macro recorder is failing.
Neal
This is how I do it with bioformats importer, maybe it can help (python code).
def BF_Importer():
options = ImporterOptions()
options.setId(filepath)
options.setOpenAllSeries(True)
options.setSplitChannels(False)
imps = BF.openImagePlus(options)
index = 0
for imp in imps:
IJ.saveAs(imp, "TIFF", savepath+str(index).zfill(3))
index += index
Thanks Sverre,
However, I have figured out the issue and I think it is a bug. A small bug.....and a very annoying one.
It turns out the issue was in the last part of the second line. The macro recorder assigned the save part to save=C:\Users\PSP_2\Desktop\20inchMach6\Run003\Calibrated\Ratio0000.fits .
The issue is the .fits part. If that is truncated to three characters or less, the command works perfectly. Regardless of what you tell it to save as, it automatically appends the .fits extension.
So, if I wanted to name the file with a .tempK (for temperature in K), the command line would be ignored since the extension was more than three characters. However, if I wanted to name it .tpK, or .tK, or .fit, or .fts, then everything works as it should. The only thing is that the files will not have that extension. It will be .fits.
Long story short, I can do what I need to with the run("Image Sequence... ") command as long as the extension on the save= is three characters or less.
Thanks Herbie and Sverre for the responses and making me try and run this down.
I think you are on the wrong track:
The last part of the path for saving the images must be a directory, not a file name and of course no suffix.
I've mentioned that before. No bug here!
Regards
Except that the original command comes directly from the macro recorder. As I mentioned in the first post, if you simply copy the command from the recorder window and use that as a macro, it will fail. I am not sure if you call that a bug or not, but on the ImageJ macro reference site, it suggests using the macro recorder to determine syntax for the run(....) command. If you did that for saving a stack as individual images, it fails. I did not treat the save= part as an indicator of the directory (though it makes sense now) becaue the macro recorder actually supplies a filename.
Maybe it is not a bug, but it is very confusing at the least.....
the line I've posted in my second contribution was recorded with the macro recorder and the last part of the path evidently is a directory.
Not sure what's going wrong on your side.
Could you please create a folder named "test" on your desktop and run the following two macro lines with internet connection open
run("MRI Stack (528K)");run("Image Sequence... ", "format=FITS use save=C:\Users\PSP_2\Desktop\test");
and report what happens?
Thanks Herbie,
After I modified the macro (change the \ to \), it worked perfectly. Nice MRI images by the way. So I modified my call to not have a filename, and it worked perfectly too.
So, I tried another macro recording. On the dialog box for the Save As Image Sequence command, I kept the name blank (with the use slice as name checked). The next dialog has the file select box. However, there has to be a filename in that dialog box (you cannot just select a directory). This filename has .fits appended and this gets written to the macro recorder command, and that is causing the issue.
I forgot to mention it, but I am using a Windows 7 64-bit machine (should have mentioned that before).....
Basically, you are correct Herbie (as usual). The macro command works perfectly if the save= portion only has a directory. I was using the marco recorder supplied command and this had the filename attached.
Thanks for supplying the test macro and leading me through this. It is all working now.
I really appreciate it!!!!
obviously I was aware that you are on windows because I wrote:
run("Image Sequence... ", "format=FITS use save=C:\Users\PSP_2\Desktop\test");
.
After I modified the macro (change the \ to ) […]
Aha!
Happy coding
OOOPS....you are quite right....my bad.
And that was to change the single slash to a double slash in case it did not come out that way (like on my phone). | http://forum.imagej.net/t/saving-an-image-sequence-as-separate-images-in-a-macro/4913 | CC-MAIN-2017-26 | refinedweb | 1,224 | 75.91 |
import "github.com/alexkappa/trie"
Iter is a function type used as an argument to ForEach. It's arguments are the same as what would be returned on each for loop cycle, namely a rune and a map of nodes.
The Node type makes up the Trie data structure.
New allocates a new node.
All returns all the strings indexed by the current node and it's children in an array each item prefixed by p.
ForEach wraps the for loop and additionally checks for the end rune and ignores it.
Index builds a Trie with the supplied dictionary d.
Insert adds a new word to the Trie. It iterates over s and creates or appends a new Node for each rune.
IsEnd returns true if the current node is an end node.
Search looks for the string s inside the Trie structure. If s is matched and the node has mode children, its children are also returned as they all match the given prefix s.
String satisfies the Stringer interface for easily printing a Trie.
Package trie imports 3 packages (graph). Updated 2017-08-31. Refresh now. Tools for package owners. This is an inactive package (no imports and no commits in at least two years). | https://godoc.org/github.com/alexkappa/trie | CC-MAIN-2019-43 | refinedweb | 207 | 75.71 |
Odoo Help
This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.
How to include a button in editable treeview cell to show an edit form on the current record?
I have a editable tree view with 3 fields of a model. I would like to add a button to show a form to edit the rests of the fields of the model. How can I do it?
You can add a button, as Yogesh said, but you'll want to make it type object. This will link to a function in the tree's model class, and this function can return a new view. For example, in the xml:
<button name="button_details" string="Details" type="object"/>
Then in the class definition for this model:
@api.multi
def button_details(self):
view = {
'name': _('Details'),
'view_type': 'form',
'view_mode': 'form',
'res_model': 'my.custom.model',
'view_id': False,
'type': 'ir.actions.act_window',
'target': 'new',
'readonly': True,
'res_id': self.id,
}
return view
Make sure to replace 'my.custom.model' with the actual model you want to edit. Also, you'll need to have already definied the ir.actions.act_window and ir.ui.view records for that model, or Odoo won't know how to bring up the details. That top line there is from the new v8 api, but if you're using v7, remove it and just add the standard args to the button_details function call (cr, uid, ids, context). There are lots of examples of button functions in the code, I'm sure you can find one. The key to the button bringing up a new modal window is the line :
'target': 'new',
This will make the details edit be its own little popup window. Alternativly, you can set target to 'current' to just redirect to that page normally, but I'm going to guess in this instance you'd rather a little popup and then return to the main view.
EDIT: Oops, I forgot that the "'res_id': self.id," line is very important, and I think it only works with the v8 API. If you're using v7, instead of "self.id", you'll probably want the "ids" arg passed in from the function arguments. I hope that makes sense.
Hi, Ben. Thanks a lot. I haven´t test yet but that looks like the solution.
Doesn´t this method should return something like {'domain': {'field':'domain'}, 'value' : 'field2': 'text'}?
Well, I guess it works in v8, but in OpenERP 7 parameter 'res_id' must be something else.
You can add a button on tree and pass action of that form in name. like :
<button name="%(action_id_of_form_you_want_to_open)d" type="action" string="Open Form"/>
Hi. Thanks for your answer but this just shows a form with no empty values in fields and no save (nor cancel) button. I need the form to edit the current record. Do I need to set some value in context! | https://www.odoo.com/forum/help-1/question/how-to-include-a-button-in-editable-treeview-cell-to-show-an-edit-form-on-the-current-record-61150 | CC-MAIN-2016-50 | refinedweb | 501 | 74.9 |
Ye-Sheng Kuo,
Thomas Schmid,
Matt Smith,
and Prabal Dutta.
See posted lab schedule for due dates, in-lab, and post-lab due dates.
As you might guess, with all the other goodies included in SmartFusion MSS the folks at Actel did not forget ADC and DAC resources. The MSS ACE (Analog Computing Engine) is relatively complex component providing DAC/ADC functionality, sampling control, analog threshold detection, filtering and DMA access just to mention a few. Despite this apparent complexity, the ACE can be relatively easy to use. The ACE like the other MSS components is automatically interfaced to the peripheral bus and a user friendly GUI is provided for configuration.
The purpose of this lab is to...
Quantizing error is inherent in most measurements and limits the certainty a measurement. The quantizing error for an ADC is defined to be 1 LSB. It can also be expressed in volts or LSBv for an n-bit ADC .
Quantizing error in volts = voltage range of conversion/2^n
For our converter, the voltage range is 2.56 volts. If we program the ACE to be an 8 bit ADC, the quantizing error in milli-volts will be
LSBv = 2.56 volts/2^8 = 10 mv
So, you can only know the value to 10 mv. The ideal quantum size of 1 LSB can actually vary to be larger or smaller from fabrication issues and other sources. These effects are characterized as integral non-linearity (INL) and differential non-linearity (DNL). Under normal conditions in the lab you will NOT observe this.
Plotting the conversion value against the analog value defines the ADC transfer characteristic or input to output relationship.
The first graph shows the ideal transfer function excluding quantizing effects. The second case illustrates the affect of quantizing resulting in a stair case like transfer function. In this case the quantization error is from 0 LSB to 1 LSB. The last graph illustrates an ADC model that shifts the transfer function to center the quantizing error over the conversion intervals. In this case, the quantization error is +/- ½ LSB. In both cases the quantizing error is 1 LSB, but the relationship of the conversion value to the input voltage is shifted by ½ LSB.
When converting relatively stable voltages to digital values a few samples are sufficient to represent the voltage. However, when sampling time varying signals the question arises, just how many samples are required to represent the signal. The Nyquist-Shannon sampling theorem predicts that periodic signals can be reproduced when the original signal is sampled at >= 2 times its period. If the signal is sampled at a rate that is less than the 2 times its period, the reconstructed signal will have a different frequency and shape. A simple predictor is given by the following equation:
alias frequency = sampled signal frequency - sampling frequency
The reconstructed signal is commonly referred to as an alias and is a common problem in applied signal processing. There are many topics forming the foundation of signal processing, but these basics should cover our needs for the present.
Each SmartFusion Eval Kit has 10 direct analog input channel and 2 Sigma-delta DAC. We want to use just one of each. Open the Libero, SmartDesign. Double click ACE
In left column, add a ADC Direct Input service. Put ADC_input0 in Signal Name and check Send raw ADC result to DMA, and click OK. On the top of configurator, set the resolution to 8 bits.
Add another Sigma Delta DAC service, select ACE Accumulator as DAC input and select the DAC resolution to 8 bits. Click OK.
Set your ADC Direct Input Package Pin to V12 ( ADC5 ), and
Sigma Delta DAC Package
Pin to V7 ( SDD0 )
Go to Controller tab, select ADC1_MAIN. Add all Available signals to sampling rate requirement. Click Calculate Sequence and Actual Rate
Notice that the Total sampling rate should be 87.000 ksps. We
want to slow it down to 8 ksps.
Select the Operating sequence entry to Manual and insert a operating sequence slot.
Insert a WAIT TIME and configure it to 115us. Move the Wait for 115.00us above Restarts the execution sequence for this timeslot. Click Calculate Actual Rate. The Actual Rate for ADC / DAC should be 8.000 ksps. Click OK and go to Firmware tab. Check the UART, ACE, NVM, PDMA drivers.
Click Save and Generate. Put the IP core to canvas and run the synthesis, place & route and flash your SmartFusion.
Create a C project in Softconsole as you did before, set the linker
script, import the drivers. The following code reads the ADC
and write the DAC with the ADC conversion value
#include <stdio.h> #include <inttypes.h> #include "drivers/mss_ace/mss_ace.h" #include "drivers/mss_uart/mss_uart.h" ace_channel_handle_t adc_handler; int main(){ ACE_init(); ACE_configure_sdd( SDD1_OUT, SDD_8_BITS, SDD_VOLTAGE_MODE | SDD_RETURN_TO_ZERO, INDIVIDUAL_UPDATE ); ACE_enable_sdd(SDD1_OUT); adc_handler = ACE_get_channel_handle((const uint8_t *)"ADC_input0"); while(1){ uint16_t adc_data = ACE_get_ppe_sample(adc_handler); ACE_set_sdd_value(SDD1_OUT, (uint32_t)(adc_data>>4)); } return 0; }
Put the code in a main.c file. Compile the source code and launch the debugger session.
Hook the signal generator to the extension board header pin 5 ( paper label) in the bottom right corner to provide input to the DAC. If you don't have a paper label this is labeled ADC1. Observe the DAC output on the BNC shown connected.
Using the signal generator as a signal source, provide a sine wave that centers a sine wave over the input range of the ADC (0 - 2.56 volts). A DC offset of 1.25 volts should be fine with a Vpp (peak to peak) voltage of 2.5 volts. Be sure the signal generator output is set to High Z to insure accurate signal levels. Verify with the scope before attaching to the kit to avoid damage to the ACE.
Set the source signal to 1 KHz sine wave. Observe the DAC output. Notice the quantizing steps in the output wave form. With the input and output waveforms displayed on the scope, it should look something like this.
For the post lab, record the number of quantizing steps there are per cycle.
Construct a low pass filter with a 1K ohm resistor and 0.068uf capacitor on a protoboard. Wire the DAC to the input of the filter and observe the output.
You should notice a signal that is pretty close to a continuous sine wave. The signal will be attenuated because of the filter.
The filter output amplitude should be about 0.707 the value of the input voltage value at the 3db down frequency (2.34KHz) . Notice that it is considerably lower. Adjust the frequency until the filter output value is 0.707 the value of the source frequency and record the frequency for the post lab.
printf("adc_result: %u\r\n", (adc_data>>4));
You will measure the transition or boundary voltages for the first 4 ADC conversion values 0, 1, 2 and 3. The lab power supply 0-6 volts output can be adjusted to ~ 1mv, so you can use this as a voltage source. The voltage meter on the power supply is not accurate enough for 1 mv measurements, so you should use the DMM. Be sure to use the cable configurations shown in the following configuration or you will introduce interference that will make it difficult to resolve the transition voltages.
The procedure for measuring the transitions voltages is to simply start at 0 volts then gradually increase the voltage until you see the conversion value change. The voltage at which the conversion value changes Is the transition voltage. You will likely find that the transition voltage does not occur neatly on a 1mv boundary. In fact, it will waggle between adjacent conversion values for several millivolts. Measure this transition phase by measuring when the waggling starts and stops. Record the following values to answer questions in the post lab assignment. The start and end boundary values should be no more than a few millivolts apart. If they are, consult your lab instructor.
Now, we learned how to use ADC / DAC in SoftConsole, we want to build a voice recorder using the SmartFusion Eval. Kit. However, we cannot connect the microphone directly to the ADC and connect the speaker to DAC. We need some signal conditioning between the board and mic / speaker.
You should received the following components in this lab.
We want to implement the voice recorder system. The system is composed of three parts,
Before building your circuit, you may want to check these references.
The following circuit is for your reference. Keep your connections short and neat as shown.
Once you are done with the Pre-Amp part, connect the power supply to the board. In this circuit, we need +/- 10 Volt for +/- VSS. Be careful not to short the power to ground. If you notice the current goes thru the roof, turn off the output of power supply! This usually means your circuit has a short between power and gnd. Connect the scope to the Pre-Amp output and the microphone(positive), observe the amplified signal. What is the gain(Vout/Vin) of the circuit? Do not need to consider the DC offset, which means you can set the scope to AC coupling to observe the gain.
When you finish the Power-Amp part, do not connect to the SmartFusion kit immediately. Instead, verify the operation of the by connecting the first part and second part together. Try to generate some voice in MIC. Can you hear the voice from speaker? If not, check the circuit until you can hear your voice in the speaker.
Connect the pre-amp output to the ADC1 as you did before, and DAC1 output to power-amp. In this typical application, we will record voice for 10 seconds to memory. The size of the data = 8k Samples/sec × 1 Byte/Sample × 10 sec = 80k bytes. We are memory limited at the moment and have to share the space with the program code.
The data is stored in 0x6002b000, if you put your code in eVNM, make sure the data won't override your code
Open the Libro, we want to configure the ACE with interrupt telling the
microprocessor the DAC data has been sampled. In other words, we want
to generate the 8K Hz interrupt and update the DAC registers. Go to the
controller tab, insert operation sequence slot, select SET
INTERRUPT
Configure the interrupt bit to GP0, click OK.
Generate the design, synthesis and program your SmartFusion. Updating the following code to SoftConsole. Find out how to subscribe the interrupt generated by ACE. (PC0_FLAG0) Update the DAC data once the interrupt is fired.
#include <stdio.h>
#include <inttypes.h>
#include "drivers/mss_uart/mss_uart.h"
#include "drivers/mss_watchdog/mss_watchdog.h"
#include "drivers/mss_ace/mss_ace.h"
#include "drivers/mss_gpio/mss_gpio.h"
#include "drivers/mss_nvm/mss_nvm.h"
#include "drivers/mss_pdma/mss_pdma.h"
uint8_t *envm = (uint8_t *) 0x6002b000;
uint32_t envm_idx;
#define FREE_BUFFER 0
#define UNDER_DMA_CONTROL 1
#define DATA_READY 2
#define SAMPLES_BUFFER_SIZE 128
#define NB_OF_SAMPLE_BUFFERS 2
#define TOTAL_SAMPLE_SIZE 81920
/* PDMA destination */
uint32_t samples_buffer[NB_OF_SAMPLE_BUFFERS][SAMPLES_BUFFER_SIZE];
uint8_t buffer_status[NB_OF_SAMPLE_BUFFERS];
void ace_pdma_rx_handler();
void process_samples();
void free_samples(uint8_t);
void play_samples();
volatile uint8_t pdma_buffer_idx = NB_OF_SAMPLE_BUFFERS;
int main()
{
uint8_t full = 0;
envm_idx = 0;
dac_irq = 0;
MSS_WD_disable();
ACE_init();
ACE_configure_sdd(
SDD1_OUT,
SDD_8_BITS,
SDD_VOLTAGE_MODE | SDD_RETURN_TO_ZERO,
INDIVIDUAL_UPDATE
);
ACE_enable_sdd(SDD1_OUT);
PDMA_init();
PDMA_configure
(
PDMA_CHANNEL_0,
PDMA_FROM_ACE,
PDMA_LOW_PRIORITY | PDMA_WORD_TRANSFER | PDMA_INC_DEST_FOUR_BYTES,
PDMA_DEFAULT_WRITE_ADJ
);
PDMA_set_irq_handler( PDMA_CHANNEL_0, ace_pdma_rx_handler );
NVIC_EnableIRQ( DMA_IRQn );
free_samples(full);
while (1)
{
// recording mode
if (full==0)
process_samples();
// playing mode
else{
play_samples();
}
if (envm_idx>=TOTAL_SAMPLE_SIZE){
envm_idx = 0;
if (full)
full = 0;
else
full = 1;
free_samples(full);
}
}
return 0;
}
void free_samples(uint8_t full_flag){
uint32_t i;
for ( i = 0; i < NB_OF_SAMPLE_BUFFERS; ++i ){
buffer_status[i] = FREE_BUFFER;
}
pdma_buffer_idx = 0;
buffer_status[pdma_buffer_idx] = UNDER_DMA_CONTROL;
if (full_flag){
}
else{
PDMA_enable_irq( PDMA_CHANNEL_0 );
PDMA_start
(
PDMA_CHANNEL_0,
(uint32_t) PDMA_ACE_PPE_DATAOUT,
(uint32_t) samples_buffer[pdma_buffer_idx],
SAMPLES_BUFFER_SIZE
);
}
}
// PDMA recived interrupt
void ace_pdma_rx_handler()
{
PDMA_clear_irq( PDMA_CHANNEL_0 );
buffer_status[pdma_buffer_idx] = DATA_READY;
PDMA_disable_irq( PDMA_CHANNEL_0 );
}
void process_samples(){
uint8_t i;
if ( buffer_status[pdma_buffer_idx] == DATA_READY){
uint32_t proc_buffer_idx = pdma_buffer_idx;
if (pdma_buffer_idx==(NB_OF_SAMPLE_BUFFERS-1))
pdma_buffer_idx = 0;
else
pdma_buffer_idx++;
if (envm_idx<TOTAL_SAMPLE_SIZE){
PDMA_start (
PDMA_CHANNEL_0,
/* Read PPE_PDMA_DOUT */
(uint32_t) PDMA_ACE_PPE_DATAOUT,
/* This is in MSS ESRAM */
(uint32_t)samples_buffer[pdma_buffer_idx],
SAMPLES_BUFFER_SIZE
);
PDMA_enable_irq( PDMA_CHANNEL_0 );
}
buffer_status[pdma_buffer_idx] = UNDER_DMA_CONTROL;
uint8_t data_processed[SAMPLES_BUFFER_SIZE];
for ( i = 0; i < SAMPLES_BUFFER_SIZE; ++i ){
volatile uint16_t raw_value;
raw_value = ACE_translate_pdma_value(samples_buffer[proc_buffer_idx][i], 0);
data_processed[i] = raw_value>>4;
}
NVM_write((uint32_t)(envm+envm_idx), data_processed, SAMPLES_BUFFER_SIZE);
envm_idx += SAMPLES_BUFFER_SIZE;
}
}
// put your code here
void play_samples(){
}
In the above code, we use the PDMA to transfer the data from ADC register to SRAM, after a simple processing, the data was stored to eNVM. However, the code uses 8K Hz interrupt to send the data from eNVM to DAC.
Questions
Voice Recorder Modification
Submit the values transitions values you measured for the In-lab. Add a column for each conversion value and calculate the difference between the start boundary high value and start boundary low value. Assume this voltage difference represents the voltage range for each conversion interval. Answer the following questions:
Voice recorder
Provide the answers from questions in the
In-Lab and a Signoff sheet for your modified voice recorder. | http://web.eecs.umich.edu/~prabal/teaching/eecs373-f10/labs/lab7/index.html | CC-MAIN-2016-40 | refinedweb | 2,158 | 56.35 |
Over the last few months there’s been something of a roadshow making its way around the country giving journalists, et al. hands-on experience of using Scraperwiki (I haven’t been able to make any of the events, which is shame:-(
So what is Scraperwiki exactly? Essentially, it’s a tool for grabbing data from often unstructured webpages, and putting it into a simple (data) table.
And how does it work? Each wiki page is host to a screenscraper – programme code that can load in web pages, drag information out of them, and pop that information into a simple database. The scraper can be scheduled to run every so often (once a day, once a week, and so on) which means that it can collect data on your behalf over an extended period of time.
Scrapers can be written in a variety of programming languages – Python, Ruby and PHP are supported – and tutorials show how to scrape data from PDF and Escel documents, as well as HTML web pages. But for my first dabblings, I kept it simple: using Python to scrape web pages.
The task I set myself was to grab details of the membership of UK Parliamentary All Party Groups (APGs) to see which parliamentarians were members of which groups. The data is currently held on two sorts of web pages. Firstly, a list of APGs:
Secondly, pages for each group, which are published according to a common template:
The recipe I needed goes as follows:
– grab the list of links to the All Party Groups I was interested in – which was subject based ones rather than country groups;
– for each group, grab it’s individual record page and extract the list of 20 qualifying members
– add records to the scraperwiki datastore of the form (uniqueID, memberName, groupName)
So how did I get on? (You can see the scraper here: ouseful test – APGs). Let’s first have a look at the directory page – this is the bit where it starts to get interesting:
If you look carefully, you will notice two things:
– the links to the country groups and the subject groups look the same:
<p xmlns=”” class=”contentsLink”>
<a href=”zimbabwe.htm”>Zimbabwe</a>
</p>
…
<p xmlns=”” class=”contentsLink”>
<a href=”accident-prevention.htm”>Accident Prevention</a>
</p>
– there is a header element that separates the list of country groups from the subject groups:
<h2 xmlns=””>Section 2: Subject Groups</h2>
Since scraping largely relies on pattern matching, I took the strategy of:
– starting my scrape proper after the Section 2 header:
def fullscrape(): # We're going to scrape the APG directory page to get the URLs to the subject group pages starting_url = '' html = scraperwiki.scrape(starting_url) soup = BeautifulSoup(html) # We're interested in links relating to <em>Subject Groups</em>, not the country groups that precede them start=soup.find(text='Section 2: Subject Groups') # The links we want are in p tags links = start.findAllNext('p',"contentsLink") for link in links: # The urls we want are in the href attribute of the a tag, the group name is in the a tag text #print link.a.text,link.a['href'] apgPageScrape(link.a.text, link.a['href'])
So that function gets a list of the page URLs for each of the subject groups. The subject group pages themselves are templated, so one scraper should work for all of them.
This is the bit of the page we want to scrape:
The 20 qualifying members’ names are actually contained in a single table row:
def apgPageScrape(apg,page): print "Trying",apg url=""+page html = scraperwiki.scrape(url) soup = BeautifulSoup(html) #get into the table start=soup.find(text='Main Opposition Party') # get to the table table=start.parent.parent.parent.parent # The elements in the number column are irrelevant table=table.find(text='10') # Hackery...:-( There must be a better way...! table=table.parent.parent.parent print table lines=table.findAll('p') members=[] for line in lines: if not line.get('style'): m=line.text.encode('utf-8') m=m.strip() #strip out the party identifiers which have been hacked into the table (coalitions, huh?!;-) m=m.replace('-','–') m=m.split('–') # I was getting unicode errors on apostrophe like things; Stack Overflow suggested this... try: unicode(m[0], "ascii") except UnicodeError: m[0] = unicode(m[0], "utf-8") else: # value was valid ASCII data pass # The split test is another hack: it dumps the party identifiers in the last column if m[0]!='' and len(m[0].split())>1: print '...'+m[0]+'++++' members.append(m[0]) if len(members)>20: members=members[:20] for m in members: #print m record= { "id":apg+":"+m, "mp":m,"apg":apg} scraperwiki.datastore.save(["id"], record) print "....done",apg
So… hacky and horrible… and I don’t capture the parties which I probably should… But it sort of works (though I don’t manage to handle the <br /> tag that conjoins a couple of members in the screenshot above) and is enough to be going on with… Here’s what the data looks like:
That’s the first step then – scraping the data… But so what?
My first thought was to grab the CSV output of the data, drop the first column (the unique key) via a spreadsheet, then treat the members’ names and group names as nodes in a network graph, visualised using Gephi (node size reflects the number of groups an individual is a qualifying member of):
(Not the most informative thing, but there we go… At least we can see who can be guaranteed to help get a group up and running;-)
We can also use an ego filter depth 2 to see which people an individual is connected to by virtue of common group membership – so for example (if the scraper worked correctly (and I haven’t checked that it did!), here are John Stevenson’s APG connections (node size in this image relates to the number of common groups between members and John Stevenson):).
I published the spreadsheet and tried to view it in my Guardian Datastore explorer, and whilst the column headings didnlt appear to display properly, I could still run queries:
Looking through the documentation, I also notice that Scraperwiki supports Python Google Chart, so there’s a local route to producing charts from the data. There are also some geo-related functions which I probably should have a play with…(but before I do that, I need to have a tinker with the Ordnance Survey Linked Data). Ho hum… there is waaaaaaaaay to much happening to keep up (and try out) with at the mo….
PS Here are some immediate thoughts on “nice to haves”… The current ability to run the scraper according to a schedule seems to append data collected according to the schedule to the original database, but sometimes you may want to overwrite the database? (This may be possible via the programme code using something like fauxscraperwiki.datastore.empty() to empty the database before running the rest of the script?) Adding support for YQL queries by adding e.g. Python-YQL to the supported libraries might also be handy? | https://blog.ouseful.info/tag/scraperwiki/?orderby=ID&order=ASC | CC-MAIN-2021-39 | refinedweb | 1,191 | 54.76 |
Dear All,
I am trying to understand how to create SDI based on ViewForm class that has a different dialog in the mainframe according to the type of user that has logged.
I have been playing our this afternoon and noticed that when you click on the ".rc" file in the resource folder you can create add a new dialog. Then I went to the view class and adding to his enum the token identifying the dialog ID.
(Something like "enum{IDD = IDD_DIALOGTEST_FORM, IDD1 = IDD_FORMVIEW1, IDD1 = IDD_FORMVIEW2}")
After this I have modified the constructor method of the myview class changing the paramenter that gives to the CFormView upper class.
(Something like "CDialogTestView::CDialogTestView()::CFormView(IDD1){}")
The goal I wanted to achieve was to change the token basing on the login and for this I tried to call the super constructor from the constructor method body:
(Something like "CDialogTestView::CDialogTestView(){
if(login==1){
CFormView(IDD1);}
else{CFormView(IDD);}
}")
Unfortunately it gives me the following error at compile time:
error C2512: 'CFormView' : no appropriate default constructor available
I was wondering if anyone know already a better way of doing this and if MICROSOFT has already implemented a class or method to do so.
Thanks for ur attention and Best Regards!
PS: If interested please find the source file and the project for VS 2008 at
Size approx 6.6 MB
You did it almost right. Try this:
CDialogTestView::CDialogTestView()
: CFormView((login == 1) ? IDD_DLG1 : IDD_DLG2)
{
}
Note that you cannot use just any kind of dialog, there are some restrictions. To have a second dialog compliant with the requirements, make a copy of the dialog created by the wizard.
Thank you very much.. so basically I can use a tree of conditions in this way and choose between 2 or more users. That's good. I am kinda of surprised that there isn't an MFC standard class or method to do so.. but happy to have fixed that.
Originally Posted by srelu
Note that you cannot use just any kind of dialog, there are some restrictions. To have a second dialog compliant with the requirements, make a copy of the dialog created by the wizard.
Regarding the quotation above I have not clear what you mean exactly. Do you refer to the dialog class created by the App Wizard at the very beginning when creating the application?
Isn't there a risk by just copying the dialog? I mean.. when using VS the dialogs are created but often there are macros and other pieces of code added in other classes, if we copy only we loose the dependencies..
To create a new dialog I went to the ".rc" file and added the dialog as new resource.. is this sound to u guys?
thanks again!
I simply answered your question. They way you're doing the job is not the standard one. Normally you should create multiple views for the same document and activate the one you need.
Not going on the standard way means that nobody can tell you for sure that everything will be ok.
But, it would be highly unusual for a parent class to access objects from the derived class. Anyway the parent class receives the dialog identifier trough the constructor.
I even checked the mfc sources, there was nowhere any IDD (except for some classes derived from CDialog - like your form view class).
Yes indeed I was talking about the dialog created by the app wizard.
When I told you that I made a copy I meant that the dialog requires some features to work properly (the WS_CHILD style). Instead of verifying all the styles, I preferred the easier way, a copy.
If you don't have a resource editor, modifying manually the rc file is the right way to add resources (dalogs).
thank you..
I am sorry to bother you but I am totally new to MFC programming.. I am trying to get my head around it but is a bit confusing sometimes.
Ok then, I will do as according to the standard way.. I do not want to re-invent the wheel.
Basically you are telling me to create different views. I am not sure how to do it but I will list the steps I would do, please correct me if I am wrong:
1 - create an SDI project using VS App wizard
2 - create a new view: ? what does this mean -
- is it correct to add a new resource choosing VIEW and then adding a class to the view?
Once createad the class I do not know how to link it with the mainframe.. how would you do that?
I am sorry for asking that, but I realize that I probably need a step by step tutorial to do that.. I would be grateful for any help.. thanks!
Normally you should create multiple views for the same document and activate the one you need.
I would say, it depends on the nature of the issue that we're not aware of. Why another user has to have another kind of dialog? How different the dialogs are? If the difference is sufficient enough, it might be better to create different document as well to correspond their views more accurate.
Best regards,
Igor
Ok well..
I am working on SDI documents since the views are supposed to be similar...
could anyone contribute with a step by step explaination of my question above? If not nevermind and thanks anyway!
Originally Posted by pengCC
2 - create a new view: ? what does this mean -
.........................
Once createad the class I do not know how to link it with the mainframe.. how would you do that?
Originally Posted by pengCC
- is it correct to add a new resource choosing VIEW and then adding a class to the view?
Yes. You must add first the dialog resource, then add the class.
I don't know what Visual Studio do you use.
In the case you use an Express Edition, well I never used one, but as I heard it doesn't have a resource editor. If that's your case, your only option is to modify manually the *.rc file to add the dialog reesource.
If you have a better VS, go to the menu click on View then click the menu intem named "Resource View". A window will open allowing you to browse resources, add, remove and edit them.
After you added the dialog resource, you can add a class for it.
1. How to add the class if you have a resource editor:
1.1 Open the dialog box in the resource editor.
1.2 Double click it's surface. The MFC Class Wizzard will pop up inviting you to add a class for that dialog box.
1.3 Enter the name of the class and click OK.
1.4 Done.
2 How to add the class if you don't hve a resource editor:
2.1 Clik the menu "Projects" item and then click "Add Class".
2.2 From the dialog box that will pop up chose MFC class then click Add.
2.3 In the next dialog:
- add a name for your class in the "Class Name" box
- In the "Base Class" combo pick "CFormView"
- In the "Dialog ID" combo pick the identifier of your dialog box. (if you don't see it there make sure the base class is CFormView and check if the identifier is added to the resource.h file.)
- Click "Finish"
2.4 Done.
For the rest, see the link I provided to you. As a beginer, you'll need to read and work a lot to understand the document-view architecture. Not to mention that the task you picked is not among the simplest.
Thank you for that, looks very helpful. I have started following your hints + the msdn tutorial but I got stuck..
I followed step by step the MSDN tutorial but it does tell me only that I need to create a new class. Once I run the program it gives me the following errors:
Compiling...
1>MyWinApp.cpp
1>c:\documents and settings\pengCC\desktop\c# trials\mywinapp\mywinapp\mywinapp.cpp(121) : error C2259: 'CNewView' : cannot instantiate abstract class
1> due to following members:
1> 'void CView::OnDraw(CDC *)' : is abstract
1> c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxwin.h(4242) : see declaration of 'CView::OnDraw'
etc..
I believe that is cause the class is abstract and I need to declare all the methods.. the thing is that I do not know how to declare manually the massage map etc..
That is what the AppWizard generates:
#include "StdAfx.h"
#include "NewView.h"
CNewView::CNewView(void)
{
}
CNewView::~CNewView(void)
{
}
I have visual studio professional 2008.
I will now try doing the same with a CFormView based project (instead of the CView based one) and see if I can get it working..
Will keep u posted..
...its still gives me a bunch of errors at compilation time.. following step by step the microsoft tutorial there are errors, trying to do what you suggested step by step as well.. something is definetely missing and I have been trying to figure it out..
At the moment:
1>Compiling...
1>MyFormApp.cpp
1>c:\documents and settings\pengCC\desktop\c# trials\myformapp\myformapp\myformapp.cpp(142) : error C2664: 'CFormView::Create' : cannot convert parameter 2 from 'const char [14]' to 'LPCTSTR'
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
etc..
And something else that looks kinda of odd to me is that when I create a newContext the m_pLastView function returns only a view but there is not way to get a similar function to return a CFormView..
CCreateContext newContext;
newContext.m_pNewViewClass = NULL;
newContext.m_pNewDocTemplate = NULL;
newContext.m_pLastView = NULL;
newContext.m_pCurrentFrame = NULL;
newContext.m_pCurrentDoc = pCurrentDoc;
I think that there is probably some problem with that..
Anyone managed to implement the MSDN tutorial successfully?
Thanks!
ok I solved. | http://forums.codeguru.com/showthread.php?495910-MFC-SDI-based-on-ViewForm-How-to-create-different-forms-according-to-the-user-log&p=1934491 | CC-MAIN-2020-24 | refinedweb | 1,663 | 74.08 |
Here is a Java Program to check Leap year, A leap year has 366 days, instead of 365. To check whether a year is a leap year or not first we have to find out the possible ways of checking a leap year mathematically. The following conditions have to be fulfilled:
- The year is a leap year if it has 366 days.
- It is not if it has 365 days.
- The year is evenly divisible by 400, then check for step 1, else move to step 2.
- If it is evenly divisible by 100, check for step 3, else move to step 1.
- The year is evenly divided by 4, check for step 4, else move to step 2.
Steps to Check Leap Year
- Take an integer variable as input for the year.
- Assign a particular value to the variable.
- We first check if the year is divisible by 4, but not 100, simply print the output as The year is a leap year.
- If the input is completely divisible by 400, simply print the same output.
- Else, we print ‘The year is not a leap year’.
How to Check Leap Year by Giving Input
import java.util.Scanner; public class LeapYear { public static void main(String[] args) { int year; Scanner scan = new Scanner(System.in); System.out.println("Enter a year to check if it is a leap year:"); year = scan.nextInt(); scan.close(); boolean Leap = false; if(year % 4 == 0) { if( year % 100 == 0) { if ( year % 400 == 0) Leap = true; else Leap = false; } else Leap = true; } else { Leap = false; } if(Leap==true) System.out.println(year + " is a Leap Year."); else System.out.println(year + " is not a Leap Year."); } }
Learn Scanner Class in Java
The output of the program will be:
Enter a year to check if it is a leap year: 2020 2020 is a leap year
Check Leap Year
This is the whole elaborated version of how to understand the algorithm. To reduce the complexity of the program, we can also write is as following:
public class DeveloperHelps { public static void main(String[] args) { //year to leap year or not int year = 2020; System.out.println(); if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) System.out.println(year + " is a leap year"); else System.out.println(year + " is not a leap year"); System.out.println(); } }
The output of the program will be:
2020 is a leap year.
Java Programs with Examples and Output
1.) Java program to get IP address
2.) Factorial Program in Java
3.) Java program to reverse a string
4.) Java Program to Convert Kilometers(KMS) to Miles
5.) Swap two numbers using bitwise operator
Thanks for the reading post. I hope you like and understand the post. If you have any doubts regarding this post please comment below. | https://www.developerhelps.com/java-program-to-check-leap-year/ | CC-MAIN-2021-31 | refinedweb | 469 | 74.49 |
I have a question about pointers.
First, how are pointers of different types interpreted? ?
char qtr = 3289; int * ptr =&qtr;
Suppose you have this code:
I think that an exception will be thrown for RISC CPUs because it spans alignment. I don't usually use it like this.
Char type address is assigned to int type pointer.
In this case, is ptr interpreted as aint pointer?Or is it achar pointer?
class Base {} class Derived: public Base {} Derived obj; Base * ptr =&obj;
How about this one? This is a code I often see.Which pointer is ptr after all? ?
Second
I don't understand dynamic_cast.
The following is written in my book.
The real class type of the object pointed to by a pointer or reference is known only at runtime.
Eh? why? ?
In the above code example, you can see that Ptr contains a Derived type object without executing it. ?
void f (Base&base) { Derived&d = static_cast<Derived&>(base);// I don't know if base refers to derived. }
In the function, it is certainly unknown whether it is referenced.
But ... you know the object you pass when you call the f function, even if it's not at runtime?
The real class type of the object pointed to by a pointer or reference is known only at runtime. Therefore, there is a possibility that the conversion always fails. Therefore, when using dynamic_cast, you must always write your code under the assumption that the conversion may fail.
N? ? What a hell it is.
Third, why is downcasting dangerous? ?
Convert basic pointer to derived pointer
You often see self-referenced pointers when creating linear lists.
typedef struct __node { int data; struct * __ node next; } Node;
This is because pointers can be used even if they are incomplete.
The reason for this is that the pointer assigns an address and does not affect the value of the address, no matter what the structure is. (May be wrong.)
Think about this theory. I made a test code. It is appropriate.
The following code will compile. However, when compiling it comes out as Never Succeed.
Why? ?
struct Base { int member = 3489; void function () { std :: cout<<"Base :: funtion"<<std :: endl; } virtual void func () { std :: cout<<"Base :: virtual_func"<<std :: endl; } }; class Derived final: public Base { public: int Derived_member = 3829; void function () { std :: cout<<"Derived :: function"<<std :: endl; } void func () { std :: cout<<"Derived :: virtual_func"<<std :: endl; } }; Base base_obj; Derived * derived_obj_ptr = dynamic_cast<Derived *>(&base_obj);
Take a look at the following code:
It is possible to assign an object of the base class to an object of the derived class.
On the other hand, derived class objects cannot be assigned to base class objects.
This means that the derived class may have a member variable that is not in the base class, so it cannot be copied.
(What is used at this time ... is a copy assignment operator? What happens when the base class object is on the right side ...)
class Base {...}; class Derived: public Base {...}; Base obj; Derived obj2; obj2 = obj;// ok! obj = obj2 // ERROR !!
I know the object, but I don't know why the pointer is not.
Also, what are the conditions for downcasting?
The environment is Linux g ++.
- Answer # 1
Related articles
- c ++ - about atcoder environment construction
- c ++ - about exclusive processing using lock_guard
- about sample site to play mp3 with c ++
- c ++ - about iterator specification
- c ++ - about the argument types of the constructor
- c ++ - about shift operator (operater operator)
- c ++ - ask about openframeworks addon "ofxmidi"
- c ++ - about meaningless definitions in typedef
- about c ++ pair
- i have a question about type conversion (c ++)
- c ++ - about exclusion of child functions
- c ++ - about the sort program
- c ++ - about standard input in visual studio code
- about c ++ compilation with vs code for mac >> error
- c ++ - about gnuplot hourly 3d animation
- a quick question about c ++
- c ++ - about #ifndef, #define, and #endif macros
- c ++ - questions about qt5 slots
- c ++ - about the node deletion function of the tree structure editing program
- an error occurs when tracing two pointers in c ++
- i want to rewrite a program written in c ++ that outputs a date 15 days later to c language
- c ++ - why you need header files and statically linked library files when building
- c ++ - no wide characters are drawn
- c ++ - i would like to make a device that converts the signal from the remote controller using an arduino and an infrared led
- c ++ - i want to know the cause of the error and the correct answer
- c ++ - how to read data with fscanf
- c ++ - templated functions for exponentiation do not work well when there are two arguments of different types
- c ++ - how to implement a stack
- c ++ - how to receive characters in opengl homebrew window
- c ++ - about the sort program
Hello.
It should be an error that a char pointer cannot be assigned to an int pointer.
int * ptr = reinterpret_cast<int *>(&qtr);
That is, ptr is a pointer to int type.
This is a little annoying. C ++ is strict on types as long as it is written normally.
Base * ptr =&obj;'s ptr is declared as a pointer to the Base type, so what you assign is a pointer to the Base type.
So it can be used with some sense of security.
However, the pointed to is a Derived type object. Even if the point you are pointing to is treated as a Base type, there is no danger of undefined behavior.
That's certainly the code, but it's a "special case". Although it may be understood, generally it is correct to think that it is not understood.
In such cases, you can only understand at runtime.
Also assume that the function f () shown in the example is defined in foo.cpp and called from bar.cpp.
The compiler when compiling foo.cpp doesn't have any information about bar.cpp, so it doesn't know what parameters are being called at compile time.
This is often the case when foo.cpp is distributed as a library and someone who gets it calls it from bar.cpp.
The code presented is dangerous if a Base type object is passed.
In such cases, it is safe to use dynamic_cast<>and make sure that the result is not nullptr. (Note that converting a null pointer to a reference with
*causes undefined behavior, so it must be handled with a pointer.)
dynamic_cast<>is surprisingly slow so you can't afford to use it, but it's quite cumbersome to handle it without using it, so you can use it where speed is not required. (Some people deny downcasts themselves, but there are times when it is better to use them. Define virtual functions for all derived classes or avoid them if possible.)
What do you see when you run the following source?
It is dangerous because it causes undefined behavior.
Eh! It's completely the opposite.
Derived classes can be assigned to base classes. And slicing may occur and cry.
However, the reverse is prohibited by the compiler. I think this is because you can't set values for variables that are only in derived classes.
This can be done by defining an assignment operator or constructor that takes a const reference to the base class. This is because it should be set at the responsibility of the person who defined it. | https://www.tutorialfor.com/questions-100471.htm | CC-MAIN-2020-40 | refinedweb | 1,219 | 64.41 |
Stephan T. Lavavej - Core C++, 7 of n
In part 8, STL digs into the do-while loop, casts, one definition rule (ODR), and his variadic template array sorter. There is a lot of information in this episode, so get comfortable, tune in, and learn.
See part 1: Name Lookup
See part 2: Template Argument Deduction
See part 3: Overload Resolution
See part 4: Virtual Functions
See part 5: Explicit and Partial Specialization
See part 6: New C++11 features added to the Visual C++ 2012 compiler (CTP)
See part 7: Usual Arithmetic Conversions and Template Metaprogramming
That was awesome, you have a very good public presentation skills !
Sorry about asking that, but as a curious doctor, why you using a eye cover ?
Thank you for the video!
Here's another extremely common do-while example -- interfacing with most many C APIs. For instance:
std::vector<unsigned char> buffer; unsigned int bufferLen = 0; unsigned int error = 0; do { buffer.resize(bufferLen); error = ::SomeCApi(buffer.data(), &bufferLen); } while (error == ERROR_MORE_DATA);
Thank you for the great video!
You mentioned as an example a templated max-function:
template<typename T>
const T& max(const T&, const T&);
and two values:
long long ll;
int i;
Why is it better to write:
max(ll, static_cast<long long>(i));
instead of:
max<long long>(ll, i);
Thanks for watching, everyone!
Bruno: I was born with unilateral microphthalmia, a birth defect where my right eye wasn't fully formed. From when I was 6 months old to a couple of years ago, I wore a scleral shell (prosthesis) that gave me a mostly-normal appearance, except that it didn't move and was uncomfortable (like an irritating contact lens, except worse). So I stopped wearing it and switched to my new glasses. This is much more comfortable and people can tell where I'm looking now.
BillyONeal: That's a perfect example of when do-while should NOT be used. If you initialize error to ERROR_MORE_DATA, you can use a simple while loop.
Remember, on the first iteration of a do-while loop, the invariant or something very close to it must hold. (I wish I could remember the book where I learned this from.) In your example, the invariant is "we need more data", indicated by error == ERROR_MORE_DATA. On the first iteration, "we need more data" is true, but you've initialized error to 0, so the condition does not hold as written. But because error's value isn't used before the call to SomeCApi() overwrites it, you can easily change your initializer so the condition holds as written, allowing you to use a while loop.
next_permutation() is different. It simultaneously modifies the sequence, and returns false when it wraps around. Users can't be tricky and start with a sequence sorted in descending order, then call while (next_permutation(v.begin(), v.end())), because that will immediately wrap around and return false. There are other ways to call next_permutation() in a loop, for example for (bool keep_going = true; keep_going; keep_going = next_permutation(v.begin(), v.end())), but they end up being more verbose than do-while.
Visitante: There are so many ways that explicit template arguments can backfire when a function isn't specifically designed for them. (forward<T>(t) is, and make_shared<T>(args, args, args) is for the first one; note that these are.
Instead, if you let template argument deduction do its job, it will realize that there is no choice of Allocator that can make Bignum<Allocator> identical to long long, and the overload is silently dropped from consideration.
I recently solved a related problem with someone saying max<T> in a different context. In that case, they were passing it to a template taking a functor, so they wanted a function pointer. But in C++11, max(const T&, const T&) has been overloaded with max(initializer_list<T>). As soon as we added that overload, max<T> became ambiguous in their context. The solution was to say static_cast<const T& (*)(const T&, const T&)>(max), which allows the compiler to correctly figure out which overload is desired.
Another awesome episode Stephan, thank you! At some point I think it would be incredibly useful if you could share your personal experience and tips for writing additional libraries that play nicely with the Standand library.
Day made.
Really good stuff as always, Stephan!
Re: include guards, what is your opinion on the use of #pragma once? I really hate writing include guards, which is especially annoying if refactor a lot and have the file path in the guard's identifier. Except for some dinosaur compilers (e.g. Sun) that don't support C++11 anyway, it is supported on all platforms (VC, gcc, Clang, Intel) so there appears to be little or no drawbacks (and yes, I know it's not Standard compliant, but in practice it just works).
When introducing people to do-while loops I usually do the following:
std::string s;
do {
std::getline(std::cin, s);
std::cout << s << std::endl;
} while(s != "end");
vs.
while(true) {
if(s == "end") {
break;
}
std::getline(std::cin, s);
std::cout << s << std::endl;
}
But I guess it all comes down to your opinion of while true loops. I dislike these since, at first glance, it looks like an infinite loop and I have to inspect the body of the loop to actually detect what kind of condition terminates the loop.
When doing a do-while loop I know for a fact that the loop termination condition is at the bottom of the loop. (Ignoring the fact that additional break statements could be placed inside the body as well.)
Is the source code for the variadic template array sorter available somewhere? (if not, could you make it available?)
Until source gets uploaded by STL: (includes online compiler for testing)
I by no means imply ownership of this code. All rights belong to STL. If the source is not supposed to be shareable, please delete this comment.
dot_tom> At some point I think it would be incredibly useful if you could share your personal experience and tips for writing additional libraries that play nicely with the Standand library.
What would you like to know, other than that your code should follow the principles of modern C++?
rhalbersma> what is your opinion on the use of #pragma once?
I personally use portable guards, but I'm willing to also use #pragma once as an optimization.
> I really hate writing include guards, which is especially annoying if refactor a lot and have the file path in the guard's identifier.
You could just use random hexits.
Mathias Vorreiter Pedersen: That's another excellent example of when do-while should NOT be used.
Your example incorrectly handles cases where cin ends without "end" appearing on a line by itself - in particular, the corner case where cin immediately ends (e.g. because an empty file was piped to it, or because the user immediately entered Ctrl-Z).
A superior way to write this is:
for (string s; getline(cin, s); ) { if (s == "end") { break; } // do stuff with s }
This consumes all lines from cin without dropping any on the floor or inventing spurious empty lines, but breaks early if it sees "end".
cmeerw> Is the source code for the variadic template array sorter available somewhere?
Here it is:
(Sorry, I should have posted it immediately, like I promised.)
I run into do .. while mostly in writing recursive-descendant parsers: for example, reading a JSON array is:
json_array json_read_array(json_input& input) {
json_array result;
input.expect(json_token::array_open);
do {
result.push_back(json_read_value(input));
} while (input.accept(json_token::comma));
input.expect(json_token::array_close);
return result;
}
Looks like the High Quality WMV file is broken.... can you fix it?
Thanks
@AlessandroV: What's wrong with it? I downloaded it and it played fine, all the way through.
C
I found just one use of the do/while loop:
if (findfirst())
do {
Sorry, the whole example should have been :
if (findfirst(...))
do
{
...
} while (findnext(...));
I have yet another question : What is the reason that
the return expressions in STL are in parentheses?
E. g. : return (this->_Mylast - this->_Myfirst);
Thanks for answer.
I totally agree with you that casts should be avoided. But when there is a good reason to downcast I would prefer dynamic_cast over static_cast. Even if I am absolutely shure that the cast will never fail the former will imediately indicate if I am mistaken while the latter will result in UB.
Simon Buchan: Does JSON (which I know virtually nothing about) permit empty arrays?
xKubo: I prefer to use a for-loop with directory_iterator or recursive_directory_iterator.
xKubo> What is the reason that the return expressions in STL are in parentheses?
This is Dinkumware's convention, which I'm careful to follow when hacking their code. My personal style (as you can see in my examples and collection.h) omits parentheses from return statements as they are unnecessary.
Visitante: Some people use helper functions that static_cast in release and dynamic_cast in debug. In my own programming, I use inheritance rarely and downcasts virtually never, so I haven't used such helper functions.
@STD: Whoops, yeah, I was throwing together a quick example late at night (not real code :P), there should be an "if (!accept(array_close))" before the do .. while. But my point stands in that there's not a natural while loop there (that I can see): tailing commas are not permitted (so no "while (!accept(array_close)) { .. if (!accept(comma)) break; }"), and you want to give explicit errors about missing a ] (or maybe a ,) so it's not natural to share the conditional and the close. This general pattern of token seperated expression lists comes up a bunch, even operator precedence trees can be done as nested do .. whiles.
Please to see do-while take some heat, it's a horrible construct I think. I wish to goodness that ATL didn't use things like 'do { /* stuff */ } while(0);' .
This episode has been an absolute goldmine of goodies, I keep coming back and re-watching it.
please, I don't underestand very well the english in the video, could you write the reasons to avoid while and do while loops?
thanks!
Oddly enough, today I just added the first do-while loop into our year-old codebase. It's not something I like to do often, but it's occasionally useful. It was the do-while-false idiom which some people may not be aware of:
The idea is to introduce a non-looping block from which you can break in order to perform simple 'local exception handling' when errors occur. In my case, I was reading a nested JSON object returned from Facebook and if any part of it wasn't in the format I expected, I wanted to ignore it:
do { auto& picture = json["picture"]; if (!picture.IsObject()) break; auto& pictureData = picture["data"]; if (!pictureData.IsObject()) break; auto& pictureUrl = pictureData["url"]; if (!pictureUrl.IsString()) break; // Do something with pictureUrl.GetString() here } while (false);
The alternatives would be:
do-while-false also has benefits in multi-statement macros:
Hi Stephen
This is not a specific question about a lecture but something I think would be useful to a lot of C++ developers, especially those working on larger code bases:
We have a C++ application (~2 million LOC) which makes heavy use of the STL throughout multiple libraries and many compilation units.
What we experienced was an exponential growth in compile and link times as our usage of the STL grew.
I believe we tried a number of different things to fix this, but ended up settling on forward declaring all of the STL templates that we wanted to use in our code. We would then only instantiate the real templates once, inside one of the libraries.
This dramatically cuts down compile and link times, but obviously requires a huge commitment every time we update the STL implementation used and is not a solution if we wanted to move to the Dinkumware STL which uses nested classes instead of private namespaces for implementation details.
What is your recommendation for developers who want to be able to use the STL freely but keep compilation time low?
Thanks
Simon Buchan: Okay, that might be another legitimate use for do-while, although I'd throw a real parser (like Boost.Spirit) at that problem.
mario: Nothing is wrong with while-loops, although they're less structured than for-loops. I specifically criticized do-while loops, which are very different. The problem with do-while (as I learned from a book whose title I forget) is that on the unconditional first iteration, either the loop invariant as expressed by the condition or something very similar to it must hold in order for the body of the loop to correctly execute. In almost all cases, such loops can be restructured into while-loops while improving clarity.
Fuz: I would probably use a helper function, but I might also use a lambda. [&] has the advantage of being extremely terse.
Mark: Are you using precompiled headers?
The C++ Programming Language, Third Edition, Bjarne Stroustrup
Section 6.3.3 says, "... In my exprience, the do-statement is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work correctly, something very much like the condition must hold even the first time through. More often than I would have guessed, I have found that condition not to hold as expected either when the program was first written and tested or later after the code preceeding it has been modified. ... Consequently, I tend to avoid do-statements."
@STL
cool video, really liked the mix of entry lvl and high lvl stuff. One small complaint is that IMHO you should have explained ... syntax a bit since it is quite new and expert lvl. :) As a Haskell expert with 10x5min tutorial experience I just look at it as head and tail, but Im not sure if Im right.
BTW I remember you talking in old old video how one of your first custom functions that you write in a project is erase-remove wrapper.
1 )Do you have some other functions or idioms you like to write?
2 ) I ask because Im often quite irritated by if (it!=v.end()) so I thought about writing
container_find and container_find_if that return boost::optional of container iterator, so usage
is
auto it = container_find_if(v, [](const double d){ return d >42.0;})
if (it) {//use it}
do you have any strong reasons why I shouldnt use this wrapper. Ignore that it is not standard and that I cant make it work atm. :)
If you ask why I dont make algorithm a template param- some smart ppl said it cant be done
aka this is impossible:
auto it = container_alg(std::find, v, [](const....
Regarding the compile time sorting example, I will be very happy if you could provide some hints for comparing literal strings rather than ints. This is because we would sometimes use const string array list in source code to use them on runtime such as finding matching string so some how if we can sort them in compile time then we can minimize searching time by using the binary search algorithm on runtime.
To give some macros a function-like call syntax it is useful to force the writing of a semicolon after the macro. You can use a do while loop: "do { /* stuff */ } while(false)" without the semicolon for that :)
6 days ago, STL.
If the compiler does that, it's buggy. Overload resolution only requires the signature of the function to be instantiated; it's definition won't be instantiated unless the function is actually selected.
Since only the signature of the function is instantiated, we only need the minimum requirements for the argument types. Basically, we can write the function prototype as instantiated and reason about that:
const Bignum<long long>& max(const Bignum<long long>&, const Bignum<long long>&);
Since these are references (and also function parameters/return values in a prototype), we don't need the complete type of Bignum<long long>. So only the class declaration is instantiated, not the class definition. In other words, since it would be sufficient to write
class Bignum_long_long;
if Bignum wasn't a template, but specialized copy&pasted code, the compiler won't write more code than that from the template either. In particular, it won't try to instantiate the definition of the class, and therefore any errors resulting from that (such as attempting to access long long::pointer, which would be likely in the case of an Allocator parameter) cannot happen.
It's a different story if the template in question actually needs to be fully instantiated. For example, if the method had some enable_if check that looked into Bignum:
typename std::enable_if<is_standard_pointer<typename Bignum<Alloc>::pointer>::value,const Bignum<Alloc>&>::type max(const Bignum<Alloc>&, const Bignum<Alloc>&);
Now it needs to fully instantiate Bignum's definition even when only instantiating the signature, in order to find out what Bignum<Alloc>::pointer is. Now the compiler may fail.
But not before.
On a different issue, C-style casts are even nastier than you've described. Here's two more nasty things they do.
First, they are even more desperate than a reinterpret_cast. A reinterpret_cast at least promises to preserve constness on pointer conversions. (You can lose constness by converting to an integer and back, but at least that requires two reinterpret_casts.) But a C-style cast doesn't do that; it will do the work of both a reinterpret_cast and a const_cast.
But it gets even more desperate! It ignores access specifiers in order to achieve its goals. Imagine you have this:
class Derived : public NonEmptyBase, private Base {};
Note the private inheritance. You cannot implicitly cast a Derived* to a Base*, nor can you static_cast a Base* to a Derived*. You can reinterpret_cast them, but that's a bitpattern cast, not a hierarchy cast.
But a C-style cast will do the hierarchy cast. Yes, that weird thing will actually ignore the fact that the relationship between Derived and Base ought to be invisible, and will do a hierarchy cast instead of falling back to a reinterpret_cast. I'm not sure if that's a good thing or not (at least it kinda works), but it's definitely weird.
Second, the missing hierarchy trap is worse that you described. To recap, you said that (Derived*)base_ptr is dangerous because, due to a programmer error, Derived might not actually derive from Base, but the C-style cast will happily fall back to a reinterpret_cast in this situation.
Well, Derived might actually be derived from Base, and this might *still* happen!
static_cast reverses implicit conversions, with some exceptions. It can't reverse added cv-qualifiers. It can't reverse array and function decay. It can't reverse constant 0 to null pointer conversions. And it can't reverse a number of boolean conversions.
And it can't reverse a hierarchy cast through a virtual base.
class Base {}; class Derived : public virtual Base {};
Base* pb = new Derived(); // valid
Derived* pd = static_cast<Derived*>(pb); // doesn't compile
Derived* pd2 = (Derived*)pb; // reinterprets!
The reason is that in the object layout of virtual inheritance, given a Derived*, I can find the Base subobject via either following a pointer in the Derived*, or adding an offset specified in the vtable to the this pointer. (Depending on the implementation.) But finding the Derived object in the actual object given only a Base*, I cannot do the reverse. The vtable for Base doesn't contain an offset to the Derived superobject, because Base might not have a Derived superobject. So I have to invoke the full dynamic_cast machinery anyway, just to find out where the Derived superobject lives.
Which can fail at runtime. static_cast must not fail at runtime. It must be simple and cheap. So it fails at compile time instead.
Whereas the C-style cast just moves on and does a reinterpret_cast, which is most definitely not the right thing.
This means that, if you have a C-style hierarchy cast, you can turn your program from well-defined to silently and nastily undefined simply by adding "virtual" to some class definition. If you had used static_cast, at least it would only fail to compile, and you could use a dynamic_cast there.
Now don't you wish you hadn't used the C-style cast?
jorgito11: Thanks! It amuses me that I was able to quote TC++PL nearly verbatim despite having forgotten where I learned this from.
Ivan: Yeah, I could spend a whole episode (or several) on variadic templates and how pack expansions work. I probably assumed too much, despite having gone over a simple example in Part 6.
> Do you have some other functions or idioms you like to write?
I used to maintain a personal library, but I haven't written a lot of code at home lately. Work is all-consuming.
> do you have any strong reasons why I shouldnt use this wrapper.
Seems like a lot of machinery to avoid a little bit of syntax.
The reason why I think erase-remove should be wrapped is that it's really easy to forget the second end(), in which case it'll compile silently and do the wrong thing.
> aka this is impossible: > auto it = container_alg(std::find, v, [](const....
Yeah, you can't pass a function template around like that. (You can if it's a struct with a templated function call operator.)
The Standard actually has a very special rule here. You *can* pass the name of a function template, but it has to be to a function parameter that provides sufficient type information for the compiler to figure out which overload/instantiation you want. There are entire sections for this, N3485 14.8.2.2 "Deducing template arguments taking the address of a function template" [temp.deduct.funcaddr] and 13.4 "Address of overloaded function" [over.over].
Nam> Regarding the compile time sorting example, I will be very happy if you could provide some hints for comparing literal strings rather than ints.
Strings can't be manipulated at compile time like this (except I don't know what constexpr is capable of). String literals are forbidden as template arguments.
> if we can sort them in compile time then we can minimize searching time by using the binary search algorithm on runtime.
I would recommend checking is_sorted() once (at startup, possibly in debug mode only) so if the sort order is damaged during maintenance, you'll quickly find out.
gnzlbg: Macros are evil!
CornedBee> If the compiler does that, it's buggy. Overload resolution only requires the signature of the function to be instantiated; it's definition won't be instantiated unless the function is actually selected.
I am aware of this. I was not referring to the function definition.
> Since these are references (and also function parameters/return values in a prototype), > we don't need the complete type of Bignum<long long>. So only the class declaration is instantiated, not the class definition.
I could have made a mistake here. I was simplifying the actual example from the STL, which involves a swap for _Vb_reference<Alloc>, and that one takes its objects by value (NOT by reference).
14.7.1 [temp.inst]." appears to agree with you.
I apologize for the confusion. Have you ever thought about applying to work on the compiler team? :->
> But a C-style cast doesn't do that; it will do the work of both a reinterpret_cast and a const_cast.
That was in the list of bullet points I showed, although I didn't spend time on it.
> But it gets even more desperate! It ignores access specifiers in order to achieve its goals.
I forgot about that, and it's a good point. (I've seen it mentioned before, although it hasn't personally burned me.)
> To recap, you said that (Derived*)base_ptr is dangerous because, due to a programmer error, Derived might not actually derive from Base, but the C-style cast will happily fall back to a reinterpret_cast in this situation.
And this was from real-world experience in the STL, not just a theoretical concern.
> And it can't reverse a hierarchy cast through a virtual base.
Really good point! (Our offending machinery in <functional> didn't involve virtual inheritance. Actually, virtual inheritance is almost never used in our C++ Standard Library implementation, except where mandated by iostreams, so I don't work with virtual bases very often.)
That reminds me of a crazy-subtle bug we fixed in weak_ptr. weak_ptr<T> has a "converting copy constructor" from const weak_ptr<Y>&. This implicitly converts Y * to T *. The bug was that our implementation didn't work with virtual inheritance. Implicitly converting from Derived * to Base * always succeeds, but when virtual inheritance is involved, the offset has to be determined at runtime. With weak_ptr, the object could be dead! Therefore, we need to lock weak_ptr<Y> to shared_ptr<Y>. If the object is alive, the shared_ptr will keep it alive while we perform the conversion, and if the object is dead, we'll be informed that it's dead so we can store a null pointer. (We always lock, instead of trying to sense whether the conversion traverses virtual inheritance.)
16 hours ago, STL wrote
I apologize for the confusion. Have you ever thought about applying to work on the compiler team? :->
Yes, but I didn't particularly want to leave Vienna. Zurich, where I am now, is already quite far in my opinion. (Yeah, I'm rather attached to my home city.)
OK, finished watching the lecture.
On the ODR rule: here's another fun thing you can do wrong in header files: unnamed namespaces. The common wisdom is not to use them in header files, and there are two reasons for that. The underlying problem is that an unnamed namespace internally gets a name that is unique not to the file it is in, but the translation unit. This means that when included from foo.cpp, an unnamed namespace in a header gets one name, and when included from bar.cpp, it gets another.
One problem with that is the duplication of everything in that namespace. The symbols are no longer the same, and thus won't be thrown out by the linker. This wastes space, and can be extremely confusing when you define variables there - every translation unit gets its own global variable that the other TUs cannot access. But the behavior, while confusing, is still defined.
But then you might add an inline function in that header that accesses something in the unnamed namespace. And now you're in trouble with the standard. Here's some actual code:
namespace { struct X { int y; }; } inline int foo(int i) { X x = { i }; return x.i; }
Looks harmless enough, right? The inline function is defined in the header, so obviously it's going to be the same in all translation units. Actually, no. When included from foo.cpp, there's a foo that references <foo-unnamed-namespace>::X, whereas when included from bar.cpp, there's a foo that references <bar-unnamed-namespace>::X. So these two are actually different, even though they are textually equal. ODR is violated, no diagnostic required.
Of course, it's very simple to avoid this. Just don't use unnamed namespaces in headers. Ever.
And finally, some comments on the sorter. Looks like a fun exercise.
sizeof... is not just syntactic sugar, though. A manually implemented sizeof... would have linear "runtime" (number of instantiations), whereas the built-in sizeof... is O(1). (One big issue of variadics as they are is that compilation tends to be very slow, due to lack of random access into arguments packs. Some guy (I think from Boost) studied this and found that compilation speed of Boost.Tuple (a preprorcessor-powered non-variadic tuple) compiled significantly faster than a naive variadics-based version.)
BisectHelper's first specialization is overly verbose. Why not just do this?
template <typename Ints1, typename Ints2> struct BisectHelper<Ints1, Ints2, true> {
typedef Ints1 first;
typedef Ints2 second;
};
Or even put the typedefs in the primary template and static_assert that Done == true, to capture implementation bugs. The only thing that the verbose version you have gives you is detecting when somebody instantiates BisectHelper with something other than a Ints specialization. Is that worth it?
Concat is also too complicated. Or rather, it is a more complicated primitive than you need. The only place where you use Concat is in MergeHelper, where you use it as Concat<Ints<N>, something>, where N is a single int. In other words, you never give more than a single int as the first parameter to Concat. Why not save yourself the Ints instantiations and use a Prepend primitive instead?
template <int A, typename Ints> struct Prepend {};template <int A, int... Vals> struct Prepend<A, Ints<Vals...>> { typedef Ints<A, Vals...> type; };
CornedBee> Of course, it's very simple to avoid this. Just don't use unnamed namespaces in headers. Ever.
Yeah, that's why header-only code like Boost uses detail namespaces. (We don't in the STL because we have _Ugly names.)
> the built-in sizeof... is O(1).
Good point. (I didn't follow its evolution very closely.)
> BisectHelper's first specialization is overly verbose. Why not just do this?
Good catch, I didn't notice that. I am extremely paranoid about setting up an unambiguous system of specializations, but in this case they are cleanly divided by true/false.
> Concat is also too complicated. Or rather, it is a more complicated primitive than you need.
Another good catch. I wrote the whole thing in the order presented, and didn't notice that I was using a fraction of Concat's power.
@STL
tnx for the answers. Sorry to hear you are very busy with your work, but at least you are doing STL and not you know maintaining COBOL :) code while hacking with c++ in free time. :D
BTW I would like to get your quick opinion on couple of things
1) I remember you (long time ago in one of your A) not being fan of ranges as fundamental element instead of iterators...now they are on their way to std, I wonder if your opinion changed.
2) What features you think will be most beneficial in C++14/17(for a lib developer/for a "normal" dev)... I know it is not clear what will get in, but you probably know the usual suspects... static if, await(or how is it gonna be called)... me personally would really like efficient serialization.
3) In your opinion what is the biggest unforced error in the core language. Unforced error here means (like Alexandrescu puts it :)) design error that wasnt necessary(for eg to make C++ compatible with C)
@CornedBee tnx for the cool comments :)
I think the point CornedBee raised regarding the ODR is worth expanding on. Consider the following example:
x.hpp: struct x {...};
y.hpp: struct y {...};
xy_swap.hpp: //swap definitions dependent on x and y
If x or y is ever visible in a translation unit without xy_swap.hpp, in a context where a provided definition may conceivably apply, the code may violate the ODR indirectly through instantiated templates like std::sort.
Ivan> 1) I remember you (long time ago in one of your A) not being fan of ranges as fundamental element instead of iterators...now they are on their way to std, I wonder if your opinion changed.
The proposal I've seen treats ranges as pairs of iterators, and I'm a huge fan of that.
> 2) What features you think will be most beneficial in C++14/17(for a lib developer/for a "normal" dev)
No major features have been voted in yet (my greater<> functors aren't a major feature), and I haven't attended the Evolution Working Group's meetings. (I live in the Library Working Group.) So I don't have a very good sense of what's coming in the Core Language. I'm also not very familiar with what's happening in Concurrency.
In the Standard Library, ranges have the potential to simplify nearly every line of code you write using the STL. Portable filesystem and networking libraries will also be important (it's about time the Standard recognized the existence of directories and the Internet).
I have not seen Boost.Serialization or other serialization libraries proposed for standardization - I hope I'm not forgetting something.
> 3) In your opinion what is the biggest unforced error in the core language.
I still don't understand why the pointer-to-member operators .* and ->* have such low precedence; they're lower than . and -> and they're right above multiplication. This forces you to write (obj.*pmf)(args) when calling a pmf. Unless I'm totally missing something, they should be at the same level as . and -> (basically the highest).
Most of C++'s other problems were inherited from C, so things like the precedence of the bitwise operators, and default fallthrough, don't count. Implicitly converting constructors are widely regarded as the wrong default now, but at the time it was consistent with C's extreme fondness for implicit conversions, and it took time for the problems to become apparent.
Paul> xy_swap.hpp: //swap definitions dependent on x and y
What is this swapping? Swap overloads should appear directly after the things they're swapping.
That example was fairly contrived I've never seen it occur personally, but it might seem reasonable to a programmer to place the definition in a separate file if it somehow depended on both structures. I was really just pointing out that it's possible for a template to implicitly violate the ODR through templates like std::sort even if the template itself never directly violates the rule, similar to how ConredBee's example violates the ODR with the user's template taking the role of X (conceptually). Non-intrusive serialization is the only place I've seen this occur in practice.
Perhaps it isn't worth mentioning, but in my experience it can lead to some truly horrific bugs :)
@STL
again tnx for answers...
I was talking about serialization in this sense:
SG7, Reflection: Chandler Carruth (Google). Initially focusing on compile-time reflection capabilities.
IDK if reflection will enable it.
BTW regarding ranges do you feel they should be implicitly convertible to bool.
From what I see from boost they have .empty() function:
I would like to be able to write if (r)
> I still don't understand why the pointer-to-member operators .* and ->* have such low precedence; they're lower than . and -> and they're right above multiplication.
It makes parsers more complicated to mix binary operator and unary operator precedences.I suspect this was the main reason.
It would so be worth it, though. I think it would work, too. Of course, it's way too late to change it now.
I was advised by one of my engineering lecturers that
do whilefinds use to handle errors- perform operation and if not error repeat. Individually, although I've forgotten when I learnt
repeat .. untilstatement (was that Pascal?), I remember using the post-condition evaluation form of loop for receiving messages, mostly by user action, where the message would cause branching by
switch .. caseand instead of using
breakfor
case '0'or
ExitI'd have
while (choice)or
UNTIL (NOT msg)as the post-condition for looping. The compilers back then were slow and as newbie with small datasets this somehow appealed more than reading message once more before entering an infinite pre-condition evaluation loop and asking for compiler optimization. If I've to write message loop for actor/bot/agent in some swarm, I guess I'll default to do-while, unless something smarter occurs to me.
On separate note, I'd write code like
cout<<a+b;rather than
c=a+b; cout<<c;until you demonstrated
&&and move semantics. Mainly owing to UI, I was doing multi-lingual .net code in my projects but always found that OO was over-rated everywhere. F# for data modeling has been nice experience, and kept reminding me of functors and STL. Now that DirectX & XAML combined apps work, and having academics wrapped up behind me, I'm concentrating on how I can isolate my app's core logic using aspects, so my team's non-Windows members can re-use the platform-neutral aspects when re-implementing the app on other platforms. Thank you for helping me learn C++ renaissance with yourself (including your team). I put on-hold my objective of aspect-oriented architectural design to come to speed with you, and will update on specific advances soon enough, now that I've almost caught up. For now only insight I'm able to frame properly for understanding is I identify aspects as domain-specific, where domain may be problem domain such as social sharing or inventory control, or platform domain such as .net or Windows.
I never grew up from C-style cast, so the points you made scored. Most notably I realized my only recollection of casting was with the intention of reinterpret_cast (btw, that should be r..._cat, meow & purr
) Reinterpret, of all the casts because after opening text file as binary, my intent was to get data trying different encodings. Rather than reopening same file multiple times assuming different encodings, I just observed the buffered data with reinterpretation. There are high-level libraries with great performance for such operations, I know. But while studying storage data structures the objective was imagining how debugger or driver can respond with multiple FAST representations to users.
Ivan> BTW regarding ranges do you feel they should be implicitly convertible to bool.
C++11 has explicit operator bool(), which is nice and safe, but I don't have a strong opinion about whether ranges/containers should be boolean-testable. I guess it would be reasonable.
VSChawathe> I was advised by one of my engineering lecturers that do while finds use to handle errors- perform operation and if not error repeat.
I don't buy that. Such do-while loops can be transformed into while loops by initializing err to success.
> Thank you for helping me learn C++ renaissance with yourself (including your team).
You're welcome!
> I just observed the buffered data with reinterpretation.
This is bad because it's dependent on your platform's integer widths, layout, endianness, etc. (fread()/fwrite() may encourage it, but they're from a simpler era.) You should use a serialization library instead.
I didn't buy that either, cause it wasn't backed up by any case study so seemed more like trivial comment, but upon revisiting the loop construct in this video my unanswered why made me bring that up.
> This is bad
I agree, as a student heterogeneous platforms weren't of any concern, but that still doesn't make it good idea. I'm weary of code snippets ending up in unintended places now and invest more time on separation of concerns.
I've got request. As I've always enjoyed your live demo-ing every point you touch upon, please cover C++ concurrency introduced in before completing the core language only series. Just requesting, nothing hard & fast. That talk was gr8 too, just that multiple independent impressions make learning faster for me.
@STL
thank you for the answers... hope that you soon find some other interesting topic. And TBH it doesnt have to be really interesting topic, the fact is that you present a topic in really almost academic way and at the same time it is not dry.
Merge sort implemented only in templates? Woah, mind = blown.
I wonder if it would be possible to create an ORM mapper with templates. It would need I guess some sort of syntax to expand a class in its various fields.
Stephan,
Perhaps you have touched that in your videos and I've missed it, regarding your std::max with long long and int example: why not explicit type conversion using functional notation instead of, longer, static_cast? I wonder, are there significant differences?
Mat
Functional notation is, sadly, semantically equivalent to a C-style cast, with all the dangers that brings. So while it looks nice, it's not a good idea to do it.
In my opinion, functional casts should be static_casts by semantics, but unfortunately we're fixed in a world where that isn't the case. I suspect that functional cast notation is older than the limited C++ casts, and by the time the verbose syntax was introduced, it was already too late to change the meaning of functional cast notation.
I'm looking forward to the next lecture from STL, anyone know when it might be.
Charles do you know? | https://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-Cpp-8-of-n | CC-MAIN-2020-24 | refinedweb | 6,870 | 64.2 |
Opened 9 years ago
Closed 9 years ago
Last modified 8 years ago
#13052 closed (duplicate)
reverse() does not resolve correctly using namespaces in some cases
Description
When reversing a set of included urls with a url prefix which contains a parameter, the resolver will treat the url chunk before the include as a prefix and not process it.
from django.conf.urls.defaults import * app1 = (patterns('', url(r'^edit/(?P<object_id>\d+)/$', 'view',>> reverse('view',>> reverse('myapp:view',>> reverse('myapp:list', current_app='theinstance1') '/site/(?P%3Csite_id%3E%5Cd+)/pages/list/'
Change History (3)
comment:1 Changed 9 years ago by
comment:2 Changed 9 years ago by
comment:3 Changed 8 years ago by
Milestone 1.2 deleted
Note: See TracTickets for help on using tickets.
The problem starts here: The extra part is just added to prefix, but it can contain parts which need to be reversed. | https://code.djangoproject.com/ticket/13052 | CC-MAIN-2019-22 | refinedweb | 149 | 50.36 |
Technical Articles
Versioning your local objects using abapgit
Leveraging the power of git in SAP can be difficult since development is usually done by multiple developers on the same system. Unless you manage to get your developers their own systems, key concepts like branches will be next to useless because while you’re pushing the results into something meant for distributed development, you’re still doing centralized development.
“Hell is other people on your system” (Jean-Paul Sartre)
However, even on a shared system, you have one place where other people generally won’t bother you – your local objects. You can consider this your single-developer system where you can put prototypes or reusable code.
But since local objects are never transported, you no longer have them if you switch systems and if something were to happen to them, you can’t recover them easily. We can get around both of these issues by versioning them using git.
I’m going to assume abapgit is already set up on your system. It is not difficult, the simplest way involves copy-pasting a report.
From what I’ve seen, most people use the organization structure
my_username->literally_everything
for their local objects and don’t structure them further. This is equivalent to putting all your files on the desktop. Which I do, but who’s not a hypocrite these days.
You will need to create at least one top level package for this. Much better!
Your local objects are stored in the package $TMP, but since you don’t want to version everyone’s code, create a subpackage of $TMP. Name it whatever you like, just remember that local package names start with $.
You can also have multiple root packages/repositories, this depends on your use cases. I don’t know what code you have in there, that’s why I’m trying to get you to share it! You just need to:
Create a package
Create a Github repository:
Don’t forget the readme checkbox.
Open ZABAPGIT and click the +Online button
Now you will learn how to add some folder structure to your repo. Abapgit will let you version one top-level package per repository. Any subpackages will be converted to folders based on the folder logic.
There are two options:
- PREFIX – the child packages must begin with the parent package name. For example, $ZFH_PROTOTYPES is a valid subpackage of $ZFH according to prefix logic. This will create a folder named prototypes in the repository. Note that prefix logic won’t work correctly if you don’t follow the convention.
- FULL – folders will be named like packages.
You can create the subpackages and also change the folder naming convention at any time.
Now just add your objects and remember to commit updates every now and then.
=
At the very least, you get a backup and the ability to import your local objects to a different system. You also have a place where you can experiment with branching, pulling or resetting code to previous versions, which you might be afraid to do with your productive code.
I never thought of this use case. Will try it out! Is there any benefit to creating the package in $TMP compared to just creating a local package without a parent? I guess each developer will get a filtered view on their subpackages when displaying the $TMP contents?
Also I am very much used to losing all local objects at system copies, which won't be an issue anymore with this approach. Thanks!
Huh, you got me there. I thought all local packages were children of $TMP, but it is just what the package wizard prefills and your can in fact have no parent package for local packages.
However, now Eclipse doesn't display it in this list:
Seems like a good idea for some scenarios and to have different branches for new development, but in terms of versioning, will this help?
If an existing solution has a class ZCL_ABC, I won’t be able to create another class ZCL_ABC as a local object to work on the next version of the solution as far as I know.
If some adjustments are made in the SAP core it would perhaps be possible to hack such a feature by using a per-developer local namespace (/$username/) and have the runtime use objects from the local namespace if they exist, otherwise the global objects!
So the ABAP runtime would for the statement “data(shipment) = new ZCL_PSLO_SHIPMENT( )” create an instance of class /$username/ZCL_PSLO_SHIPMENT if that class existed, otherwise create an instance of class ZCL_PSLO_SHIPMENT.
As mentioned, it would be a hack.
And it would of course also have to handle /$username/RL_NMSPC/CL_SOME_CLASS 🙂 ... but even so I think that could perhaps be the path of least resistance to support parallel development.
No, unfortunately you can't have ZCL_ABC on the same system twice. But what you're describing is possible using proper architecture - you can have IF_ABC with ZCL_ABC1 and ZCL_ABC2 implementing it.
I sometimes stick a simple if uname into a factory to return a different implementation just for me, so I can try it out without breaking other people's stuff. Then I remove the if once I'm reasonably sure my implementation works.
This is of course only usable during development. Look into dependency injection if you need a less temporary solution.
That's true, but that's not really versioning (IMNSHO) 🙂
And it would not solve the problem for reports, function modules, or any other object that can't have dynamic implementation resolution. So for instance if I wanted to extend a table with two new fields in the next version I don't really think it is a viable solution.
You're right. This is not something ABAP allows you to do - multiple versions of the same object simply can't coexist on the same system. The best you can do currently is work around it and stay tuned for news from the future :). This might take some time.
Some good news: the bleeding edge of ABAP already has an early working version of package management: | https://blogs.sap.com/2019/08/19/versioning-your-local-objects-using-abapgit/ | CC-MAIN-2021-43 | refinedweb | 1,024 | 61.77 |
TypeScript for the C# Developer: TypeScript Classes and Interfaces
If you read the previous article on this subject, "TypeScript for the C# Developer," you'll recall we covered the type system that TypeScript makes available, and how much alike to the C# type system it is.
In this article, we'll go a little bit further and look at the concept of interfaces and classes.
Classes in TypeScript are nothing more than a thin wrapper around already existing JavaScript class-orientated programming; they make things easier by abstracting away what a JavaScript class actually looks like, and making it look more like the type of class we, as software developers, are used to.
Interfaces, on the other hand, are a specific TypeScript construct that exist only in the TypeScript world and have no actual equal in JavaScript.
The Secret's in the Filename
Before we take a look at them both, however, there's a little bit of TypeScript magic that you need to know.
If you've looked at any TypeScript code, you'll note that the files usually have a ".ts" file extension.
When TypeScript comes across a file with this extension, it compiles it and produces a JavaScript file with the same name, but with a ".js" extension.
TypeScript also recognises the ".d.ts" extension too, but, upon encountering this, it does something a little bit different.
Instead of compiling it into a JavaScript file, it treats it as a set of in memory definitions, and uses them as references when compiling other parts of your code.
It's this trick that allows TypeScript to have definition files for popular JavaScript libraries such as JQuery, Angular, and Knockout, and use them to provide strong typing and Intellisense against the code you're writing.
In a way, these ".d.ts" files (normally known as TypeScript Definitions) are much like having external assemblies referenced in your C# program, but not actually needing the code in them until you come to run things.
You can find 1000s of these definition files at the 'TypeScript Definition library' (Definitely Typed).
This Web site now has so many different definition files available for all manner of JavaScript libs, that its listing is too big for GitHub to list everything available.
Your Own Definitions Can Benefit, Too
This, is turn, brings me back to the subject we started out discussing in the first place.
If you define an interface and place it in a ".d.ts" file, something like the following:
interface MyType {] id: number;] firstName: string; lastName: string; emailAddress: string; isMember: Boolean; }
You'll then find that it acts entirely like the Intellisense system does for C# inside Visual Studio:
Figure 1: Showing an Intellisense-like tag
Not only that, but it also means that if you try to use a property you've not defined, or have defined as a different type, TypeScript's type system will kick in and prevent compilation of bad or incorrect code.
Because you defined it as a ".d.ts" file, it's all virtual, and the resulting JS file generated will not require the definition file once your code is deployed.
If all you need is to shape your data, this is by far the best way to achieve it. I find it works very well for defining the shape of JSON data that I send from a C# service to an HTML User interface, and, as long as I keep the two sides in sync with each other, things are usually very smooth.
There are a number of extensions in the Visual Studio gallery to help with this, including a couple that will actually generate ".d.ts" files for you at build time.
Three of the more worthy mentions available in the Visual Studio Store are:
- Mads Kristensen's "TypeScript Definition Generator"
- ViFrankenstien's "Export POCO to ts"
- "Typewriter" by frhagn
I would encourage you to have a look through all the offerings, however, and decide for yourself which works best for you.
On with the Class…
As you've probably gathered by now, defining a class is very much the same. As in C#, interfaces and classes exist alongside each other, and, like C#, interfaces define, whereas classes implement.
Because of this, you can't define a class as a ".d.ts" file, but you can define an interface using either.
The key difference, as I mentioned before, is the physical production of a file.
For this reason, if all you need is to define the shape of something (and that includes a class with methods), your best defining it as an interface.
If you want to define and implement something, you define it as a regular-looking class.
For the most part, classes in TS look more or less the same as classes in C#:
export class Test { constructor() { } private myPrivateVar: number = 0; public myPublicVar: string = "Hello World"; protected myProtectedVar: Boolean = true; private myFunction(parameter: string): number { return 0; } private myNonReturnFunction() { } }
There are a few 'gotchas' to be aware of, though.
First and foremost, constructors are ALWAYS defined by using the "constructor" keyword, unlike C#, where the constructor is typically a public un-typed function with the same name as the defining class.
The "export" part is essential to make the class publicly accessible to other parts of the code. Although public and private modifiers are available, they apply ONLY to members inside the class, and not to the overall class itself. If you look back at our discussion on interfaces, you'll see the same applies there, also.
You don't have to put "export" on the class itself; you can put it as the last line in a file and assign to the variable "export," but it's generally preferred to have one class per file and export that class.
You also can use something called a "default export," which you use depending on a) how you want to structure your code and b) how you want to consume your classes.
If you use:
export class Test
You easily can define multiple classes in one file:
export class Test1 { } export class Test2 { } export class Test3 { }
You then consume these classes in your using code, by using the curling braces version of the import statement:
import { Test1, Test2, Test3 } from 'myclasses';
Doing things this way, you can hold all your classes in one file, but only include what you need from that file, when you need it.
If you use "default:"
export default class Test1
You can ONLY have one class in the file; any others cannot be accessed by your calling code. To consume the code, you use:
import Test1 from 'myclasses';
If you study the ES6 specifications, you'll see that this is actually not a TypeScript thing, but it's the new ES6 way of defining classes for modern day JavaScript. TS just helps you by enforcing types and syntax in a compiler-based way.
TS Classes also support modifiers, but, unlike C#, they only support "private," "public," and "protected."
There is something very important to remember here, though.
Modifiers in TypeScript are used ONLY by TypeScript.
If you define a property as "private," for example, and then try to access that property from a regular JavaScript class against the class previously compiled using TS, you'll quickly find that it's just as fully accessible as anything that is/was defined public.
JavaScript itself as a language has no concept of property or function modifiers, so everything is public and always will be.
Having modifiers exists only to help you use TypeScript to write better code. It cannot enforce something that JavaScript by itself cannot do by default.
Just as with C#, "private" means accessible only inside that class, "public" means accessible by everything, and "protected" means accessible inside that namespace.
Namespaces are also implemented in TypeScript, but generally are not used all that much, unless you're writing framework and library code. You can define a namespace, exactly as you would define one in C#:
namespace MyNamespace { }
And then, you can create your class definitions and interfaces inside of that.
ONE word of warning, though: If you do use interfaces, don't go overboard with them.
Unlike with C#, namespaces CANNOT be defaulted, so, for example:
namespace MyNamespace1 { namespace MyNamespace2 { namespace MyNamespace3 { export class MyData{} } } }
Must be quoted in full when using it EG:
private myData:MyNamespace1.MyNamespace2 .MyNamespace3.MyData = new MyNamespace1 .MyNamespace2.MyNamespace3.MyData();
You can't shortcut any of this, and there's nothing in TypeScript that works in the same way as a using does in C#. Long nested namespaces mean LOTS of typing.
The rest is quite straightforward, as I mentioned in the article on Types. A type name is a suffix, suffixed using a ": ", classes use them in the same way for parameters, properties and function returns. The TS compiler also will enforce return types.
If you define a function to return something, don't return something from that function, or if you miss a return path because of a missing IF clause, for example, you'll get build errors just as you would with C#.
That's all for this installment. Join me for the third and final part, where we'll take a look at generics, and I'll show you a few tricks that will allow you to add things like C#-style enumerable lists to your TS code.
Shawty | https://www.codeguru.com/csharp/csharp/cs_webservices/typescript-for-the-c-developer-typescript-classes-and-interfaces.html | CC-MAIN-2019-47 | refinedweb | 1,571 | 56.18 |
Listen to this article at EuRuKo on a boat. If you've got the time, here's the talk:
- Intro to Tidying Object Allocations
- Tidying Example 1: Active Record respond_to? logic
- Performance and Statistical Significance
- Tidying example 2: Converting strings to time takes time
- Tidying Example 3: Lightning fast cache keys
Intro to Tidying Object Allocations
The core premise of this talk is that we all want faster applications. Here I'm making the pitch that you can get significant speedups by focusing on your object allocations. To do that, I'll eventually show you a few real-world cases of PRs I made to Rails along with a "how-to" that shows how I used profiling and benchmarking to find and fix the hotspots.
At a high level, the "tidying" technique looks like this:
- Take all your object allocations and put them in a pile where you can see them
- Consider each one: Does it spark joy?
- Keep only the objects that spark joy
An object sparks joy if it is useful, keeps your code clean, and does not cause performance problems. If an object is absolutely necessary, and removing it causes your code to crash, it sparks joy.
To put object allocations in front of us we'll use:
To get a sense of the cost of object allocation, we can benchmark two different ways to perform the same logic. One of these allocates an array while the other does not.
require 'benchmark/ips' def compare_max(a, b) return a if a > b b end def allocate_max(a, b) array = [a, b] # <===== Array allocation here array.max end Benchmark.ips do |x| x.report("allocate_max") { allocate_max(1, 2) } x.report("compare_max ") { compare_max(1, 2) } x.compare! end
This gives us the results:
Warming up -------------------------------------- allocate_max 258.788k i/100ms compare_max 307.196k i/100ms Calculating ------------------------------------- allocate_max 6.665M (±14.6%) i/s - 32.090M in 5.033786s compare_max 13.597M (± 6.0%) i/s - 67.890M in 5.011819s Comparison: compare_max : 13596747.2 i/s allocate_max: 6664605.5 i/s - 2.04x slower
In this example, allocating an array is 2x slower than making a direct comparison. It's a truism in most languages that allocating memory or creating objects is slow. In the
C programming language, it's a truism that "malloc is slow."
Since we know that allocating in Ruby is slow, we can make our programs faster by removing allocations. As a simplifying assumption, I've found that a decrease in bytes allocated roughly corresponds to performance improvement. For example, if I can reduce the number of bytes allocated by 1% in a request, then on average, the request will have been sped up by about 1%. This assumption helps us benchmark faster as it's much easier to measure memory allocated than it is to repeatedly run hundreds or thousands of timing benchmarks.
Tidying Example 1: Active Record
respond_to? logic
Using the target application CodeTriage.com and derailed benchmarks, we get a "pile" of memory allocations:
$ bundle exec derailed exec perf:objects allocated memory by gem ----------------------------------- 227058 activesupport/lib 134366 codetriage/app # ... 11109 … 8440 …/code/rails/activerecord/lib/active_record/attribute_methods.rb 8304 …/code/rails/activemodel/lib/active_model/attribute.rb 8160 …/code/rails/actionview/lib/action_view/renderer/partial_renderer.rb 8000 …/code/rails/activerecord/lib/active_record/integration.rb 7880 …/code/rails/actionview/lib/action_view/log_subscriber.rb 7478 …/code/rails/actionview/lib/action_view/helpers/tag_helper.rb 7096 …/code/rails/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb # ...
The full output is massive, so I've truncated it here.
Once you've got your memory in a pile. I like to look at the "allocated memory" by file. I start at the top and look at each in turn. In this case, we'll look at this file:
8440 …/code/rails/activerecord/lib/active_record/attribute_methods.rb
Once you have a file you want to look at, you can focus on it in derailed like this:
$ ALLOW_FILES=active_record/attribute_methods.rb \ bundle exec derailed exec perf:objects allocated memory by file ----------------------------------- 8440 …/code/rails/activerecord/lib/active_record/attribute_methods.rb allocated memory by location ----------------------------------- 8000 …/code/rails/activerecord/lib/active_record/attribute_methods.rb:270 320 …/code/rails/activerecord/lib/active_record/attribute_methods.rb:221 80 …/code/rails/activerecord/lib/active_record/attribute_methods.rb:189 40 …/code/rails/activerecord/lib/active_record/attribute_methods.rb:187
Now we can see exactly where the memory is being allocated in this file. Starting at the top of the locations, I'll work my way down to understand how memory is allocated and used. Looking first at this line:
8000 …/code/rails/activerecord/lib/active_record/attribute_methods.rb:270
We can open this in an editor and navigate to that location:
$ bundle open activerecord
In that file, here's the line allocating the most memory:
def respond_to?(name, include_private = false) return false unless super case name when :to_partial_path name = "to_partial_path" when :to_model name = "to_model" else name = name.to_s # <=== Line 270 here end # If the result is true then check for the select case. # For queries selecting a subset of columns, return false for unselected columns. # We check defined?(@attributes) not to issue warnings if called on objects that # have been allocated but not yet initialized. if defined?(@attributes) && self.class.column_names.include?(name) return has_attribute?(name) end true end
Here we can see on line 270 that it's allocating a string. But why? To answer that question, we need more context. We need to understand how this code is used. When we call
respond_to on an object, we want to know if a method by that name exists. Because Active Record is backed by a database, it needs to see if a column exists with that name.
Typically when you call
respond_to you pass in a symbol, for example,
user.respond_to?(:email). But in Active Record, columns are stored as strings. On line 270, we're ensuring that the
name value is always a string.
This is the code where name is used:
if defined?(@attributes) && self.class.column_names.include?(name)
Here
column_names returns an array of column names, and the
include? method will iterate over each until it finds the column with that name, or its nothing (
nil).
To determine if we can get rid of this allocation, we have to figure out if there's a way to replace it without allocating memory. We need to refactor this code while maintaining correctness. I decided to add a method that converted the array of column names into a hash with symbol keys and string values:
# lib/activerecord/model_schema.rb def symbol_column_to_string(name_symbol) # :nodoc: @symbol_column_to_string_name_hash ||= column_names.index_by(&:to_sym) @symbol_column_to_string_name_hash[name_symbol] end
This is how you would use it:
User.symbol_column_to_string(:email) #=> "email" User.symbol_column_to_string(:foo) #=> nil
Since the value that is being returned every time by this method is from the same hash, we can re-use the same string and not have to allocate. The refactored
respond_to code ends up looking like this:
def respond_to?(name, include_private = false) return false unless super # If the result is true then check for the select case. # For queries selecting a subset of columns, return false for unselected columns. # We check defined?(@attributes) not to issue warnings if called on objects that # have been allocated but not yet initialized. if defined?(@attributes) if name = self.class.symbol_column_to_string(name.to_sym) return has_attribute?(name) end end true end
Running our benchmarks, this patch yielded a reduction in memory of 1%. Using code that eventually became
derailed exec perf:library, I verified that the patch made end-to-end request/response page speed on CodeTriage 1% faster.
Performance and Statistical Significance
When talking about benchmarks, it's important to talk about statistics and their impact. I talk a bit about this in Lies, Damned Lies, and Averages: Perc50, Perc95 explained for Programmers. Essentially any time you measure a value, there's a chance that it could result from randomness. If you run a benchmark 3 times, it will give you 3 different results. If it shows that it was faster twice and slower once, how can you be certain that the results are because of the change and not random chance?
That's precisely the question that "statistical significance" tries to answer. While we can never know, we can make an informed decision. How? Well, if you took a measurement of the same code many times, you would know any variation was the result of randomness. This would give you a distribution of randomness. Then you could use this distribution to understand how likely it is that your change was caused by randomness.
In the talk, I go into detail on the origins of "Student's T-Test." In derailed, I've switched to using Kolmogorov-Smirnov instead. When I ran benchmarks on CodeTriage, I wanted to be sure that my results were valid, so I ran them multiple times and ran Kolmogorov Smirnov on them. This gives me a confidence interval. If my results are in that interval, then I can say with 95% certainty that my results are not the result of random chance i.e., that they're valid and are statistically significant.
If it's not significant, it could mean that the change is too small to detect, that you need more samples, or that there is no difference.
In addition to running a significance check on your change, it's useful to see the distribution. Derailed benchmarks does this for you by default now. Here is a result from
derailed exec perf:library used to compare the performance difference of two different commits in a library dependency:
Histogram - [winner] "I am the new commit." ┌ ┐ [11.2 , 11.28) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 12 22 30 [11.43, 11.51) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 17 Time (s) [11.5 , 11.58) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 13 [11.58, 11.66) ┤▇▇▇▇▇▇▇ 6 [11.65, 11.73) ┤ 0 [11.73, 11.81) ┤ 0 [11.8 , 11.88) ┤ 0 └ ┘ # of runs in range Histogram - [loser] "Old commit" ┌ ┐ [11.2 , 11.28) ┤▇▇▇▇ 3 19 17 [11.43, 11.51) 25 Time (s) ▇▇▇▇ 3 [11.73, 11.81) ┤▇▇▇▇ 3 [11.8 , 11.88) ┤▇▇▇ 2 └ ┘ # of runs in range
The TLDR of this whole section is that in addition to showing my change as being faster, I was also able to show that the improvement was statistically significant.
Tidying example 2: Converting strings to time takes time
One percent faster is good, but it could be better. Let's do it again. First, get a pile of objects:
$ bundle exec derailed exec perf:objects # ... 11148 … 8304 …/code/rails/activemodel/lib/active_model/attribute.rb
Zoom in on a file:
36097 …/code/rails/activemodel/lib/active_model/type/helpers/time_value.rb
Isolate the file:
$ ALLOW_FILE=active_model/type/helpers/time_value.rb \ bundle exec derailed exec perf:objects Total allocated: 39617 bytes (600 objects) Total retained: 0 bytes (0 objects) allocated memory by gem ----------------------------------- 39617 activemodel/lib allocated memory by file ----------------------------------- 39617 …/code/rails/activemodel/lib/active_model/type/helpers/time_value.rb allocated memory by location ----------------------------------- 17317 …/code/rails/activemodel/lib/active_model/type/helpers/time_value.rb:72 12000 …/code/rails/activemodel/lib/active_model/type/helpers/time_value.rb:74 6000 …/code/rails/activemodel/lib/active_model/type/helpers/time_value.rb:73 4300 …/code/rails/activemodel/lib/active_model/type/helpers/time_value.rb:64
We're going to do the same thing by starting to look at the top location:
17317 …/code/rails/activemodel/lib/active_model/type/helpers/time_value.rb:72
Here's the code:
def fast_string_to_time(string) if string =~ ISO_DATETIME # <=== line 72 Here microsec = ($7.to_r * 1_000_000).to_i new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec end end
On line 72, we are matching the input string with a regular expression constant. This allocates a lot of memory because each grouped match of the regular expression allocates a new string. To understand if we can make this faster, we have to understand how it's used.
This method takes in a string, then uses a regex to split it into parts, and then sends those parts to the
new_time method.
There's not much going on that can be sped up there, but what's happening on this line:
microsec = ($7.to_r * 1_000_000).to_i
Here's the regex:
ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
When I ran the code and output $7 from the regex match, I found that it would contain a string that starts with a dot and then has numbers, for example:
puts $7 # => ".1234567"
This code wants microseconds as an integer, so it turns it into a "rational" and then multiplies it by a million and turns it into an integer.
($7.to_r * 1_000_000).to_i # => 1234567
You might notice that it looks like we're basically dropping the period and then turning it into an integer. So why not do that directly?
Here's what it looks like:
def fast_string_to_time(string) if string =~ ISO_DATETIME microsec_part = $7 if microsec_part && microsec_part.start_with?(".") && microsec_part.length == 7 microsec_part[0] = "" # <=== HERE microsec = microsec_part.to_i # <=== HERE else microsec = (microsec_part.to_r * 1_000_000).to_i end new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec end
We've got to guard this case by checking for the conditions of our optimization. Now the question is: is this faster?
Here's a microbenchmark:
original_string = ".443959" require 'benchmark/ips' Benchmark.ips do |x| x.report("multiply") { string = original_string.dup (string.to_r * 1_000_000).to_i } x.report("new ") { string = original_string.dup if string && string.start_with?(".".freeze) && string.length == 7 string[0] = ''.freeze string.to_i end } x.compare! end # Warming up -------------------------------------- # multiply 125.783k i/100ms # new 146.543k i/100ms # Calculating ------------------------------------- # multiply 1.751M (± 3.3%) i/s - 8.805M in 5.033779s # new 2.225M (± 2.1%) i/s - 11.137M in 5.007110s # Comparison: # new : 2225289.7 i/s # multiply: 1751254.2 i/s - 1.27x slower
The original code is 1.27x slower. YAY!
Tidying Example 3: Lightning fast cache keys
The last speedup is kind of underwhelming, so you might wonder why I added it. If you remember our first example of optimizing
respond_to, it helped to understand the broader context of how it's used. Since this is such an expensive object allocation location, is there an opportunity to call it less or not call it at all?
To find out, I added a
puts caller in the code and re-ran it. Here's part of a backtrace:
==================================================================================================== …/code/rails/activemodel/lib/active_model/type/date_time.rb:25:in `cast_value' …/code/rails/activerecord/lib/active_record/connection_adapters/postgresql/oid/date_time.rb:16:in `cast_value' …/code/rails/activemodel/lib/active_model/type/value.rb:38:in `cast' …/code/rails/activemodel/lib/active_model/type/helpers/accepts_multiparameter_time.rb:12:in `block in initialize' …/code/rails/activemodel/lib/active_model/type/value.rb:24:in `deserialize' …/.rubies/ruby-2.5.3/lib/ruby/2.5.0/delegate.rb:349:in `block in delegating_block' …/code/rails/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb:8:in `deserialize' …/code/rails/activemodel/lib/active_model/attribute.rb:164:in `type_cast' …/code/rails/activemodel/lib/active_model/attribute.rb:42:in `value' …/code/rails/activemodel/lib/active_model/attribute_set.rb:48:in `fetch_value' …/code/rails/activerecord/lib/active_record/attribute_methods/read.rb:77:in `_read_attribute' …/code/rails/activerecord/lib/active_record/attribute_methods/read.rb:40:in `__temp__57074616475646f51647' …/code/rails/activesupport/lib/active_support/core_ext/object/try.rb:16:in `public_send' …/code/rails/activesupport/lib/active_support/core_ext/object/try.rb:16:in `try' …/code/rails/activerecord/lib/active_record/integration.rb:99:in `cache_version' …/code/rails/activerecord/lib/active_record/integration.rb:68:in `cache_key' …/code/rails/activesupport/lib/active_support/cache.rb:639:in `expanded_key' …/code/rails/activesupport/lib/active_support/cache.rb:644:in `block in expanded_key' …/code/rails/activesupport/lib/active_support/cache.rb:644:in `collect' …/code/rails/activesupport/lib/active_support/cache.rb:644:in `expanded_key' …/code/rails/activesupport/lib/active_support/cache.rb:608:in `normalize_key' …/code/rails/activesupport/lib/active_support/cache.rb:565:in `block in read_multi_entries' …/code/rails/activesupport/lib/active_support/cache.rb:564:in `each' …/code/rails/activesupport/lib/active_support/cache.rb:564:in `read_multi_entries' …/code/rails/activesupport/lib/active_support/cache.rb:387:in `block in read_multi'
I followed it backwards until I hit these two places:
…/code/rails/activerecord/lib/active_record/integration.rb:99:in `cache_version' …/code/rails/activerecord/lib/active_record/integration.rb:68:in `cache_key'
It looks like this expensive code is being called while generating a cache key.
def cache_key(*timestamp_names) if new_record? "#{model_name.cache_key}/new" else if cache_version && timestamp_names.none? # <== line 68 here "#
On line 68 in the
cache_key code it calls
cache_version. Here's the code for
cache_version:
def cache_version # <== line 99 here if cache_versioning && timestamp = try(:updated_at) timestamp.utc.to_s(:usec) end end
Here is our culprit:
timestamp = try(:updated_at)
What is happening is that some database adapters, such as the one for Postgres, returned their values from the database driver as strings. Then active record will lazily cast them into Ruby objects when they are needed. In this case, our time value method is being called to convert the updated timestamp into a time object so we can use it to generate a cache version string.
Here's the value before it's converted:
User.first.updated_at_before_type_cast # => "2019-04-24 21:21:09.232249"
And here's the value after it's converted:
User.first.updated_at.to_s(:usec) # => "20190424212109232249"
Basically, all the code is doing is trimming out the non-integer characters. Like before, we need a guard that our optimization can be applied:
# Detects if the value before type cast # can be used to generate a cache_version. # # The fast cache version only works with a # string value directly from the database. # # We also must check if the timestamp format has been changed # or if the timezone is not set to UTC then # we cannot apply our transformations correctly. def can_use_fast_cache_version?(timestamp) timestamp.is_a?(String) && cache_timestamp_format == :usec && default_timezone == :utc && !updated_at_came_from_user? end
Then once we're in that state, we can modify the string directly:
# Converts a raw database string to `:usec` # format. # # Example: # # timestamp = "2018-10-15 20:02:15.266505" # raw_timestamp_to_cache_version(timestamp) # # => "20181015200215266505" # # PostgreSQL truncates trailing zeros, # # to account for this we pad the output with zeros def raw_timestamp_to_cache_version(timestamp) key = timestamp.delete("- :.") if key.length < 20 key.ljust(20, "0") else key end end
There's some extra logic due to the Postgres truncation behavior linked above. The resulting code to
cache_version becomes:
def cache_version return unless cache_versioning if has_attribute?("updated_at") timestamp = updated_at_before_type_cast if can_use_fast_cache_version?(timestamp) raw_timestamp_to_cache_version(timestamp) elsif timestamp = updated_at timestamp.utc.to_s(cache_timestamp_format) end end end
That's the opportunity. What's the impact?
Before: Total allocated: 743842 bytes (6626 objects) After: Total allocated: 702955 bytes (6063 objects)
The bytes reduced is 5% fewer allocations. Which is pretty good. How does it translate to speed?
It turns out that time conversion is very CPU intensive and changing this code makes the target application up to 1.12x faster. This means that if your app previously required 100 servers to run, it can now run with about 88 servers.
Wrap up
Adding together these optimizations and others brings the overall performance improvement to 1.23x or a net reduction of 19 servers. Basically, it's like buying 4 servers and getting 1 for free.
These examples were picked from my changes to the Rails codebase, but you can use them to optimize your applications. The general framework looks like this:
- Get a list of all your memory
- Zoom in on a hotspot
- Figure out what is causing that memory to be allocated inside of your code
- Ask if you can refactor your code to not depend on those allocations
If you want to learn more about memory, here are my recommendations:
- Why does my App's Memory Use Grow Over Time? - Start here, an excellent high-level overview of what causes a system's memory to grow that will help you develop an understanding of how Ruby allocates and uses memory at the application level.
- Complete Guide to Rails Performance (Book) - This book is by Nate Berkopec and is excellent. I recommend it to someone at least once a week.
- How Ruby uses memory - This is a lower level look at precisely what "retained" and "allocated" memory means. It uses small scripts to demonstrate Ruby memory behavior. It also explains why the "total max" memory of our system rarely goes down.
- How Ruby uses memory (Video) - If you're new to the concepts of object allocation, this might be an excellent place to start (you can skip the first story in the video, the rest are about memory). Memory stuff starts at 13 minutes
- Jumping off the Ruby Memory Cliff - Sometimes you might see a 'cliff' in your memory metrics or a saw-tooth pattern. This article explores why that behavior exists and what it means.
- Ruby Memory Use (Heroku Devcenter article I maintain) - This article focuses on alleviating the symptoms of high memory use.
- Debugging a memory leak on Heroku - TLDR; It's probably not a leak. Still worth reading to see how you can come to the same conclusions yourself. Content is valid for other environments than Heroku. Lots of examples of using the tool
derailed_benchmarks(that I wrote).
- The Life-Changing Magic of Tidying Active Record Allocations (Video) - This talk shows how I used tools to track down and eliminate memory allocations in real life. All of the examples are from patches I submitted to Rails, but the process works the same for finding allocations caused by your application logic.
Get ahold of Richard and stay up-to-date with Ruby, Rails, and other programming related content through a subscription to his mailing list. | https://blog.heroku.com/tidying-ruby-object-allocations | CC-MAIN-2020-50 | refinedweb | 3,596 | 51.44 |
I");
}
}
}
Try adding the assembly in the namespace declaration attribute
"xmlns:local="clr-namespace:Project1;assembly=%Name of the Assembly%" i.e.
(Presentation.Infrastructure) where Presentation is the project name, and
Infrastructure is the folder where the control lives. –
I think you're trying to redefine the ResourceDictionary that you've
created when setting up your custom control. You've already created the
resource dictionary for use with the control, and you're then attempting to
create it again (hence the re-initialize exception).
You could move your styling for the DataGridCell into the main template
(which you wouldn't want to do in your case, because of your EvenSetter,
which is presumably instance specific).
A better solution for you may be to define that style in another
ResourceDictionary and reference it, or add the Style to the resources for
the Window/Page where you're using the custom control (e.g. you could add
it to the resources of a parent Grid).
I believe you can also merge resource dictionaries, although I've never
tried it:
http://
You have already had a uc in your form class, but you defined a new uc
(local variable) in the btnSaveToPath_Click handler which of course has the
initial FolderPath property as empty.
private void btnSaveToPath_Click(object sender, EventArgs e)
{
MessageBox.Show(uc.FolderPath); //NOT blank
MessageBox.Show(uc.folderBrowserDialog1.SelectedPath); //NOT blank
}
UPDATE
You don't have any code to fire the custom event in your UserControl:
public partial class FolderSelectDDL : UserControl
{
public delegate void ButtonClickedEventHandler(object sender, EventArgs
e);
public static event ButtonClickedEventHandler OnUserControlButtonClicked;
private string folderPath;
public string FolderPath
{
get { return folderPath; }
set { folderPath = value; }
}
public Fold
If your senior cannot backup his/her claims.. then he/she isn't really
someone you should try learning from. I'm not sure what the "memory issue"
is that he/she is referring to, however it's hard to tell with your
stripped down code.
That being said, I would reconsider databinding in a property set purely
because you open yourself up to "gotcha's" later down the track when people
start setting this property.
Instead, I would have a Refresh() method. Therefore, the calling code would
be:
UserControl.Property = value;
UserControl.RefreshData();
This gives the calling API the option of refreshing at that point or
deferring the decision.
I would be more inclined to use a partial view which you could place in the
shared views folder then call passing the model you wish to render with
that view:
@Html.Partial("propertySummary", property)
Just a thought
Adding a user control to window after creating it:
Step1:
Adding reference to the window in xaml:
xmlns:Views="clr-namespace:WpfApplicationName.Views"
Step2:
Adding the view to grid/stackpanel/wrappanel
<Grid>
<Views:UsercontrolName/>
</Grid>
Add this and once build your project.
You usercontrol will be loaded into the window.
Hope this helps you.
If these properties and methods are all leverage by user controls then how
about this:
public abstract class MyBaseUserControl : UserControl
{
// shared properties and methods
}
and then when building your user controls:
public class YourUserControl : MyBaseUserControl
The MyBaseUserControl can reside in a basic .cs file somewhere in the
assembly. Further, the only reason I listed the MyBaseUserControl as
abstract is because it's strictly built to be inherited from.
instead of using dependency properties you can go an easy way when your
customer object also has the address property
<AdressView>
<TextBlock Text="{Binding Path=MyAddress.Name}" />
<TextBlock Text="{Binding Path=MyAddress.Street}" />
mainwindow
<ComboBox X:Name=cbo .../>
<local:AddressView DataContext="{Binding ElementName=cbo,
Path=SelectedItem}"/>
customer.cs
public Address MyAddress {get;set;}
if you want your dependency property stuff to work, you have to post the
code for your addressview, so that we can check the bindings to the
dependency properties and you have to give some information how you wanna
get the address with your customerid.
I would add a method on the user control you need to pass data to.
Then you can call that method from the container and pass in the value.
Another approach is to put the value in session or viewstate.
Putting the grid view into a user control will lock you off from making
<Columns> definitions in your markup where you include your user
control, because the grid view definition is not accessible via properties
of the user control.
From the description of the changes you made that you want to reuse
elsewhere, it seems to me that you are better off creating a CSS class that
can be applied to all grid views in your application instead of a user
control.
As for the paging logic, you can have that be in a utility class that all
grid views in your application can call to do their paging, if the paging
logic is generic enough.
The bottom line is you have locked the structure of your grid view by
putting it into a user control, because there is no mechanism to alter the
structure. You c
I think you’ve gone about this the wrong way.
Ideally, you should have a users table and a corresponding User model, and
then use ACL to determine what a user can and can’t do. You can create
roles for clients and employees, and set permissions on these groups, and
assign each user to a group.
If you have client- and employee-specific data you wish to store, then you
can always create these tables/models and set them to belong to a User.
No, you either cut and paste or look into using custom Server Controls.
The custom server controls are basically a way of building the same .ascx
style controls but doing it all in code without a UI portion. If done
correctly, you can still have a UI drag and drop interface for your
controls.
Basically, Silverlight supports a sub-set of code available to WPF
developers. Rather than go into all the details here, I would instead
advise you to read the answers provided to a similar posted question and
preferably search the existing posts before you ask already asked
questions:
WPF vs Silverlight
i've solved my question..
So, i created a DependencyProperty on code behind of my User Control,
named selection, and i put this in Text of my text box.. after, when i
will using my user control, in my main page, i passed the value in for
porperty..
Like this:
User Control
public sealed partial class UCNotes : UserControl
{
public string selection
{
get { return (string)GetValue(selectionProperty); }
set { SetValue(selectionProperty, value); }
}
public static readonly DependencyProperty selecionadoProperty =
DependencyProperty.Register("selection", typeof(string),
typeof(UCNotes), new PropertyMetadata(null));
User Control XAML
<UserControl
xmlns=""
xmlns:x="
the VerifyRenderingInServerForm is method of Page class, so you need to add
this to the
page containing the UserControl
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
This is not exctly what you need:
ResourceManager manager = new ResourceManager("Resources.Messages",
Assembly.Load("App_GlobalResources"));
string test = manager.GetString("EmailBodyMagazine",new
System.Globalization.CultureInfo("fr-CA"););
But maybe you can also use the resource manager to access your files
directly
The / has a special meaning in a date format string. It means: "replace me
with your curent culture's date separator". In germany for example it is ..
MSDN
The "/" custom format specifier represents the date separator, which
is used to differentiate years, months, and days. The appropriate
localized date separator is retrieved from the
DateTimeFormatInfoDateSeparator property of the current or specified
culture. ...
I think the only way is using a CustomValidator to check this format. Then
you can parse the date in this way(on serverside):
DateTime dt;
if(DateTime.TryParseExact(txtDate, "MM/dd/yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
// now there is a valid date in dt
}
Notice the CultureInfo.InvariantCulture which i have used to enforce th have the names wrong - in the xaml you call them Control1Visibility and
Control2Visibility, but in the ViewModel, you are calling them
UserControl1Visibility and UserControl2Visibility. Change the names in one
or the other, and make sure the PropertyChanged events are raised with the
appropriate string.
Remember, {Binding} will default wise always take the DataContext as the
source of the property. Thats why your code isn't working, NewContent is
not a property in your ViewModel.
You want to change the source of your binding, to your UserControl, this is
one way to do it:
<UserControl x:Class="WpfApplication2.UserControl1"
xmlns=""
xmlns:x=""
xmlns:mc=""
xmlns:d=""
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300"
x:
<Grid>
&l
I think you are trying to do something like this.
Parent
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="Parent.ascx.cs" Inherits="StackOverFlow.Parent" %>
<table>
<tr>
<td>Parent Start Date </td>
<td>
<asp:TextBox
</td>
</tr>
<tr>
<td>Parent End Date </td>
<td>
<asp:TextBox
</td>
</tr>
</table>
Child
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="Child.ascx.cs" Inherits="StackOverFlow.Child" %>
<table>
<tr>
<td>Child Start Date </td>
<td>
You should try out the Block UI Plugin Here is a jsfiddle on how it works
So all you have to do is add a reference to the block ui script in your
code. On click of your search button just call:
$.blockUI({ message: '<div class="loading"><img
src="../images/Loading/466.gif" title="Cargando" alt="Cargando"
class="Load" /></div>' });
The above code will block all functions on your screen and show your custom
message(which in this case is the html that you passed to the plugin)
After your search returns a result you should do:
$.unblockUI();
This will remove the loading image and the user can again interact with
your page.;
You need to add CommandArgument to your button like CommandArgument="<%#
Container.ItemIndex %>".
This way, in the code; e.CommandArgument gives you the item number, with
which you can get the item that you want.
Note: In fact instead of specifying ItemIndex as CommandArgument, you can
use any Primary Key (Unique Identifier) from the DataSource that you bind
to the repeater from where you will be able to get hold of the record
directly from the list object (DataSource).
Try using a PlaceHolder. A PlaceHolder does not load a container element.
Assume that the Placeholder is called plcTest:
UserControl userControl = Page.LoadControl("~/Controls/userControl.ascx");
plcTest.Controls.Add(userControl);
Frontend code would look like this:
<li><asp:PlaceHolder</asp:PlaceHolder></li>
If I understand your problem correctly, check your anchor points of the
controls on your form. Also, check that form controls are set to grow and
shrink, as you see fit. The combination of the two may fix your problem.
Focus in WPF is a complex topic. I think you'll find that the proper way to
do what you want is to use FocusManager in your XAML:
<UserControl ... FocusManager.FocusedElement="{Binding
ElementName=myTextBox}">
<TextBox x:
</UserControl>
If you use FocusManager like this to establish all focus requirements (that
is, you use FocusManager on all Windows and UserControls that have any sort
of focus requirements), then you'll probably find that all the focusing
works exactly like you expect.
There is another event that you can attach to the TabControl instead of the
actual tab. Using the SelectionChanged event you can gain access to both
the tabs removed (hidden) and the tabs shown (active).
You will then need to add a flag in your class to check if the tab has
already been shown. Something like this should work.
readonly List<string> shownTabs;
public MainWindow()
{
InitializeComponent();
this.shownTabs = new List<string>();
this.tabCtrl.SelectionChanged += tabCtrl_SelectionChanged;
}
void tabCtrl_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
if(e.AddedItems.Count == 0)
return;
var tabItem = e.AddedItems[0] as TabItem; | http://www.w3hello.com/questions/-ASP-NET-User-Control- | CC-MAIN-2018-17 | refinedweb | 1,948 | 53.31 |
Code. Collaborate. Organize.
No Limits. Try it Today.
The biggest aim when I developed that architecture was to be able to simplify the whole mapping process between the database and the application, but without performance losses. As we all know, the four things that can be done with a set of data are:
No matter how difficult the business logic is in the application, these four actions are the things that can be done and must be done with a table or a view. The next figure illustrates the N-tier architecture of the system.
Let’s start with the BusinessEntities project. It is the most separated of them all but the simplest to be understood.
BusinessEntities
The project BusinessEntities is a class library project. It’s a part of the middle layer in the N-tier architecture. It consists of container classes, which will be filled with data from the database. These kinds of classes are used only for programming representations of the data returned from the database. Usually a class like this represents a table or view in the common scenario a query which gives a list of data from the database. The name of the class corresponds to the name of the table; the name of the properties of the class corresponds to the names of the columns. These corresponding items are set by attributes. It’s done in EntityAttributes.cs file. The class MapField inherits the base .NET class Attribute. This attribute is used to map the property of the class to the column of the database. For example:
MapField
[MapField("Title")]
public string Title
{
get { return _title; }
set { _title = value; }
}
The property called ‘Title’ of the class corresponds to the column called ‘Title’ returned from the database according to MapField attribute. The class ‘SpNames’ also inherits from the base .NET class attribute. It is used to set the names of the stored procedures for the main four actions – ‘select’, ‘select one’, ‘insert or update’, and ‘delete’. For example:
Title
SpNames
[SPNames("pContactList", "pContactSelect", "pContactSave", "pContactDelete")]
public class ContactEntity : BaseEntity, IContactEntity
{
The constructor of the class ‘SpNames’ is overridden and if there is a need, it can be initialized with one or more of the names of the stored procedures. The way these custom attributes are used will be explained in details later. As you can see, there is a ‘BaseEntity’ class. It is used to store the two main properties in all entity classes – ‘ID’ and ‘ReturnMessage’. Every table has an id; the return message in the entity class is used to store the return message from the stored procedures. The interface ‘IBaseEntity’ is the base interface for all entities. It makes the properties ‘ID’ and ‘ReturnMessage’ to be required. It’s good if all entity classes have a corresponding interface in which all the properties can be described, but this is not compulsory.
BaseEntity
ID
ReturnMessage
IBaseEntity
This makes the connection with the database. It’s also a class library project. Its class diagram can be seen in Fig. 2:
The file named Reflection.cs consists of one class called Mapper. This class, as you can guess, contains methods for mapping the entity classes and their properties with table names and columns. This is made by reading the attributes by reflection mechanism in the .NET Framework. The method ‘GetMapFields’ is one of the methods implemented in this class. By its explanation, you will be able to understand the whole reflection mechanism.
Mapper
GetMapFields
private static void GetMapFields
(Type type, DbDataReader reader, ref Dictionary<int> fields)
{
PropertyInfo[] pInfo = type.GetProperties();
for (int i = 0; i < reader.FieldCount; i++)
{
foreach (PropertyInfo pi in pInfo)
{
object[] attributes =
pi.GetCustomAttributes(typeof(MapField), false);
if (attributes.Length > 0)
{
MapField field = attributes[0] as MapField;
if (field != null && field.DbField ==
reader.GetName(i) && !fields.ContainsKey(i))
{
fields.Add(i, pi);
break;
}
}
}
}
if (type.BaseType != null && type.BaseType.IsClass)
Mapper.GetMapFields(type.BaseType, reader, ref fields);
}
The method ‘GetProperties()’ returns all properties of the type. Because the class Type is the base class of all types, here can be passed all the entity classes from the ‘BusinessEntities’ project. After the properties are returned, each property must collect its attribute defined by the developer and then they are checked if they are matched with the returned data from the ‘DbDataReader’ object. After that, the matches are saved in the Dictionary collection. By this code:
GetProperties()
Type
BusinessEntities
DbDataReader
Dictionary
if (type.BaseType != null && type.BaseType.IsClass)
Mapper.GetMapFields(type.BaseType, reader, ref fields);
Properties are taken as well as the properties of the base types, which are added to the Dictionary collection when there is a match. There are different implementations of the method ‘GetMapFields()’. In some are passed the type and the output collection, others the type and others the type and the object DbDataReader. The class GetEntitiesPaging will be explained in my next posting when I will say more for returning paged data. The file Filter.cs consists of ‘FilterInfo’ class, which is used for passing the parameters, when the data from the stored procedure is taken by using filtering parameters. (The filtering parameters are the parameters which limit the result or which sort the result by some criteria). The class DBAccess contains methods for creation of commands, for creation of parameters to that command and for returning of an object with type ‘DbDataReader’ and ‘DataTable’. This is the base class of the class DataTransaction. In the class ‘DataTransaction’ are made the opening and closing of the connection to the database and there are also additional methods for working with the transactions. The class ‘Paging’ stores the properties, which are necessary when there is paging of the results. The class ‘DataSource’ inherits the interfaces ICollection and IEnumberable. It contains the property ‘Paging’ which has type ‘Paging’ (the previous explained class), which is used for the paging, and also the properties for the total number of records, the list of records and the messages from the database. The class ‘Enumerator’ inherits the interface ‘IEnumerator’, there is also a property which returns the current element and methods for navigation into the collection. Another very important class is the class ‘Utils’. It contains methods which support the work of the application with the database. ‘GetDbType’: This is a method by which input type checks its name and returns the representation of the type in the database. ‘GetPropertyValue’ is a method by which input type and the name of the property returns the value of the property.
GetMapFields()
GetEntitiesPaging
FilterInfo
DBAccess
DataTable
DataTransaction
Paging
DataSource
ICollection
IEnumberable
Enumerator
IEnumerator
Utils
GetDbType
GetPropertyValue
public static DbType GetDbType(Type pType)
{
DbType ret;
switch (pType.ToString())
{
case "System.Int16":
ret = DbType.Int16;
break;
case "System.Int32":
ret = DbType.Int32;
break;
case "System.Int64":
ret = DbType.Int64;
break;
The method ‘GetProcedureName’ by input type and the type of the procedure (enum type) return the name of the procedure. This also is made by reflection mechanism. There is one nested enumerated type called ‘ProcedureType’ for all types of the stored procedures and the class EntityException. This class has as a base class - the ‘class Exception’ and it is used to throw exception when there is no defined stored procedure by the attribute of the class. The class ‘DBAccessBase’ is in the file EntityMethods.cs. It is a major class for the whole class library application. There are lots of methods for data processing, which are divided into regions.
GetProcedureName
enum
ProcedureType
EntityException
DBAccessBase
GetEntities
static
GetEntity
SaveEntity
DeleteEntity
DeleteEntities
This project also like the two which I explained before is a class library project. This is a place for realization of the business rules. It consists of only one class ‘BLBase’. This class has methods, which called methods directly from the class library project ‘DBAccess’.
BLBase
DBAccess
As you can see from the class diagram, there are methods which are very important for working with database. The method ‘DeleteEntity’ deletes one element according to the id of the element. The method ‘DeleteEntities’ deletes many elements according to filter criteria. (array of objects with type FilterInfo). The method ‘ExecuteProcedure’ executes stored procedure. The name of the stored procedure is passed as a parameter. It’s not taken like in the other methods by reflection. The method ‘GetEntities’ returns object with type DataSource. There are several implementations of that method according to the input parameters. The method GetEntitiesPaging also returns DataSource object, but with records which are determined by the input parameter of type Paging. By this parameter are passed the start record, the last record, and the count of the records. With that input data, the stored procedure will be able to return only the necessary records. The method ‘GetEntity’ returns only one element from a particular type according to an id. The method ‘SaveEntity’ saves the changes from a particular object or creates a new one according to the id property of the passed object. It returns the created object or the updated one.
ExecuteProcedure
DataSource
This is another layer. It’s not required but it helps because it separates the methods for returning data from the business logic of an aspx page or from the other presentation files of other projects.
This is a simple console application which is used just to call methods from ‘BusinessActions Project’.
BusinessActions
In my opinion, it’s very good layered architecture which is very easy to use. The only loss of performance is when the creation of the object is done. This is because reflection mechanism needs time to get properties of the class, the stored procedure name and to match them. I have made some test regarding its performance and it turns out that this only becomes a problem when a lot of objects are returned from the database, but this is not likely to happen in real life case. If you have any questions, please feel free to ask. I am open to criticism. In the next publication, I will show you a stored procedure for sorting and filtering the data. The C# code for getting data from such a procedure is written in the code, so don't worry if you don't understand it. (Example: GetEntitiesPaging procedure in the Reflection.cs | http://www.codeproject.com/Articles/64941/Fast-Flexible-and-Easy-to-Use-N-tier-Software-Arch?fid=1564235&df=90&mpp=10&noise=1&prof=False&sort=Position&view=None&spc=None | CC-MAIN-2014-15 | refinedweb | 1,703 | 56.55 |
List outdated packages using poetryHistory / Edit / PDF / EPUB / BIB / 2 min read (~230 words)
I use poetry as my python package manager and I'd like to know the packages that I depend on that are currently outdated.
An easy way to get this list is to run
poetry show --outdated. This will return you a list of all the packages that are outdated, their current version, the latest version, as well as a description of the package.
There are in my opinion three missing features here:
- having the command respect the semantic versioning constraint and only letting you see the latest version according to those constraints
- having a flag to switch between showing the latest version available without semantic versioning constraint vs the latest version constrained by semantic versioning
- having a flag to list only the packages that are direct dependencies (listed in the
pyproject.tomlfile)
Mypy and implicit namespacesHistory / Edit / PDF / EPUB / BIB / 1 min read (~137 words)
I use mypy but it doesn't seem to scan all my files. Why?
You might be using implicit namespaces in your code (see PEP 420). Support for implicit namespaces in
mypy is rather flaky as of 2020-03-03.
One solution for the moment is to add
__init__.py and make all your namespaces explicit.
Another solution is to replace your calls to
mypy some-path with
mypy $(find some-path -name "*.py").
Some imports in my python code are slow. How can I figure out which ones are the source of slowness?
Python offers a really useful functionality you can use that will list how long each import took. By passing the
-X importtime argument to your python command when you execute your script it will print out both the cumulative time (including nested imports) and self time (excluding nested imports) of each import.
python -X importtime your-script.py
Running
python -X importtime my-script.py on an empty script returns the following (on Windows 7, Python 3.7.5)
import time: self [us] | cumulative | imported package import time: 52 | 52 | zipimport import time: 367 | 367 | _frozen_importlib_external import time: 55 | 55 | _codecs import time: 530 | 585 | codecs import time: 520 | 520 | encodings.aliases import time: 1107 | 2210 | encodings import time: 328 | 328 | encodings.utf_8 import time: 39 | 39 | _signal import time: 357 | 357 | encodings.latin_1 import time: 34 | 34 | _abc import time: 312 | 345 | abc import time: 474 | 819 | io import time: 113 | 113 | _stat import time: 264 | 377 | stat import time: 269 | 269 | genericpath import time: 794 | 1062 | ntpath import time: 871 | 871 | _collections_abc import time: 915 | 3223 | os import time: 490 | 490 | _sitebuiltins import time: 57 | 57 | _locale import time: 934 | 991 | _bootlocale import time: 421 | 421 | encodings.cp1252 import time: 472 | 472 | types import time: 394 | 394 | warnings import time: 440 | 834 | importlib import time: 263 | 263 | importlib.machinery import time: 554 | 816 | importlib.abc import time: 64 | 64 | _operator import time: 792 | 856 | operator import time: 343 | 343 | keyword import time: 43 | 43 | _heapq import time: 405 | 447 | heapq import time: 85 | 85 | itertools import time: 328 | 328 | reprlib import time: 69 | 69 | _collections import time: 1460 | 3585 | collections import time: 44 | 44 | _functools import time: 596 | 640 | functools import time: 784 | 5008 | contextlib import time: 651 | 7308 | importlib.util import time: 1095 | 1095 | pywin32_bootstrap import time: 231 | 231 | sitecustomize import time: 10744 | 24972 | site
For a script with a simple
import argparse, I get the following output:
import time: self [us] | cumulative | imported package import time: 70 | 70 | zipimport import time: 341 | 341 | _frozen_importlib_external import time: 54 | 54 | _codecs import time: 457 | 511 | codecs import time: 456 | 456 | encodings.aliases import time: 1030 | 1997 | encodings import time: 215 | 215 | encodings.utf_8 import time: 38 | 38 | _signal import time: 268 | 268 | encodings.latin_1 import time: 33 | 33 | _abc import time: 398 | 431 | abc import time: 311 | 741 | io import time: 87 | 87 | _stat import time: 271 | 357 | stat import time: 196 | 196 | genericpath import time: 416 | 612 | ntpath import time: 714 | 714 | _collections_abc import time: 610 | 2292 | os import time: 229 | 229 | _sitebuiltins import time: 48 | 48 | _locale import time: 246 | 293 | _bootlocale import time: 217 | 217 | encodings.cp1252 import time: 488 | 488 | types import time: 279 | 279 | warnings import time: 461 | 740 | importlib import time: 269 | 269 | importlib.machinery import time: 557 | 825 | importlib.abc import time: 63 | 63 | _operator import time: 808 | 871 | operator import time: 336 | 336 | keyword import time: 41 | 41 | _heapq import time: 336 | 376 | heapq import time: 69 | 69 | itertools import time: 341 | 341 | reprlib import time: 70 | 70 | _collections import time: 1136 | 3197 | collections import time: 69 | 69 | _functools import time: 642 | 710 | functools import time: 801 | 4708 | contextlib import time: 688 | 6959 | importlib.util import time: 934 | 934 | pywin32_bootstrap import time: 224 | 224 | sitecustomize import time: 9323 | 20954 | site import time: 698 | 698 | enum import time: 55 | 55 | _sre import time: 417 | 417 | sre_constants import time: 372 | 789 | sre_parse import time: 443 | 1286 | sre_compile import time: 323 | 323 | copyreg import time: 716 | 3021 | re import time: 725 | 725 | locale import time: 948 | 1673 | gettext import time: 986 | 5678 | argparse
The package are listed in order that they are resolved. In
argparse case,
os and
sys were already loaded, so it first loads
re, then
gettext. Once both are loaded,
argparse has finished loading.
The way the cumulative column is computed is to take all the prior self that are a level higher than the package you're looking at. For example (if we take the io package):
import time: 33 | 33 | _abc import time: 398 | 431 | abc import time: 311 | 741 | io
311 + 398 + 33 = 742
We can see here that the numbers are not necessarily equal to one another, this might be due to precision used to do the computation while the rendering of numbers is rounded.
Note that the load time of a package may be different depending on which script you load because dependendencies of the package may have already been loaded in some cases, while in others it may have to load them.
Looking at text might be your thing, but if you're more visual, there's a tool called tuna which will consume this output and create an icicle plot you can look at to find which imports are the slowest/longest.
Improving the performance of a slow click CLIHistory / Edit / PDF / EPUB / BIB /
Pytest with tests files with similar namesHistory / Edit / PDF / EPUB / BIB / 2 min read (~248 words)
I have two test files with the same name and pytest complains. How do I make it work without changing the test filenames?
Example directory structure
/path/to/project/tests ├── a/ │ └── test_a.py └── b/ └── test_a.py
Error message:
import file mismatch: imported module 'test_a' has this __file__ attribute: /path/to/project/tests/a/test_a.py which is not the same as the test file we want to collect: /path/to/project/tests/b/test_a.py HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules
Add a
__init__.py to each directories with tests files that have the same name. Technically, you only to have a
__init__.py file in one of the two directories, so that one is in a package while the other one is in a different one. Adding it in both simply prevents this issue from occurring again if you were to add a third file
test_a.py.
/path/to/project/tests ├── a/ │ ├── __init__.py │ └── test_a.py └── b/ ├── __init__.py └── test_a.py | https://blog.tomrochette.com/category:Python | CC-MAIN-2020-24 | refinedweb | 1,253 | 56.69 |
#include <rpc/client.h>
#include <util/system.h>
#include <cstdint>
#include <set>
Go to the source code of this file.
Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) as well as objects and arrays.
Definition at line 209 of file client.cpp.
Convert named arguments to command-specific RPC representation.
Definition at line 237 of file client.cpp.
Convert positional arguments to command-specific RPC representation.
Definition at line 218 of file client.cpp.
Definition at line 203 of file client.cpp.
Specify a (method, idx, name) here if the argument is a non-string RPC argument and needs to be converted from JSON.
Definition at line 25 of file client.cpp. | https://bitcoindoxygen.art/ABC/client_8cpp.html | CC-MAIN-2021-49 | refinedweb | 117 | 61.83 |
Vision and Sound From the Ideally Bare Numeric Impression giZmo 38 exception."
But (Score:1)
Un messago sponsoro (Score:2, Funny)
Very cute. (Score:4, Informative)
That's very cute. That's the most obscure programming language I've ever seen not created as a joke. They can generate mediocre techno with about 20 characters of code.
Re: (Score:3)!"
Re: (Score:2)!"
I see Skrillex has already been covered, logging out of this thread satisfied.
:P
Re: (Score:2)
Thank you! I thought the exact same thing! Ahhh.. the good old days of spending hours on end dutifully typing in programs from the pages of Antic! saving the results to cassette... It was what got me into the minimal programming I do today.
and yeah.. get off my lawn, I'm reminiscing here, and you're getting in the way!
simple but fairly clever (Score:5, Interesting)
The simplicity of the code you can write in this language seems to be mostly due to the cyclic nature, which is something other beat-oriented computer-music languages also have: once you have "repeat" as a built-in thing, anything built on regular repetitions is easy to program. But it adapts it in a way that feels more low-level and demo-scene-ish by tying it to a cyclical "stack" in a bastard-son-of-Forth sort of way. Will have to play around with it a bit.
libglitch and making music a with C compiler (Score:5, Interesting)
I wrote something similar to IBNIZ, yet vastly simpler, a composing software called glitched [github.com] (needs pygame 1.9.1). The forth variant I use has no subroutines or recursion and is not even turing complete and the stack has only 256 fields. However, it is compatible with that of several other implementations (see README). Like IBNIZ, it has live editing and stack visualisation [dieweltistgarnichtso.net].
It is important to note that sound made with this kind of tools is not limited to chiptunes. There is a video of an older version of glitched [dieweltistgarnichtso.net], doing Karplus-Strong-string synthesis [wikipedia.org].
(Apologies in advance to the users of a totally unrelated glitch library [rhydd.org], which is also written in python. I have met one of it's developers last night and we agreed insane troll logic dictates a merger of our two projects to rectify the namespace collision. I may have to bring that up again when he is sober.)
Oops, forgot the C compiler part. (Score:3)
Before IBNIZ, viznut was using a C compiler to, well, discover minimal music. You should read his paper regarding algorithmic composition using small programs. [arxiv.org] und check out my repository of formulas for C programs that generate sound [github.com].
People without easy access to compilers (I met a gal a few days ago who had old OS X and no 99$ to spare for a dev account) should still check out a track from the repository as wave file [dieweltistgarnichtso.net] to get an impression of the style.
I also wrote a program generating a crude chiptune [dieweltistgarnichtso.net]
Re: (Score:3)
You don't need a dev account to develop for OS X, just for putting things on the Mac App Store. Xcode is available for download without an account, or you could just install your own gcc.
Re: (Score:2)
This page [apple.com] asserts that "Xcode 4 is a free download for all members of the iOS and Mac Developer Programs.", continuing "Sign in to your account to begin the download." and according to Apple [apple.com], an account costs 99$/year.
Maybe I am missing something big here, for example "free" meaning "free" as in "free beer if you buy a subscription", but I have since suggested installing Debian [debian.org]. Proper package management makes it vastly easier to install and develop software.
Re: (Score:2) [apple.com]
It is free to everyone.
Re: (Score:2)
Re: (Score:2)
Well, the older versions are available for download somewhere, just hard to find.
Re: (Score:2)
All versions of OS X came with XCode. If you have
Re: (Score:2)
The glitter.py script is your friend; it just outputs the audio bitstream. You can pipe that into sox [sourceforge.net] but I wouldnt know how to capture the output of this in Windows *SCNR*.
Working example that outputs 16 seconds of the track "sidekick" (128000 = 8000 * 16):
./glitter.py `cat tracks/sidekick.glitch` | head -c128000 | sox -c 1 -r 8000 -t u8 - sidekick.wav
Re: (Score:2).
Ow, my ears! (Score:1)
How about
/dev/mem >/dev/audio; done
while true; do cat
?
"Politically Correct"? (Score:2)
Re: (Score:2)
"A quick Google search didn't come up with anything relevant. How would IBNIG be non-PC compared to IBNIZ?"
Technically, it probably wouldn't. But living as we do in a society in which a celebrity can catch all kinds of hell for using the word "niggardly" (which has absolutely nothing to do with race or racism), I think they were playing it safe.
Re: (Score:2)
Fractal Music Implementation (Score:1)
Might work with some of [shameless plug] my fractal formulas * [fractalforums.com] [/shameless plug], although you'd have to use sqrt [1-sin^2 (x)] for cosine as it apparently isn't implemented? (I only see sin and atan2).
Probably try it with simple 2d fractal formulas first. Nice...
On another note (I'll scan thread carefully), any recommendations for other open source mathematical music programs?
*others scattered around the website.....
256 bytes including the interpreter? (Score:3)
Otherwise, a SPORE creature save file is a better "demo". (note, must install interpreter...)
this one is for bookmarks (Score:2)
Wilhelm scream (Score:2)
As if it was not enough that the same scream is used in many blockbuster movies.
Visual Perl (Score:2)
nuf sed
:-) | http://developers.slashdot.org/story/11/12/31/1726251/vision-and-sound-from-the-ideally-bare-numeric-impression-gizmo?sdsrc=nextbtmprev | CC-MAIN-2015-35 | refinedweb | 985 | 67.15 |
[email protected]
or have you any complete free of cost send sms fet help me on "why subclass of stack is
View Tutorial By: mahendra at 2012-12-15 03:39:22
2. import java.lang.*;
import java.io.*;
View Tutorial By: satya at 2012-12-09 10:57:28
3. i have connected my phone through bluetooth using
View Tutorial By: nikitha at 2013-02-06 05:05:04
4. everything is easy to learn from your website.I un
View Tutorial By: sumitra barua at 2012-05-30 03:13:10
5. can i use PrintWriter to save to a word document o
View Tutorial By: philip at 2013-03-20 10:21:01
6. Hi,
I am getting this exception..My modem i
View Tutorial By: divya at 2008-04-27 04:12:19
7. Thanks, much appreciated!
Saved a great dea
View Tutorial By: alan at 2009-08-14 01:35:01
8. today Iam getting time ,date of sending and "
View Tutorial By: raghu at 2012-01-07 14:43:32
9. Nice Explanation
View Tutorial By: sam at 2010-11-24 02:23:57
10. its working... thanks.. thank you very much...!!!!
View Tutorial By: Viswanathan at 2008-08-18 06:54:09 | https://java-samples.com/showcomment.php?commentid=33536 | CC-MAIN-2022-33 | refinedweb | 209 | 76.42 |
Re: JESS: Question about defquery
I think Lakshmi Vempati wrote: I am using a simple defquery to find a fact and then modify it. For reasons that are too difficult to go into (although we've actually discussed it before on this list) when you get a jess.Fact out of a jess.Token (as you do when you're working with a query
Re: JESS: query about numeric variables
I think Moore, David [IES] wrote: (defrule age (benefit-seeking) = (printout t Please enter your age (in years) crlf) (assert (age(read The disappointment is that the value
Re: JESS: Getting detailed match information
I think Douglas Pearson wrote: For example if I had: (defrule simple-rule (child (id ?x) (name ?name)) (parent (id ?y) (child ?x)) = (printout t Child ?x name ?name crlf) ) and I know fact-3 and fact-7 were matched...how can I tell (programmatically) which fact
Re: JESS: jess.Console question
I think Maxim Tretyak wrote: Hi Can I get advantages of jess.Console by such a way: Jess (new jess.Console Hi (engine)) External-Address:jess.Console Console is appearing, but connand line input is transmitted directly to output text area, without interaction with Rete. Very clever!
Re: JESS: Passing an instance of Rete to java
I think Greg Biegel wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hi, Is there a way to pass a reference to the current instance of the rule engine from Jess, to a Java object. I tried using the 'this' keyword, but doesn't seem to work. So basically, I would like to
Re: JESS: problems writing defrule...
I think Katie Truong wrote: Dear Jess Support Team, I started writing a program that develops a small knowledge system for health assessment and longevity planning. The health assessment system will evaluate a persons current health status based on input values for predefined risk
JESS: Announcing Jess 6.1p7
Hi Folks, I am pleased to announce that version 6.1p7 of Jess, the rule engine for the Java platform, is now available for download at the usual place: This is a bug fix release with some improved performance characteristics. From the change log:
Re: JESS: Pausing the execution cycle without returning
I think Steffen Luypaert wrote: The basic trick is this: From one rule, set up the GUI to ask a question, then call ((engine) waitForActivations), which pauses the (run) thread until a new rule is activated. The problem is that waitForActivations will still fire the
Re: JESS: Clarification of Jess Performance in a multi-threaded environment...
I think Jin Lian wrote: It seems that the default Java synchronization mechanism has been used to coordinate which thread will be able to fire rules. If 10 threads come in simulstaneously and all want to fire a different rule, then 9 of them will have to wait while the execution engine is
Re: JESS: Combining the logical CE and backward chaining
I think Steffen Luypaert wrote: Hi all, No backward chaining will occur for patterns inside a conditional element. I was wondering that this will change in a future version of Jess, especially for the logical conditional element. This is basically an oversight in the rule compiler;
Re: JESS: JESS defmodules and focus
I think Michael Knapik wrote: Question: why are they fired/reported in reverse order of the focus statements? As the manual explains at the end of section 2.10.3, there's a focus stack containing the list of modules from which rules will be fired; rules will be fired only from the module
Re: JESS: Rules not firing
I think Rajani Sadasivam wrote: == f-1 (MAIN::book (name Java for beginners) (keyword Java) (publisher oreilly) (price 15)) -vs- == f-5 (MAIN::book (name samplebook) (keyword Java) (publisher oreilly) (price 14)) Jess has both a String type and a symbol or atom type (this is covered over
Re: JESS: Java and Jess
I think [EMAIL PROTECTED] wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hi there, i made the board game Stratego with java. and i want to use agents for every piece. my quastion is: i have now the complete game done with java. And someone else made all the Agents
Re: JESS: asserting javabeans
I think =?iso-8859-1?Q?Diego_Alonso_Gonz=E1lez?= wrote: I'm really confused, by shadow concept. There are two kinds of definstances: static and dynamic. Dynamic ones use PropertyChangeEvents, static ones don't. If you use (modify) in Jess, both kinds of JavaBeans will be immediately updated.
Re: JESS: Problem updating shadow fact data
I think Michael Knapik wrote: ;;(call event setConditionCodeId ) Variables always have a ? in their name: (call ?event setConditionCodeId ) (modify 2 (conditionCodeID )) Slot names are case-sensitive: (modify 2 (conditionCodeId ))
Re: JESS: Problem updating shadow fact data
I think Michael Knapik wrote: How do I do that - how do I get the shadow fact data to change (so that Java code that is executing this Jess code knows about it). (modify ?e (conditionCodeId )) would do it. - Ernest
Re: JESS: Problem updating shadow fact data
I think Michael Knapik wrote: (defrule report-subject-and-event-status ?s - (subject (subjectId ?sId) (caseStatusId ?csId)) ?e - (event (eventId ?eId) (conditionCodeId ?ccId)(eventDescriptor ?evtDescriptor)) = (modify ?e (conditionCodeId )) (printout t * Event ?eId has a condition
Re: JESS: JessAgentTab
I think Chintan Shah wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Can you please provide the fully qualified server name in the url. does not work for anybody outside your DNS. It the same as his email;
Re: JESS: Embedded executeCommand() performance problem
I think Douglas Pearson wrote: The problem is that loading a list of about 2,000 facts this way is taking 30 seconds and I'm just wondering why? For debugging we dump the same commands to a file which we can then load into a standalone instance of Jess through the (batch file) command and
Re: JESS: Comparing string
Jess doesn't have an explicit else-if feature; if you put an if into the else of another if, then that second if is a separate function call, so it needs its own parentheses. If I may, I will point out a few other things here: You don't need to spell out the names of any classes in java.lang, as
Re: JESS: Pattern Binding for CE
I think Krasnigor, Scott L (N-AST) wrote: I have an ID slot defined for the Bean object used to define the facts but can't seem to figure out how to get the fact that triggered the rule so I can modify it for this particular case (all my other rules allow pattern binding). I formatted your
Re: JESS: How to write constraint for shadow fact list/set properties ?
I think robert fields wrote: Classes are loaded from java by Jesp j = new Jesp(new StringReader((defclass {Role, ...} package.{Role,})), aEngine); j.parse(false); The Rete class has a defclass method which would be much more convenient to use! Barring that, it also has an
Re: JESS: Facts and modules
I think Henrique Lopes Cardoso wrote: So, if I understood correctly, facts can only be asserted in the module where their templates are defined Yes. Therefore, if I have a template defined in MAIN, I cannot create a fact based on that template in another module. Right. Another
Re: JESS: Matching a static variable
Hi Erich, First, let me mention that I'm happy to see someone using the brand-new static imports feature -- the thing that lets you use (CarClass.MINI) as a constant. Second, your code looks fine except that the defclass defines a short template tag RentalCarReservation, but the rules are using
Re: JESS: Matching a static variable
I think Alan Moore wrote: Third, let me mention, as I often do on this list (I really need to make this point more strongly in the manual) that direct matching should always be preferred to function calls, and anything else should be preferred to the test CE; this is not only a style
Re: JESS: Rules Management
I think Brian Corbin wrote: How do you manage your rules? Do you bundle the rule sets with the application? Are they stored in a database that the application references? Maybe even using an interface to CVS or Subversion? Since nobody has answered yet, I'll tell you some of the ways I've
Re: JESS: Jess DE JSR-94
I think erich.oliphant wrote: Hi, We are using the JSR-94 interface but would like to use JessDE for debugging,etc. Will jessDE support the XML formatted files required by the JSR-94 interface ? There are two JSR94 drivers. There's the reference implementation that comes with the JSR94
Re: JESS: Problem with definstance
I think David Firmin wrote: I'm trying to create shadow facts that subclass a deftemplate that's already been added to the Rete. When I try and add the java bean using definstance I get a ClassCastException as follows: java.lang.ClassCastException at
Re: JESS: Problem with definstance
I think David Firmin wrote: Hi, Thanks for this, although I'm still missing something I think. The Order class I'm trying to define as an instance does have accessors and modifiers for all its properties, including the two defined on the superclass deftemplate that's already been created
Re: JESS: Central data storage for multiople Jess instances
I think Bogdan Werth wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hello everybody, I working on the model from the field of social simulation. I am using RePast and Jess to make my agents think in a declarative way. At the moment I have a separate Jess instance for every agent
Re: [JESS:Problem with Running the Jess T][ab without the Prot_g_ User Interface]
I think Eunice Palmeira wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] I don't get to run my application in Eclipse, because the line under report the error: java.lang.NoClassDefFoundError: edu/stanford/smi/protege/model/Instance, but i get run direct in protege.
Re: JESS: New to JESS
I think nikita berdikov wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hello, I'm new to Eclipse and JESS, so can anyone tell me how to start working with JESS in Eclipse 3.1. What variables should i set? I did everything that is written in Using the JessDE, but something is
Re: JESS: So lame, and so sorry - disregard last post
I think Matthew Hutchinson wrote: So it's not a complete waste, is the following line still the reccomended way of loading rules from Java? engine.executeCommand((batch jess_test.clp)); In Jess 7, there's a Rete.batch() method you can use instead; otherwise, what you've shown works fine.
Re: JESS: The JessTab PAL-integration functions are not available
I think Eunice Palmeira wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hello, I have a problem when i try run Jess with Protigi: JessTab: Note that the PAL engine is not currently installed in Protege. (The JessTab PAL-integration functions are not available.) Well,
Re: JESS: For-loop bug
You're right -- that's not the correct behavior. Thanks for the report. I think Yura wrote: [Charset koi8-r unsupported, filtering to ASCII...] Hi I think there is a bug in the 'for'-loop implementation. The following code returns '1' (incorrect): (bind ?x 1) (for (bind ?i 1) ( ?i 2)
Re: JESS: New to JESS
In the first screenshot, I see an editor window named awtdraw.clp, but I don't see a file by this name in the navigator view; my guess, then, is that you've used the Eclipse File | Open... menu to try to open a file not in your workspace. This doesn't work. You can only edit .clp files that are
Re: JESS: JessDE buggy
I think Jim Goodwin wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Are you interested in bug reports? Where do I send them? Very interested. You can send them to this list or directly to me at [EMAIL PROTECTED] Is further work on the JessDE active right now? Absolutely.
Re: JESS: Memory requirements of jess.Value
I think Jon Weygandt wrote: Any thoughts about a Value factory returning specialized objects (especially for common Values), by a rough back of the envelope calculation this could save 50% of the space in the Value object instance, resulting in an overall savings of 20% application memory
Re: JESS: Using not and and
I think Dusan Sormaz wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] I was able to run it in 7.0a6. I am curious, what is the interpretation of and in this example? Is it AND of 4 items? or only 2? 2. It means that there's not a (bar ?x) fact where ?x is the fact (a b c).
Re: JESS: Using not and and
Hmmm, OK, I see. This is a known issue which has (as another poster pointed out) been dealt with in Jess 7. In Jess 6, the workaround is to reverse the order of these patterns: (not (and ?b - (a b c) (foo (bar ?b)) ) ) I think Henrique Lopes Cardoso wrote:
Re: JESS: jess
I think =?iso-8859-1?Q?=5BEXTERN=5D_Manuel_Kollmu=DF?= wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] hi is it possible to read out informations from a *.dll and to handle the return value (string)? Sure, in the same way you'd do it from any Java program: you wrap the DLL
Re: JESS: TextArea Buffer Size
I think Semmel, Glenn S wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hello. Under Jess 7.0a4, the TextAreaWriter class has the following attribute: private static final int MAXSIZE = 3 In a future release, can this attribute be changed to be either a user
Re: JESS: Converting from/to strings
I think Henrique Lopes Cardoso wrote: (defrule r1 ?x - (foo) = (bind ?string (implode$ ?x)) ;; IS THERE A WAY OF DOING THIS? ?x is a jess.Fact object. You can call any of the methods of jess.Fact on it -- including toString() and toStringWithParens(), one of which
Re: JESS: Jess in a multithreaded environment
I think Florian Fischer wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hello, I am using Jess in a multithreaded environment... I need to understand how Jess works in a multithreaded environment. Is the following description correct? - One lock is on all the data (facts,
Re: JESS: Jess in a multithreaded environment (Copies of the fact data)
Ultimately, of course, a Fact is an array, with one element for each slot. When you compile a rule, the rule compiler will look up the names of any slots that are mentioned, and it's the index of the slot that gets compiled into the rule. On the other hand, fact-slot-value is a function that has
Re: JESS: Date: Wed, 26 Oct 2005 15:13:21 +0200
I think Vladimir Florian wrote: Could you please give me a hint why the second rule is not fired and the fact f3 is not retracted? Because the rule says (communicative-act QUERY_REF) (with an underscore) and the fact says (communicative-act QUERY-REF) (with a hyphen)?
Re: JESS: MethodNameComparator generates error in 70b3
I think Semmel, Glenn S wrote: I looked at the source files and noted the following differences: 70b3's compare() ends with: return ((String) o1).compareTo(o2); Whereas 70a4's compare ends with: return ((String) o1).compareTo((String) o2); Interesting! If you look at the
Re: JESS: exists description in the documentation missing?
I think Fred Janon wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] I am reading the Jess in Action book and noticed that it lists exists as a Jess' CEs but I could not find it in the online doc for version 6.1. It's here, in chapter 2:
Re: JESS: Pocket PC
I think nikita berdikov wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hello to everybody, i wanted to know if u can with jess on my pocket pc, is it possible? No, not out of the box. Work on a PDA edition of Jess is underway, however, and may be available next year. and
Re: JESS: WebSite navigation
I think Daniel B. Davis wrote: All browsers I have tested show the navigation items on the web site as too small to read.nbsp; These include: ul liMozilla Firefox 1.0 liNetscape Navigator 7.1 liInternet Explorer 6.0 /ulThese are the ones high on the left-hand side of the page, rendered in
JESS: Announcing Jess 7.0b4
Hi Folks, We're pleased to announce the availability of the latest release of Jess, the rule engine for the Java platform, at the usual location: This release adds a lot of polish to Jess 7 as we approach the final version. There are a number
Re: JESS: multiple shadow fact templates
I think Scott Moss wrote: If the defrules are ordered as above, then no shadow facts are created for producer. If the producers rule is defined first, then three producers shadowfacts are created followed by seven agents shadow facts. Is it the case that there cannot be two points to a
Re: JESS:Modular deffacts problem
I think David Firmin wrote: I'm trying to use deffacts with a specific module, but am having some problems changing out of that module once the deffacts has taken place. At present, I'm doing the following (although I've simplified the code here, the sense remains the same): I'm afraid
Re: JESS: multiple shadow fact templates
I think Scott Moss wrote: The order in which rules are fired depends first on the conflict resolution strategy, but if two rules are of equal priority by that criterion, then they'll fire in an arbitrary order that just falls out of the Rete network implementation. That order is affected by,
Re: JESS: String to Symbol
I think [EMAIL PROTECTED] wrote: How can I convert a string into a symbol? In Java, String string = whatever; Value symbol = new Value(string, RU.SYMBOL); In Jess, (bind ?string whatever) (bind ?symbol (sym-cat ?string)) -
Re: JESS: empty list pattern and ppdefrule
I think Jonathan Sewall wrote: However, in Jess v7.0b4, ppdefrule omits the (data ) pattern from its output. Is our simpler syntax for testing multislots unsupported? Many thanks, Seems to work as ever; this is apparently just a bug in the pretty-printer. Thanks for the report.
Re: JESS: RE: Understanding JESS
I think Daniela CLARO wrote: However I have more two questions, the first one I thought that (reset) clear my knowledge base, I mean, my facts, rules, all things and actually it doesn't. What is the command I can use to clear my knowledge base? There's a chapter entitled The Jess Function
Re: JESS: String to Symbol
I think Roger Studner wrote: (defrule count-icd9-codes ?c - (accumulate (bind ?count 0) ;; initializer (bind ?count (+ ?count 1)) ;; action ?count ;; result (encounter (code ?c : (eq ?c 440))) ) ... This (and anything in the accumlates match
Re: JESS: Behavior change from 6.1p7 to 7.0b3 with modify function
I think Jon Weygandt wrote: it looks like modifying a fact sometimes requires the equivalent of: For each slot modified { Retract the fact Set the slot Assert the fact } Yes, more or less. Special versions of retract and assert can be used to cut a few corners in this
Re: JESS: How does the pattern match: ?trans_state SI | MI | EI
I think Jon Weygandt wrote: Jess, That's her picture on the cover of Jess in Action :) (TRANS_STATE ?trans_state SI | MI | EI) My procedural view would be the pattern is evaluated as: (TRANS_STATE (?trans_state SI) | MI | EI) And if the match for SI fails, not sure what
Re: JESS: String to Symbol
I think Roger Studner wrote: (deftemplate employee (slot salary)) (deffacts employee-facts (employee (salary 1007700)) (employee (salary 1002347700)) (employee (salary 107712000)) ) (watch all) (reset) (defrule count-highly-paid-employees ?c - (accumulate (bind ?count 0) ;;
Re: JESS: Strange Jess / Eclipse crash
I think Matthew Hutchinson wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] G'day everyone, This is more of an Eclipse question, however, I only get this error when trying to open CLP files. Eclipse with Jess has been working fine for weeks, and now suddenly Eclipse completely
Re: JESS: Strange Jess / Eclipse crash
I think Matthew Hutchinson wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hi, Actually, I have already got the full version from Craig and it works fine. Also, my classpath and eclipse stuff is all set to the full version jar file also. Good, but be that as it may, one can
Re: JESS: Checking if a fact exists
I think [EMAIL PROTECTED] wrote: (defrule rule1 (x1 value1 ?cf1) (x2 value2 ?cf2) (x3 value3 ?cf3) = (assert (x3 value3 (min ?cf1 ?cf2 ?cf3))) Perhaps this rule should retract or modify the existing fact, rather than asserting a second one, as this does?
Re: JESS: variable facts
I think =?iso-8859-1?Q?=5BEXTERN=5D_Manuel_Kollmu=DF?= wrote: Isn_t it possible to assert a variable as a fact or a variable fact? like this: (bind ?var number1) _. (assert (?var)) No, the type of the fact must be known when the call to assert is compiled. You can use an extra level of
Re: JESS: Or problem
I think mauricio rincon wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hi... I have a problem with OR (v) operator. I_m using this operator in a rule, that should be fired only once when both of the conditions happened . The problem is that if both events are happening, the
Re: JESS: Multifield matching nil
I think Steve Solomon wrote: This is a minor complaint. Why can't one use nil to match an empty list? Short answer: because Jess inherited its basic rule language semantics from CLIPS, and that's how it works in CLIPS. Only the pattern (sprocket ?id) matches (sprocket 2) with no following
Re: JESS: Hrmm.
[ Forwarded for Jason Morris -- Moderator ] I think that Roger Studner wrote: Can someone explain slot-specific to me? You've stumbled right into what Dr. Friedman-Hill warns about in section 7.15 in the Jess documentation. You're modifying a slot that is *not* part of the LHS, so Jess will
Re: JESS: Hrmm.
I think Roger Studner wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Can someone explain slot-specific to me? Based on your hints about what your code might look like, I wrote this rule: (defrule foo ?cGroup - (ICD9_COUNTING_GROUP (codes $?codes)) = (bind ?theCount
Re: JESS: defquery
I think Roger Studner wrote: When I try to modify the fact.. I get an error that 'the fact is not in working memory'. Short answer: before trying to modify the facts you get from a query, use getIcon to resolve them: (bind ?fact (?fact getIcon)) Better answer: upgrade to Jess 7, and use the
Re: JESS: runQueryStar
I think Scott Moss wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] I am unable to get the QueryResult returned by runQueryStar() in Java to recognise column headings in a Userfunction. The argument to the getXxx() methods isn't a slot name; it's a variable name. Remember that
Re: JESS: slot-specific and multifields
along at home, is [EMAIL PROTECTED] Jess]$ cvs diff -r 1.5 -r 1.6 jess/Node1MTMF.java Index: jess/Node1MTMF.java === RCS file: /home/ejfried/cvsroot/Jess/jess/Node1MTMF.java,v retrieving revision 1.5 retrieving revision 1.6 diff -r1.5
Re: JESS: Debugger
I think Jeffrey Davine wrote: I'll do the research, but as a general matter, do you think the Jess API exposes enough information (particularly concerning the rete tokens) so that I could write such a tool? Alan's more optimistic, but I myself don't think this can really be done at the level
Re: JESS: Converting Object to Object[]
Jess's usual representation for arrays is a Jess list -- is that what you're looking for? There isn't a public API built into Jess for turning an array into a List, but now that you're pointing out the need, it seems like a good addition. For now, though, your obj2array function is the best way
Re: JESS: Object to built-in type
I think Roger Studner wrote: v = new Value(l, RU.SYMBOL); ... v = new Value(i, RU.SYMBOL); For the record, note that both of these lines will throw exceptions at runtime. To contstruct an RU.SYMBOL from a numeric type, you have to convert the value to a String yourself and pass that String to
Re: JESS: Size of an activation record
I think Kristina Marasovic wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hi, can someone tell me if it is possible (and how) to get or to measure the size of an activation record. You don't really know the size of *any* Java object, as the details of object representation
Re: JESS: Conflic Resolution Implementation
There's no tutorial guide or anything like that. The basic procedure is very easy: implement the jess.Strategy interface, then use (set-strategy classname) to load it into Jess. There's really just the one compare() method to write; it's supposed to implement the spaceship operator (ie.,
Re: JESS: Template Hierarchy
I think Jeffrey Davine wrote: Perhaps the place to ask this question is the Constantine Planning Wiki - but would it be difficult in the next version of Jess to implement a hierarchical template structure? ... (deftemplate Individual extends LegalAgent OK, let's get in the time machine...
Re: JESS: Size of an activation record
I think Roger Studner wrote: Is there (I read something 'akin' to this in the mailing archive) a big performance hit as well? I like to use beans/shadow facts for a variety of reasons, but have always been under the impression that when i'm going to assert a 'huge' number of a particular
Re: JESS: Editor couldn't be initialized
I think Yura wrote: I'm receiving the Editor couldn't be initialized when trying to open clp-files in Jess70b4-editor (yes, I tried the -clean switch). Jess70b3 works well. Can anybody help? JessDE 7.0b4 now requires Eclipse 3.1 -- the sudden changeover with this particular version wasn't
Re: JESS: definstance
You can use (undefinstance *) to remove all definstances. There is currently no undeffacts function but one is slated to be added for Jess 7. I think Subrahmanyam wrote: HI All Is there a flag which can be set so that (reset) command removes all the general stuff it removes and does not
Re: JESS: Fact object not in working memory error
Most likely the problem is that some of your classes (perhaps com.ngc.dts.domain.common.PerDiemEntitlement) have mutable hash codes, making them unsuitable for use as keys in a hash table (try using one of these objects as a key in a HashMap, change the values of some properties, then try to look
Re: JESS: Userfunctions and Jess - Java type conversion
If you can a Java function from Jess, and that function returns a java.lang.Boolean, then Jess will turn it into a Jess boolean value (the symbols TRUE or FALSE, of type RU.SYMBOL). On the other hand, new Value(Boolean.TRUE) will give you a Value of type RU.JAVA_OBJECT that contains a
Re: JESS: Userfunctions and Jess - Java type conversion
I think erich.oliphant wrote: [Charset iso-8859-1 unsupported, filtering to ASCII...] Hmm, ok thanks, I understand better now. However, jess.Userfunctions return Value's so is there anything I can do in that case to activate the type conversion? I tried Value.resolve() but that did not help.
Re: JESS: creating an audit trail
Re: JESS: Userfunctions and Jess - Java type conversion
Re: JESS: Accumulate Function - LHS
Re: JESS: Possible bug: using apply with str-cat inside a function
Jess's apply differs from the classic Lisp apply in that the varargs are in the apply funcall, rather than being bundled up in a list. This is by accident rather than by design, I'm afraid. In classic Lisp, this form (apply str-cat foo bar baz) is an error, but in Jess, it's correct. In
Re: JESS: Bug?
I
Re: JESS: Re: Bug
I think Yura wrote: I'm sorry - it's there in the manual. I should be more attentive. By my calculation, you've reported 4 bugs, and 3 of them were real -- so you're batting .750 . Seems like an excellent average to me! - Ernest
Re: JESS: Recognizing JessTab functions in JessDE / Eclipse
I think Dona Mommsen wrote: Now it would be nice if JessDE would recognize the JessTab functions, so that I could get rid of all the warnings about undefined functions. I added the JessTab14.jar to the project, yet JessDE does not recognize that there are Jess functions in the jar. Adding
Re: JESS: Probelm with property change listeners in Jess7b4
Hi, In Jess 7.0b3, the default for definstance type changed from dynamic to auto. If you specified dynamic as the last argument to definstance, then Jess would try to register itself with your Bean as a PropertyChangeListener; this used to be the default, so that you had to write static if you
Re: JESS: Bug?
I. Yep. I can reproduce this and now that you
Re: JESS: DefRule - Memory Leak
I think Hariprasath Manivannan wrote: - Has anyone faced this issue with Jess5.0? If so please send the possible solutions. Jess 5.0 is unsupported. The last release of any version of Jess 5 was 5.2 in June, 2000; that's over five years ago. Jess has evolved considerably since then, and many
Re: JESS: defadvice before/after bug?
I (+, -, *, /, , =, , =,
Re: JESS: Problems with SWT_AWT in Eclipse on MacOS X
I think Dona Mommsen wrote: On MacOS X, Eclipse will crash with error: Can't start the AWT because Java was started on the first thread. Make sure StartOnFirstThread is not specified in your application's Info.plist or on the command line Yes, I can reproduce this on my Powerbook.
Re: JESS: Which comes first, the chicken or the rule?
I
Re: JESS: Using a string in a bind or as a jess command
I think Bret Kellihan wrote: Also, Is there anyway to build up an entire jess expression into a variable and then execute it? I've tried something on the lines of: (bind ?command (str-cat (bind ?x 1))) (?command) The eval function parses and evaluates a String (or a variable containing
Re: JESS: Help on the syntax of a rule.
I think ROSSEL, Olivier (CIMPA) wrote: I am using Jess with Protege. I want to write a rule that says: run when you get an oject FOO with a non-empty slot called 'name' and where there is no fact foo with property bar equal to the slot value. I would intuitively wirte that this way:
Re: JESS: Help on the syntax of a rule.
I think ROSSEL, Olivier (CIMPA) wrote: But such a syntax seems to fail: defrule doStuff ?o - (object (is-a FOO) (name ?name~nil)) (not (foo (bar (?name trim ... Any comment? In Jess, just as in all computer languages, you have to use the proper syntax. An unadorned function call | https://www.mail-archive.com/search?l=jess-users@mailgate2.sandia.gov&q=from:%22ejfried%22 | CC-MAIN-2018-47 | refinedweb | 5,263 | 71.14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.