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
For understanding this vulnerability, you first have a thorough understanding of the stack layout. - What is a format string? From my understanding (quite naive), a format string is a string which determines the format of the rest of the arguments passed to a function. In the case of C language, functions such as printf(), scanf(), fprintf(), vsprintf() take format strings as argument. Example: printf(“%d”,i); => Here, ‘%d’ is a format string which determines the format of ‘i’ (in this case – integer). - What is a format string vulnerability? A format string vulnerability is where an unsanitized input is passed to a function which is capable of taking a format string as argument. From a programmer’s perspective, this unsanitized string is assumed to be a normal string, but if given as a format string, can lead to examining values of the stack and much more. - What can be done by exploiting one? By exploiting such a vulnerability, an attacker can dump the entire program’s stack, write into arbitrary memory locations and even execute custom written machine code. Let’s take an example and proceed: #include <stdio.h> #include <string.h> int main ( int argc, char **argv ) { char buffer[1024]; if ( argc >= 2 ) { strncpy ( buffer, argv[1], strlen(argv[1]) > 1024 ? 1024 : strlen(argv[1]) ); printf ( buffer ); } return 0; } This program should ideally print the first command line argument (maximum length 1024) given to the program. One question we have to ask ourselves is: - Since the input given to the printf() function is unsanitized, what if we give a format string as argument? Let’s analyze this a bit more. Let’s consider: printf ( “%d”, i ); Here, you can see that there are two arguments to be passed to the printf function. Now, when printf takes the first argument and parses it, it sees “%d”. There, it knows that there is a second argument which must’ve been provided and that’s an integer i. So it takes the next argument (next 4 bytes below 1st argument) from the stack (which it assumes the calling function must’ve pushed) and prints it. Let’s take the case: printf ( buffer ); // Here, ‘buffer’ contains “%d”. It’s clear from this that if ‘%d’ is present in buffer, printf tries to take the next argument from stack. Now, there isn’t any argument that would’ve been pushed by the calling function, and yet printf assumes that an argument should’ve been pushed and takes the next word from stack as the integer and prints it. Now, the value which is printed is some random value (mostly a local variable of the calling function). So, since we have the freedom to enter whatever format string we want in ‘buffer’, we have to ability to print the local variables of the calling function, and much more. Let’s also learn about some possibilities in format strings: - “%p” – prints the value of the pointer provided as argument (essentially a 4 byte hex dump). - “%n” – stores the number of bytes written till now, in the pointer provided as argument. - “%Nd” – prints the integer provided as argument prefixed by ‘N’ empty spaces. So given all this and a vulnerable printf() function: - We can dump the values of the stack by appropriate number of %p’s. - We can write the number of bytes written till now into an address provided as argument using ‘%n’. - We can use ‘%Nd’ to control the value written into the pointer. Coming back to our example, we know that the argument passed to printf is the starting address of the character array ‘buffer’. The memory layout is: Now, let’s see what we can put in ‘buffer’: - If ‘buffer’ = “abcd”, nothing new will happen and the function will just print ‘abcd’. - If ‘buffer’ = “%p”, then printf will see the next 4 bytes (part of buffer itself) from the stack as the argument and print the value. - If ‘buffer’ = “%nAB”, then printf will consider the next argument (first 4 bytes of ‘buffer’) as a pointer to a variable and write the number of bytes printed till now (that’s zero), into the address pointed to by these 4 bytes. Essentially, it should give segmentation fault (SIGSEGV) as the value of the address to be written is “0x4241673e” (hex of ‘BAn%’ in little-endian) and that address is not accessible by this process. - If ‘buffer’ = “\x9c\xd8\xff\xbf%n”, then printf will consider the next argument as a pointer and try to write 4 into it (since \x9c\xd8\xff\xbf is 4 bytes). The next argument itself is 0xbfffd89c, which we assume in this case to be the address where the return address of printf is stored. If not, we try to debug the program, get the pointer to the return address of printf appropriately store that value. Hence, the program will again give a segmentation fault since after printf executes, it’s return address is 0x00000004 (overwritten by printf itself), and tries to execute instructions at that address, resulting in SIGSEGV. - If ‘buffer’ = - “”+ - “%10u%n%10u%n%10u%n%10u%n” In this case, assuming that the return address is 4 btyes from 0xbfffd89c to 0xbfffd89f, printf will write 26 into the first byte of return address, 37 into the second byte, 48 into the third byte and 59 into the fourth byte. Thus the return address of printf this time is overwritten as 0x3b30251a. It’ll still result in a segmentation fault, but atleast we now know that we can write any arbitrary value into the return address of printf. - If we place some shellcode in the buffer after our format string and we know the starting address of the format string, then we can successfully execute our own code. Let’s assume that the format string starts at address 0xbfffd8a4. Now, the format string will end at 0xbfffd8a4 + 40 = 0xbfffd8cc and this is where our shellcode starts. Hence, we need to write this address 0xbfffd8cc as the return address of printf. - buffer =“”+ - “%175u%n%64u%n%217u%n%204u%n”+ - “<shellcode>” The above code will write the value ofbfffd8a4 into the return address of printf. 16 bytes were already written for the return address, so 175+16 = 191 (decimal of bf) will be written on the first byte of the return address. Subsequently, 191+64 = 255 (decimal of ‘ff’) will be written on the second byte of return address, and so on Hence, with the above exploit, we’ll be able to execute any code we want using the format string. How do we make our code secure? Simple, don’t allow the user to be able to pass a format string to the function. A simple solution would be to write the format string yourself, and expect just the data from the user. printf ( buffer ); —> INSECURE printf ( “%s”, buffer ); —-> SECURE
https://hrishikeshmurali.wordpress.com/2011/09/18/understanding-a-format-string-vulnerability/
CC-MAIN-2018-30
refinedweb
1,141
67.99
TimerInfo(), TimerInfo_r() Get information about a timer Synopsis: #include <sys/neutrino.h> int TimerInfo( pid_t pid, timer_t id, int flags, struct _timer_info* info ); int TimerInfo_r( pid_t pid, timer_t id, int flags, struct _timer_info* info ); Arguments: - pid - The process ID that you're requesting the timer information for. - id - The ID of the timer, as returned by TimerCreate() . - flags - Supported flags are: - _NTO_TIMER_SEARCH — if this flag is specified and the timer ID doesn't exist, return information on the next timer ID. This provides a mechanism to discover all of the timers in the process. - _NTO_RESET_OVERRUNS — reset the overrun count to zero in the _timer_info structure. - info - A pointer to a _timer_info structure where the function can store the information about the specified timer. For more details, see struct _timer_info , below. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: These kernel calls get information about a previously created timer specified by id, and stores the information in the buffer pointed to by info. The TimerInfo() and TimerInfo_r() functions are identical except in the way they indicate errors. See the Returns section for details. - Instead of using these kernel calls directly, consider calling timer_getexpstatus() , timer_getoverrun() , or timer_gettime() . - In order to get timer information, your process must have the PROCMGR_AID_TIMER ability enabled. For more information, see procmgr_ability() . struct _timer_info The _timer_info structure pointed to by info contains at least these members: - uint32_t flags - One or more of these bit flags: - _NTO_TI_ACTIVE - The timer is active. - _NTO_TI_ABSOLUTE - The timer is waiting for an absolute time to occur; otherwise, the timer is relative. - _NTO_TI_EXPIRED - The timer has expired. - int32_t tid - The thread to which the timer is directed (0 if it's directed to the process). - int32_t notify - The notify type. - clockid_t clockid - The type of clock used. - uint32_t overruns - The number of overruns. - struct sigevent event - The event dispatched when the timer expires. - struct itimerspec itime - Time when the timer was started. - struct itimerspec otime - Time remaining before the timer expires. For more information, see the description of TimerCreate() . Blocking states These calls don't block. Returns: The only difference between these functions is the way they indicate errors: Errors: - EINVAL - The timer specified by id doesn't exist. - EPERM - The calling process doesn't have the required permission; see procmgr_ability() . - ESRCH - The process specified by pid doesn't exist.
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/t/timerinfo.html
CC-MAIN-2020-34
refinedweb
399
58.69
As I discussed last time, were we to introduce interface and delegate variance in a hypothetical future version of C# we would need a syntax for it. Here are some possibilities that immediately come to mind. Option 1: interface IFoo<+T, -U> { T Foo(U> { … interface IFoo<[Covariant] T, [Contravariant] U> { … Similar to option 3. Option 5: interface IFoo<out T, in U> { … 🙂 There is the danger of more and more being expressed in the constraints/freedoms (especially if you add static operator constraints 🙂 🙂 *); } Luke's idea seems very compelling but I still find it hard to wrap my head around. It seems like it ought to make the Action / Meta thing easier to follow but it really doesn't, to me. I have a hard time following what Meta might actually do so here's a concrete example - using EventHandler<T> instead of Action, then an AddHandler method seems like it would have approximately the same signature as Meta. Am I following that right? delegate void EventHandler<* is TEventArgs>(object sender, TEventArgs e) where TEventArgs : EventArgs; delegate void AddHandlerMethod<TEventArgs is *>(EventHandler<TEventArgs> handler) where TEventArgs : EventArgs; Nope, I'm still lost. What does that mean I can actually do with such an EventHandler compared to if it was declared as a regular EventHandler? What can I do with AddHandlerMethod? I still feel like this kind of declaration-site variance is terribly unuseful compared to Java's use-site variance, which *does* make sense to me (and offers a solution to the scenario in my prior comment, at least sort of...) apenwarr, I do not think newbies will be exposed to covariance and contravariance [knowingly]. This will be useful to people who like to take the language to the limits and people who write frameworks. Maybe I'm wrong, but I think support for covariance and contravariance will show itself by things working more naturally, because people will use code that allows for variance more often than write it. Eric, I don't recall seeing any real-life, motivating examples for this where such support would make code significantly more readable (or somewhat more readable in many places). In other words, what scores points against the -100? If this is coming up in a future post, ignore this question. 🙂 With the "is" keyword, would we really even need the "*"? To me it seems like unnecessary typing, and I'm a hprrbile tpyer so the less typing the better. In my eyes, "delegate R Func<is A, R is> (A a)" conveys just as much information as "delegate R Func<* is A, R is *> (A a)" But so far, I like that general idea the best, asterisk or not. My previous comment didn't seem to go though, so forgive me if this ends up getting posted twice. Option 3 should be : interface IFoo<T, U> where T: covariant [where] U: contravariant { … to be consistant with existing constraints. Commas only seperate constraints on a single parameter. I would also like to suggest you avoid confusion between generic constraints and 'freedoms', using a 'let' clause. interface IFoo<T, U> where T: IBar //a constraint on T let T: covariant //a 'freedom on T where U: new() //a constraint on U let U: contravariant //a freedom on U { … basically, seperate out constraints (where) from freedoms (let) in a LINQ like declaritive way. This is better IMO than putting anything in between <>'s because it fits more with the current constraint model (just where clauses) -Brandon I think the description of U in Option 2 is reversed. The post says that "*:U" means “something which U extends”. Shouldn't that be “something which extends U”? The description of "T:*" could also be simplified to “something which T extends”. Freedoms are certainly the most palatable solution. Whether 'covariant' and 'contravariant' are the most intuitive keywords is debatable. How about: interface IFoo<T, U> where T : IBar let * : T where U : IStuff let U : * { ... The relatively universal wildcard '*' still denotes 'any type where' and the freedoms provide a clean, extensible syntax. My only reservation is using ':' to denote a non-inheritance relationship. How about this even: nterface IFoo<T, U> where T : IBar let * >= T where U : IStuff let U <= * { ... my vote is for lukes idea for readability; it's great. a secondary vote for the attribute approach due to backwards compat and further 'verbose-ness'. it does allow searching for the concepts which is great. but out of all; i prefer lukes. great idea. it actually helped me understand the concept incredibly easily. I am wavering on the "constraint/freedom" question. Saying 'U may be anything like this' is equivalent to saying 'U cannot be anything out of this range', so I would still consider variance a constraint, not a freedom. From that perspective, I like "assignment constraints": where T : IBar where T <= * where U : IStuff where U >= * Check for a maximum of 1 inheritance constraint and 1 assignment constraint. Option 1: interface IFoo<+T, -U> { T Foo(U u); } I am most accustomed to this notation from the CLR. It's well attested and works. This immediately gets my vote. Option 2: interface IFoo<T:*, *:U> { … The first thing that comes to my mind is some kind of strange pointer... Not very intuitive. Option 3: interface IFoo<T, U> where T: covariant, U: contravariant { … Not bad, but really no strong points over option 1. Also, IMO, it is too verbose. Option 4: interface IFoo<[Covariant] T, [Contravariant] U> { … I can not really explain why, but I do not want to think of variance as an attribute of a something. Option 5: interface IFoo<out T, in U> { … I have a handle on + and -, but I have a hard time digesting in/out. Options 6 (Luke) delegate R Func<* is A, R is *> (A a) I like the is keyword being used here. However, I am opposed to the * notation. Again, it looks like some kind of weird pointer. Can it be done without the *? And if so, how? Not that I have a better suggestion. Weighing all of the pros and cons, I prefer option 1. Slightly crazy syntax suggestion: delegate R Func<A, R>(A a) using A as params using R as return; It has the same problem as the "in/out" proposal though. I've been trying to articulate my problem with this compared to Java-style use site variance and I think I've figured it out. With this system, interfaces are only variant in a fairly limited set of scenarios: IEnumerable and IEnumerator can be made variant but IList never can. And the circumstances in which a *class* could be variant are so few as to be almost not worth considering. It's illuminating that Eric hasn't even mentioned the possibility of variance on classes, while strongly hinting that variance on delegates and interfaces is likely. But in fact it's not the type, per se, that is variant; it's the particular *use* of it. For instance: public void printAll(List<*> list) { foreach (var obj in list) Console.WriteLine(obj.ToString()); } List<T> is not and cannot be covariant, but the list parameter of the printAll method *is* covariant, because it's being *used* covariantly. (The * in this case is essentially shorthand for "* is object" since everything "is object"). On the other hand: public void populateList(List<String is *> list) { list.Add("Hello"); list.Add("World"); } List<> isn't contravariant either, but in this case it's being used contravariantly. C#'s historical way of handling this has been to make all the *s into explicit type parameters, so we'd have something like public void printAll<T>(List<T> list) {...} and public void populateList<T>(List<T> list) where String : T {...} (actually I'm not completely sure that second one is really even legal) and then hope that we can hide the complexity from end users by always inferring the T. This fails in all sorts of ways, ranging from method overloading (if there was a printAll or a populateList that *didn't* have a generic parameter, C# seems to fail to do anything useful or intuitive with inference) to the scenario I mentioned where T is a type instantiated by reflection and completely unknown at compile time. Or another example - T is an internal type only exposed by a public interface (and yes, I know using List<> here would be bad in real code, but it's the best-known generic type out there, the same situations occur with homegrown generic classes): public interface IFrobbable { void Frob(); } internal class VeryFrobbable : IFrobbable { ... } public class FrobbableFactory { private List<VeryFrobbable> frobbables; public static List<* is IFrobbable> GetFrobbables() { initialize(); return frobbables; } } Client code: public void FrobEveryOther() { var frobbables = FrobbableFactory.GetFrobbables(); for (int i = 0; i < frobbables.Count; i += 2) { frobbables[i].Frob(); } } The declaration-site variance that you're talking about seems to allow a very limited number of scenarios and depends incredibly heavily on the provider of all your interfaces creating variant versions of every interface. For example, to make anything like the frobbable scenario work using what you're proposing, you need: interface IReadList<* is T> {...} interface IWriteList<T is *> {...} interface IList<T> : IReadList<T>, IWriteList<T> {...} Is it really realistic to assume that everyone who defines an interface will think to split it up that way? Or that nobody will want to use an interface whose author *didn't* think of this, in a variant way? The situation gets even worse for classes because you need to create three interfaces *plus* the class. And the kicker? That only works for classes with one type parameter. IDictionary<K,V>? Fuhgeddaboudit. Combinatoric growth of number of interfaces needed to cover everything that a user might want to do. Last comment of the night, I promise. But I just want to emphasize how important I feel this is. I've been begging for variance in generics for a very long time and very strenuously. But if all you're going to do is the delegate/interface variance you've been talking about, no matter how intuitive you manage to make the syntax, I'd actually argue strongly *against* bothering to include it at all. It adds a lot of complexity and helps in pretty much zero of the scenarios where I've encountered a need for variance in real life. If you can't offer use-site variance, just stick to covariant return types on overridden methods, and beyond that, don't even bother. The following Microsoft Research is an interesting read: "Variance and Generalized Constraints for C# Generics" And it discusses variant classes. While it would be useful, at least variant interfaces would be a great start which hopefully could be extended in the future. How about using base, it already has some meaning relevant to this: delegate R Func<base A, R base> (A a) So the position of base indicates the co/contra Marc, All your base are belong to us. Option 1 (+/-) looks good enough for me. minus by minus equals plus in general math too, this is a benefit of this syntax. Option 2 (T:*/*:U) confuses me. Like Bradley, I thought it to be reversed, and I still don't understand how *:U (or ? extends U, for that matter) expresses "something which U extends". It's also hard to relate "something which U extends" to "interface is contravariant on U"... Option 3 (where "constraints"): I share the reservations about using where for constraints AND variance. Option 4 (Attributes): good enough. + and - might be easier to relate to bigger/smaller types, but co/contravariance are easier to google. tough to decide, i suppose either one will do. I'd perfer a contextual keyword to attributes though. this is a first class language feature after all! Option 5 (in/out): I see how you like this for simple cases, but get real: it's incorrect for others, and at the end of the day, you're not going to include incorrect syntax into the language, even if we'd all love it. (which I do not, for exactly this reason) Luke's suggestion (* is A) and Matt's one (positional "base"): I find those just as confusing as option 2. Rasmus's suggestions indicates that he didn't understand the problem, the "where" syntax led him to believe that we're talking about constraints (or maybe I'm not getting it). Goes to prove that option 3 is a bad idea. Actually I like Peter Ritchie's suggestion a lot, only that I would recommend built-in syntax: interface IFoo<T,U> covariant on T contravariant on U having this on the interface rather than on the type parameters themselves indicates that we're talking about a quality of the interface, not of the type parameter. all other options except #5 (especially #3) seem to lead people to think more about what the type parameter is, when variance actually says nothing about that type parameter, but only about the generic interface's (or delegate's) relation to that parameter. The example above reads quite intuitively. I have an interface with two parameters, they can be whatever the user likes (unless there are additional where constraints). the interface is covariant on T and contravariant on U. covariant means that assignability of IFoo goes with T, and contravariant goes into the other direction. this is not hard to remember, "co" and "contra" express this well. The only thing that needs to be remembered (or logically deduced, which is possible) is that covariance is typically useful for output parameters, while contravariance is typically useful for input parameters. since this is only the typical case, and wrong in others (Meta<+T>) I don't see how you could make this mapping more implicit. My opinion is that for the sake of correctness, we have to accept this difficulty. How about re-using the existing c# syntax and allow re-ordering the parameters interface IFoo<T, U> where T: Mammal where Mammal : U { } > I still don't understand how *:U expresses "something which U extends". You and Bradley are right, that is badly worded. I intended to say "something which extends U". I'll fix it. Stuart: I want to be able to declare a variable of type List<?> Indeed, when we were designing anonymous types we considered doing that kind of inference. We're calling those "mumble types", as in "I have a list of... mumble mumble mumble". Obviously we didn't end up doing them for C# 3.0 but it does seem like a generally useful addition to the type system, so we'll consider it for hypothetical future versions. I'm going to cast my vote for Luke's "is * / * is" idea. In present-day C# where we don't have cov/cnv, I would have to test and cast the interface manually, and that is precisely the test I'd be using. It seems natural to put it in the definition instead. I strongly dislike the overly verbose versions (#3 and #4). I thought that the reason we used C# instead of VB is that we don't particularly like the verbosity. Plus, even though I can remember what covariant and contravariant mean on a basic level, I'm never going to remember the exact effect each one has within the language. I agree that #2 is conflating two very different concepts, but they're already conflated in Generics in exactly this way. If I declare IFoo<T> where T : IBar, and I have a class MyClass which implements IBar, I can legally use an IFoo<MyClass>. Furthermore, this doesn't bother me and I don't find it the slightest bit confusing; it mirrors the real inherits/implements syntax. #1 is okay. It conveys a bit more information about what's actually happening than the verbose versions, but I still know I'm going to screw it up eventually if I have to contend with it. And if I were to hand the code off to an unfamiliar programmer, he might very well look at it and go, "huh"? #5 bugs me because in/out are already reserved words that mean something totally different. It does make sense, but please, no more overloaded keywords. Also, I don't think any of these suggestions truly address the Meta issue. It's a conceptual problem, a double-negative in a sense. I think if people really want to program like this (I can't imagine why), then they probably already know that they're playing with fire. It's the rest of us, who might have no idea how dangerous it is, that you should be worrying about. 🙂 Eric, that's fantastic news that you're considering "mumble types" for a future version. I really hope it's a sooner rather than later future version - in particular I hope it ends up being at least the same version as the changes you're discussing now. I think that introducing both concepts together would help to come up with a coherent syntax between the two. And I'll shut up now about pushing for the feature because you know how I feel about it, and go back to discussing what we're talking about now. I'm trying to think of ways to express what Foo<* is T> actually means in english to see if there's a better way to express it in the language. What it really means is "Foo<T1> is Foo<T2> if T1 is T2". I find it really hard to read that meaning into *any* of the proposals (except the "in/out" one which everyone hates). Similarly contravariance means "Foo<T1> is Foo<T2> if T2 is T1" So how about this as an actual syntax proposal: public interface IEnumerable<T> where IEnumerable<this> is IEnumerable<base> { ... } public delegate Action<T>(T t) where Action<base> is Action<this>; When there's multiple type parameters it becomes a little less obvious. Some possible approaches: public delegate R Func<R, A>(A a) where Func<this, base> is Func<base, this>; (problem of how to express a parameter that isn't variant at all - "this" on both sides?) public delegate R Func<R, A>(A a) where Func<this, *> is Func<base, *> where Func<*, base> is Func<*, this>; (which I think I like better except that it still has the confusion of people expecting * to mean "pointer" rather than "wildcard". There are other symbols that could be used but I can't think of any actual words that carry the right meaning...) Ooh, or: public delegate R Func<R, A>(A a) where Func<this, A> is Func<base, A> where Func<R, base> is Func<R, this>; Yes, it's verbose, and probably not terribly easy to write correctly (although I suspect the IDE could help a LOT with this kind of clause) but code is read much more often than it's written. And having the code written this way gives some kind of intuitive sense of what it means. Plus it doesn't have the meta problem: public delegate Action<T>(T t) where Action<base> is Action<this>; public delegate Meta<T>(Action<T> action) where Meta<this> is Meta<base>; It accurately expresses what's actually going on there without presuming the meaning as input or output. just a thought experiment: instead of interface IFoo<T:*, *:U> we could write interface IFoo<T, U> : IFoo<T:*, *:U> or, using Luke's syntax, interface IFoo<T, U> : IFoo<T is *, * is U> this is not beautiful, but it gives a better hint as to what it really implies for the interface. now ":" goes to mean "assignable from" in addition to "implements" and "extends" (which is worse, because the latter two were easily identifiable due to the I-prefix for interfaces). so no actual syntax recommendation, but just a way that makes it more understandable for me, and might inspire other ideas. we could take Luke's way even further: interface IFoo<T, U> is IFoo<T is *, * is U> even more explicit: interface IFoo<T, U> is IFoo<A, B> where T is A where B is U ugly, I know. plus, I'm still unhappy with the positional thing. Makes me think more than it should. end of thought experiment. Thinking about in/out, I believe automatic variance would not be a bad thing in every case. I know, I voted against it even before you explained it, but think about this: when is any of the problems really present in case of delegates? I believe automatic co/contravariance on delegates is both easier to resolve and less likely to introduce breaking changes. also, we could use a single keyword/attribute to indicate that we want co/contravariance, and let the compiler detect which one. here's how I got there. The Meta<> Problem delegate void Action<in T> (T arg); delegate void Meta<out T>(Action<T> action); If we would be able that we want to use Action<T> as the input parameter, not T, the compiler could figure it out that T needs to be covariant, because Action<T> is already contravariant on T. So we would need some way indicate that "input" refers to Action<T>, not just T. The easiest thing would be to indicate that with the action parameter, but there it is already clear that it is an input parameter. So why bother? It's harder for interfaces though. They are more complex, and while it's quite clear that adding/modifying parameters in a delegate would change assignment semantics, it's more unexpected in interfaces (and essentially impossible to control, who thinks about variance whenever changing or adding interface members?). Plus, there's the exponential growth problem. Can we come up with something better? Let's take an example in +/- syntax: interface IDoer<-T> { void Do(T obj); } interface IDoable<+T> { void ApplyDoer (IDoer<T> doer); } now, we obviously would like to write IDoer<in T>, but absolutely not IDoable<out T>. Now imagine this in the syntax I recommended above: interface IDoer<T> contravariant on T interface IDoable<T> covariant on T if we replace contravariant with "in" and covariant with "out", we end up having the same problem. but what if, instead of "covariant on T", we could just say "contravariant on IDoer<T>"? Just like with implicit delegate co/contravariance, the compiler could easily figure out that in order for IDoer<T> to be contravariant, T needs to be covariant. interface IDoer<T> variance: in T interface IDoable variance: in IDoer<T> now the wording sucks. we need better keywords/syntax. but besides that, I really love this. we have in/out semantics, it is correct, and it is easily resolvable by the compiler, because it doesn't need to look at the entire interface. an additional problem is that documentation generation tools like ndoc could not tell that the user wrote "in IDoer<T>" instead of "out T". this is essential for documentation, so the compiler would somehow have to annotate this. another thought: specifying variance for interfaces is really just a promise to not use T in any other way than specified (input/output). once this has been made clear, there's simply no reason why the compiler would not assume co/contravariance as needed, but the programmer would have to comply with that statement, which the compiler could check. you're not going to keep design by contract away from us forever. there's even fascinating research in MS research (spec#). how do those fit together? if variance can be derived from an explicit constraint (contract), you might want to use similar syntax, or at least align them in some way. then again, it's probably to early to know how C#'s hypothetical future DBC syntax is going to look like. still, this could be a hint when trying to cook up a syntax for what I've proposed above. (note that "variance: in IDoer<T>" above also implies that T is not used directly by this interface, only via IDoer<T>. this would probably have to be made explicit when using a constraint syntax.) Well, since Stefan already opened the door, I love Spec#, and I want contracts in C# :). that's right, mike. DBC would have a greater impact on the way we code than any co/contravariance, however fascinating this is. (even without the amazing static analysis spec# does) (while the door is open, can we please automatically generate unit tests from those contracts too?) but then I want memberof (ldtoken for members), generics and lambdas in attributes, I want Expression<Func<T>> parameterized (lambdas) so that the expression tree does not have to be parsed and processed for every call (I'll just say i4o, the indexed variant of LINQ 2 objects), and ... - no, wait, let's stay focused for a minute, OK? 😉 (ok, I can't hold it back. pattern matching. now I've said it. but before we get into macros and meta-programming, let's get back to that covariance syntax problem of that hypothetical... hey, can we give it an imaginary version number, like C# 4i? or does that sound too much like oracle?) interface IFoo<T, U> where T is Animal, Mammal is U looks very intuitive - no need to remember anything. In my opinion it is important to have a clear verbose format. This is something quite complicated that should not be hidden away in a small added + or -. I am just brainstorming here, but how about this (introducing a new keyword "assignable to"): interface IFoo<T,U> assignable to IFoo<R, S> where R is T where U is S; { ... } This has the advantage of making it extremely clear for the user of the interface what flexibility the co-/contravariance gives him, at the cost of making it unclear for the implementor which restrictions this imposes on him. Since interface-users should clearly outnumber implementors - especially for the types of interface where co- and contravariance is an issue - this should be an ok tradeoff. I'm very much against a very verbose syntax. In my experience though symbols are initially confusing, you get used to them and they're much easier to skim (since they're easier to ignore). Frequently, you'll be perfectly happy to ignore covariance and contravariance, so that's a plus. Consider also the competition which C# faces from dynamic languages. These are often preferable precisely because they contain less "superfluous" non-behavioural syntax. Succintly; they just say what needs to be done, nothing more. I'm also hoping that a good number of other "restraints" might make it into the language. Currently, it's not possible to demand a type have a particular static member (except the parameterless constructor). That capability would be immensely useful almost instantly for easy requirement of things like operators, to implementations of wrapping types which add functionality such as .Equals based on .CompareTo or whatnot. What core problem does covariance and contravariance solve? It allows more generic code. It reduces the problem of "leaky abstractions". Basically, it improves encapsulation. But it's not a big win. For example, the ability to implement an interface as defined by a class (i.e. to _not_ inherit it's implementation optionally) might be a far greater win. Or the ability to "add" features to a class. Or the ability to "uncurry" an instance method into a static method. A lot of code I encounter isn't properly structured because it's too much work to do so in C#. If I have a custom list which implements, say, a priority queue, then implementing that as a class (with all the appropriate interfaces, including IEnumerable, IEnumerable<T>, ICollection, etc...) is a lot of work, so instead, everyone generally opts for the less encapsulated, more spagetti-code but easier option: just implement the key feaures of a priority queue internally and don't abstract it out, don't allow code reuse, and leave the data structure implicit, not explicit. And not just "framework" creators need these kind of abilities (the ability to easily generate a class or instance with a particular set of "interfaces" or behaviours). Many real-world frameworks require the "user" of the framework to provide objects which fit certain interfaces and conventions. This pattern is sometimes called "Inversion of Control" or "Dependancy Injection" - but what it means is that: Everyone needs to be able to flexibly, easily, and comprehensibly be able to implement interfaces and other functionality contracts. Improving Covariance/Contravariance in C# should not imply that doing so becomes more complex, since that would defeat the purpose of language improvement. Eamon, I don't disagree with a lot of your argument, but I don't think it applies to this particular scenario. The basic principle is "simple things should be simple, and complicated things should be possible". The fact that it doesn't say "complicated things should be simple" is *deliberate* - trying to achieve that always inherently hurts the simple things. I agree that it should be a lot simpler than it is to implement ICollection<T>, and for that matter IList<T> and IDictionary<K,V> (although I'm not sure how much easier it could be to implement IEnumerable than it is today with "yield" - that's already practically trivial). These are simple things and shouldn't be so damn hard. But covariance and contravariance are not simple things. They're advanced features for advanced framework designers. I can't think of a single use of this kind of variance outside of a framework. (The use-site "mumble type" variance could be used by everyone, which is one of the reasons I like it better overall). That means that (a) writing variant interfaces and delegates will be rare, and done by technically advanced users, (b) USING variant interfaces and delegates will be common by people who AREN'T so proficient, and (c) the less proficient people will only occasionally encounter variant types, so they won't have any opportunity to "get used to" the feature. All of that means that it's ok to write a little bit more (and we're only talking about one extra line of code per variant type parameter, here, even in the more verbose suggestions such as mine) when you're implementing the type, because the person doing that NEEDS to know what they're doing, but it's very important that someone READING the code be able to understand what it means without being an expert. One of the reasons C# is so much more friendly than C++ is that there aren't miscellaneous punctuation symbols all over the place that radically change the meaning of your code. Even the comments here show that the meaning of this stuff isn't at all intuitive. Eric has spent eight blog posts explaining variance in detail, along with various syntax suggestions, and yet Kerneltrap is making a syntax suggestion that demonstrates a complete lack of grasp of what variance actually means. (Not picking on you, Kerneltrap, it's NOT obvious and it IS hard to get your head around. Hence why it's so important to have a syntax that helps rather than being more obscure) I agree to the notion that in this case, verbosity hurts less than perl-like obscurity. rasmus' notation is similar to my last proposed "is" notation (just replaces "is" with "assignable to"). i don't think "assignable to" is bad, but I do think that "is" is clear enough in this case, no need for another keyword (would avoid the untypical two-word keyword too). but that's just me. still, of the two syntaxes, i like the first one better: interface IFoo<T, U> is IFoo<T is *, * is U> (instead of crossing out explicit type parameter names, which is maybe easier to read if you do it the very first time and have to spend minutes reading it anyway, but harder if you do it on a regular basis. I posted the crossed-out syntax merely as a trigger for other people's ideas, but I don't like it as it is). disclaimer: i don't think that verbosity works for delegates, where variance will arguably be more common, and the overhead of verbose syntax would probably double a typical delegate declaration. i still favor automatic co/contravariance for delegates, or alternatively a single keyword that indicates that I want it, but leaves the details to the compiler. Eric: would variance be limited to interfaces, or could we have it for generic classes too? (after all, delegates are just classes anyway) interface IFoo<T, U, V> is IFoo<base(T), U, derived(V)> Another variant on the notation I proposed earlier: delegate R Func<R, A>(A a) where Func<R, base(A)> is Func<base(R), A>; or delegate R Func<R, A>(A a) where Func<R, A> is Func<base(R), A> where Func<R, base(A)> is Func<R, A>; stuart: but this re-introduces the double-meaning of where (contraints/variance), plus I don't think that base() and derived() make it any clearer who is the base and who derives than the T:* notation I'm still not entirely happy with the "is" constraint syntax. it's clear, but is it really useful to have a syntax that spells out the meaning of variance? I don't have a problem with the verbosity, but for me the "covariant on" and "contravariant on" clauses on the interface (not on the type arguments) would be the most intuitive ones when I'm working with it. I have to grasp co/contravariance once, the only notation that takes this away is the in/out notation, which is either wrong (Erics option #5) or overly verbose (my proposal of applying the in/out constraints not only to T, but maybe also to IDoer<T> etc.). plus, while in/out syntax is easier to write and understand, it makes it much harder to actually understand what assignment compatibility it really achieves. I also ask everyone to challenge my assumption that automatic variance is less of a problem for delegates than for interfaces. the more I think about it, I believe that it would be a Good Thing, probably even as opt-out (on by default). Am I wrong here? to summarize, for interfaces I'd prefer interface IFoo<T,U> covariant on T contravariant on U clear in what it does (google-able keywords) to which party (interface, not type parameters). once you grasped, easy to understand which assignment results from it (co: same as type-parameter, contra: opposite) for delegates I'd prefer automatic co/contravariance, maybe with the possibility to opt out ("invariant on T") everything else I've posted are mere thoughts that I would not like to see in the language unless somebody comes up with better variations. Stefan, I don't need to challenge your proposal of automatic variance on delegates, because Eric already ruled it out as actually impossible. delegate void Circular1<T>(Circular2<T> param); delegate void Circular2<T>(Circular1<T> param); If Circular1 is covariant on T then Circular2 is contravariant on it, and vice versa. So simply stating that variance is intended is not sufficient, you really do have to spell out which way round. I could live with the "covariant on" / "contravariant on" syntax but I actually do think it's helpful to spell out the meaning of it. Even after all eight of Eric's blog posts on the subject, I still didn't really fully grok it until I started thinking about it in terms of how IFoo<T> relates to IFoo<T's base class> and IFoo<T's derived classes>. Describing the meaning *concretely*, in terms of how it relates to the actual type you're declaring, made a huge difference to my ability to understand it. I can actually write statements about Action and Meta and get their variance the right way round with this kind of syntax. Which isn't true for any of the others, including "covariant on" and "contravariant on" - at least until I spent some time writing code using them. And I don't think that *users* of the interfaces will ever spend enough time to get that understanding. Thank you all for this fascinating discussion. I have not yet absorbed nearly all of it. There is a wealth of possibilities here which I shall summarize and take to the design team at some point over the next few weeks. To answer the earlier question -- the proposed feature is guaranteed-typesafe interface and delegate variance on reference types, no more, no less. No variance on classes, at least not this go-round. No unsafe variance. No call-site variance, no virtual overload return type variance, etc. Those are all features that we will consider, of course, but interface and delegate variance is the one I'm interested in today. sure, but do circular type references in delegates make any sense? do they even exist in the wild? how bad would it be if automatic co/contravariance would not work in this case, and you'd have to spell it out in those few cases (given there are any, and variance matters)? circular type references are quite common in interfaces, but in delegates? if that's really a problem, an alternative solution would be automatic variance detection for delegates with opt-in, so that the compiler could produce an error message if you want variance, but it cannot find out which one. ok, back to the topic of spelling out the meaning. my problem with that is that, once I've found out the meaning, I need a way to remember it in an intuitive way, or I wouldn't be able to use it. the difference between T:* and *:T, or worse, IFoo<T> assignable to IFoo<X> where T:X (as opposed to X:T), is something that I'll have forgotten when I'm reading the next line of code. I'd have to grasp the concept that assignability of IFoo goes WITH assignability of T in the class hierarchy, or against it. co/contravariance spell this concept out. I can remember it, communicate it in whiteboard sessions, etc. T:* or *:T are just obvious while I'm looking at exactly this line of code. I guess it would be the same for base(T) and derived(T). + and - are better, but still worse than covariance/contravariance IMO. ok, we have to separate our concerns here. 1) which one is easiest to write? 2) which one is easiest to grasp when you're not familiar with co/contravariance? 3) how important is it to grasp the intention of the author when you're not familiar with variance? would you typically not just try it and fix it if your assignments fail? (after all, who knows assignment compatibility rules of arrays? still, they're being used every day) 4) which one is easiest to work with once you're familiar with variance? we need to set priorities on these problems. I think priority #1 should be that programmers familiar with variance get a syntax that is logical to read AND write. everyone else is probably best served with trial and error. in/out (as well as automatic detection) would be easier to write, but you'd still have to think about how this translates to variance when using those types. in fact, any constraints-based syntax would have this disadvantage. so besides being overly verbose, specifying that I'm only using T by using Action<T> as an input might be easier to write, but I'd have to think much harder to understand how this affects assignability of the Meta delegate type. this is probably a shot in the foot. (note: if I'd have automatic detection for delegates, decompilers/help generators could still spell it out for me using the "normal" covariant on/contravariant on syntax.) Eric, you're welcome, but I'd really love to see you take part in that discussion here, and not just take it to the Holy Halls, disappear for a few years just to announce something way later that might or might include what we thought up here. I love your blog, but it's really sometimes a bit frustrating that you leave a lot of (sometimes thoughtful, I like to think) comments unanswered. I'm fully aware that you don't want to democratize language design, but that's a different story. Back to the topic. I'm no longer sure that we need to make it clear that the co/contravariance clause describes a quality of the interface (as opposed to the type parameter), because I believe this is pretty much commutative and ultimately doesn't matter. Still, I think you should separate this information out of the angle brackets, because it's just too much information in a single place. We dont write IFoo<class T, struct U> either. How about that? interface IFoo<T,U> where T: class where U: struct covariant T (I could live with unmodified options 3 and 4 too, these are just minor flaws IMO, and ultimately matters of taste) quote: C# Language Specification 12.5 Array covariance For any two reference-types A and B, if an implicit reference conversion (Section 6.1.4) or explicit reference conversion (Section 6.2.3). I believe this way explanation is much easier to understand than anything that involves bigger and smaller types. Covariance: If you can assign A to B, you can assign IFoo<A> to IFoo<B> Contravariance: If you can assign A to B, you can assign IFoo<B> to IFoo<A> I believe that apart from automatic detection, it doesn't get any easier than this. It's relatively easy to understand, and once you've grasped it, very easy to remember. (That would rule out option 1 btw.) Option 2 and all suggestions involving "T:*", "X where T:X", "X where T is X", "base(T)" etc. are just an attempt to put a formal specification of co/contravariance into the declaration syntax. although I came up with a few of them myselves, those would hurt MY brain when I'd be busy _using_ co/contravariance in the course of solving another problem instead of thinking about it on its own. Please let's not let the discussion about automatic detection in delegates die. The more I think about it, the more I like it. What about introducing an accept clause: interface Foo<T> accept base for[/on/of] T Or: interface Foo<T> accept derrived for[/on/of] T Thomas, I liked that at the first look. However, I think you have to know what co/contravariance is in order to understand this. Otherwise, it would be misleading. Just reading your syntax and not knowing about variance, I'd assume that this somehow indicates that an IFoo<Mammal> can take an Animal object (for accept base/contravariance), which is nonsense, or a Giraffe object (for accept derived/covariance), which goes without saying. Welcome to the thirty-fifth edition of Community Convergence. We have an interesting and controversial Stefan's idea of automatic variance for delegates is growing on me. If you automatically assign variance in the cases where it can be unambiguously determined (which is 99% of cases) but also allow it to be specified manually using the same syntax that interfaces use, that seems to fit well with the "simple things should be simple; complex things should be possible" principle. I'm not sure you even need a syntax to explicitly specify that a delegate type should NOT be variant when it could be. You don't want it to be automatic on interfaces because of the fact that adding members to the interface could inadvertantly change the variance - and adding members to an interface is not normally a breaking change for consumers of the interface (although it is for implementers). I'm not sure there's any equivalent to that for delegates - ANY change to a delegate is a breaking change for consumers of the delegate. So if the variance changes too in that case it's not a big deal as all code consuming the delegate is already broken. Stuart, exactly. The chance of a delegate signature breaking assignability and the chance of a modification to an interface's body causing this are two very different things. Plus, for the remaining 1% of delegates (if it's really that much), figuring out sensible variance declarations even manually would probably make my brain explode. delegate Circular1<T> (Circular2<T>) ... - I wasn't even sure this would compile until I tried it 😉 I guess there are languages out there who provide some sort of variance on higher-order functions with type parameters. I doubt that they have explicit syntax for this, but in any case looking at them (and talking to users of these languages) could be helpful. Does anybody know any such language? While scanning the examples, something like T:*, *:U really draws my attention to the * in the font my browser uses. I'm wondering if something like T:var, var:U might be better. Does var have the right connotation linking the generic's type to its variance? You could combines Lukes idea with the F# way and use underscores instead of asterisks: delegate R Func<_ is A, R is _> (A a) hey, if * looks bad in murman's font, shouldn't we make this symbol configurable? 😉 Personally, I like #1 and #5. I haven't read the comments... perhaps some much smarter syntax was introduced there. "But covariance and contravariance are not simple things." Yes they are, or at least, they certainly should be. The +/- syntax is far and away the best. I think it corresponds nicely to the "or bigger (more general)" and "or smaller (less general)" concept, it's already used in other languages, and it's already used in the spec. I don't really understand what you might be doing where you want use-site Java-style wildcarding more than covariant and contravariant generic arguments. Instead of [in] and [out] or [+] and [-] we may have a keyword that describe the "bigness"/"smallness" of covariance/contravariance-ness. When you explained the terms you have explained it using the "Big" metaphor, similarly we can use keywords like [encompasses] and [encompassed]. Those keywords may be long 11 characters differing by the last letter "s" and "d", though I like the concept. [surrounds] and [surrounded] are 9 and 10 characters, better but not ideal. However, we can expand and as of now my favorite is: [enfold] and [strip]. They are different enough that they will not cause likely mistakes even with dyslexic folks like me who can see "North" and interpret "South" when driving on the highway. Thank you for your attention --Avi Farah I have not yet read the whole bunch of comments and suggestions, but i would prefer something like this: delegate R Func<atleast A, atmost R> (A a) It has the benefit that it avoids the fancy "*", plus it is easy readable once the programmer understood the concept of inheritance and specializing through inheritance. delegate R Func<_ is A, R is _> (A a) is good another option: delegate R Func<A, R> (A a) where R>A So nicely step by step blogged by Eric Lippert for "Covariance and Contravariance" as "Fabulous
https://blogs.msdn.microsoft.com/ericlippert/2007/10/31/covariance-and-contravariance-in-c-part-eight-syntax-options/
CC-MAIN-2017-30
refinedweb
7,971
60.35
Metal Boar - 1911, 1971, 2051 Followed by a personality description: "A proud, passionate Boar with overpowering sentiments, who values his reputation. Intense and more dominating than others, this type of Boar often has excessive appetites and could lack refinement or tact..." Now, say the user is a Boar. There are five Boars in the Boar-file, since there are five elements. Based on the input of the user, I have to FIND the personality description (a chunk of text) that comes after the "Element Animal, xxxx, xxxx, xxxx" - up until the next "Element Animal, xxxx, xxxx, xxxx". This is what I've done so far: - Code: Select all def personalitydescription (self): # Provides a personality description based on the user's element and animal. djur = input("What is your animal?") element = input("What is your element?") """Creates a list that opens all twelve animal files.""" animals = ["rat", "ox", "tiger", "rabbit", "dragon", "snake", "horse", "sheep", "monkey", "rooster", "dog", "boar"] for animal in animals: file = open("5_" + animal + ".txt", "r") # Finds the string "-" followed by year(s) of birth. Finds the element and animal occuring before the string "-". for animal in file: if "-" ... I have no idea how to write my for / if in order to return the relevant personality description. Could somebody please help me?
http://python-forum.org/viewtopic.php?p=3309
CC-MAIN-2017-04
refinedweb
213
57.57
#include <segwayrmp.h> #include <segwayrmp.h> Inherits bj::PThread. Inheritance diagram for bj::SegwayRMP: SegwayRMP class provides an interface to Segway RMP robots. A destructor. [inline] Return the latest roll & pitch angles. Return the integrated angular position. Return the latest battery gauge. Return the yaw position in the odometry coordinates. Return the integrated linear position. Return wheel odometry data. Return the odometry data of the left wheel. Return the odometry data of the right wheel. Return the latest pitch angle. Return the latest pitch rate. Return the integrated position. Return the latest roll, pitch & yaw rates. Reset all integrators. Reset the angular position. Reset the left-wheel odometer. Reset the linear position. Reset the wheel odometers. Reset the positions. Reset the right-wheel odometer. Return the latest roll angle. Return the latest roll rate. A constructor. Return the servo frames. Set the angular velocity. Set the current limit scale factor. The available wheel torque may be limited using a normalization factor (Full torque=256, No torque=0). The peak torque of the each wheel is 122 Newton-meters. Dynamic balancing rquires transient torque to accelerate, decelerate and traverse small obstacles. However, the amount of torque required depends on the environment, task and payload and reducing available torque may be prudent in some cases. In balance mode, reducing the torque too low will result in the RMP falling over during a transient. Set the gain schedule. There are three controller gain schedules, each optimized for a different payload configuration. Set the linear velocity. Set the maximum acceleration scale factor. The minimum stopping distance may be calculated from the maximum velocity, , and maximum acceleration, : Thus, large velocities with small accelerations produce large stoppping distances. Choose your acceleration limits with care, considering both the need to stop quickly and the top speed you have chosen. Set the maximum turn rate scale factor. A turning scale factor parameter may be used to limit the maximum lateral acceleration of the RMP. This may be particularly useful with tall payloads, to prevent the RMP from tipping. In most cases though, higher turning sensitivity is useful for navigating around obstacles. Set the maximum velocity scale factor. Set the linear & angular velocities. Disable power immediately to the motors. Use of this command will cause the balancing function of the Segway RMP to stop. Use this message with caution. Stop the robot. Return wheel velocities. Return the velocity of the left wheel. Return the velocity of the right wheel. Return the X position in the odometry coordinates. Return the Y position in the odometry coordinates. Return the latest yaw rate.
http://robotics.usc.edu/~boyoon/bjlib/d2/d78/classbj_1_1SegwayRMP.html
CC-MAIN-2014-41
refinedweb
431
55.1
Socialwg/2016-08-23-minutes Contents - 1 Social Web Working Group Teleconference Social Web Working Group Teleconference 23 Aug 2016 Attendees - Present - ben_thatmustbeme, wilkie, eprodrom, cwebber, rhiaro, csarven, aaronpk, sandro - Regrets Chair - eprodrom - Scribe - wilkie Contents - Topics - Summary of Action Items - Summary of Resolutions <aaronpk> no, iOS, i don't want to update my phone right before i call in to this meeting <eprodrom> Can anyone scribe? I can scribe <eprodrom> scribenick: wilkie <eprodrom> akim, who's here? <cwebber2> badoop <eprodrom> Can anyone hear my voice? not yet, no <rhiaro> nope <cwebber2> nope <ben_thatmustbeme> nope <sandro> Nope, eprodrom <eprodrom> OK, that explains a lot <cwebber2> :) <sandro> we can hear each other but not you <eprodrom> Give me 30 seconds to call back in <cwebber2> I was thinking it was a pretty quiet start! <cwebber2> yes eprodrom: can you hear me now? <cwebber2> :D eprodrom: sorry about that. thanks for your patience. probably a good time to get started ... I will be chairing today because Arnaud is unavailable ... let's start out with approving the minutes for the previous meeting Approval of Minutes <eprodrom> PROPOSED Accept as minutes for 20016-08-02 meeting <cwebber2> +1 <rhiaro> +1 <wilkie> +1 <eprodrom> +1 <aaronpk> +1 you might need a colon? how does "proposed" work RESOLUTION: Accept as minutes for 20016-08-02 meeting <ben_thatmustbeme> +1 eprodrom: barring anything else we have resolved on that ... moving on to our next topic Publish a New Working Draft for ActivityPub <eprodrom> <Loqi> Social Web WG Face to Face Meeting in Lisbon (F2F7) eprodrom: probably an important thing but not listed is to cover registration for TPAC ... we are having a meeting at TPAC september 21st to 23rd ... if you haven't registered yet, please do. if you believe you will not be going also let us now. tentively or not. <tantek> eprodrom++ for chairing <Loqi> eprodrom has 41 karma (40 in this channel) eprodrom: great. so. we don't have any other administrative issues to discuss. ... I'd like to move on to our discussion items. <tantek> re: f2f is anyone else coming? eprodrom: the first is an update on activity pub and LDN and have rhiaro start us off rhiaro: last week I went to madison and worked on activity pub and made lots of progress. ... it might be better to have cwebber2 talk about those changes because we didn't do much to LDN but rather catch activitypub up to LDN cwebber2: sounds good. first, rhiaro was an immense help. ... the first is to clarify client to client and client to server stuff. although some of this isn't in the document. ... first, there is a list of side effects of using various activities in activity streams. <tantek> I'll add a specific item about f2f at the end of the agenda and try to get on the phone cwebber2: and a separate section showing targetting and delivery and side effects of activities. ... these are cleaning separated which we've been talking about for some time ... one thing we discuss is having two separate documents and saying this makes sense from the payload and protocols ... but we have seen that the differences is a specialization of some of the LDN specifications ... clarifying and using much of the LDN stuff has made the sections clearer and more concise ... since we have linked data notifications referenced cleanly in activitypub and sections for client-client and client-server... we will keep it as one document ... rhiaro and I agree about this and tsyesika also seems to agree ... one concern is... "I want to publish this note to my followers" and somebody replies to you, how does this reply get out to your followers? ... pump.io has encountered this issue too. we did a demo implementation and drew things out on paper and we think we've come up with a method and put that in the spec <eprodrom> Bravo cwebber2: that if somebody does write a reply you can forward it under some conditions ... there are changes to make to the WD and I can make those and go toward a new working draft and feel confident about the state of the document eprodrom: rhiaro, you were saying there aren't major changes to LDN at this point? rhiaro: right. there are editorial changes and we should still publish a new LDN WD as well to make sure things are in sync. ... lately I've changed social web protocols to catch things up and so we need to publish a new version of that too eprodrom: great. this might open a can of worms; we discussed last meeting... this is a social web protocols / ldn question, how do we handle having ldn and aligning it with others rhiaro: right, that's next on my things to attack eprodrom: ah, sorry, ok rhiaro: I added it to the social web protocols and hopefully I can talk to julien about that eprodrom: cwebber2, are we ready for a next version then? <ben_thatmustbeme> changelog++ <Loqi> changelog has 2 karma (1 in this channel) cwebber2: I think so I just have to add one thing eprodrom: my next question is: should we go to working draft or wait until the group can review or just push the next version? I'm also fine with review on the WD. rhiaro: I was thinking we would publish the new WD today and then have it reviewed since we have some time off <eprodrom> PROPOSED: publish current editor's draft of ActivityPub plus changelog as new working draft cwebber2: I agree with that because we want to get to CR either before or by TPAC and this would help us move along <tantek> is there a link to the changelog? eprodrom: before we start +1'ing it, cwebber2 and rhiaro, does this reflect what you want to do next? cwebber2: yep rhiaro: yep <eprodrom> +1 <tantek> we really should provide a link to a changelog for anything we want to propose publishing <rhiaro> +1 eprodrom: changelog right now? <cwebber2> +1 <wilkie> +1 <sandro> +1 <csarven> +1 <ben_thatmustbeme> 0, don't really like publishing without a review or some changelog, but i will abstain in the interest of saving time <tantek> 0, similarly <cwebber2> I could write a fast changelog that'll be done before meeting end if necessary <KevinMarks> traffic noises <cwebber2> would that help? <tantek> (cwebber2 yes please!) <tantek> any document that is rec track should have a changelog with summaries eprodrom: cwebber2, don't do the changelog during the call if you can help it, but some <laughs> have other opinions on that RESOLUTION: publish current editor's draft of ActivityPub plus changelog as new working draft eprodrom: I'm going to mark this as resolved and... great <tantek> I believe AS2, Micropub, Webmention have all done a good job of providing changelogs for every published draft and that's been very helpful <cwebber2> ACK eprodrom: in all aspects, next time we have proposals coming up from editors moving to WD that you bring a changelog with you. either something you can link or drop into the channel. ... great <tantek> (if anyone would like examples of existing changelogs in the group) eprodrom: I'd like to move on to the next topic <KevinMarks> cwebber2: reading scrollback your notification issue sounds like salmentions Proposal: publish new WD of SWP <rhiaro> rhiaro: this morning I added PuSH and refactored a section. the link of the git log I dropped in the channel should give you an idea of the changes. <KevinMarks> rhiaro: I'd like to propose those changes. eprodrom: do we have questions on Social Web Protocols? <tantek> (since SWP is not rec-track, having an in-draft changelog is not as important) eprodrom: ok. great. I'd like to ask... rhiaro would you mind adding a changelog to this document? <tantek> rhiaro: can you provide a link to the draft you have staged to publish? rhiaro: no problem <KevinMarks> I mentioned Social Web Protocols on TWiG this week :D <ben_thatmustbeme> tantek, is SWP non-rec-track? eprodrom: I'd like to propose publishing this editors draft as a new working draft <eprodrom> PROPOSED: publish + Changelog as new working draft for Social Web Protocols <tantek> ben_thatmustbeme: yes that's my understanding since it non-normatively compares / relates *other* specs eprodrom: does that look right, rhiaro? rhiaro: yeah, looks right eprodrom: great <eprodrom> +1 <aaronpk> +1 <rhiaro> +1 <KevinMarks> +1 eprodrom: please vote <cwebber2> +1 <wilkie> +1 <csarven> +1 <sandro> +1 eprodrom: I'll give some time to look it over rhiaro: just to add this has a less important time table but it is important that people not see it too out of date <cwebber2> oops, realized I wasn't muted <cwebber2> sorry for typing noises <ben_thatmustbeme> +0 again as before eprodrom: I think it is important to keep this up to date and appreciate that you took the time to do that <ben_thatmustbeme> but it is important to get SWP changes out eprodrom: tantek? ... I don't want to rush you. I know you are reading it now. <tantek> rhiaro typo: "ontent is deleted" <rhiaro> will fix :) <tantek> (start of 3.2) eprodrom: I need all the votes in <tantek> +1 great update rhiaro. Thank you. RESOLUTION: publish + Changelog as new working draft for Social Web Protocols eprodrom: alright. great. I'm going to mark this as resolved. rhiaro, if you won't mind to fix that typo even if it isn't part of the resolution. ... next agenda item is to publish a new working draft of LDN Publish New Working Draft of LDN eprodrom: rhiaro, can you tell us all what's going on with LDN <rhiaro> rhiaro: nothing substantive except some clarifications ... it does have a changelog here but it is just editorial stuff but thought it doesn't hurt to keep things up-to-date eprodrom: great <tantek> changelog++ <Loqi> changelog has 3 karma (2 in this channel) <aaronpk> "editorial" <aaronpk> that's not very descriptive :) eprodrom: the document doesn't have a changelog? rhiaro: I linked to the document that has a changelog eprodrom: ah, I see, great ... maybe in the future, especially since you did say there are explanatory differences, to explain what those differences are <tantek> +1 on that eprodrom: everybody please mute if you aren't me <laughs> thank you <rhiaro> This is the version to publish eprodrom: the one on linkedresearch.org is the editor's draft? I believe? <rhiaro> ED ready to be WD <eprodrom> PROPOSED: publish + detailed changelog as new working draft of LDN eprodrom: great. so I am going to propose publishing this as a new working draft of LDN <rhiaro> Looks good <tantek> this is a second WD right? we already did a FPWD? eprodrom: rhiaro, does that make sense to you? <rhiaro> yep eprodrom: and yeah, this is the second WD I believe <eprodrom> +1 <rhiaro> +1 <cwebber2> +1 <sandro> +1 <ben_thatmustbeme> +1 <aaronpk> +1 eprodrom: (upon seeing rhiaro's affirmative on IRC) ok. great. if this makes sense, let's vote. <wilkie> +1 <tantek> +1 <csarven> +1 eprodrom: <laughs> everyone is more willing to make progress when we've had 2 weeks off. ... and yes, next week we have off RESOLUTION: publish + detailed changelog as new working draft of LDN eprodrom: if you are to vote please do so. in this case I will mark it resolved. ... there is a new working draft. great. ... let's move on to our next item which is about AS2 ... probably easier to have tantek chair while we go over the next item since it makes sense for me to address what is going on with AS2 <aaronpk> tantek is not on the phone ActivityStreams 2.0 <tantek> I can't chair, I'm speaking in person at the AB meeting :/ eprodrom: ah. ok. I'll chair myself and try to push through this. ... so. the state of AS2, a brief recap, on AS2. We had our CR meeting. <tantek> so that eprodrom can be free to discuss AS2 as editor eprodrom: after our meeting we had some issues brought up by i18n group. ... we decided to pull out of CR to better address these concerns and we've been addressing them for the last few weeks. <eprodrom> eprodrom: as of today, jasnell_ did a few PRs to resolve these existing issues and so, depending on your measurement, we might be ready to go to CR right now ... however we have new issues that are currently on our list ... a couple of those are editorial ... those will probably not be a problem but there are at least 1 or 2 normative changes ... where I am, as an editor, wondering is if we need to get to 0 issues to reach CR, or is it better to go to CR with the document as we've agreed and resolve these in the next months <cwebber2> vote going to CR <cwebber2> *I vote eprodrom: that's where we are at the moment. we are in an administrative point. as an editor, I want to move to CR and resolve as we go along ... ben? <tantek> is sandro on the phone? <tantek> we really need other people who were on the AS2 CR transition call to contribute to this discussion (apologies that I cannot) ben_thatmustbeme: I was wondering if we go to CR and have normative changes, we have to redo CR. what does that entail sandro: I am on the phone. the second version of CR involves us being willing to do it and its not a lot of work but it has about a 3 week turn-around so it is better to avoid it if you can <tantek> in my experience any "real" / practical spec has at least 2 CRs <rhiaro> He's done it, the i18n issues are resolved in the current ED sandro: my understanding, though, is that we had a meeting (you weren't on this meeting) and we were waiting for these issues and jasnell_ said he would fix them and then said he would fix them today and we had resolved these <tantek> that is, implementers of the first CR nearly always find substantial issue that require normative changes <aaronpk> here is the thread <tantek> and thus a second CR sandro: what is the status of these edits? anyone know? <aaronpk> and here is the new paragraph: <Loqi> [James M Snell] Activity Streams 2.0 eprodrom: yeah. jasnell_ has made a PR for changes to how we handle bi-directional text ... basically, for those who aren't following this, we came down to a fundamental difference between using bidirectional markers at the unicode level and using bidirectional markup in the html level ... there were strong resolution to not use the markup in certain fields and we can to a satisifactory compromise that doesn't require markup in the name field <KevinMarks> what's the PR? <eprodrom> <Loqi> [James M Snell] Activity Streams 2.0 <tantek> could you link to the "satisfactory compromise" for ther ecord? eprodrom: jasnell_ made those changes and they are in the editor's draft... let me make sure... yes. section 4.7... I can drop this <tantek> link to the *discussion* that resulted in the "satisfactory compromise" eprodrom: ah, yeah, satisfactory compromise... let me see if I can link to that <eprodrom> eprodrom: here is the pull request ... that jasnell_ made <aaronpk> 336 has the discussion eprodrom: let me see if I can summarize ... this is about using natural language and bidirectional text ... this is a significant change <sandro> +1 that all sounds right <eprodrom> sandro: sounds like we solved the bidirectional issues eprodrom: yes <KevinMarks> that BIDI makes sense given the tests we conducted. <tantek> is this the compromise? eprodrom: we have 6 issues. one is easy to fix. one is normative and a change from a MAY to a SHOULD. <tantek> issue 336 is too long to be considered a "Summary" <tantek> shh trackbot eprodrom: either than that... they seem to be resolved sandro: sounds like there is nothing here that would need a second CR if we changed it? anything that would change implementations? <tantek> my understanding is that NO properties are added to AS2 as a result of this discussion right? <aaronpk> correct <tantek> eprodrom: could you confirm ^^^ ? <KevinMarks> right <tantek> ok then I am +1 eprodrom: it doesn't seem like that a publisher or consumer would be significantly different between this MAY or SHOULD ... it is just a shift of emphasis, I'd think sandro: we don't know what we want to do with this one at this point? <ben_thatmustbeme> how long would it take to figure out the may or should? eprodrom: I can't make that call right now ... I'd make it a SHOULD but jasnell_ probably has different ideas about it ... rhiaro? rhiaro: realistically we would have a second CR on this sandro: why? rhiaro: seems like we will get feedback from implementers, unless you don't think so. seems like it would probably happen sandro: I just want to avoid extra work rhiaro: ok <tantek> are we willing to write tests for this detail? sandro: I feel like MAY vs SHOULD won't hurt but the safest thing we could do is make it at-risk <tantek> or get i18n to write tests? eprodrom: so put it as SHOULD and say "at-risk" <tantek> that's one way to address may/should sandro: or leave it as MAY and say "at-risk" and it may change to a SHOULD ... whatever way we think it is likely to go and just put it 'at-risk' eprodrom: I like marking it 'at-risk' and publishing as-is sandro: sounds good <tantek> can we actually make it at-risk when i18n says it's a requirement? sandro: and the other 5 issues don't seem like normative changes? <eprodrom> <rhiaro> the https one? <tantek> I'm worried that we drop it, then i18n objects when we try to go CR->PR <rhiaro> isn't w3c ns taking care of that? <rhiaro> it officially switched to https on 1 Aug I believe <rhiaro> ..sandro? eprodrom: one is normative but... it is whether we support the HTTP content or what makes most sense ... rhiaro, can you say this outloud? sandro: I don't think I've thought about this for context uris, but for namespace URIs this doesn't change rhiaro: right, but this changes javascript implementations... this is an implementation problem <KevinMarks> which may is becoming a should? sandro: it does seem possible that browsers will be a pain in this way <eprodrom> eprodrom: my feeling is HTTPS makes most sense. our implementor base is small and this is the time to do it ... the only down-side is that there are some older libraries that don't support HTTPS but I think they are a smaller and smaller number ... and it makes sense to push it to HTTPS everywhere sandro: let's make this at-risk too ... there are complexities here that I didn't think were there at first <csarven> I hope there is alignment with eprodrom: let's make it HTTPS in the editor's draft and we'll mark it 'at-risk' that we might also support just HTTP <csarven> ^ eprodrom sandro: yeah. the main reason to not put HTTPS there is... <csarven> The contents of @context stays as HTTP <csarven> It is the reference to context in HTTP is a problem if on HTTPS - client side / browser issue <csarven> Hope for the best and have implementations fix their stuff?? sandro: the URIs might need some place to mark that it is HTTPS or not otherwise it will pull it from the base url ... I never thought about the mixed-content warnings so I don't know what the right thing to do is <csarven> ok with eprodrom 's suggestion with AT RISK sandro: let's say 'at-risk' and figure it out. <rhiaro> And maybe having it called out in the CR doc will help with getting feedback <KevinMarks> <Loqi> [Kevin Marks] inline RTL works in reverse without implementers knowing <Loqi> #indieweb eprodrom: we're ok with at-risk and then figure it out? sandro: yep eprodrom: ok. great. ... sounds like I have two 'at-risk' notes to put in. and besides that looks like we are ready to go and I can have a version ready to have out thursday? <ben_thatmustbeme> just reference with "//..." and make it decide on its own :P eprodrom: does that work time-wise? rhiaro? rhiaro: yeah ... if they say no for thursday we can do it next tuesday eprodrom: ok! sandro: let's get a new resolution on record <eprodrom> ben_thatmustbeme: I'll keep that in mind eprodrom: if anyone has a question about AS2 and what we are doing right now, this is a great time to ask <sandro> PROPOSED: Proceed to CR with both ActivityStreams documents, including the changes worked out with i18n and items marked At Risk in this meeting, as per Ralph's go-ahead from the transition meeting. <cwebber2> +1 <eprodrom> +1 <rhiaro> +1 <sandro> +1 <csarven> +1 <ben_thatmustbeme> +1 <wilkie> +1 <KevinMarks> +1 RESOLUTION: Proceed to CR with both ActivityStreams documents, including the changes worked out with i18n and items marked At Risk in this meeting, as per Ralph's go-ahead from the transition meeting. eprodrom: unless we have any objections, now is the time to do so ... now we have something to point to in terms of resolutions. <rhiaro> cwebber2++ for speedy changelog! <Loqi> cwebber2 has 70 karma <cwebber2> thanks rhiaro :) eprodrom: we are now at the top of the hour <cwebber2> since I did a /me earlier, here's the changelog for log records eprodrom: aaronpk, are you good with pushing micropub for two weeks from now? or should we extend? aaronpk: I'm ok with waiting two weeks and come up with a more concrete proposal eprodrom: great. how long do you think it will take? we can extend 10 minutes <tantek> +1 on AS2 CR (sorry to be delayed, multitasking is hard) aaronpk: it is fine. we can just wait eprodrom: great. thank you very much. appreciate your flexibilty on that. <cwebber2> good call! eprodrom: thank you everybody for your time. I believe that wraps it up for us. <cwebber2> productive :) <rhiaro> wilkie++ <Loqi> wilkie has 33 karma <ben_thatmustbeme> wilkie++ <Loqi> wilkie has 34 karma <cwebber2> wilkie++ <Loqi> wilkie has 35 karma thanks all <ben_thatmustbeme> eprodrom++ <Loqi> slow down! <eprodrom> trackbot, end meeting <cwebber2> eprodrom++ <tantek> I'm worried about only 5 people coming to the f2f - will we have enough to talk about for 2 days? Summary of Action Items Summary of Resolutions - Accept as minutes for 20016-08-02 meeting - publish current editor's draft of ActivityPub plus changelog as new working draft - publish + Changelog as new working draft for Social Web Protocols - publish + detailed changelog as new working draft of LDN - Proceed to CR with both ActivityStreams documents, including the changes worked out with i18n and items marked At Risk in this meeting, as per Ralph's go-ahead from the transition meeting.
https://www.w3.org/wiki/Socialwg/2016-08-23-minutes
CC-MAIN-2017-13
refinedweb
3,864
67.69
Up to [cvs.netbsd.org] / pkgsrc / devel / boost-build Request diff between arbitrary revisions Default branch: MAIN Revision 1.5 / (download) - annotate - [select for diffs], Thu Feb 24 11:05:34 2011 UTC (14 months, 4 weeks: +5 -3 lines Diff to previous 1.4 (colored) Changes 1.46.0: New Libraries * Icl: Interval Container Library, interval sets and maps and aggregation of associated values, from Joachim Faulhaber. Updated Libraries * Array: - Added support for cbegin/cend - Fixed a problem with the Sun compiler * Asio: - Fixed a problem on older Linux kernels (where epoll is used without timerfd support) that prevents timely delivery of deadline_timer handlers, after the program has been running for some time * Bind: - make_adaptable now documented * Concept Check: - fixed warnings with self-assignment * Filesystem: - Version 3 of the library is now the default. - IBM vacpp: Workaround for compiler bug affecting iterator_facade - Verify, clarify, document that <boost/config/user.hpp> can be used to specify BOOST_FILESYSTEM_VERSIO - Replaced C-style assert with BOOST_ASSERT. - Undeprecated unique_path(). Instead, add a note mentioning the workaround for lack of thread safety and possible change to cwd. unique_path() is just too convenient to deprecate! - Cleared several GCC warnings. - Changed V2 code to use BOOST_THROW_EXCEPTION. - Windows: Fix status() to report non-symlink reparse point correctly. - Add symlink_option to recursive_directory_iterator, allowing control over recursion into directory symlinks. Note that the default is changed to not recurse into directory symlinks. - Reference documentation cleanup, including fixing missing and broken links, and adding missing functions. - Miscellaneous implementation code cleanup. * Fusion: - vector copy constructor now copies sequence members in the same order on different platforms * Graph: - Fixed Graphviz output to work on Visual C++ 7.1. - Replaced assert with BOOST_ASSERT. - Changed to Boost.Filesystem v3. More... Revision 1.4 / (download) - annotate - [select for diffs], Sat Oct 30 09:29:58 2010 UTC (18 months, 3 weeks ago) by adam Branch: MAIN CVS Tags: pkgsrc-2010Q4-base, pkgsrc-2010Q4 Changes since 1.3: +3 -3 lines Diff to previous 1.3 (colored) Added support for Clang Revision 1.3 / (download) - annotate - [select for diffs], Sat Apr 22 09:22:07 2006 UTC (6 years, 1 month ago) by rillig.2: +2 -2 lines Diff to previous 1.2 (colored) Removed the superfluous "quotes" and 'quotes' from variables that don't need them, for example RESTRICTED and SUBST_MESSAGE.*. Revision 1.2 / (download) - annotate - [select for diffs], Sat Jan 21 09:02:16 2006 UTC (6 years, 4 months ago) by jmmv Branch: MAIN CVS Tags: pkgsrc-2006Q1-base, pkgsrc-2006Q1 Changes since 1.1: +4 -2 lines Diff to previous 1.1 (colored) Fix build and install of Boost under Mac OS X: - Correctly use threads. - Use the correct tool set. - Make libraries (Boost.Test) with undefined symbols build correctly. - Change the installed library names so that they match other systems (thus avoiding manual PLIST substitutions). There is a hack here, though, to let the dylib stuff kick in... Revision 1.1 / (download) - annotate - [select for diffs], Sat Feb 26 22:48:35 2005 UTC (7 years, 2 months ago) by jmm Complete rework of the Boost packages: - Drop devel/boost and devel/boost-thread. - Add devel/boost-docs which includes all the documentation related to Boost (previously included in devel/boost). - Add devel/boost-build which includes bjam, the Boost.Build framework. - Add devel/boost-headers which includes all the header files needed at build time by programs using Boost (previously included in devel/boost). - Add devel/boost-libs which includes all the binary libraries needed at build and run time by programs using Boost (previously included in devel/boost and devel/thread). All of them are multithreaded, to make things easier. - devel/boost-python includes the Boost Python library (as it did before), but now works, given that everything is threaded again. - Drop our thread_user.hpp customization. Avoids some build failures that appeared when the previous boost-thread package was not installed. - Use static PLISTs. - Install unversioned files. Makes things *a lot* easier when building stuff outside pkgsrc. - Add meta-pkgs/boost, a meta package that depends on all of the above. Thanks go to jlam@ and tv@ for their comments. While here, update to 1.32.0:: o Added bundled properties to the adjacency_list and adjacency_matrix class templates, greatly simplifying the introduction of internal vertex and edge properties. o The LEDA graph adaptors have been ported to LEDA 4.5. o Added algorithms for betweenness centrality and betweenness centrality clustering. o Added circle layout and undirected spring layout algorithms. * MPL Library: o Updated to use the Boost Software License. o New documentation, including a complete reference manual. o Major interface changes and improvements, many of which are not backward compatible. Please refer to the 1.32 changelog for the detailed information about upgrading to the new version. * Python Library: o Updated to use the Boost Software License. o A new, better method of wrapping classes with virtual functions has been implemented. o Support for the new Python Bool type, thanks to Daniel Holth. o Support for upcoming GCC symbol export control features have been folded in, thanks to Niall Douglas. o Improved support for std::auto_ptr-like types. o Components used by other libraries have been moved out of python/detail and into boost/detail to improve dependency relationships. o: o namespace names gets shorten; old one still supported till next release o added proper encoding of XML PCDATA o support for wide string comparison implemented For complete list of changes see Test Library release notes.. This form allows you to request diff's between any two revisions of a file. You may select a symbolic revision name using the selection box or you may type in a numeric name using the type-in text box.
http://cvsweb.netbsd.org/bsdweb.cgi/pkgsrc/devel/boost-build/toolset.mk
crawl-003
refinedweb
956
58.18
Class variables are shared in the class hierarchy. This can result in surprising behavior. class A @@variable = :x def self.variable @@variable end end class B < A @@variable = :y end A.variable # :y Classes are objects, so instance variables can be used to provide state that is specific to each class. class A @variable = :x def self.variable @variable end end class B < A @variable = :y end A.variable # :x Local variables (unlike the other variable classes) do not have any prefix local_variable = "local" p local_variable # => local Its scope is dependent on where it has been declared, it can not be used outside the "declaration containers" scope. For example, if a local variable is declared in a method, it can only be used inside that method. def some_method method_scope_var = "hi there" p method_scope_var end some_method # hi there # => hi there method_scope_var # NameError: undefined local variable or method `method_scope_var' Of course, local variables are not limited to methods, as a rule of thumb you could say that, as soon as you declare a variable inside a do ... end block or wrapped in curly braces {} it will be local and scoped to the block it has been declared in. 2.times do |n| local_var = n + 1 p local_var end # 1 # 2 # => 2 local_var # NameError: undefined local variable or method `local_var' However, local variables declared in if or case blocks can be used in the parent-scope: if true usable = "yay" end p usable # yay # => "yay" While local variables can not be used outside of its block of declaration, it will be passed down to blocks: my_variable = "foo" my_variable.split("").each_with_index do |char, i| puts "The character in string '#{my_variable}' at index #{i} is #{char}" end # The character in string 'foo' at index 0 is f # The character in string 'foo' at index 1 is o # The character in string 'foo' at index 2 is o # => ["f", "o", "o"] But not to method / class / module definitions my_variable = "foo" def some_method puts "you can't use the local variable in here, see? #{my_variable}" end some_method # NameError: undefined local variable or method `my_variable' The variables used for block arguments are (of course) local to the block, but will overshadow previously defined variables, without overwriting them. overshadowed = "sunlight" ["darkness"].each do |overshadowed| p overshadowed end # darkness # => ["darkness"] p overshadowed # "sunlight" # => "sunlight" Class variables have a class wide scope, they can be declared anywhere in the class. A variable will be considered a class variable when prefixed with @@ class Dinosaur @@classification = "Like a Reptile, but like a bird" def self.classification @@classification end def classification @@classification end end dino = Dinosaur.new dino.classification # => "Like a Reptile, but like a bird" Dinosaur.classification # => "Like a Reptile, but like a bird" Class variables are shared between related classes and can be overwritten from a child class class TRex < Dinosaur @@classification = "Big teeth bird!" end TRex.classification # => "Big teeth bird!" Dinosaur.classification # => "Big teeth bird!" This behaviour is unwanted most of the time and can be circumvented by using class-level instance variables. Class variables defined inside a module will not overwrite their including classes class variables: module SomethingStrange @@classification = "Something Strange" end class DuckDinosaur < Dinosaur include SomethingStrange end DuckDinosaur.class_variables # => [:@@classification] SomethingStrange.class_variables # => [:@@classification] DuckDinosaur.classification # => "Big teeth bird!" Global variables have a global scope and hence, can be used everywhere. Their scope is not dependent on where they are defined. A variable will be considered global, when prefixed with a $ sign. $i_am_global = "omg" class Dinosaur def instance_method p "global vars can be used everywhere. See? #{$i_am_global}, #{$another_global_var}" end def self.class_method $another_global_var = "srsly?" p "global vars can be used everywhere. See? #{$i_am_global}" end end Dinosaur.class_method # "global vars can be used everywhere. See? omg" # => "global vars can be used everywhere. See? omg" dinosaur = Dinosaur.new dinosaur.instance_method # "global vars can be used everywhere. See? omg, srsly?" # => "global vars can be used everywhere. See? omg, srsly?" Since a global variable can be defined everywhere and will be visible everywhere, calling an "undefined" global variable will return nil instead of raising an error. p $undefined_var # nil # => nil Although global variables are easy to use its usage is strongly discouraged in favour of constants. Instance variables have an object wide scope, they can be declared anywhere in the object, however an instance variable declared on class level, will only be visible in the class object. A variable will be considered an instance variable when prefixed with @. Instance variables are used to set and get an objects attributes and will return nil if not defined. class Dinosaur @base_sound = "rawrr" def initialize(sound = nil) @sound = sound || self.class.base_sound end def speak @sound end def try_to_speak @base_sound end def count_and_store_sound_length @sound.chars.each_with_index do |char, i| @sound_length = i + 1 p "#{char}: #{sound_length}" end end def sound_length @sound_length end def self.base_sound @base_sound end end dino_1 = Dinosaur.new dino_2 = Dinosaur.new "grrr" Dinosaur.base_sound # => "rawrr" dino_2.speak # => "grrr" The instance variable declared on class level can not be accessed on object level: dino_1.try_to_speak # => nil However, we used the instance variable @base_sound to instantiate the sound when no sound is passed to the new method: dino_1.speak # => "rawwr" Instance variables can be declared anywhere in the object, even inside a block: dino_1.count_and_store_sound_length # "r: 1" # "a: 2" # "w: 3" # "r: 4" # "r: 5" # => ["r", "a", "w", "r", "r"] dino_1.sound_length # => 5 Instance variables are not shared between instances of the same class dino_2.sound_length # => nil This can be used to create class level variables, that will not be overwritten by a child-class, since classes are also objects in Ruby. class DuckDuckDinosaur < Dinosaur @base_sound = "quack quack" end duck_dino = DuckDuckDinosaur.new duck_dino.speak # => "quack quack" DuckDuckDinosaur.base_sound # => "quack quack" Dinosaur.base_sound # => "rawrr"
https://sodocumentation.net/ruby/topic/4094/variable-scope-and-visibility
CC-MAIN-2021-21
refinedweb
946
56.45
{-# LANGUAGE MagicHash, DoRec, RankNTypes, EmptyDataDecls, GADTs, GeneralizedNewtypeDeriving, PatternGuards #-} -- for the exported rank-2 type of runPeg, -- as well as the implementation using GADTs, generalised newtype deriving, -- also a phantom datatype used with unsafeCoerce -- | -- -- <> -- module Text.Parsers.Frisby( -- * The basic types -- ** The type of primitive parsers P(), -- ** The monad used to create recursive parsers via rules PM(), newRule, runPeg, module Control.Applicative, -- * Basic operators (//), (<>), (<++>), -- ** Derived operators (->>), (<<-), (//>), -- ** Modification operators (##), (##>), -- * Basic combinators anyChar, bof, eof, getPos, char, noneOf, oneOf, text, unit, rest, discard, parseFail. -- peek, doesNotMatch, isMatch, onlyIf, matches, -- ** Looping combinators many, many1, manyUntil, -- ** Various utility combinators between, choice, option, optional, -- *, regex, showRegex )where import Control.Applicative hiding(many,optional) --though same meaning 'many', and superior 'optional' import qualified Data.IntSet as IntSet import Control.Monad.Fix import Control.Monad.Identity import Data.Char(ord,chr) import Control.Monad.State import Data.Array hiding((//)) import Data.Monoid hiding(Any) import qualified Data.Map as Map --inline usable part of Unsafe.Coerce until that module is commonly available import GHC.Base (unsafeCoerce#) unsafeCoerce :: a -> b unsafeCoerce = unsafeCoerce# -- Essentially we are manipulating a polytypic cyclic graph (the P structure). -- This is difficult to do in Haskell. -- Graphs have always been difficult in Haskell. They're not inductive. -- GADTs suffice well for polytypic trees. -- The moment it becomes non-inductive... -- _Implicit_ (directed-)acyclic-graph sharing can be introduced -- with non-recursive lets/lambdas. -- _Implicit_ (directed or not)-cyclic-graph-sharing can be introduced -- with recursive lets / the least fixed point operator. -- But when sharing is implicit we can't detect it while performing induction -- over the graph, so we get infinite loops or simply failing to detect -- intended sharing. After all Haskell is referentially transparent! -- But we want to be able to optimize this graph to achieve the potential -- of PEG parsers. This is possible to do explicitly, though a bit ugly -- and seems to be beyond Haskell's static type system when not everything -- in the graph has the same type. -- -- To specify input in a way that we can understand the finite structure, -- the best we have, to recommend, is mdo. With this, it's the user's -- responsibility not to create cycles that don't go through the monad. -- (e.g. let q p = (conid <++> text "." <++> q p) // p -- needs to involve mdo/mfix such as -- let q p = mfix $ \qp -> (conid <++> text "." <++> qp) // p -- , which makes its usage a little different) -- With rank-2 types, it is *not* the user's responsibility to avoid mixing -- up P's from different PM's, which is a good thing because that's not -- typesafe or at least not abstraction-safe. (e.g. this can't be used -- in a parser monad that is itself runPeg'd: -- runPeg (mdo -- good <- newRule $ text "good" -- evil <- newRule $ unit good -- return evil -- ) -- ). -- -- Now we have the polytypic cyclic graph, can we manipulate it with Haskell's -- type-system? Unfortunately, the Named graph-vertices pose a difficulty. -- The PM monad could perhaps be based on, instead of numerical indexes, -- ST(Refs) (since the ST interface cannot be implemented in any known Haskell -- typesystem without unsafeCoerce, it constitutes an extension to the -- type system, in a sense -- is this correct?). But then we have to -- duplicate the memoization for each character in the input stream, keeping -- each reference to a top-level parser referring to it -- -- not to the original, but to the saturated, memoized (lazy thunk) version! -- Not sure this is possible here without unsafeCoerce. -- -- Of course, with unsafeCoerce we could theoretically eliminate a bunch of -- other type system extensions we internally use, such as GADTs. That would -- be a terrible hack. newtype Token = Token Int deriving(Eq,Ord,Num,Show,Ix) -- the monad used for creating recursive values newtype PM s a = PM (PMImp a) deriving(Monad,MonadFix,Functor) type PMImp a = State Token a -- 's' added for safe state, just as the ST monad's interface uses newtype P s a = P { fromP :: PE a } deriving(Functor,Applicative,Alternative,Monoid) data PE a where Char :: IntSet.IntSet -> PE Char Any :: PE Char Failure :: PE a Named :: Token -> PE a -> PE a Not :: PE a -> PE () PMap :: (a -> b) -> PE a -> PE b Slash :: PE a -> PE a -> PE a ThenCat :: PE [a] -> PE [a] -> PE [a] Star :: PE a -> PE [a] StarUntil :: PE a -> PE b -> PE [a] StarMax :: Int -> PE a -> PE [a] Then :: PE a -> PE b -> PE (a,b) GetPos :: PE Int Unit :: a -> PE a When :: PE a -> (a -> Bool) -> PE a Rest :: PE [Char] Peek :: PE a -> PE a instance Functor PE where fmap = PMap instance Applicative PE where --should another constructor be added, rather? --perhaps Then and ThenCat combined and parameterized by --the function (++), (,) ... but, 'text', etc, does this too mf <*> ma = PMap (\(f,a) -> f a) (Then mf ma) pure = Unit instance Alternative PE where (<|>) = Slash empty = Failure instance Monoid (PE a) where mappend = Slash mempty = Failure -- | Return a value, always succeeds unit :: a -> P s a unit a = P $ Unit a -- | Match a specified character char :: Char -> P s Char char c = P $ Char (IntSet.singleton (ord c)) -- | Match some text text :: String -> P s String text (x:xs) = fmap ( \ (c,cs) -> c:cs) $ char x <> text xs text [] = unit [] -- | Immediately consume and return the rest of the input -- equivalent to (many anyChar), but more efficient. rest :: P s String rest = P Rest -- | Match any character, fails on EOF anyChar :: P s Char anyChar = P Any infixl 1 //, //> infix 2 ##, ##> infixl 3 <>, <++> infixl 4 ->>, <<- -- | Match first argument, then match the second, returning both in a tuple (<>) :: P s a -> P s b -> P s (a,b) P x <> P y = P $ x `Then` y -- | Match a pair of lists and concatenate them (<++>) :: P s [a] -> P s [a] -> P s [a] P x <++> P y = P $ x `ThenCat` y -- | Match first argument, then match the second, returning only the value on the left. -- -- > x <<- y = x <> y ## fst -- (<<-) :: P s a -> P s b -> P s a x <<- y = x <> y ## fst -- | Match first argument, then match the second, returning only the value on the right. -- -- > x ->> y = x <> y ## snd (->>) :: P s a -> P s b -> P s b x ->> y = x <> y ## snd -- | Ordered choice, try left argument, if it fails try the right one. -- This does not introduce any backtracking or penalty. (//) :: P s a -> P s a -> P s a P x // P y = P $ x `Slash` y -- | Ordered choice, try left argument, if it fails then return right argument. (//>) :: P s a -> a -> P s a x //> y = x // unit y -- | Map a parser through a function. a fancy version of 'fmap'. (##) :: P s a -> (a -> b) -> P s b x ## y = fmap y x -- | Parse left argument and return the right argument. (##>) :: P s a -> b -> P s b x ##> y = discard x ->> unit y -- | Succeeds when the argument does not. doesNotMatch :: P s a -> P s () doesNotMatch (P x) = P $ Not x -- | Succeeds when the argument does, but consumes no input. -- Equivalant to \p -> discard (peek p) matches :: P s a -> P s () matches = peek . discard -- | Parse something and return it, but do not advance the input stream. peek :: P s a -> P s a peek (P p) = P $ Peek p -- | Succeed only if thing parsed passes a predicate. onlyIf :: P s a -> (a -> Bool) -> P s a onlyIf (P x) y = P $ When x y -- | Parse many of something. Behaves like * in regexes. -- This eats as much as it possibly can, if you want a minimal much rule, then use 'manyUntil' which stops when a. -- many :: P s a -> P s [a] many (P p) = P $ Star p -- | Parse many of something via the minimal munch rule. behaves like *? in -- perl regexes. The final item is not consumed. manyUntil :: P s b -> P s a -> PM s (P s [a]) manyUntil final p = do rec rule <- newRule $ matches final ##> [] // p <> rule ## uncurry (:) return rule -- | First matching parse wins, a simple iteration of (\/\/). choice :: [P s a] -> P s a choice = mconcat -- | Get current position in file as number of characters since the beginning. getPos :: P s Int getPos = P GetPos -- | Equivalent to -- -- > between open close thing = open ->> thing <<- close between :: P s a -> P s b -> P s c -> P s c between open close thing = open ->> thing <<- close -- | Parse something if you can, else return first value -- -- > option a p = p // unit a option :: a -> P s a -> P s a option a p = p // unit a -- | Parse something if you can, discarding it. -- -- > option a p = discard p // unit () optional :: P s a -> P s () optional p = discard p // unit () -- | Throw away the result of something. -- -- > discard p = p ->> unit () discard :: P s a -> P s () discard p = p ->> unit () -- | am at the end of string. eof :: P s () eof = doesNotMatch anyChar -- | am at the beginning of the string. bof :: P s () bof = discard (getPos `onlyIf` (== 0)) -- | Match one or more of something via maximal munch rule. many1 :: P s a -> P s [a] many1 x = (\ (c,cs) -> c:cs) `fmap` (x <> many x) -- | Match one of the set of characters. oneOf :: [Char] -> P s Char oneOf [] = parseFailure oneOf xs = P $ Char (IntSet.fromList $ map ord xs) -- foldl (//) parseFailure (map char xs) -- | Match any character other than the ones in the list. noneOf :: [Char] -> P s Char noneOf [] = anyChar noneOf xs = doesNotMatch (oneOf xs) ->> anyChar -- foldl (//) parseFailure (map char xs) -- | Fails, is identity of (\/\/) and unit of (\<\>). parseFailure :: P s a parseFailure = P Failure -- Just used to coerce values to so they can be stashed away in the array. data Unknown type DerivMapTo a = Array Token a type NM a = State (Token,Map.Map Token Token,[(Token,PE Unknown)]) a normalizePElem :: PE a -> (PE a, DerivMapTo (PE Unknown)) normalizePElem pe = (rootNormPE, normPEs) where (rootNormPE, state) = runState (normalizePElemNM pe) (0,mempty,mempty) normPEs = array (0, nTokens - 1) assocNormPEs where (nTokens, _, assocNormPEs) = state normalizePElemNM :: PE a -> NM (PE a) normalizePElemNM pe = f pe where f :: forall a . PE a -> NM (PE a) f (Then x y) = do x <- f x y <- f y case (x,y) of (Failure,_) -> return Failure (_,Failure) -> return Failure (Unit a,Unit b) -> return (Unit (a,b)) (x,y) -> return (Then x y) f (ThenCat x y) = do x <- f x y <- f y case (x,y) of (Failure,_) -> return Failure (_,Failure) -> return Failure (Unit a,Unit b) -> return (Unit (a ++ b)) (x,y) -> return (ThenCat x y) f (Slash x y) = do x <- f x y <- f y return $ slash x y f (Char x) | IntSet.null x = return Failure f c@Char {} = return c f p@Failure = return p f p@Unit {} = return p f p@Any = return p f p@GetPos = return p f Rest = return Rest f (When p fn) = f p >>= \p' -> return (When p' fn) f (PMap fn x) = liftM (PMap fn) (f x) f (Star p) = f p >>= \x -> case x of Failure -> return $ Unit [] -- Unit x -> return $ repeat x x -> return (Star x) f (Not p) = do x <- f p case x of Rest -> return Failure Unit {} -> return Failure Failure -> return (Unit ()) x -> return (Not x) f (Peek p) = f p >>= \x -> case x of -- No need to backtrack-Peek if we're not consuming anything anyway x | mayConsumeInput x == False -> return x x -> return (Peek x) f (Named n p) = do (i,m,cm) <- get case Map.lookup n m of Just v -> return (Named v (error "no need")) Nothing -> do put (i + 1,Map.insert n i m,cm) p' <- f p (ni,m,cm) <- get put (ni,m,(i,unsafeCoerce p' :: PE Unknown):cm) return (Named i (error "no need")) slash :: forall a . PE a -> PE a -> PE a slash a Failure = a slash Failure b = b slash (Unit a) _ = (Unit a) slash (Rest) _ = Rest slash (Char x) (Char y) = (Char (x `mappend` y)) slash Any Char {} = Any slash Char {} Any = Any slash x y = Slash x y -- It's okay, just suboptimal, to return True when input can't be consumed; -- it's incorrect to return False when it might in fact consume input. mayConsumeInput :: PE a -> Bool mayConsumeInput Failure = False mayConsumeInput Unit {} = False mayConsumeInput (Then x y) = mayConsumeInput x || mayConsumeInput y mayConsumeInput (ThenCat x y) = mayConsumeInput x || mayConsumeInput y mayConsumeInput (Slash x y) = mayConsumeInput x || mayConsumeInput y mayConsumeInput Not {} = False mayConsumeInput _ = True -- these fields must not be strict! -- although, derivIndex is explicitly seq'd in one place before -- being put into a Derivs, which is fine (in fact, important, -- so that an unevaluated chain of thunks from the past doesn't -- build up when the character index isn't needed for a while) data Derivs = Derivs { derivChar :: (Results Char), derivIndex :: Int, derivArray :: DerivMapTo (Results Unknown), derivRest :: String } data Results a = Parsed a Derivs | NoParse --this instance really should be derived --(once deriving Functor is available) : instance Functor Results where fmap f (Parsed a arr) = Parsed (f a) arr fmap _ NoParse = NoParse -- | -- -- runPeg :: (forall s . PM s (P s a)) -> String -> a runPeg peg = --there is a nontrivial amount of work that only depends --on peg, so let's suggest that to be shared by using an --explicit lambda here that the where clause is not "inside" (\input -> pout input) where pout input = case rootParser (f 0 input) of Parsed a _ -> a NoParse -> error "runPeg: no parse" emptyDAt n = emptyD { derivIndex = n } where emptyD = f 0 [] --is the sharing here (particularly the array) -- worth much? (does it necessarily even exist if we stuff -- it into a where clause like this?) --Optimize the parser once initially --The two separate uses of state: -- -first (evalState) we number all parsers (newRules) to make -- loops detectable. The numbering scheme is entirely arbitrary here; -- it doesn't really matter what number to start with in the state. -- -then (runState) we optimize the parsers to be more similar to -- each other where possible(?), in the process renumbering the -- parsers such that unused ones are not included and the order -- is somewhat arbitrary. The new set of numbers (called "Token"s) -- start counting from zero, to be compactly used in an -- array of length equal to the number of referenced (potentially-used) -- named parsers. This state's Map is just to look up the meaning -- of the old token-numbering in terms of the new numbers. -- --rootPElemBeforeNormalization actually contains all parsers it references, --recursively, just labelled by PM so the infinite recursion can be --detected and stopped. rootPElemBeforeNormalization = fromP $ evalState (case peg of PM x -> x) 1 --rootPElemAfterNormalization need not be among the array if it is just --the parser used to get started at the beginning of input, such as: -- mdo p <- newRule $ ...; return (p <> rest) (rootPElemAfterNormalization, arrayNormalizedPElems) = normalizePElem rootPElemBeforeNormalization --arrayParsers, rootParser are out here for increased sharing of g's work arrayParsers = fmap g arrayNormalizedPElems rootParser = g rootPElemAfterNormalization f n s = n' `seq` d where --At each position in the file, we memoize (lazily) the results of all --our finite number of parsers. Since lookahead is similarly --memoized... When(onlyIf) (some asymptotically complex function) --risks a more difficult than O(n) parse however. d = Derivs chr n (fmap ($ d) arrayParsers) s --chr is the secret recursion over the input characters that --grabs all of their positions and generates the lazy shared --sequence of arrays. chr = case s of (x:xs) -> Parsed x (f n' xs) ; [] -> NoParse n' = n + 1 --the lets are explicitly floated outside the deriv-lambdas so that --their results will be shared given the partial application in defs --(essentially this avoids repeating the process of turning the PE tree --into functions, nothing huge) g :: PE a -> Derivs -> Results a g (Named n _) = \ (Derivs _ _ d _) -> unsafeCoerce (d ! n) g Any = \ (Derivs p _ _ _) -> p g (Char cs) = \ (Derivs p _ _ _) -> case p of Parsed c d | ord c `IntSet.member` cs -> Parsed c d _ -> NoParse g GetPos = \d -> Parsed (derivIndex d) d g Failure = \_ -> NoParse g (Not p) = let m = g p in \d -> case m d of Parsed {} -> NoParse NoParse {} -> Parsed () d g (PMap fn p) = let p' = g p in \ d -> fmap fn (p' d) g (Slash x y) = let x' = g x; y' = g y in \d -> case x' d of p@Parsed {} -> p NoParse -> y' d g (Then x y) = let x' = g x; y' = g y in \d -> case x' d of NoParse -> NoParse Parsed a d' -> case y' d' of Parsed b d'' -> Parsed (a,b) d'' NoParse -> NoParse g (ThenCat x y) = let x' = g x; y' = g y in \d -> case x' d of NoParse -> NoParse Parsed a d' -> case y' d' of Parsed b d'' -> Parsed (a ++ b) d'' NoParse -> NoParse g Rest = \d -> Parsed (derivRest d) (emptyDAt (derivIndex d + length (derivRest d))) g (Unit x) = \d -> Parsed x d g (Peek p) = let p' = g p in \d -> case p' d of Parsed r _ -> Parsed r d NoParse -> NoParse g (When x fn) = let x' = g x in \d -> case x' d of NoParse -> NoParse Parsed x d -> if fn x then Parsed x d else NoParse g (Star p) = let p' = g p in \d -> let r d = case p' d of Parsed x d' -> let (a,b) = r d' in (x:a,b) NoParse -> ([],d) (fv,fd) = r d in Parsed fv fd -- |. -- newRule :: P s a -> PM s (P s a) newRule pe@(P Any {}) = return pe newRule pe@(P Char {}) = return pe newRule pe@(P x) = f x where f Named {} = return pe f Unit {} = return pe --f Any {} = return pe --f Char {} = return pe f Failure {} = return pe f pe = PM $ do x <- get put $! (x + 1) return (P $ Named x pe) data Regex = RegexChars Bool IntSet.IntSet | RegexAny | RegexMany { regexWhat :: Regex, regexMin :: Int, regexMax :: Maybe Int, regexMunch:: Bool } | RegexCat [Regex] deriving(Show,Eq,Ord) normalizeRegex :: Regex -> Regex normalizeRegex r = f r where f RegexAny = RegexAny f (RegexCat xs) = regexCat $ g (map f xs) f rm@RegexMany { regexWhat = r } | RegexCat [] <- r' = RegexCat [] | otherwise = regexCat (replicate (regexMin rm) r' ++ [rm { regexWhat = r', regexMin = 0, regexMax = fmap (subtract $ regexMin rm) (regexMax rm) }]) where r' = f r f r@RegexChars {} = r g (RegexCat x:xs) = x ++ g xs g (x:xs) = x:g xs g [] = [] regexCat [x] = x regexCat xs = RegexCat xs regexToParser :: Regex -> P s String regexToParser r = f r where f RegexAny = anyChar ## (:[]) f (RegexChars True m) = oneOf (map chr $ IntSet.toList m) ## (:[]) f (RegexChars False m) = noneOf (map chr $ IntSet.toList m) ## (:[]) f (RegexCat []) = unit "" f (RegexCat (x:xs)) = f x <++> f (RegexCat xs) f RegexMany { regexWhat = r, regexMin = 0, regexMax = Nothing } = many (f r) ## concat f rm@RegexMany { regexWhat = r, regexMin = n, regexMax = Nothing } = f r <++> f rm { regexMin = n - 1 } f RegexMany { regexWhat = r, regexMin = 0, regexMax = Just 1 } = f r // unit "" parseRegex :: forall s . PM s (P s (Maybe Regex)) parseRegex = do rec regex <- newRule $ primary <<- char '*' <> isMatch (char '?') ## (\ (r,m) -> RegexMany { regexWhat = r, regexMin = 0, regexMax = Nothing, regexMunch = m }) // primary <<- char '+' <> isMatch (char '?') ## (\ (r,m) -> RegexMany { regexWhat = r, regexMin = 1, regexMax = Nothing, regexMunch = m }) // primary <<- char '?' <> isMatch (char '?') ## (\ (r,m) -> RegexMany { regexWhat = r, regexMin = 0, regexMax = Just 1, regexMunch = m }) // primary primary <- newRule $ char '(' ->> fregex <<- char ')' // char '.' ##> RegexAny // text "[^" ->> char_class <<- char ']' ## RegexChars False . IntSet.fromList . map ord // char '[' ->> char_class <<- char ']' ## RegexChars True . IntSet.fromList . map ord // rchar ## RegexChars True . IntSet.singleton . ord rchar <- newRule $ text "\\n" ##> '\n' // text "\\t" ##> '\t' // text "\\f" ##> '\f' // text "\\a" ##> '\a' // text "\\e" ##> '\033' // text "\\r" ##> '\r' // text "\\0" ##> '\0' // char '\\' ->> anyChar // noneOf ".[*+()\\" char_class1 <- newRule $ anyChar <<- char '-' <> anyChar ## uncurry enumFromTo // anyChar ## (:[]) char_class <- fmap (fmap concat) $ manyUntil (char ']') char_class1 fregex <- newRule $ many regex ## RegexCat return $ fmap (Just . normalizeRegex) (fregex <<- eof) // unit Nothing -- | always succeeds, returning true if it consumed something. isMatch :: P s a -> P s Bool isMatch p = p ->> unit True // unit False parse_regex :: String -> Maybe Regex parse_regex = runPeg parseRegex -- | Create a new regular expression matching parser. it returns something in a -- possibly failing monad to indicate an error in the regular expression itself. newRegex :: Monad m => String -> m (PM s (P s String)) newRegex s = case parse_regex s of Just r -> return (return $ regexToParser r) Nothing -> err where err = fail $ "invalid regular expression: " ++ show s -- | Show a representation of the parsed regex, mainly for debugging. showRegex :: String -> IO () showRegex s = do putStrLn $ "Parsing: " ++ show s print (parse_regex s) -- | Make a new regex but abort on an error in the regex string itself. regex :: String -> PM s (P s String) regex s = runIdentity (newRegex s)
http://hackage.haskell.org/package/frisby-0.1/docs/src/Text-Parsers-Frisby.html
CC-MAIN-2015-35
refinedweb
3,422
60.99
12345678910111213141516171819202122232425262728293031323334 #include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { float inHand, interestRate, loanMonths, loanYears, faceValue, finalFaceValue, monthlyPayment, totalInterest, test; string goAgain; do { cout<<"How much money do you need in hand? "; cin>> inHand; cout<<"What is the interest rate (in decimal form) "; cin>> interestRate; cout<<"How many months is the loan (in months) "; cin>> loanMonths; loanYears = (loanMonths / 12); faceValue = inHand / (1 - interestRate * loanYears); totalInterest = (interestRate * faceValue * loanYears); finalFaceValue = faceValue + totalInterest; monthlyPayment = (finalFaceValue /loanMonths); cout<<"\nYou need a loan with a face value of $"<< finalFaceValue <<"\n"; cout<<"Your monthly payment is $"<< monthlyPayment <<"\n"; cout<<"\nWould you like to try another loan? (Enter yes or no) "; cin>> goAgain; } while (goAgain == "Yes" || goAgain == "yes"); system("PAUSE"); return 0; 123456 Please enter amount you need in hand: 8000 Please enter the interest rate: 0.05 Please enter the loan period in months: 18 You need a loan with face value equal to $8648.65 Your monthly payment will be $480.48 12345678 How much money do you need in hand? 8000 What is the interest rate (in decimal form) .05 How many months is the loan (in months) 18 You need a loan with a face value of $9297.3 Your monthly payment is $516.516 Would you like to try another loan? (Enter yes or no) 12 finalFaceValue = faceValue + totalInterest; finalFaceValue = faceValue;
http://www.cplusplus.com/forum/general/108975/
CC-MAIN-2017-13
refinedweb
224
51.99
Bond valuation and bond yields - Octavia Curtis - 2 years ago - Views: Transcription 1 RELEVANT TO ACCA QUALIFICATION PAPER P4 AND PERFORMANCE OBJECTIVES 15 AND 16 Bond valuation and bond yields Bonds and their variants such as loan notes, debentures and loan stock, are IOUs issued by governments and corporations as a means of raising finance. They are often referred to as fixed income or fixed interest securities, to distinguish them from equities, in that they often (but not always) make known returns for the investors (the bond holders) at regular intervals. These interest payments, paid as bond coupons, are fixed, unlike dividends paid on equities, which can be variable. Most corporate bonds are redeemable after a specified period of time. Thus, a plain vanilla bond will make regular interest payments to the investors and pay the capital to buy back the bond on the redemption date when it reaches maturity. This article, the first of two related articles, will consider how bonds are valued and the relationship between the bond value or price, the yield to maturity and the spot yield curve. It addresses, in part, the learning required in Sections C3a and C3d of the Paper P4 Syllabus and Study Guide. Bond value or price Example 1 How much would an investor pay to purchase a bond today, which is redeemable in four years for its par value or face value of $100 and pays an annual coupon of 5% on the par value? The required rate of return (or yield) for a bond in this risk class is 4%. As with any asset valuation, the investor would be willing to pay, at the most, the present value of the future income stream discounted at the required rate of return (or yield). Thus, the value of the bond can be determined as follows: Year Year 1 Year 2 Year 3 Year 4 Cash flows $5 $5 $5 $105 PV (4%) 5 x = x = x = x = Value/price (sum of the PV of flows) = $ Note: Mathematically, for year one, 5 / is the same as 5 x , and similarly for all the years If the required rate of return (or yield) was 6%, then using the same calculation method, the price of the bond would be $ And where the required rate of 2 2 return (or yield) is equal to the coupon 5% in this case the current price of the bond will be equal to the par value of $100. Thus, there is an inverse relationship between the yield of a bond and its price or value. The higher rate of return (or yield) required, the lower the price of the bond, and vice versa. However, it should be noted that this relationship is not linear, but convex to the origin. Bond price Yield (or required return) The plain vanilla bond with annual coupon payments in the above example is the simpler type of bond. In addition to the plain vanilla bond, candidates as part of their Paper P4. Yield to maturity (YTM) (also known as the [Gross] Redemption Yield (GRY)) If the current price of a bond is given, together with details of coupons and redemption date, then this information can be used to compute the required rate of return or yield to maturity of the bond. Example 2 A bond paying a coupon of 7% is redeemable in five years at par ($100) and is currently trading at $ Estimate its yield (required rate of return). $ = $7 x (1+r) -1 + $7 x (1+r) $107 x (1+r) -5 The internal rate of return approach can be used to obtain r. Since the current price is higher than $100, r must be lower than 7%. Initially, try 5% as r: $7 x [5%, five-year annuity] + $100 x [PV 5%, five-year] = $ $78.35 = $108.66 3 3 Try 6% as r: $7 x [6%, five-year annuity] + $100 x [PV 6%, five-year] = $ $74.73 = $ Yield = 5% + ( / ) x 1% = 5.46% The 5.46% is the yield to maturity (YTM) (or redemption yield) of the bond. The YTM is the rate of return at which the sum of the present values of all future income streams of the bond (interest coupons and redemption amount) is equal to the current bond price. It is the average annual rate of return the bond investors expect to receive from the bond till its redemption. YTMs for bonds are normally quoted in the financial press, based on the closing price of the bond. For example, a yield often quoted in the financial press is the bid yield. The bid yield is the YTM for the current bid price (the price at which bonds can be purchased) of a bond. Term structure of interest rates and the yield curve The yield to maturity is calculated implicitly based on the current market price, the term to maturity of the bond and amount (and frequency) of coupon payments. However, if a corporate bond is being issued for the first time, its price and/or coupon payments need to be determined based on the required yield. The required yield is based on the term structure of interest rates and this needs to be discussed before considering how the price of a bond may be determined. It is incorrect to assume that bonds of the same risk class, which are redeemed on different dates, would have the same required rate of return or yield. In fact, it is evident that the markets demand different annual returns or yields on bonds with differing lengths of time before their redemption (or maturity), even where the bonds are of the same risk class. This is known as the term structure of interest rates and is represented by the spot yield curve or simply the yield curve. For example, a company may find that if it wants to issue a one-year bond, it may need to pay interest at 3% for the year, if it wants to issue a two-year bond, the markets may demand an annual interest rate of 3.5%, and for a three-year bond the annual yield required may be 4.2%. Hence, the company would need to pay interest at 3% for one year; 3.5% each year, for two years, if it wants to borrow funds for two years; and 4.2% each year, for three years, if it wants to borrow funds for three years. In this case, the term structure of interest rates is represented by an upward sloping yield curve. 4 4 The normal expectation would be of an upward sloping yield curve on the basis that bonds with a longer period of maturity would require a higher interest rate as compensation for risk. Note here that the bonds considered may be of the same risk class but the longer time period to maturity still adds to higher uncertainty. However, it is entirely normal for yield curves to be of many different shapes dependent on the perceptions of the markets on how interest rates may change in the future. Three main theories have been advanced to explain the term structure of interest rates or the yield curve: expectations hypothesis, liquiditypreference hypothesis and market-segmentation hypothesis. Although it is beyond the remit of this article to explain these theories, many textbooks on investments and financial management cover these in detail. Valuing bonds based on the yield curve Annual spot yield curves are often published by the financial press or by central banks (for example, the Bank of England regularly publishes UK government bond yield curves on its website). The spot yield curve can be used to estimate the price or value of a bond. Example 3 A company wants to issue a bond that is redeemable in four years for its par value or face value of $100, and wants to pay an annual coupon of 5% on the par value. Estimate the price at which the bond should be issued. The annual spot yield curve for a bond of this risk class is as follows: One-year 3.5% Two-year 4.0% Three-year 4.7% Four-year 5.5% The four-year bond pays the following stream of income: Year Payments $5 $5 $5 $105 This can be simplified into four separate bonds with the following payment structure: Year Bond 1 $5 Bond 2 $5 Bond 3 $5 Bond 4 $105 5 5 Each annual payment is a single payment in that particular year, much like a zero-coupon bond, and its present value can be determined by discounting each cash flow by the relevant yield curve rate, as follows: Bond 1 $5 x = $4.83 Bond 2 $5 x = $4.62 Bond 3 $5 x = $4.36 Bond 4 $105 x = $84.76 The sum of these flows is the price at which the bond can be issued, $ The yield to maturity of the bond is estimated at 5.41% using the same methodology as example 2. Some important points can be noted from the above calculation; firstly, the 5.41% is lower than 5.5% because some of the returns from the bond come in earlier years, when the interest rates on the yield curve are lower, but the largest proportion comes in Year 4. Secondly, the yield to maturity is a weighted average of the term structure of interest rates. Thirdly, the yield to maturity is calculated after the price of the bond has been calculated or observed in the markets, but theoretically it is term structure of interest rates that determines the price or value of the bond. Mathematically: Bond price = Coupon x (1+r 1 ) -1 + coupon x (1+r 2 ) coupon x (1+r n ) -n + redemption value x (1+r n ) -n Where r 1, r 2, etc are spot interest rates based on the yield curve and n is the number of time periods in which an amount of the coupon is paid and, finally, the value when the bond is redeemed. In this article it is assumed that coupons are paid annually, but it is common practice to pay coupons more frequently than once a year. In these circumstances, the coupon payments need to be reduced and the time period frequency needs to be increased. Estimating the yield curve There are different methods used to estimate a spot yield curve, and the iterative process based on bootstrapping coupon paying bonds is perhaps the simplest to understand. The following example demonstrates how the process works. 6 6 Example 4 A government has three bonds in issue that all have a face or par value of $100 and are redeemable in one year, two years and three years respectively. Since the bonds are all government bonds, let s assume that they are of the same risk class. Let s also assume that coupons are payable on an annual basis. Bond A, which is redeemable in a year s time, has a coupon rate of 7% and is trading at $103. Bond B, which is redeemable in two years, has a coupon rate of 6% and is trading at $102. Bond C, which is redeemable in three years, has a coupon rate of 5% and is trading at $98. To determine the yield curve, each bond s cash flows are discounted in turn to determine the annual spot rates for the three years, as follows: Bond A: $103 = $107 x (1+r 1 ) -1 r 1 = 107/103 1 = or 3.88% Bond B: $102 = $6 x x (1+r 2 ) -2 r 2 = [106 / ( )] 1/2-1= or 4.96% Bond C: $98 = $5 x $5 x x (1+r 3 ) -3 r 3 = [105 / ( )] 1/3 1 = or 5.80% The annual spot yield curve is therefore: Year % % % Discussion of other methods of estimating the spot yield curve, such as using multiple regression techniques and observation of spot rates of zero coupon bonds, is beyond the scope of the Paper P4 syllabus. As stated in the previous section, often the financial press and central banks will publish estimated spot yield curves based on government issued bonds. Yield curves for individual corporate bonds can be estimated from these by adding the relevant spread to the bonds. For example, the following table of spreads (in basis points) is given for the retail sector. Rating 1 year 2 year 3 year AAA AA A 7 7 Example 5 Mason Retail Co has a credit rating of AA, then its individual yield curve based on the government bond yield curve and the spread table above may be estimated as: Year 1 Year 2 Year % 5.37% 6.35% These would be the rates of return an investor buying bonds issued by Mason Retail Co would expect, and therefore Mason Retail Co would use these rates as discount rates to estimate the price or value of coupons when it issues new bonds. And Mason Retail Co s existing bonds market price would reflect its individual yield curve. Conclusion This article considered the relationship between bond prices, the yield curve and the yield to maturity. It demonstrated how bonds can be valued and how a yield curve may be derived using bonds of the same risk class but of different maturities. Finally it showed how individual company yield curves may be estimated. A following article will discuss how forward interest rates are determined from the spot yield curve and how they may be useful in determining the value of an interest rate swap. It will address the learning required in Sections F1 and F3 of the Paper P4 Syllabus and Study Guide. Shishir Malde is the examiner for Paper P4 Practice Set and Solutions #2 723G26/2012-10-10 Practice Set and Solutions #2 What to do with this practice set? Practice sets are handed out to help students master the material of the course and prepare for the final exam. YIELD CURVE GENERATION 1 YIELD CURVE GENERATION Dr Philip Symes Agenda 2 I. INTRODUCTION II. YIELD CURVES III. TYPES OF YIELD CURVES IV. USES OF YIELD CURVES V. YIELD TO MATURITY VI. BOND PRICING & VALUATION Introduction 3 A Chapter 3 Fixed Income Securities Chapter 3 Fixed Income Securities Road Map Part A Introduction to finance. Part B Valuation of assets, given discount rates. Fixed-income securities. Stocks. Real assets (capital budgeting). Part C Determination LOS 56.a: Explain steps in the bond valuation process. The following is a review of the Analysis of Fixed Income Investments principles designed to address the learning outcome statements set forth by CFA Institute. This topic is also covered in: Introduction ANALYSIS OF FIXED INCOME SECURITIES ANALYSIS OF FIXED INCOME SECURITIES Valuation of Fixed Income Securities Page 1 VALUATION Valuation is the process of determining the fair value of a financial asset. The fair value of an asset is Bond Valuation. Capital Budgeting and Corporate Objectives Bond Valuation Capital Budgeting and Corporate Objectives Professor Ron Kaniel Simon School of Business University of Rochester 1 Bond Valuation An Overview Introduction to bonds and bond markets» What Chapter 4 Valuing Bonds Chapter 4 Valuing Bonds MULTIPLE CHOICE 1. A 15 year, 8%, $1000 face value bond is currently trading at $958. The yield to maturity of this bond must be a. less than 8%. b. equal to 8%. c. greater than Bond Market Overview and Bond Pricing Bond Market Overview and Bond Pricing. Overview of Bond Market 2. Basics of Bond Pricing 3. Complications 4. Pricing Floater and Inverse Floater 5. Pricing Quotes and Accrued Interest What is A Bond? Bond: Management Accounting Financial Strategy PAPER P9 Management Accounting Financial Strategy The Examiner provides a short study guide, for all candidates revising for this paper, to some first principles of finance and financial management Based Term Structure of Interest Rates CHAPTER 13 The Term Structure of Interest Rates CHAPTER 13 Chapter Summary Objective: To explore the pattern of interest rates for different-term assets. The term structure under certainty Forward rates Theories Interest Rates and Bond Valuation Interest Rates and Bond Valuation Chapter 6 Key Concepts and Skills Know the important bond features and bond types Understand bond values and why they fluctuate Understand bond ratings and what they mean NATIONAL STOCK EXCHANGE OF INDIA LIMITED NATIONAL STOCK EXCHANGE OF INDIA LIMITED Capital Market FAQ on Corporate Bond Date : September 29, 2011 1. What are securities? Securities are financial instruments that represent a creditor relationship Duration and convexity Duration and convexity Prepared by Pamela Peterson Drake, Ph.D., CFA Contents 1. Overview... 1 A. Calculating the yield on a bond... 4 B. The yield curve... 6 C. Option-like features... 8 D. Bond ratings... Bonds and Yield to Maturity Bonds and Yield to Maturity Bonds A bond is a debt instrument requiring the issuer to repay to the lender/investor the amount borrowed (par or face value) plus interest over a specified period of time. 6. Debt Valuation and the Cost of Capital 6. Debt Valuation and the Cost of Capital Introduction Firms rarely finance capital projects by equity alone. They utilise long and short term funds from a variety of sources at a variety of costs. No Mid-Term Exam Practice Set and Solutions. FIN-469 Investments Analysis Professor Michel A. Robe Mid-Term Exam Practice Set and Solutions. What to do with this practice set? To help students prepare for the mid-term exam, two practice sets with Untangling F9 terminology Untangling F9 terminology Welcome! This is not a textbook and we are certainly not trying to replace yours! However, we do know that some students find some of the terminology used in F9 difficult to understand.: Fin 3312 Sample Exam 1 Questions Fin 3312 Sample Exam 1 Questions Here are some representative type questions. This review is intended to give you an idea of the types of questions that may appear on the exam, and how the questions might Debt Instruments FIN 472 Fixed-Income Securities Debt Instruments Professor Robert B.H. Hauswald Kogod School of Business, AU The Most Famous Bond? Bond finance raises the most money fixed income instruments types of bonds CHAPTER 10 BOND PRICES AND YIELDS CHAPTER 10 BOND PRICES AND YIELDS 1. a. Catastrophe bond. Typically issued by an insurance company. They are similar to an insurance policy in that the investor receives coupons and par value, but takes Understanding Fixed Income Understanding Fixed Income 2014 AMP Capital Investors Limited ABN 59 001 777 591 AFSL 232497 Understanding Fixed Income About fixed income at AMP Capital Our global presence helps us deliver outstanding Practice Set #2 and Solutions. FIN-672 Securities Analysis & Portfolio Management Professor Michel A. Robe Practice Set #2 and Solutions. What to do with this practice set? To help MBA students prepare for the assignment and the exams, Review for Exam 1. Instructions: Please read carefully Review for Exam 1 Instructions: Please read carefully The exam will have 21 multiple choice questions and 5 work problems. Questions in the multiple choice section will be either concept or calculation FINANCIAL AND INVESTMENT INSTRUMENTS. Lecture 6: Bonds and Debt Instruments: Valuation and Risk Management AIMS FINANCIAL AND INVESTMENT INSTRUMENTS Lecture 6: Bonds and Debt Instruments: Valuation and Risk Management After this session you should Know how to value a bond Know the difference between the term Alliance Consulting BOND YIELDS & DURATION ANALYSIS. Bond Yields & Duration Analysis Page 1 BOND YIELDS & DURATION ANALYSIS Bond Yields & Duration Analysis Page 1 COMPUTING BOND YIELDS Sources of returns on bond investments The returns from investment in bonds come from the following: 1. Periodic 2015 Exam 2 Syllabus Financial Mathematics Exam 2015 Exam 2 Syllabus Financial Mathematics Exam The syllabus for this exam is defined in the form of learning objectives that set forth, usually in broad terms, what the candidate should be able to do 14: BOND PRICES AND YIELDS CHAPTER 14: BOND PRICES AND YIELDS PROBLEM SETS 1. The bond callable at 105 should sell at a lower price because the call provision is more valuable to the firm. Therefore, its yield to maturity Investment Analysis (FIN 670) Fall Homework 3 Investment Analysis (FIN 670) Fall 2009 Homework 3 Instructions: please read carefully You should show your work how to get the answer for each calculation question to get full credit You should make 5: Valuing Bonds FIN 302 Class Notes Chapter 5: Valuing Bonds What is a bond? A long-term debt instrument A contract where a borrower agrees to make interest and principal payments on specific dates Corporate Bond Quotations 7: FIXED-INCOME SECURITIES: PRICING AND TRADING CHAPTER 7: FIXED-INCOME SECURITIES: PRICING AND TRADING Topic One: Bond Pricing Principles 1. Present Value. A. The present-value calculation is used to estimate how much an investor should pay for a bond; Bond Valuation. What is a bond? Lecture: III 1 What is a bond? Bond Valuation When a corporation wishes to borrow money from the public on a long-term basis, it usually does so by issuing or selling debt securities called bonds. A bond Learning Curve September 2005. Understanding the Z-Spread Moorad Choudhry* Learning Curve September 2005 Understanding the Z-Spread Moorad Choudhry* A key measure of relative value of a corporate bond is its swap spread. This is the basis point spread over the interest-rate swap Current liabilities and payroll Chapter 12 Current liabilities and payroll Current liabilities are obligations that the business has to discharge within 12 months or its operating cycle if longer than one year. Obligations that are due 2. Determine the appropriate discount rate based on the risk of the security Fixed Income Instruments III Intro to the Valuation of Debt Securities LOS 64.a Explain the steps in the bond valuation process 1. Estimate the cash flows coupons and return of principal 2. Determine the 10. Fixed-Income Securities. Basic Concepts 0. Fixed-Income Securities Fixed-income securities (FIS) are bonds that have no default risk and their payments are fully determined in advance. Sometimes corporate bonds that do not necessarily have certain Chapter Nine Selected Solutions Chapter Nine Selected Solutions 1. What is the difference between book value accounting and market value accounting? How do interest rate changes affect the value of bank assets and liabilities under the Econ 330 Exam 1 Name ID Section Number Econ 330 Exam 1 Name ID Section Number MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) If during the past decade the average rate of monetary growth Analysis of Deterministic Cash Flows and the Term Structure of Interest Rates Analysis of Deterministic Cash Flows and the Term Structure of Interest Rates Cash Flow Financial transactions and investment opportunities are described by cash flows they generate. Cash flow: payment Hot Topics in Financial Markets Lecture 1: The Libor Scandal Hot Topics in Financial Markets Lecture 1: The Libor Scandal Spot and Forward Interest Rates Libor Libor-Dependent Financial Instruments The Scandal 2 Spot Interest Rates Bond Market The yield on a bond CHAPTER 16: MANAGING BOND PORTFOLIOS CHAPTER 16: MANAGING BOND PORTFOLIOS PROBLEM SETS 1. While it is true that short-term rates are more volatile than long-term rates, the longer duration of the longer-term bonds makes their prices and their Asset Valuation Debt Investments: Analysis and Valuation Asset Valuation Debt Investments: Analysis and Valuation Joel M. Shulman, Ph.D, CFA Study Session # 15 Level I CFA CANDIDATE READINGS: Fixed Income Analysis for the Chartered Financial Analyst Program: Fixed Income: Practice Problems with Solutions Fixed Income: Practice Problems with Solutions Directions: Unless otherwise stated, assume semi-annual payment on bonds.. A 6.0 percent bond matures in exactly 8 years and has a par value of 000 dollars. What is a financial instrument? RELEVANT TO ACCA QUALIFICATION PAPERS F7 AND P2 What is a financial instrument? Let us start by looking at the definition of a financial instrument, which is that a financial instrument is a contract that Financial Mathematics Exam 2014 Exam 2 Syllabus Financial Mathematics Exam The purpose of the syllabus for this examination is to develop knowledge of the fundamental concepts of financial mathematics and how those concepts are Global Financial Management Global Financial Management Bond Valuation Copyright 999 by Alon Brav, Campbell R. Harvey, Stephen Gray and Ernst Maug. All rights reserved. No part of this lecture may be reproduced without the permission Chapter 11. Stocks and Bonds. How does this distribution work? An example. What form do the distributions to common shareholders take? Chapter 11. Stocks and Bonds Chapter Objectives To identify basic shareholder rights and the means by which corporations make distributions to shareholders To recognize the investment opportunities in Answers to Review Questions Answers to Review Questions 1. The real rate of interest is the rate that creates an equilibrium between the supply of savings and demand for investment funds. The nominal rate of interest is the actual Fixed Income Portfolio Management. Interest rate sensitivity, duration, and convexity Fixed Income ortfolio Management Interest rate sensitivity, duration, and convexity assive bond portfolio management Active bond portfolio management Interest rate swaps 1 Interest rate sensitivity, duration, Yield Measures, Spot Rates & Forward Rates Fixed Income Yield Measures, Spot Rates & Forward Rates Reading - 57 1 Sources of Return Coupon interest payment: Periodic coupon interest is paid on the par value of the bond FIN 534 Week 4 Quiz 3 (Str) Click Here to Buy the Tutorial- str/ For more course tutorials visit Which of the following CALCULATOR TUTORIAL. Because most students that use Understanding Healthcare Financial Management will be conducting time CALCULATOR TUTORIAL INTRODUCTION Because most students that use Understanding Healthcare Financial Management will be conducting time value analyses on spreadsheets, most of the text discussion focuses 3st lecture IES, UK October 7, 2015 Outline Bond Characteristics 1 Bond Characteristics 2 Bond Characteristics Government bond listing Rate Maturity mo/yr Bid Asked Chg Ask yld 3.000 July 12 108:22 108:23-20 Chapter 3. Fixed Income Securities IE 5441 1 Chapter 3. Fixed Income Securities IE 5441 2 Financial instruments: bills, notes, bonds, annuities, futures contracts, mortgages, options,...; assortments that are not real goods but they carry Practice Set #1 and Solutions. Bo Sjö 14-05-03 Practice Set #1 and Solutions. What to do with this practice set? Practice sets are handed out to help students master the material of the course and prepare for the final exam. These sets Figure 10.1 Listing of Treasury Issues CHAPER 10 Bond Prices and Yields 10.1 BOND CHARACERISICS Bond Characteristics reasury Notes and Bonds Face or par value Coupon rate Zero coupon bond Compounding and payments Accrued Interest Indent Equity-index-linked swaps Equity-index-linked swaps Equivalent to portfolios of forward contracts calling for the exchange of cash flows based on two different investment rates: a variable debt rate (e.g. 3-month LIBOR) and the Zero-Coupon Bonds (Pure Discount Bonds) Zero-Coupon Bonds (Pure Discount Bonds) The price of a zero-coupon bond that pays F dollars in n periods is F/(1 + r) n, where r is the interest rate per period. Can meet future obligations without reinvestment I. Readings and Suggested Practice Problems. II. Risks Associated with Default-Free Bonds Prof. Alex Shapiro Lecture Notes 13 Bond Portfolio Management I. Readings and Suggested Practice Problems II. Risks Associated with Default-Free Bonds III. Duration: Details and Examples IV. Immunization Dick Schwanke Finite Math 111 Harford Community College Fall 2013 Annuities and Amortization Finite Mathematics 111 Dick Schwanke Session #3 1 In the Previous Two Sessions Calculating Simple Interest Finding the Amount Owed Computing Discounted Loans Quick Review of The Time Value of Money (contd.) The Time Value of Money (contd.) February 11, 2004 Time Value Equivalence Factors (Discrete compounding, discrete payments) Factor Name Factor Notation Formula Cash Flow Diagram Future worth factor (compound Lecture 2 Bond pricing. Hedging the interest rate risk Lecture 2 Bond pricing. Hedging the interest rate risk IMQF, Spring Semester 2011/2012 Module: Derivatives and Fixed Income Securities Course: Fixed Income Securities Lecturer: Miloš Bo ović Lecture outline Term Structure of Interest Rates Appendix 8B Term Structure of Interest Rates To explain the process of estimating the impact of an unexpected shock in short-term interest rates on the entire term structure of interest rates, FIs use
http://docplayer.net/4979449-Bond-valuation-and-bond-yields.html
CC-MAIN-2018-13
refinedweb
4,723
58.01
Robert Bosch Interview Experience 2019(On-campus) I attended the placement drive of RBEI on Aug 2019 in our college G.L. Bajaj Institute of Technology & Management, Gr, Noida. Almost 500 students appeared for this drive. The profile offered for CSE students was Associate Software Engineer. Round 1: Online test The test consisted of Apt+Logical Reasoning+Output based questions. Level of Apt and Reasoning was easy. You can solve it easily with some practice. Total time is around 60 mins. There is also a negative marking of 0.25 marks per question. There was also 2 coding questions and the time given was 30 mins. I did one question completely and was not able to attempt the other due to time limit. The result came in the evening through mail and I was shortlisted for the interview round scheduled for the next day. 120 students were shortlisted for the next round. Round 2: Technical Interview There were 18 panelists for interview including both for CS and EC. This round was the most difficult in all the 3 rounds. Mine interview lasted for approx 2 hours.He asked numerous questions from my projects, coding questions, DBMS, OS questions, microprocessor questions, C & C++ questions. ->Questions on Project: Idea behind project, technologies used with thorough explanation. ->Coding ques: Searching algos, Implement stack (push, pop funs) in C, Exception handling in C++ (as I mentioned C & C++ in my resume), Multithreading in C++, Call by value & reference in detail. ->DBMS: Normalization with types, ACID properties. ->Operating System: Semaphores, Mutex, Monitors, Thrashing, Deadlock with causes and preventive measures. ->C & C++ questions: Advantages of C over C++, Explain namespace in c++, Virtual in C++, Access specifiers and some more conceptual questions. I almost answered all questions except one or two. The panelist was very humble and listened to all my answers patiently with a smile. Around 40 students cleared this round. Round 3: Hr interview After a wait for 30 mins, results came and I was shortlisted for the next round. My advice is do not take this round lightly as lot of my friends were eliminated from this round even after qualifying the tech interview. The interviewer was polite and asked me to relax and asked few questions such as Tell me about urself, tell about ur family, Why do u want to join Bosch, how much serious are you about Bosch and some other questions. The interview lasted for 10 mins. The final result came on the next day through mail and I was selected. Advice: Prepare the basics of programming languages, coding questions and subjects. Believe in yourself and most importantly be confident and you will get selected. All the best!!!
https://www.geeksforgeeks.org/robert-bosch-interview-experience-on-campus/
CC-MAIN-2022-40
refinedweb
449
66.74
- Encapsulation - Class Access Modifiers - Other Modifiers - Class Constructors - Class Destructors - this In the previous article, we discussed classes in their basic form. At this point, we've just seen the tip of the iceberg. Here we'll explore what more we can do with them. Encapsulation As mentioned before, encapsulation is the organizing of related items (such as fields, properties, methods, etc) within a logical unit. This process is more than combining members in a class. Its purpose is more about "protecting" members of a class and the ability to hide information from other parts of the program. We can use the above modifiers to assist in that effort. Class Access Modifiers Objects can be modified with special keywords to change their accessibility. These modifiers change the scope of what we can do with the object and how other namespaces can access them, if at all. Namespaces are logical collections of objects that provide a hierarchical organization for classes, structs, functions, variables, etc in a project. Typically a single class or many related classes will be a part of a namespace, or a subsection of an existing namespace. More information at Microsoft Public Objects marked as public can be accessed by any other code, whether it's in the same class or another that references it. There are no restrictions on accessing them. class Coords { public int x; public int y; } static void Main() { Coords point = new Coords(); point.x = 40; point.y = 80; // We can access x & y directly because they are public } Private Private objects are only accessible by the class or struct that it directly declared within. If an access modifier (e.g. private or public) is not specified, the object is private by default. class Dog { private string name; public string Name { get { return name; } set { name = value; } } } static void Main() { Dog doggo = new Dog(); // Cannot do this because 'name' is private string dog_name = doggo.name; // Instead access 'name' indirectly via the Name property string dog_name = doggo.Name; // And we can use the same property for setting the value on 'name' doggo.Name = "Doggo"; } Why are we doing this? The answer to this question is called Abstraction. While encapsulation is the process of organizing items within a logical unit, abstraction takes it a step further by hiding unnecessary details and providing properties and methods in order for the programmer to implement more complex logic on top of it. One example of a real world abstraction is a bank transaction. You can make deposits, withdraw money, check your balance, pay your bills, etc. There are processes behind each of these activities but you don't have to worry about it, especially with an online bill-pay system: You know there's a process of writing a check and mailing it to your cable company but you don't have to do that part. You just fill out the form on the web site and it's getting taken care of. The major leg-work has been abstracted away. This concept is very noticeable in coding frameworks, where we can write out an application without needing to code the implementation of the finer details like database connections, URL routing, and DOM manipulation. Abstraction separates the interface from the implementation. In OOP, we don't want any class or namespace to be able to change a class field's value. We want those changes to come through a common channel, like a property or method, so all changes are uniform and allows for regulation of data, verification, and security. Auto-Implemented Properties If there is no additional logic required for a property other than a getter & setter, we can use an auto-implemented property to save a few lines of code. // Instead of class Dog { private string name; public string Name { get { return name; } set { name = value; } } } // Use this class Dog { public string Name { get; set; } } Protected An objected marked as protected is only accessible within its class and any class derived from it. Further in this series, we'll explore classes that are made from other classes. The protected keyword allows a class member to be a part of those as well. Sealed A sealed class prevents other classes from inheriting from it, quite the opposite of the protected modifier. Summary of Access Modifiers Other Modifiers Constants & Read-only Variables You can use the const keyword to indicate that the variable is a constant, which is resolved at compile-time. That is - when the program is compiled, the const declared variable is replaced with the value it had been assigned instead. Constants are fairly usable for things such as standard paths or custom values that are easier to read in the code as a name versus a number value. const string PUBLIC_URL = ""; const int ACCESS_LVL_ADMIN = 5; Use the readonly modifier to prevent a variable from being modified after construction. Readonly and constants differ in 3 major ways: - A constant must be initialized when it is declared. A readonly field does not need to be. - A readonly field value can be changed in a constructor. - A readonly field can be assigned a value that is a result of a calculation. Constants cannot. class Age { readonly int year; Age(int year) { this.year = year; } void ChangeYear() { year = 1942; // This won't work; it will give a compile error. } } Static Variables and methods marked as static belong only to the class, not the object that is created. Within memory, there is only one copy of the static member. This member must be accessed by the class, not the object. In the example below in the Main() method, try changing Cat.Meow(); to c2.Meow(); and notice the error that is reported. class Cat { public static int count = 0; public static void Meow() { Console.WriteLine("Meow"); } public Cat() { count++; } } public static void Main() { Cat c1 = new Cat(); Cat c2 = new Cat(); Console.WriteLine(Cat.count); // 2 Cat.Meow(); // Meow } Static classes can only contain static members and cannot be instantiated into an object. Common examples of static classes are the Main and Math classes. Constant members (initialized by const) are static by definition. Class Constructors A constructor is a method that is defined within a class (or struct) and is invoked upon instantiation. It has the exact same name as its class, has no return type, and is always public. class Person { public string Name { get; set; } // v-- this is the constructor public Person() { Console.WriteLine("Hello there!"); } } In this example, every time a Person object is created, "Hello there!" will be written to the console. Constructors can be used for setting intial values via parameters. class Person { private string name; public Person(string _name) { name = _name; } public string getName() { return name; } } public static void Main() { Person bob = new Person("Bob"); Console.WriteLine(bob.getName()); // outputs: "Bob" } Class Destructors A destructor is a method that is defined within a class and is invoked when an object is destroyed. It has the exact same name as its class, like a constructor, except that it is prefixed with a tilde (~). class Person() { ~Person() { // things to do when an object is destroyed } } this The this keyword can be used inside a class to refer to the current instance of the class (the current object). It also can be used to differentiate between method parameters and class fields if they have the same name (such as in a constructor). If you're still confused how on what this refers to, go outside its code block (where its braces { }'s are) one level. See below: class Person { public string name { get; set; } public Person(string name) { // using this to distinguish between the class variable name & the parameter name this.name = name; } public void GetDetails() { Console.WriteLine("Name: {0}", name); // using this to pass the current instance of this class to another class method Console.WriteLine("Favorite Number: {0}", Stuff.MakeNumberFromName(this)); } } class Stuff { // This method takes the name from a Person object that is passed to it // and multiplies its length by 10. public static int MakeNumberFromName(Person p) { return p.name.Length * 10; } } public static void Main() { Person Bob = new Person("Bob"); Bob.GetDetails(); // outputs: // Name: Bob // Favorite Number: 30 } The constructor parameter "name" is assigned to class property "name" using this.name to specifically tell which one you are talking about in the code. Also we're using this as an argument to the MakeNumberFromName method in the Stuff class (which is separate from the Person class). It may sound like we're sending the Person class to it but we're not. We are sending the current instance of the class, which when the program is run, the current instance is the Bob object we created from the Person class. That's a handful! Now we know how to apply keywords to classes, variables, objects, etc to control how they are accessed and used. There is a lot to learn and we'll be getting to the fun parts soon but this foundation will show its purpose as we learn more about classes. Discussion (0)
https://dev.to/aromig/c-oop-class-modifiers-51a
CC-MAIN-2021-39
refinedweb
1,511
62.98
From: Christopher Kohlhoff (chris_at_[hidden]) Date: 2006-06-25 23:23:56 Hi Peter, Peter Petrov <ppetrov_at_[hidden]> wrote: > There is one thing that caught my eye. In the changelog you > have the following comment: > >> * Resolver replaces ipv4::host_resolver. >> >> ... >> >> ip::tcp::resolver resolver(io_service); > > Why is "resolver" in the "ip::tcp" namespace? A DNS resolver > certainly has nothing to do with the TCP protocol. It should > be in the "ip" namespace instead. Unlike the old host_resolver class, which would resolve a host name into an address, the new resolvers turn host name and service name into a list of endpoints. This interface is based on getaddrinfo() function. We now have: - ip::tcp::resolver, which returns a list of ip::tcp::endpoint objects - ip::udp::resolver, which returns a list of ip::udp::endpoint objects Resolvers for other protocols, can (if supported by getaddrinfo on the target platform) be created by instantiating the asio::basic_resolver<> template on an appropriately defined protocol class. So, ip::tcp::resolver is very much specific to TCP, but basic_resolver<> isn't - it's not even specific to IP (in theory, anyway). Cheers, Chris Boost list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
http://lists.boost.org/Archives/boost/2006/06/106801.php
crawl-001
refinedweb
214
58.28
I recently convert a ASP.NET 1.1 web app to 2.0 and included MasterPages to define a consistent look, menu etc but ran into a problem with the <meta name="DownloadOptions" content="noopen"/> code. Our site allows users to export data to Excel and text files and also upload pictures and some other file types. Problem is you need to have the <meta name="DownloadOptions" content="noopen"/> tag in the html <header> which exist in the MasterPage and as you know content pages can not contain top level html content. For those of you who don't know what <meta name="DownloadOptions" content="noopen"/> does, it modifes the ShowDialog popup and removes the "Open" button so the user only see's the "Save" and "Cancel;" button. So the problem is, how do I allow users to export to Excel and text files (without the option of "Open" and upload the other files. The way I decided to go is I created a custom attribute class called "ShowDialogNoOpen" and used this attribute on every class in my application that allows exporting files (I don't have an instance where I export and allow the used to upload in one class). Next I put code in the MasterPage file that is called during the Page_Load event that checks if the current "this.Page" has this attribute. If the class does have this attribute I wrote a method that emits a new meta tag. The code is pasted below that shows this. This is the custom attribute class public class ShowDiaglogNoOpen: Attribute {public bool ShowOpen() {return false;} } In the MasterPage I created a method that looks like private void CheckForAttribute() { MemberInfo info = this.Page.GetType(); // Instead of gettting ALL attributes I only want to search for one object[] attr = info.GetCustomAttributes(typeof(ShowDialogNoOpen),true); // Check if anything was returned if(attr != null && attr.GetLength(0) >0) EmitMetaTag(); } private void EnitMetaTag() { // New class for creating meta tags HtmlMeta meta = new HtmlMeta(): //Use the Name property to specify the meta tag we want to use meta.Name = "DownloadOptions"; //Add the Content param meta.Content = "noopen"; // add this new meta tag to the page this.Page.Header.Controls.Add(meta); So, now to stop allowing users the "open" button all I have to do is add [ShowDialogNoOpen] to the class that uses this masterpage and all is well.
http://geekswithblogs.net/Ramblings/archive/2009/02/02/meta-namedownloadoptions-contentnoopen.aspx
CC-MAIN-2020-24
refinedweb
394
60.45
Check if a given string is NaN in Python Hi guys, today we will learn about NaN. In addition, we will learn about checking whether a given string is a NaN in Python. You will be wondering what’s this NaN. So let me tell you that Nan stands for Not a Number. It is a member of the numeric data type that represents an unpredictable value. For example, Square root of a negative number is a NaN, Subtraction of an infinite number from another infinite number is also a NaN. so basically, NaN represents an undefined value in a computing system. How to Check if a string is NaN in Python We can check if a string is NaN by using the property of NaN object that a NaN != NaN. Let us define a boolean function isNaN() which returns true if the given argument is a NaN and returns false otherwise. def isNaN(string): return string != string print(isNaN("hello")) print(isNaN(np.nan)) The output of the following code will be False True We can also take a value and convert it to float to check whether it is NaN. For these, we import the math module and use the math.isnan() method. See the below code. def isnan(value): try: import math return math.isnan(float(value)) except: return False print(isnan('hello')) print(isnan('NaN')) print(isnan(100)) print(isnan(str())) Output: False True False False A NaN can also be used to represent a missing value in computation. See the below code: import numpy as np l=['abc', 'xyz', 'pqr', np.nan] print(l) l_new=['missing' if x is np.nan else x for x in l] print(l_new) Output: ['abc', 'xyz', 'pqr', nan] ['abc', 'xyz', 'pqr', 'missing'] Also read:
https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/
CC-MAIN-2022-27
refinedweb
295
73.98
Hi folks, how are we all... i just started to look at python as of yesterday and seems quite powerfull and am slowly learning one thing i hate and have always hated is double for loops ( thats what i think i need here) hoping someone can help me as the code stands at the moment as soon as a program is missing it exits. what i would like it to do is cycle thru the program list and print all the missing programs then exit only if 1 or more are missing Many thanks and lool forward to helping you guys some day.Many thanks and lool forward to helping you guys some day.PHP Code: #!/usr/bin/env python import os import sys # programs needed progs = ['reformime','unzip'] # test for programs for prog in progs: if os.system('which ' + prog) != 0: print 'Could not find ' + prog sys.exit() else: pass print 'next'
http://forums.devshed.com/python-programming-11/loop-help-71156.html
CC-MAIN-2016-44
refinedweb
153
75.84
One. Launch code in new window » Download code as text file » Running this page, the initial output is: But, once I click on the "Find Hotties" link, the output gets changed to:? Download Code Snippet ZIP File Comments (7) | Post Comment | Ask Ben | Permalink | Other Searches | Print Page [ local search ] jquery custom selectors Ask Ben: Creating An Archive Folder / File List (Part II) Referring To The Proper Row Of The Outer CFLoop (With Nested CFLoops) Sweet man! You're really digging jQuery from what I see! :) Posted by Rey Bango on Feb 23, 2007 at 6:32 PM Hey Ben, cool for showing how easy it is to make a custom selector, but shouldn't you use a namespace to add custom/arbitrary attributes to existing tags? Otherwise your code wont validate as xhtml. Posted by Jordan Clark on Feb 23, 2007 at 6:54 PM And how do you declare namespaces Jordan? Posted by William from Lagos on Feb 24, 2007 at 6:48 AM . Posted by Ben Nadel on Feb 24, 2007 at 10:49 AM Posted by Glen Lipka on Feb 25, 2007 at 6:38 PM --Otherwise your code wont validate as xhtml. But who cares what a validator somewhere thinks? It affects nothing. Posted by stylo on Feb 27, 2007 at 5:24 AM Stylo, While I would agree with you in theory, in practice, a surprising number of clients will require that their site validates as XHTML. But other than client needs, agreed, it affects nothing. Posted by Ben Nadel on Feb 27, 2007 at 7:26 AM
http://www.bennadel.com/blog/547-jQuery-Custom-Selectors-Holy-Cow-That-Is-So-Badass-.htm
crawl-001
refinedweb
264
77.06
Microsoft announced Community Technology Preview (CTP) of Roslyn project during BUILD 2011. I am really excited about the Roslyn project (and I will tell you why soon…). Roslyn? Isn’t it name of a city? Well you are right and many of Microsoft product code names are now based on city/town names mainly due to copyright issue. If you don’t have idea and you love to dig in languages/compilers, it’s a MUST SEE for you. The concept is simple that traditionally compilers are kind of black box thing where we provide source files as input and it provide assemblies/DLLs/exe as output. The Roslyn project is all about opening the black box of compiler and allowing us to get internal language object model and things such as syntax tree etc. through Compiler APIs. The objective of the project is to rewrite the VB and C# compilers and language services in managed code. See slide below from Anders’ talk at BUILD 2011. Interested? Check out for project overview document and to download the available bits. For further introduction, please read Introducing the Microsoft “Roslyn” CTP on Visual Studio blog. Roslyn APIs Roslyn APIs exposes four collection of APIs. You can read details of each API in project overview document (from where the image below is taken). The Services API have dependency over Visual Studio SDK and contains Visual Studio IDE features, such as intellisense, code refactoring and formatting etc. Before reading on, if you haven’t installed Roslyn binaries, go ahead download them and skim through overview document. Exciting Part? If you have been kind of student, who enjoyed compiler construction course(s) during undergrad and really enjoy in going deep into mechanics, then you would definitely love exploring Roslyn APIs. This is because the rewriting of compiler and exposed APIs would allow you to understand the syntactical and semantic model of your code. With this you can not only generate code on fly but also REPL (read-eval-print-loop) operations can be done. Plus you can visualize/parse your existing code and see what syntax tree it has generated. For example, consider the following code snippet using Roslyn API: SyntaxTree tree = SyntaxTree.ParseCompilationUnit( @"using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); If you traverse/print tree or use Roslyn Syntax Visualizer control, you would get to know the underlying syntax tree structure and its components. Using the above code, the syntax tree has parsed the code and decomposed it into tokens, nodes, and trivia. The debugger visualizer (see image on left) will help you understand the syntax tree generated. This debugger is of great aid if you are developing any IDE extension using Roslyn API. Please note that syntax visualizer control is available with samples, along with source code, in Samples folder created when you downloaded Roslyn bits. Currently there are some known issues with this control and workaround (code modification) has been explained at Roslyn forum “Known Limitations and Unimplemented Language Features”. Another fun point is Workspace API which allows you to programmatically do stuff with your solution, projects, assemblies and documents. As a very simple example, consider the following code snippet: IWorkspace workspace = Workspace.LoadSolution(@"<%PROVIDE PATH OF .SLN FILE"); ISolution solution = workspace.CurrentSolution; foreach (IProject project in solution.Projects) { Debug.WriteLine(project.DisplayName); foreach (IDocument document in project.Documents) { Debug.WriteLine(document.DisplayName); } } And if you are interested to create visual studio extension for developers productivity, Roslyn Service APIs are going to provide you breakthrough. Try exploring Service APIs project using “Roslyn Installed Templates”. Surely, you can VS extensions directly using SDK but with the power of Roslyn, you can get into the code tree and provide intelligent refactoring and productivity aids to developer. Do I need Roslyn? You need to explore Roslyn APIs, - if you do a lot of heavy lifting with Reflection in the .NET Framework. At my previous employer, when we used to develop Form Designer for BPM Suite, much percent of our code was based on Reflection due to dynamic nature of the application - Already using Visual Studio SDK - Interested to understand compiler services - Interested to create Visual Studio extensions But there is much more in Roslyn and I would try to share my experience of whatever I experiment with Roslyn APIs in spare time. If you are working on Roslyn, please do share your experience in comments below.
http://adilmughal.com/blog/2012/03/why-am-i-excited-about-roslyn-project/
CC-MAIN-2018-51
refinedweb
739
53.92
- Our goal - Major Steps - Creating a project - Calculator concept - Creating an editor for Calculator - Input Fields - Output fields - Adding expressions support - Extending Expressions concept MPS Home » JetBrains Home » Recording of the Tutorial » The calculator language tutorial Introduction This tutorial will guide through many areas of language design in MPS. You'll define an abstract structure of a simple standalone language, design editors for them, constrain types, scopes and finally prepare a generator that generates Java code. Depending on your prior exposure to MPS, the tutorial may require about a day of your time to complete. The tutorial primarily targets language designers, who need to evaluate MPS and want to see more than just a bare-bone example. Basic knowledge of Java will help you complete the generator more easily. Have you tried the Fast Track to MPS tutorial yet? If you are completely new to MPS, we highly recommend you to follow the instructions in the Fast Track to MPS tutorial. It will guide you through the very basics of MPS and projectional editing, serving you new information gradually in digestible chunks, so that when you eventually come back to this Calculator tutorial, you will have the knowledge to benefit from the tutorial best. The easy Shapes tutorial for quick overview Additionally, consider trying the Shapes introductory tutorial, if you only have an hour or two to spend and want to walk the easy path first. You will get your toes wet, but you won't have to swim just yet. Our goal In this tutorial we will create a calculator language. The language will define a couple of simple entities that describe some sort of computation. We call these entities calculators. A calculator has a set of input and output values, plus it defines one or more math formulas to calculate output values using the available input values. We take an artificial use-case: a Java/PHP Developer who wants to quickly calculate her earnings by simply entering the number of hours spent on Java and PHP projects. The resulting application would look as follows (Output value is calculated automatically from the hour values): Our goal is to make it possible for our Developer to create such an application by writing only the following 4 lines of code ("10" and "5" are just constants that denote corresponding payment rates for Java and PHP): calculator MySalary input PHP Hours input Java Hours output Java Hours*10 + PHP Hours*5 The whole Swing-based application will be generated from these four lines of DSL code. You may also watch this tutorial as a screen-cast. Episode 1 covers the tutorial core, while episode 2 focuses on constraints and type-system definitions. PrerequisitiesThe experience shows that if you want to avoid unnecessary glitches on your way throughout this tutorial, you need to familiarize yourself with the MPS projectional editor. If you followed the Fast Track to MPS tutorial, you are well prepared. If you didn't, please consider at least learning the basic editor keyboard shortcuts at the Commanding the Editor page or checking up the quick tips listed in the How to use MPS editor appendix of this page. Major Steps In this tutorial, we: - Create a language which allows us to implement a calculator using the previously mentioned syntax. Our language will define the basic logical concepts that comprise a calculator, their construct specifications, relationships, and individual behavior. - Create a generator that will define the rules for building swing applications from calculators. - Implement a calculator in our language. It might seem that language creation takes too much effort for such a simple application. Obviously, it can be created by means of any existing language much faster than with MPS. However, our goal is to demonstrate how MPS can help when you need a very specific functionality that is supposed to be re-implemented multiple times. It also shows how straight-forward and simple development can be, when one uses a proper language for a particular task. In our case, people who only know how to write simple expressions can create such calculators, without knowing how to use Swing. Creating a project A project in MPS may consist of languages, solutions, or both. A bit further, you will see how it is structured. First, we start MPS. You see a welcome screen with different options: you can quickly open samples from here, start browsing documentation, etc. Since we are going to create a new language, we need to create a new project first. Click File | New Project. The wizard appears: Let's name our project "calculator": Now we need to name the language (DSL) that we want to get created: We recommend the following naming convention for your languages. This convention is similar to that used for Java packages: companyName.meaningful.name. So let's name our language jetbrains.mps.tutorial.calculator. Additionally, check the Create sandbox solution checkbox. A solution is a set of models written in specified languages. We will be using the solution to test our newly created language right away. Ideally, you would have separate projects for languages and solutions that use those languages. However, we recommend that your project contains a "sandbox" solution for the language you are developing, so that you can instantly test your new language by writing sample applications. Now it is the time to hit OK. In the Project View that opens, expand the jetbrains.mps.tutorial.calculator tree node marked with the language sign ( ): The "S"-marked tree node above it ( ) represents our solution, and the Modules Pool node ( ) contains a collection of all available languages and solutions, for your reference. We'll take a closer look at these items in further chapters. Let us first explore the structure of the language node. This will also help us realize the basic ideas behind MPS. We see the child nodes of the language marked with the "M" diamond-shaped icon. They are called aspect models. Unlike other languages where programs are usually stored in text files, in MPS they are stored inside models. Each model represents a tree of nodes, where each node may have a parent, child nodes, properties and references to other nodes. Each node is defined by its concept. Aspect models comprising our language describe different features of a language (their icons differ by color). For now, we consider the 4 basic aspect models that we will need for our language: - structure — describes the syntax of a language - editor — describes how a model written in the language looks in the editor - constraints — describes things like which name is appropriate for a node, which variable a variable reference can point to, etc - type system — describes how to compute types of nodes Calculator concept Let's start working on our language. First, we need to create a top level concept, in our case calculator. Each instance of this concept will contain input and output fields. To create a concept, right click the structure aspect model and choose New | concept: The concept declaration opens in the editor: A concept declaration defines the class of nodes and specifies the structure of nodes in that class. If you have worked with XML schemas or DTD, it can serve as a good analogy to help you understand the approach used in MPS in defining node concepts and their individual elements. Limited analogy can be drawn with objects and classes in object oriented languages. Like class declares structure of its instances with fields, methods and other members, concept specifies its instances' structure with property, reference and children declarations. A node can have the following elements, which are defined in the corresponding sections of the concept declaration: - Properties store primitive values inside a node. For example, you can define a node's name as a property. - References store links to other nodes. For example, we can use them to store a reference to a local variable. - Children store aggregated nodes, i.e. nodes which are physically contained inside a current node. For example, method declaration aggregates its return type and arguments. In our case these would be input and output fields. - Other sections are quite advanced and we won't discuss them in this tutorial. You can read about them in the MPS User's Guide. Concept declarations form an inheritance hierarchy. By default, every concept extends the BaseConcept concept (you can see it immediately after the extends keyword). You can, however, specify another direct parent instead as necessary. If a concept extends another, it inherits all properties, children, and references from its parent. To edit an element in the editor, position the caret at its placeholder surrounded by grey < > symbols. To quickly navigate between the placeholders, press Tab/Shift+Tab. When within a placeholder, don't forget to use Ctrl+Space, as in most cases MPS would have a list of relevant suggestions for auto-completion. Ctrl+Space is applicable almost everywhere in MPS editor. If you simply want to know what can be entered at a particular place, just press Ctrl+Space. Possible options will be displayed in the completion menu. You may consider checking out an introductory screen-cast covering the fundamental principals of working with the MPS projectional editor. So, let's name our concept Calculator. Press Tab until you get to the 'instance can be root' placeholder, and press Ctrl+Space to set its value to true. You can also type true directly, you don't have to press Ctrl+Space everywhere. This will let us create Calculator instances through the Create Root Node menu item in the Project View (right as we did for our Calculator concept itself): We will further need to reference our calculators by name. We could create a property name inside it; however, there is a better way (and the recommended practice) to do so. We have to make our concept implement the INamedConcept interface. This concept interface contains only one property — name. MPS IDE knows about this interface and allows for more advanced support for concepts which implement it. For example, if you want to create references to INamedConcepts, their names will be displayed in completion menu; or when you explore your nodes in the Project View, you will see the names of INamedConcepts in the tree. Position the caret at the <none> placeholder after the implements keyword, and press Ctrl+Space (for more details about effectively using the editor, please see Appendix A): Choose INamedConcept and press Enter: We have defined syntax for a node. Now we need to define its aspects. Let's create an editor. Creating an editor for Calculator MPS editor looks like a text editor but it isn't one exactly. It is a structural editor that works with the syntax tree directly. You might wonder why someone would want to use a structural editor when almost all existing languages are text-based. Text based languages are good until we want to extend them. Text-based languages usually have a parser. In order to make parsing deterministic, the grammar should be carefully designed, which proves almost impossible in case of language extensions. If we extend a language, we should extend its grammar, but since we don't know what other extensions might do, we can't be sure whether this grammar is sufficient. Consider two language extensions which add monetary-value support for Java. Both of them would add the money keyword. When we parse some code that uses these two language extensions, we don't know how to interpret the money keyword. Should it be interpreted as a keyword from the first language or from the second one? In case of the structural editor, where a program is stored directly as a syntax tree without intermediate text presentation, there's no such problem. The structural editor in MPS uses cells to represent nodes. Like nodes, cells form a tree. There are several types of cells: - property cells are used to edit node's properties - constant cells always show the same value - collection cells are used to layout other cells inside of them We want the editor for our calculator to look as follows: calculator name To implement such a design, we do the following (keep using Ctrl+Space): - create an indent collection cell. Indent collection layouts cells text like way. - create a constant cell and property cells inside of the collection. To define new editor for Calculator concept you have to select Editor tab in the bottom line of editor tabs — empty tab with No Editor label on it will be displayed since editor aspect was not defined yet for this concept. You can click onto this empty editor pane and choose concept editor from the assistance menu to create a new editor Let's create a root indent collection cell. Press Ctrl+Space and choose [- there: Now, let's create a constant cell: and type calculator inside of it: You can enter this constant in one step if you type: "calculator. The " symbol will make the cell a constant cell. Now we need a property cell for the name property (from the INamedConcept concept interface). To insert another cell at the end of the horizontal list, press Enter at the end of calculator word and choose {name} in completion: Now, when the basics have been defined, we can Build our language and try to create an instance of its concept. To build a language, choose the Make Language action from our language's popup menu in the Project View. Make a language After you implement a change in the language, you need to "make" the language for the changes to take effect. Remember in the future to run 'make' or alternatively a full 'rebuild' using the "Make Language"/"Rebuild Language" commands from the pop-up menu before trying to use the updated language in your programs. The code was generated, so you can create and edit instances of this concept in MPS models. MPS probably created an empty solution model for you already during the initial project creation. If you for some reason do not have a model, we can create a new MPS model in jetbrains.mps.tutorial.calculator.sandbox now: right-click on sandbox node in project tree and choose New | Model from the pop-up menu. Type jetbrains.mps.tutorial.calculator.sandbox in the Model name field of New Model dialog and press Ok button. In order to use jetbrains.mps.tutorial.calculator language inside this model you have to import it by pressing + button in Used Languages section of the displayed Model Properties dialog and choosing jetbrains.mps.tutorial.calculator language: Now you can press OK in the Model Properties dialog to finally create a sandbox model and start working with Calculator instances there. Define your first calculator Click the sandbox model, and then choose Calculator from the New menu: You will have a simple calculator where you can type in a name: Type the name in the property cell. For our example, we took the MyCalc name. As you can see, the calculator's editor is quite similar to what we have written in the editor aspect. Input Fields Now let's create concepts for input fields. The field will implement INamedConcept since we want to reference it in the output fields. We need it since when we reference a node, we need to see it in the completion menu. In case of INamedConcept instances, their names are correctly displayed, since MPS understands what names these instances have. It is certainly possible to reference concepts other than INamedConcept, but INamedConcept is the easiest way to do so. Let's create an editor for it: In order for the calculator to contain input fields, we need to adapt its structure and editor a little. Let's create a child of type InputField to Calculator with 0..n cardinality. To do so, put a caret on children section and press Enter or Insert. After that, specify InputField as a target Concept, set child name to inputField and cardinality to 0..n: Now we add a new line to name cell. A light bulb will appear when you position the cursor on the name cell. Actions that can be invoked with a light bulb are called intentions. There are a lot of them in different languages. In case you don't know how to enter something, in addition to pressing Ctrl+Space you can press Alt+Enter and use corresponding intention. Now press Alt+Enter and apply the Add New Line intention. Now we want to show a vertical list of input fields in editor. Press Enter in the end of {name} label and then press Ctrl+Space. Choose %inputField% there: We want input field to be placed verticaly. So, a new line should be added after every cell. This can be done with an intention: press Alt+Enter and choose Add New Line for Children. Now let's make our language using the pop-up menu on the Language node in the left-hand side Project View panel (you can also press Ctrl/Cmd+F9 to do it) and take a look at our sandbox: The editor has been updated. Now we have the cell below the line with a name where we can add new input fields. Let's add a couple of input fields: Output fields Let's create a concept for output field. It doesn't need to contain a property name since we want to reference values in input fields only (compare with InputField that implements INamedConcept): Let's create an editor for it: Let's add a child of type OutputField to the calculator concept: Now we change its editor. You can use copy/paste here; use Ctrl+Up/Down to select cells, then Ctrl+C/V to copy/paste. In order to paste a node after %inputField% collection, press Ctrl+V on the closing "-)" parenthesis. Replace inputField with outputField. We separated input fields from the output field with an empty cell. To add it, position the caret after inputField's cell and press Enter, choose constant, then using Add new line intention add line separator after this constant. Now, let's make our language (right-click on the Language or hit Control/Cmd + F9) and take a look at our sandbox concept: We can add output fields but we can't type any expressions inside it since we haven't declared anything to allow storing expressions: Adding expressions support In MPS we have BaseLanguage, the MPS's counterpart of Java. When we create a new language, we often extend it or reuse concepts from the BaseLanguage. Let's reuse its expression language for our output fields. To do so, we need to make our language extend BaseLanguage. Language extension in MPS means that you can use and extend concepts from extended language. We want to use the Expression concept from BaseLanguage, so we need to add it to the extended languages section. Open the language properties dialog: Let's add BaseLanguage to the list of extended languages. To do this, select the Dependencies tab, click the Add button ( ) and choose jetbrains.mps.baseLanguage. Then select Extends from the drop-down box for Scope. BaseLanguage contains an Expression concept. It represents expressions of the form: "2", "2+3", "abc+abc", etc. It's exactly what we need for our output field expression. Let's take a look at it. Press Ctrl+N and choose Expression from the BaseLanguage there: Expression itself is an abstract concept. Let's take a look at it: An expression has no properties of its own. So let's take a look at its subconcepts in order to understand which kinds of expressions we have in MPS. Choose 'Show Concept in Hierarchy' action in popup menu: As you can see, there are a lot of different expressions in different languages. Expression is extended very widely: Now let's add a child of type expression to the OutputField: And change its editor accordingly (you can use Ctrl+Space here): Now let's make the language (right-click on the Language or hit Control/Cmd + F9) and take a look at what we've got: You may need to add BaseLanguage to the dependencies of your model: Now we can type expressions in output fields, but, unfortunately, we still can't reference the input fields there: Extending Expressions concept In order to support references to input fields, we need to create our own kinds of Expression. Let's name it "InputFieldReference" and make it extend Expression. Let's create it: We added a reference here. It has type InputField, and 1-cardinality. Concepts, which have exactly one reference of 1-cardinality, are called smart references and have special support in the editor. You will learn more about it a little bit later. Now let's create an editor for it. Choose %field%->: And inside of the rightmost cell, choose {name}: We use %field%-> {name} to show a name of a node that is referenced by the field reference. Now make our language, and take a look at what we've got. We can now type input field for our nodes: This is possible because of smart references. Here's how they work. If a concept which is a smart reference is available in the current context, MPS takes a look at a list of possible nodes, which it can reference, and adds one completion item for each such a node. That's why we have width, height, depth, etc in the completion menu. Creating a generatorLet's create a generator for our language — we want to generate an implementation in Java. MPS might have created one already for you, but if it didn't, choose the New->Generator menu item in the Language pop-up menu: Leave generator name empty: Now your language contains a new generator: The entry point of a generator is a mapping configuration. It specifies which nodes are transformed and how: Deciding what to generate Before we start developing a generator, we need to think about what kind of code we want to generate. We might want to generate something like this: public class Sandbox extends JFrame { private JTextField myInput1 = new JTextField(); private JTextField myOutput = new JTextField(); private MyListener myListener = new MyListener(); public Sandbox() { setTitle("Sandbox"); setLayout(new GridLayout(0, 2)); myInput1.getDocument().addDocumentListener(myListener); add(new JLabel("Input 1")); add(myInput1); add(new JLabel("Output")); add(myOutput); update(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } private void update() { int i1 = 0; try { i1 = Integer.parseInt(myInput1.getText()); } catch (NumberFormatException e) { } myOutput.setText("" + (i1)); } private class MyListener implements DocumentListener { public void insertUpdate(DocumentEvent e) { update(); } public void removeUpdate(DocumentEvent e) { update(); } public void changedUpdate(DocumentEvent e) { update(); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new Sandbox(); } }); } } Here's how our application looks when executed: Now let's implement it. Implementing generator Let's first create a skeleton for the main class. We need to create a class with the update method, main method and DocumentListener that invokes the update method etc. Let's choose a new class from the new menu: And you will get this: As you can see, MPS added a root template annotation on the top of a class. Every non generator language node inside of generator model is treated as template. Every template should have an input node, the node which is used to generate from. A root template annotation is required in order to specify the type of this input node. Let's set input to Calculator: Let's give a name to the class: Now let's create a rule in mapping, which will generate a class with this template from each calculator in our input model. Let's add this to the mapping: This rule instructs to take each Calculator from the input model and apply to it to the Calculator template. Let's rebuild our language (right-click on the Language and choose Rebuild Language) and then preview the text generated from our model: We will obtain the output into a new editor tab, labelled with the name of the generated Java file: As you can see, there is one class with the name CalculatorImpl in the output. Implementing the template Why is this so tedious? You might be asking this question now or later in the process of building the generator, especially if you are not versed in Java programming. Remember, this tutorial was not created as a motivation example that gives you quick reward of having a functional application with minimum effort. Its purpose is to expose you to a wide range of core principles so that you better understand the underlying machinery. Language implementers, who realize languages in MPS, need to understand the MPS generator as well as Java, since Java is the most frequent target of code generation in MPS. We can give you three advices: - For quick and funny examples, feel free to turn to the Fast Track to MPS tutorial, watch the screen-casts and try the samples bundled with MPS. You may get back to this tutorial once you are certain that MPS can give you the solutions that you are looking for. - Open the calculator-tutorial sample project that has been installed in your home folder during MPS installation and continue in this tutorial while playing with the already implemented language. - Do it the hard and brave way - continue in this tutorial and get your own language implementation in the end. Let's make our template use the name of the Calculator node that we give it in the source model. Put the caret on the class name. Press Alt+Enter and choose the Add Property Macro: Property macros allow us to specify a value for a property, which depends on an input node. Let's type this into the inspector: Now let's rebuild the language again (right-click on the Language and choose Rebuild Language) and then preview the code generated from our sandbox model. You will see a class with the correct name corresponding to the name of the Calculator instance: Now, let's enter the rest of the class skeleton into the template. To do so, we need to import models corresponding to Java classes. If one model imports another, an importing model can reference nodes from another. In order to simplify interoperation with Java, MPS can create models corresponding to jar-files or folders with classes. These models have names of the package.name@java_stub form and can be added from the model properties dialog: Let's import javax.swing@java_stub, javax.swing.event@java_stub, java.awt@java_stub and javax.swing.text@java_stub models into the template model: Let's inherit our class from JFrame, create a main method, a documentListener field, and an update method in the Calculator template. Note that you should create the update method before you create calls to it. Now let's create code that will set up a frame for us: Put a property macro on "Calculator" string and add node.name to the inspector so as the title reflexes the name of the calculator: Now let's create a visual text field component for each input field. First, we need to add a single text field of the JTextField type: Now we'll make sure such a text field gets created for each calculator's input field. Let's select the whole field declaration (use Ctrl+Up/Down shortcuts) and choose Add Node Macro: We get the following: Choose loop from the completion menu: The Loop macro allows you to repeat a construct under macro many times: one time for each node in a collection that is returned by a code in inspector. In the loop's inspector type the following: This means that we want to have a field in a class for each inputField that we have in the source calculator. Let's give each visual text field a unique name. We need to add a property macro to its name and type this piece of code inside the macro: This code will give our variables unique names like inputField_a, inputField_b, etc. We also need to do the same for outputFields: The only difference is that we use node.outputField in $LOOP$ and use "outputField" as a base name. In order to make your changes available to MPS, make the language. Let's make our sandbox and take a look at what we have: As you can see, the fields have been generated. Now we want to add these fields to the visual frame. Type this: Essentially, you create a BlockStatement (code wrapped in {}), so as we can treat the content of the BlockStatement as a single unit belonging to a single InputField. Then we can easily repeat the block for each calculator's InputField. Surround the block and the code inside it with a $LOOP$ and use node.inputField as the value in the inspector: Add a property macro to the JLabel's constructor's parameter so that the label will have the same text as the corresponding input field's name: The situation is more complicated with creating a reference to a field declaration, in which the current field is stored. From the reference to an inputField, we need to generate a reference to the corresponding JTextField generated from current inputField. To do so, we need to label the field declaration and use this label to find the field. Go to mapping and add this: Now we have a storage for generated FieldDeclarations indexed by the original InputFields. This means that the inputField label will reference a node of type FieldDeclaration generated from the InputField. Now let's add the label to the generated field's LOOP macro: Now we need to change the reference to an inputField to a reference found by using the lookup via the label. In order to do so we need to add a reference macro to the field reference: Go to the inspector and type this: You will have: Do the same with the second reference: Now, let's make our language (right-click on the Language and choose Rebuild Language) and take a look at what we get generated from our sandbox model: As you can see, the references are set correctly.: Now let's implement the only thing that's left: the code that updates the result with a calculated value. We want to have something like this: public void update() { int i1 = 0; try { i1 = Integer.parseInt(myInput1.getText()); } catch (NumberFormatException e) { } myOutput.setText("" + (i1)); } We create an int local variable for each input node and assign it a value in that field. Let's create a loop macro for such variables. Make sure that ";" is inside the $LOOP$ macro: Let's generate a unique name for each of these variables: Let's initialize these variables. In order to reference our variables, we need to create yet another label: And assign it to the local variable declaration. To do so, you need to surround the local variable with a $MAP_SRC$ macro. In most cases, this macro is used just to add labels to nodes, which we want to reference and which don't have any other macros associated. Make sure to select LocalVariableDeclaration, not LocalVariableDeclarationStatement. To check this, take a look at the semicolon. If it's outside of the macro bracket, then choose the right node: Another LOOP will be needed to properly initialize these local variables with values from the calculator's input fields. First, add a try ... catch block. You will have this: Surround it with a LOOP macro: Please make sure the whole statement (the line including the ending semicolon) is wrapped by the LOOP macro. Then create reference macros and use the labels to find corrent targets (i.e. LocalVariableDeclarations and InputFields, respectively) for these references. With local variable: With field reference: Now we need to set output values into the text fields that represent the calculated outputs. Type the following code: Surround it with a LOOP macro: Again, please make sure the whole statement including the ending semicolon is wrapped in the LOOP macro. Then add a reference macro to the outputField: Now we need to set the text so that it will display the calculated result. So we need to generate the output field's expression to where the null value is. Remove null argument of setText() method and type: "" + (null). Use Ctrl+Space on each step. We add parentheses here to make sure that the output code will be correct. If we didn't have parentheses and expression is 2—3, the output code will be "" + 2 — 3, which isn't correct. On the other hand, "" + (2 — 3) is correct: Add a node macro to the null value and change it to a $COPY_SRC$ macro. $COPY_SRC$ macro replaces a node under the macro with a copy of the node returned by the code in the inspector. We return node.expression: The only thing that's left is handling the InputFieldReference. We don't have a generator for it yet. We need to replace the reference with the value retrieved from the JTextField corresponding to the refered input field. So assentially the corresponding i variable stored in the LocalVar label. To create a generator for an InputFieldReference, we need to define a reduction rule. Reduction rules are applied to all the nodes that are copied during generation, for example, in $COPY_SRC$ macro. Let's create the corresponding reduction rule in the mapping configuration: Since the template will not be very long, we will use an in-line template with context. Chose <in-line template with context> from completion list. We translate the InputNodeReference to a local variable reference, so we have to create valid context node that would contain such a local variable reference. Let's use BlockStatement as a context node: Inside this BlockStatement let's define local variable i and create simple expression referencing it: This reference to a local variable i is what we will use as a result of the in-line template, so we should mark it as a template fragment. Press Alt+Enter and choose "Create Template Fragment" intention: Now let's create reference macro for this local variable reference: and specify proper reference query to get the correct i from LocalVar: Now, let's rebuild our language (right-click on the Language and choose Rebuild Language) and take a look at what happens with the sandbox model. As you can see, MPS generates exactly the code that we wanted: Entering Salary program Having finished the language and its generator, we can enter salary program. Here it is: Running generated code In order to run code, you need to make your solution model: Your sources will be available in solution source_gen directory. (Don't forget to switch to File System View): You can run them with your favorite Java IDE. We finished the main part of our language, now let's do some polishing. Creating a scope for InputFieldReference If we create another Calculator root in the sandbox model, we will be able to reference input fields from the first calculator, which isn't correct: Let's fix it. To do so, we need to define the scope for the InputFieldReference concept. We do that by defining a constraint: open InputFieldReference, go to the Constraints tab, and create a constraints root for it: We will use the new hierarchical (inherited) mechanism of scope resolution. This mechanism delegates scope resolution to the ancestors, who implement ScopeProvider. Our InputFieldReference thus searches for InputField nodes and relies on its ancestors to build a list of those. Add a referent constraint and choose field as its link: Now let's create a scope for this link. Go to the scope section and hit Control + Space. We need to specify how to resolve elements that the InputFieldReference can link to: _120<< The Calculator in our case should return a list of all its InputFields whenever queried for scope of InputField. So in the Behavior aspect of Calculator we override (Control + O) the getScope() method: . Now we can finally). After you make the language (right-click on the Language and choose Ma Language), you will no longer be able to access a field from the first calculator in the second one: But you can still access fields in the first calculator: Creating a type system rule for InputFieldReference We can now type something like this: This code isn't correct because width must be Boolean, since it's used as part of a ternary operator's condition. In order to make this error visible, we need to create a type system rule for our concept. Let's do it. Open the InputFieldReference and go to Typesystem tab. Create an InferenceRule there: Our typesytem engine operates on type equations and inequations. Equations specify which nodes' types should be equals. In equation, specify which nodes' type should be subtypes of each other. We need to add an equation that states that the type of our reference is always int. Let's define equation. Choose the equals sign in the completion menu: Choose typeOf in its left part: Type 'inputFieldReference' inside of typeof: Choose <quotation> on the right part of the equation: Quotation is a special construct that allows us to get a node inside of quotation as a value. Usually nodes we want to create are quite complicated, so creating them with sequential property/children/reference assignments is an error-prone and boring activity. Quotations simplify such a task significantly. Type IntegerType inside of it: Now our rule is complete: Let's make the language (right-click on the Language and choose Make Language) and take a look at code with error: It's now highlighted. You can press Ctrl+F1 and see the error message: "type int is not subtype of Boolean". How to use MPS editor Despite looking like a text editor, MPS editor isn't one exactly. Because of this, working with it is different from working with text editor. In this section we will describe the basics of working with MPS editor. Navigation works similar to that of a text editor. You can use the arrow keys, page up/down, and home/end, and they behave the same way as in text editors. Selection works differently: you can't select an arbitrary interval in the editor, since there is no such thing in MPS. You can only select a cell or a set of adjacent cells. To select the parent of the current cell, press Ctrl+Up. To select a child of the current cell, press Ctrl+Down. If you want to select adjacent cells, use Shift+Left/Right. Unlike text editors where code completion is optional, MPS gives you this feature out of the box. You can press Ctrl+Space almost everywhere and see a list of possible items at the current position. If you want to explore a language's features, the best way to do so is to use this shortcut in the place which you are interested in and look at the contents of the completion menu. Another commonly used feature of MPS is intentions. Intentions are actions which can be applied to a node in the editor. You can apply intentions if you see a light bulb in the editor. If you press Alt+Enter, the light bulb will be expanded to a menu so you can choose the actions you want. In MPS we often want to add a new element to a place where multiple such elements are possible. For example, we might add a new statement in a method body, a new method in a class declaration, etc. To do so, you can use two shortcuts: Insert and Enter. The former adds a new item before the current item. The latter adds a new item after the current one. In order to remove the current item, press Ctrl+Delete. You may check out the screen-cast dedicated to MPS editor usage on JetBrains TV. Consider also tuning the MPS channel for more MPS tips and tricks.« Back to MPS overview
https://www.jetbrains.com/mps/docs/tutorial.html
CC-MAIN-2015-18
refinedweb
6,708
61.06
Hi and welcome to Just Answer!Yes - that is possible. A Limited Liability Company (LLC) is a business structure allowed by state statute.Depending on elections made by the LLC and the number of members, the IRS will treat an LLC as either a corporation, partnership, or as part of the LLC’s owner’s tax return (a “disregarded entity”).An LLC that does not want to accept its default federal tax classification, or that wishes to change its classification, uses Form 8832, Entity Classification Election, to elect how it will be classified for federal tax purposes. Election may be made any time.Generally, an election specifying an LLC’s classification cannot take effect more than 75 days prior to the date the election is filed, nor can it take effect later than 12 months after the date the election is filed.See here - Yes, I understand. But how about the LLC already operated for like 3 years, and has filed tax returns by using tax form 1065, is it still possible to elect as C-Corporation? Or is it too late to elect at this point? Yes - that is possible. You may file form 8832 and change LLC's classification.You will file a final tax return for the partnership (mark 1065 as Final) and will start filing income tax return for the C-corporation.For easy transition - it might be more simple to change classification from January 1. However if you want to change election as soon as possible - you may file form 8832 now - and election will be in effect 75 days prior to the date the election is filed. However - if you want that election will be in effect 3 years prior to the date the election is filed - that would not be possible. I am getting a bit confused with the 75 days rule and 3 years rule could you please show me a simple example? thanks! By the way, by filling out 8832, for my case, do I have to fill out Part II? relief of late filing? Example 1.- you decide to change your LLC which is treated as a partnership to C-corporation. The best approach would be to make such change on the year end. Thus you may file form 8832 now and ask to change be in effect from Jan 1, 2014. In this case you will file your partnership tax return for 2013 as final. And C-corporation tax treatment will start from Jan 1, 2014.Example 2.For whatever reason you want your change to be in effect as soon as possible. You may file form 8832 now - May 1, 2013 and request that election would be in effect 75 day prior of that date - which is Mar 16, 2013. In this case you will file a short final tax return for the partnership (form 1065) . Starting Mar 17, 2013 - your LLC will be treated as C-corporation. That is not a late filing - and no need to fill out Part II. I need to step out - please post all your question and I will address them later tonight. Thanks very much, it should be much more clear now. Just wonder if I still need to fill out Part II for filing form 8832, thanks! Sorry, I misread your answer, so no need to fill out part II...got it your explanation is very clear, thanks for your help!
http://www.justanswer.com/tax/7qimo-hi-tax-professional-if-llc-operated-couple-years.html
CC-MAIN-2014-52
refinedweb
571
71.95
Help:Starting a new page There are several ways to start a new page. These can vary based on the type of page started, as well as the wiki and namespace. Contributors who desire to draft new work can do so in their userspace and move new content to articles in the main namespace when finished. Any new article started in the main namespace will immediately be announced on the Gentoo hompage. Especially wiki newbies are highly recommended to start new articles only in their userspace.. Page title By default the page title is displayed with the first letter upper-case. Putting {{Lowercase title}} in the first line will force the title to be displayed lower-case. Working with article blueprints For getting the basic elements of the page structure it seems convenient to copy content from a suitable article blueprint. So, once in the (still empty) editing canvas of the page to be created, put the string {{subst:<name of the page template>}} in the first line. Preview mode will then display the content to be copied, and after saving, the {{subst:<name of the page template>}} will have disappeared and be replaced by the pulled-in content. E.g. {{subst:Help:Templates}} will copy the content of Help:Templates. Protecting your new page Normally a new wiki page can be edited by other people (that is one of the main ideas of a wiki!). However, a sysop could 'protect' the page, if desired, to prevent normal users from editing it.
https://wiki.gentoo.org/wiki/Help:Starting_a_new_page
CC-MAIN-2021-39
refinedweb
252
61.06
Quick access Share your "How To" samples announcement - Sticky1Votes Windows Phone 7 Developer Support ‘Mango’ How-To IndexHello, As promised back in July, here are some Mango FAQs that will hopefully help you in your projects going forward. Check back as we might add a few more ...0 Replies | 3486 Views | Created by Jonathan Tanner - Tuesday, January 31, 2012 12:21 AM - Sticky0Votes This forum is not for asking questions. Do not post questions here.This forum is for posts on how to do things, not for asking how to do things. Please posts questions in the appropriate forum. Posts in this forum asking questions may be moved or deleted.0 Replies | 3125 Views | Created by Jim Perry - Tuesday, August 30, 2011 1:02 AM - Sticky1Votes Windows Phone 7 Developer Support How-To IndexUPDATED (7/11/2011): Hello, Some of you might notice that a few new FAQs ...0 Replies | 12672 Views | Created by Jonathan Tanner - Wednesday, January 26, 2011 7:25 PM - Answered0Votes how to use "clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"Hi, If I try to use it a follows: xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls" I get this error: Error 1 Assembly 'Microsoft.Phone.Controls' was ...5 Replies | 1871 Views | Created by masiboo - Tuesday, June 07, 2011 1:47 PM | Last reply by arkulpa - 14 hours 3 minutes ago - Unanswered0Votes ENLACE AVANZADO 21 - MainPagel.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using ...1 Replies | 28 Views | Created by Arnold Smith If - Monday, December 02, 2013 11:22 AM | Last reply by Matt Small - Monday, December 02, 2013 4:42 PM - Discussion0Votes ENLACE AVANZADO DE DATOS= 0 && value <= 15)) { throw new Exception("El valor del pH esta comprendido entre 0 y 15"); ...0 Replies | 29 Views | Created by Arnold Smith If - Monday, December 02, 2013 11:12 AM - Answered0Votes How to get model name of device using pure c++How to get model name of device using pure c++ wp8 application?? in c# there is DeviceStatus class. how i may do this in c++?1 Replies | 68 Views | Created by Chapaev28 - Tuesday, November 19, 2013 5:03 PM | Last reply by Prashant H Phadke - Tuesday, November 19, 2013 7:52 PM - Discussion0Votes Use ConsoleUtilización números aleatorios. int semilla = (int)DateTime.Now.Ticks; Random aleatorio = new Random(semilla); int a = aleatorio.Next(-100, 100); //ENTRE -100 Y ...0 Replies | 99 Views | Created by Arnold Smith If - Friday, November 15, 2013 5:40 AM - Discussion0Votes wp8Diseño de la Aplicación: MainPage.xaml Insertaremos los controles dentro del espacio que para ello ...0 Replies | 86 Views | Created by Arnold Smith If - Friday, November 15, 2013 5:40 AM - Discussion0Votes [MD] - APDiseño de la Aplicación: MainPage.xaml Insertaremos los controles dentro del espacio que para ello ...0 Replies | 69 Views | Created by Arnold Smith If - Friday, November 15, 2013 5:38 AM - Discussion0Votes Example Use CodeTRATAMIENTO MONEDAS private void cmdSuma_Click(object sender, RoutedEventArgs e) { double importe, porcentaje, resultado; ...0 Replies | 92 Views | Created by Arnold Smith If - Thursday, November 14, 2013 7:30 PM - Discussion0Votes VirtualJoystick control (on-screen joystick for WP/Silverlight)Recently I developed (for my HoBo control center project) a virtual joystick control - couldn't find anything suitable on internet. I've decided to share my code; may be my work will save ... - Discussion0Votes How To Add a Privacy Policy to Windows Phone AppsHi, since I hadn't found a great thread about this yet I thought I'd open one up - I'm also doing this to get your input and keep improving my knowledge about this ...0 Replies | 319 Views | Created by Simon's Thoughts - Thursday, October 03, 2013 9:59 AM - Discussion2Votes How Do I Load an Image from Isolated Storage and Display it on the Device?This HowTo is provided via Microsoft’s Windows Phone 7 Developer Support team. They are intended to serve as a guide in helping developers quickly find ...4 Replies | 10058 Views | Created by Jonathan Tanner - Tuesday, January 25, 2011 11:19 PM | Last reply by raincast - Saturday, July 27, 2013 12:57 PM - Discussion1Votes Making a Windows Phone weather app in 20 lines of codeHere is my talk from TechEd Africa where I show the basics of creating a good app in an hour, with a tiny bit of ...3 Replies | 1208 Views | Created by roguemat - Monday, April 22, 2013 6:51 AM | Last reply by roguemat - Friday, June 14, 2013 5:15 PM - Discussion2Votes Encrypt in WP7 and decrypt in PHPdecryptRJ256($pkey, $piv ,$string); function decryptRJ128($key,$iv,$encrypted) { //get all the bits $key = base64_decode($key); $iv = ...1 Replies | 1363 Views | Created by Sigurdur Eggertsson - Saturday, February 02, 2013 2:08 PM | Last reply by zAppU - Tuesday, April 30, 2013 4:47 PM - Discussion0Votes How to do a Stopwatch<phone:PhoneApplicationPage x:Class="PhoneApp1.MainPage" xmlns="" ...0 Replies | 954 Views | Created by FabianHenzler - Sunday, April 21, 2013 2:10 PM - Answered0Votes How In App purchase facility in windows 8 phone works?I have read given documentation for In App purchase on the Microsoft site. I done the program for that by using a mock In App Purchase library. But I am not getting where the ...1 Replies | 998 Views | Created by k_amol - Wednesday, April 10, 2013 9:31 AM | Last reply by k_amol - Monday, April 15, 2013 11:05 AM - Unanswered7Votes WP7 How to: Give Haptic Feedback ( Vibration ) on Button Press.{ & ...5 Replies | 3061 Views | Created by Evan Larsen - Saturday, April 09, 2011 5:12 PM | Last reply by Steven Charles White - Saturday, April 13, 2013 2:58 AM - Discussion1Votes Tombstoning in MVVMHello all, I recently created a nuget package to handle tombstoning in MVVM through the use of attributes. You can read ...1 Replies | 1066 Views | Created by Kenneth Truyers - Tuesday, March 26, 2013 12:10 AM | Last reply by pumpkinszwan - Sunday, April 07, 2013 6:29 AM - Discussion0Votes How to get an rss feed last dateI was trying to figure out how to check my blog for any updates before downloading any new ones. My original intent was to figure out how to download the first x posts, but I haven't figured that out ... - Discussion0Votes How to Handle the User’s Refusal of the License Agreement/Privacy Policy in WP Apps (in VB)Its a good idea to put the apps privacy policy, or license agreement or whatever you need the user to agree on before using the app, in a separate page and navigate to it in the first ...0 Replies | 811 Views | Created by Dr.Alani - Monday, April 01, 2013 5:55 AM - Unanswered1Votes How can I record audio on the phone and then use that as my ringtone?SilverlightMicrophoneSample Properties… Once you see the project property pages, look for the option ‘Target Windows Phone OS ...1 Replies | 3724 Views | Created by Jonathan Tanner - Tuesday, January 31, 2012 12:15 AM | Last reply by ggsmartboy - Saturday, February 02, 2013 11:15 AM -
http://social.msdn.microsoft.com/Forums/wpapps/en-us/home?forum=wphowto
CC-MAIN-2013-48
refinedweb
1,165
59.23
Here, we are going to see some live actions of the brand new Visual Studio 2017. Please note that this is not the complete series of new functionalities of Visual Studio 2017. Here, I am going to share only few things to get you started with the new Visual Studio 2017. I hope you will like this. Now let’s begin. Background Today, the wait is over. Visual Studio 2017 is here, so I thought of trying it out today itself. That’s how this article is made. If you never use Visual Studio, you can find some articles and code snippets related to it here. Installing Visual Studio 2017 You can always install the brand new Visual Studio 2017 from here. While installing, you can always select the things you may need, for example, if you are a Xamarin developer, you can select Xamarin. Visual Studio 2017 has the option for it. This makes the installation pretty much fast. Once after you install, it is time to launch. After_installing_Visual_Studio_2017 You can always set the development settings and the theme as per your wish. These features are already available in other lower versions too. Just thought of saying it. Selecting_theme_in_Visual_Studio_2017 Recent, Open, New Project Template In the start screen, you can see some slight changes as listed below: - Recent This is where your recent projects will be shown, so that you can easily open it up. - Open This, helps you to open the projects you need in an easy manner. It not only helps to open a project from your local computer, but also from Visual Studio Team services. Things are pretty much easier now. Right? - New project Here, you can see the templates that you recently worked with, and you can always search the templates too. Recent_menu_and_open_menu_in_Visual_Studio_2017 Creating First Visual Studio Applciation Now, let’s create an empty MVC application and a controller in it. namespace WhyVisualStudio2017.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } } } Now, if you look at the preceding image, you can see that there are dotted lines between the namespaces, classes, methods. New_layered_structure This will help you to understand how the namespaces, class, methods are related to. If you have worked in heavy projects where you can have 1000s of lines of codes in a single class, you may find this feature very useful. Now let’s create a model class as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WhyVisualStudio2017.Models { public class Calculator { public static int CalculateMe(int v1, int v2) { return v1 * v2; } } } Go back to your controller and type ‘ cal’, you can see the new intellisense, where you can separate the lists by classes, snippets, interfaces, etc. New_Intellisense_feature New_Intellisense_feature Now, if you have given your function name as in camelCase manner, Visual Studio 2017 will give a suggestion to rename it as follows: Naming_Suggestions_in_Visual_Studio As an additional feature, if you click on the preview changes, you can get to know where exactly your recent code changes may affect and what fix you can give. Preview_Changes_in_Visual_Studio Searching for a file is much easier in Visual Studio 2017, all you have to do is type CTRL + T, then you can see a box as shown below: Find_files_in_Visual_Studio_2017 You can select any kind of files by typing the file name as shown below: Find_Files_in_Visual_Studio You can always use the filters given there in the box. Another important feature available in Visual Studio 2017 is, Exception User Handled. If you get any error, the Visual Studio 2017 will tell you where exactly the error is. For example, we all know the preceding codeblock will give you a null reference exception. List<string> lstString = new List<string>(); lstString = null; lstString.Add("Sibeesh"); Now, if you run your application, Visual Studio 2017 will give you the entire details of the error as follows: Exception_User_Handled_In_Visual_Studio_2017 In the exception box, it has been mentioned as: For every developer, one of the headaches is finding where exactly the error occurs. Now Visual Studio 2017 makes that much easier. Way to go. That’s all for today. I will come with all the features of Visual Studio 2017 very soon. Happy coding!. References See also Conclusion Did I miss anything you may think is needed? Could you find this post useful? I hope you liked this article. Please share.
http://ugurak.net/index.php/2017/03/08/why-visual-studio-2017-let-us-try-it-by-sibeesh-passion/
CC-MAIN-2018-47
refinedweb
728
63.9
How do I make each bar a different color for a top 10 graph in a report? I found this where you can change the color based on the value in the scripting(below) and it works fine for that but I can’t figure out how to make it work for my case. Thanks from org.jfree.chart.renderer.category import BarRenderer from java.awt import Color class myBarRenderer(BarRenderer): def getItemPaint(self, row, column): v = chart.getCategoryPlot().getDataset().getValue(row, column) if v < 70: return Color.blue else: return Color.red plot = chart.getCategoryPlot() plot.setRenderer(myBarRenderer()) *Edited so it actually made sense.
https://forum.inductiveautomation.com/t/reporting-top-10-bar-chart-colors/18550
CC-MAIN-2021-39
refinedweb
105
53.17
Setting up a queue service: Django, RabbitMQ, Celery on AWS In this post, I’ll walk you through the process of setting up a jobs-queueing infrastructure, using Django, Celery, RabbitMQ, and Amazon Web Services. While building this system, I found that there was good documentation for each different component, but relatively little on how to fit the pieces together. First, let’s discuss the motivation of this project. We have a Django project deployed on AWS OpsWorks. The stack is broken into two layers: - The internet-facing app layer, where the Django project is run in conjunction with Nginx and WSGI to serve HTTP requests from the outside world. - The internal-facing jobs layer, containing the same Django code, but which runs cron jobs and other long-running, CPU-intensive processes. The app’s user base is growing, and there is pressure to make the app more performant. There are many operations performed by the app servers which take place within the context of a single request, but which could easily be performed separately, allowing the request to be completed faster. Unfortunately, Django does not come out-of-the-box with support for this sort of delayed execution – a request is received, operations are performed, and a response is returned (the request-response cycle). There are no long-running processes outside of requests and response. Something else is required. Here we see the value of a piece of infrastructure known as a “queue”. A queue is, as it sounds, a system for “lining up” tasks for later execution. Processes send tasks to the queue during the course of a request-response cycle, and elsewhere these tasks are carried out by “workers”. A queue system allows for time-intensive but non-critical tasks to be offloaded from the internet-facing servers, bringing better performance. Additionally, we want our system to be easily deployable, and flexible enough to accomdate the addition or removal of servers from either the app or jobs layers of the project. The queue system we are going to build consists of four parts: - Django, the popular Python web framework. - RabbitMQ, an enterprise-grade messaging platform. - Celery, a python library which sits on top of RabbitMQ and provides workers to execute tasks. - AWS OpsWorks, Amazon’s infrastructure-management product. We will begin with the server and network aspects of this service, and then turn to configuration and deployment. For this tutorial, we will consider a deployment in which there is one EC2 instance in each layer. Towards the end, we will discuss the addition of multiple instances to both layers. Step 1: Install RabbitMQ RabbitMQ is the messaging server which powers this service. Written in Erlang, RabbitMQ does the following: - Listens for messages sent via the AMQP protocol. - Stores these messages in one or more queues. - Releases these messages to workers for consumption and processing. Note that RabbitMQ does not actually execute tasks. Rather, it is the mechanism by which tasks (“messages”) will be sent between instances and stored until executed. The first thing we will do is install RabbitMQ on our jobs instance. SSH into your instance and run the following: ubuntu@jobs:~$ sudo apt-get install rabbitmq-server Now, lets check to make sure that RabbitMQ is up and running: ubuntu@jobs:~$ sudo rabbitmqctl status Status of node 'rabbit@jobs' ... [{pid,1087}, {running_applications,[{rabbit,"RabbitMQ","3.2.4"}, {mnesia,"MNESIA CXC 138 12","4.11"}, {os_mon,"CPO CXC 138 46","2.2] [async-threads:30] [kernel-poll:true]\n"}, {memory,[{total,34656304}, {connection_procs,2632}, {queue_procs,5264}, {plugins,0}, {other_proc,13257200}, {mnesia,57952}, {mgmt_db,0}, {msg_index,30568}, {other_ets,744920}, {binary,7080}, {code,16522377}, {atom,594537}, {other_system,3433774}]}, {vm_memory_high_watermark,0.4}, {vm_memory_limit,1572403609}, {disk_free_limit,50000000}, {disk_free,4563763200}, {file_descriptors,[{total_limit,924}, {total_used,3}, {sockets_limit,829}, {sockets_used,1}]}, {processes,[{limit,1048576},{used,122}]}, {run_queue,0}, {uptime,2732}] ...done. Excellent. Let’s set up our user. RabbitMQ comes with a “guest” user out of the box, but this user is not configured to accept external requests. This would be fine if you were planning on sending and consuming messages locally, but we are not. The easiest way to configure RabbitMQ to accept external requests is to create a new user. Go ahead and run the following (angle brackets denote user values): ubuntu@jobs:~$ sudo rabbitmqctl add_user <username> <password> ubuntu@jobs:~$ sudo rabbitmqctl set_permissions -p / <username> ".*" ".*" ".*" This will create a new user on the RabbitMQ server. We will use this username and password to configure the app-layer instance to send messages to Rabbit. Let’s check to make sure the user was created correctly: ubuntu@jobs:~$ sudo rabbitmqctl list_users Listing users ... guest [administrator] <username> [] ...done. Finally, let’s start our first worker process. A RabbitMQ server is useless unless there are workers (processes) configured to consume its messages. Navigate to the root directory of your project (if you’re not there already), and run the following: ubuntu@jobs:~$/you_proj$ celery -A <your_proj> worker -l INFO You should see an output like this: -------------- celery@jobs v3.1.17 (Cipater) ---- **** ----- --- * *** * -- Linux-3.13.0-24-generic-x86_64-with-Ubuntu-14.04-trusty -- * - **** --- - ** ---------- [config] - ** ---------- .> app: your_proj:0x7f6fab1d2810 - ** ---------- .> transport: amqp://<username>:**@jobs.your_proj.com:5672// - ** ---------- .> results: cache+memcached://cache.your_proj.com:11211/ - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- --- ***** ----- [queues] -------------- .> default exchange=default(direct) key=default [tasks] . tasks.add [2015-05-15 03:42:59,653: INFO/MainProcess] Connected to amqp://<username>:**@jobs.your_proj.com:5672// [2015-05-15 03:42:59,675: INFO/MainProcess] mingle: searching for neighbors [2015-05-15 03:43:00,740: INFO/MainProcess] mingle: sync with no nodes [2015-05-15 03:43:00,740: INFO/MainProcess] mingle: sync complete [2015-05-15 03:43:00,785: WARNING/MainProcess] celery@jobs ready. This is the celery worker outputting to STDOUT. At this moment, any message received by the RabbitMQ server will be consumed by this worker, and the result printed to the screen. In production, you will wanto to run these workers in the background. You can background a task in a simple way by appending & to the command. For a more complete solution, it is worth using a tool such as supervisor. That will be enough for now. Much more info on setting up RabbitMQ for Celery can be found here. Step 2: Configure AWS So, RabbitMQ is now up and running. But it not yet possible to send messages between the layers of our project. We will need to make a number of modifications to the stack: - Update the settings for the stack’s security group - Create an Elastic Load Balancer (ELB) for the jobs layer. - Create a stable DNS address for the ELB. RabbitMQ servers communicate via AMQP, a popular messaging protocol. In order for your stack layers to be able to communicate with each other, you’ll need to update that stack’s security group (if you have one) to allow this traffic. Security Groups If you have never worked with security groups, they are an AWS feature which makes it easy to secure groups of instances (EC2, RDS, and so on) by restricting the ports and protocols through which they can communicate to the outside world (or to each other). AMQP is an application-layer protocol, and as such can be transmitted via TCP, a lower-level transport-layer protocol. This means we will need to update our security group to open up a port for TCP traffic. Navigate to AWS Services -> EC2 -> Network & Security -> Security Groups. You will want to add a new “rule”, allowing TCP traffic to come through on port 5672 (the RabbitMQ default). For now, let the connection come from “anywhere”. Your setting should look something like this: Great. Now you can send messages between your app layers. Currently, though, you’ll need to use the exact address of your jobs server to send messages. This is disadvantageous, as you will have to update your settings every time that address changes (i.e., every time you deploy a new instance). It would be much better to create a persistent address to receive messages, which will remain the same even as the servers themselves change. Enter the “load balancer”. Load Balancers Load balancers are barriers placed between a group of your servers and any computers which they will need to interact with. The load balancer receives all requests, and routes them to one of its servers. This provides a single point of contact for your client-facing servers, abstracting away the individual instances. To create a new load balancer, navigate to: AWS Services -> EC2 -> Network & Security -> Load Balancers Hit the big blue button labeled Create Load Balancer Set up the load balancer (hereafter LB). The following settings should be good (you can leave everything else to default): - Define Load Balancer: - Name: '<stack>-JOBS' - LB Protocol: TCP / 5672 - Instance Protocol: TCP / 5672 - Configure Health Check: - Ping Protocol: TCP / 5672 - Add EC2 Instances: - Here you can add all the instances currently running in the relevant layer of the OpsWorks stack. In our case, there is only one server, jobs, to add. - Add Tags (can ignore for now) - Review You should see something like this: If you’re curious, what we’ve done is tell the load balancer to receive and re-route TCP requests coming to port 5672 to the same port on one of the jobs instances. We’ve also told it to repeatedly ping the servers it is associated with to make sure they’re still alive (a “health check”). AWS load balancers will remove “unhealthy” instances (those which repeatedly fail the health check), to ensure that requests are going to a valid server. Congratulations! You’ve created a load balancer. Navigate to the “Description” tab and make a note of the LB’s “A Record”. This is the address that you can use to send messages your jobs server. This address will be permanent, meaning you can add it to your Django settings without having to worry about updating it later – this address will remain constant, even as you add and remove individual instances. But, it’s a pretty ugly URI. It would be a lot nicer if we could assign it to something more semantic and human-readable. Fortunately, we can! AWS has a DNS product called Route 53 which allows you to assign easy, clear domain names to otherwise-confusing IP addresses. Go ahead and navigate to: AWS Services -> Route 53 -> Hosted Zones -> <your hosted zone> From here, click the big blue button Create Record Set. You’ll see a settings box pop up on the right of your screen. All we’re doing here is setting the human-friendly URI for your load balancer. Pick your name, and then paste your load balancer’s A Record (remember that) into the “Value” box. Make sure you set “type” to CNAME, because you’re creating a relationship between two DNS records, not between an IP address and a DNS record (in which case you would use A - IPv4 or AAAA - IPv6 ). Leave everything else to default and hit Create. Finally, we have to add this LB to the OpsWorks layer. First, navigate to: AWS Services -> OpsWorks -> <your stack> -> Layers -> <your tools layer> -> Network. You should see something that looks like this: Alright! Let’s take stock of where we are. We’ve: - Gotten RabbitMQ running on a jobs server. - Set up some AWS layers to protect and stabilize our stack. - Taught our servers to play nicely together. Now we turn away from AWS and back to our actual app. Step 3: Setting up Django and Celery Let’s crack open our settings.py file and add some Celery: BROKER_URL = 'amqp://username:password@jobs.yoursite.com:5762//' The final slash in that URI refers to a RabbitMQ virtual host. The default vhost is /, hence the //, but this could in theory be different for more advanced deployments. Don’t worry about this right now, but remember it in case you come across something different in the future. That’s all you’ll need to teach Celery to talk to Rabbit. The nice thing is that you’ll never have to change this setting, even as you add/remove jobs servers. Load balancers! Celery itself will be defined in a file we’ll call your_app/celery.py, which will look something like this: from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_app.settings') app = Celery('your_app') app.config_from_object('django.conf:settings') Our Celery tasks themselves will be defined in a file called tasks.py: from your_app.celery import app as celery @celery.task def add(x, y): return x + y You can then call these tasks: >>> import tasks >>> tasks.add(3,5) 8 >>> tasks.delay.add(3,5) <AsyncResult: 2e031f3f-5284-48cb-bb57-fcef3638c746> What has happened here is that the @celery.task decorator has given add the delay property, a function which wraps the Celery API to allow for easy queuing of tasks. While calling your_func(*args, **kwargs) will execute the task immediately, calling your_func.delay(*args, **kwargs) will queue the same task for later execution. Thinking about the last couple of steps, consider how we: - Communicated to the Django project the location of the RabbitMQ server, and how to communicate with it. - Defined a Celery application, with configuration information telling it the location of the Django project settings. - Wrapped your function of interest with Celery’s taskdecorator, which informed Celery of the task and its code, and gave the function some additional properties. - Used one of the properties defined by Celery to easily send the task to the queue. And with that, the system is complete! Step 4: OpsWorks Amazon OpsWorks is an invaluable tool for managing infrastructure requiring the coordination of multiple independent servers, or “nodes”. One of the great features of OpsWorks is the ability to upload Chef “recipes” to any stack and configure them to be run at various points in the lifecycle of the instances in that stack. Let’s consider how we can apply Chef recipes to the challenge of our new infrastructure. For the system to be “complete”, let’s say we want the following: - A RabbitMQ server up and running, and able to receive external requests - One or more Celery workers running, and able to consume messages from one or more queues We want this system to be resilient to failure and to operator error, meaning we want to automate as much as possible, including: - Installing RabbitMQ if it is not found - Creating the correct users/permissions on the RabbitMQ server - Correctly starting the Celery workers - Restarting the Celery workers in case of failure Fortunately, all of this can be accomplished via Chef recipes! Here are the two cookbooks we will be considering: cookbooks/ rabbitmq/ recipes/ default.rb supervisor/ attributes/ default.rb recipes/ default.rb celery.rb First, let’s consider the one-recipe cookbook for RabbitMQ: cookbooks/rabbitmq/recipes/default.rb package 'rabbitmq-server' service 'rabbitmq-server' do action [:enable, :start] end def user_exists?(name) cmd = "rabbitmqctl -q list_users |grep '^#{name}\\b'" cmd = Mixlib::ShellOut.new(cmd) cmd.environment['HOME'] = ENV.fetch('HOME', '/root') cmd.run_command Chef::Log.debug "rabbitmq_user_exists?: #{cmd}" Chef::Log.debug "rabbitmq_user_exists?: #{cmd.stdout}" begin cmd.error! true rescue false end end unless user_exists?(<username>) execute "create-user" do command "sudo rabbitmqctl <username> <password>" end end execute "set-permissions" do command 'sudo rabbitmqctl set_permissions -p / <username> ".*" ".*" ".*"' end Here we have four “resources” (the individual actions/goal-states that a recipe will take/bring about). These resources, do, in order: - Install RabbitMQ if not already installed - Start the RabbitMQ server if it is not already running - Create your user if it does not exist - Configure permissions for your user You have almost certainly noticed the large Ruby function sitting between resources 2 and 3. This function exists to make the recipe “idempotent”, so that repeatedly running the recipe will not cause a failure. More advanced Chef usage would involve breaking these type of helper functions off into a seperate module, but in this case having all of the logic presented together seems instructive. Now, let’s turn to the recipes for managing the Celery workers. Here, we seen example of a more fully-featured cookbook, used to control the Supervisor service (which is what we will be using to manage our Celery workers). Cookbooks like these can often be found online, and are often mature and fully-featured. Peeking into cookbooks/supervisor/attributes/default.rb, we discover a settings module used to store configuration for the entire cookbook: default['supervisor']['unix_http_server']['chmod'] = '700' default['supervisor']['unix_http_server']['chown'] = 'root:root' default['supervisor']['inet_port'] = nil default['supervisor']['inet_username'] = nil default['supervisor']['inet_password'] = nil normal['supervisor']['dir'] = '/etc/supervisor.d' normal['supervisor']['conffile'] = '/etc/supervisord.conf' default['supervisor']['log_dir'] = '/var/log/supervisor' default['supervisor']['logfile_maxbytes'] = '50MB' default['supervisor']['logfile_backups'] = 10 default['supervisor']['loglevel'] = 'info' default['supervisor']['minfds'] = 1024 default['supervisor']['minprocs'] = 200 default['supervisor']['socket_file'] = '/var/run/supervisor.sock' # Celery default['celery']['project'] = "<your_proj>" default['celery']['workdir'] = "<path/to/your_proj>" default['celery']['log_directory'] = "/var/log/celery" default['celery']['log_path'] = "/var/log/celery/worker.log" default['celery']['log_level'] = "INFO" Turning to supervisor/recipes/celery.rb, we see the specific resources controlling Celery: # Add the celery log folder directory node['celery']['log_directory'] do owner node[:user] group node[:group] mode 0766 end supervisor_service "celery1" do action [:enable, :start, :restart] autostart true autorestart "unexpected" user node[:user] directory node[:celery][:workdir] command "/usr/local/bin/celery -A #{node[:celery][:project]} worker -l #{node[:celery][:log_level]} -Q high -n worker1" stdout_logfile "/var/log/celery/worker.log" stderr_logfile "/var/log/celery/worker.log" end supervisor_service "celery2" do action [:enable, :start, :restart] autostart true autorestart "unexpected" user node[:user] directory node[:celery][:workdir] command "/usr/local/bin/celery -A #{node[:celery][:project]} worker -l #{node[:celery][:log_level]} -Q high,default -n worker2" stdout_logfile "/var/log/celery/worker.log" stderr_logfile "/var/log/celery/worker.log" end This recipe, when run, will create the Celery log folder (if it does not exist), and start or restart two Celery workers process under Supervisor’s control. Notice how worker1 is set up to consume only from the high priority queue, while worker2 is set up to consume from both high and default priority queues. Celery does not support explicit queue priority, but by allocating workers in this way, you can ensure that high priority tasks are completed faster than default priority tasks (as high priority tasks will always have one dedicated worker, plus a second worker splitting time between high and default). This recipe is also idempotent, in that repeated executions of the recipe will restart any running workers, or start them if they are not running. Returning to OpsWorks, we have to now assign each recipe to a different lifecycle stage. EC2 instances managed by OpsWorks have a “lifecycle” consisting of five stages: - Setup (recipes run when the instance is first launched) - Configure (recipes run whenever a new instance comes online in a layer) - Deploy (recipes run whenever deploying updated code for your app) - Undeploy (recipes run whenever undeploying or removing an app) - Shutdown (recipes run when shutting down an instance) In our case, we will add the rabbitmq::default recipe to the Setup stage, and the supervisor::celery recipe to the Deploy stage. We do this because the RabbitMQ configuration needs to occur only once in the instance’s lifecycle (although the recipe is written in such a way that repeated runs will not fail). The Celery workers, on the other hand, must be restarted every time the app is updated (since a Celery worker knows the app code at the time it was started – a worker must be restarted to include any code changes). With these two recipes, we have set up our jobs layer to be able to correctly launch and configure an instance, without requiring any manual intervention. This means we can easily scale up our queue system to two, four, or a dozen instances without any additional work. The combination of the load balancer and our recipes will cause the work to be distributed evenly across all instances. If an instance were ever to fail, it would automatically be removed from the load balancer, and we can easily launch another instance to take its place. Step 5: Inspecting There are a number of commands and tools you can use to help you get a view on the behavior of your queue system. Worker statuses: ubuntu@jobs:/your_proj$ celery -A <your_proj> status celery@worker1: OK 1 node online. Listing worker processes: ubuntu@jobs:/your_proj$ ps -aux | grep celery ubuntu 7493 0.1 1.5 156712 61144 ? S 14:14 0:01 /usr/bin/python /usr/local/bin/celery -A <your_proj> worker -l INFO -n worker1 ubuntu 9937 0.0 0.0 10460 932 pts/0 S+ 14:32 0:00 grep --color=auto celery Listing queues, number of messages, and number of workers consuming from them: ubuntu@jobs:/your_proj$ sudo rabbitmqctl list_queues name messages consumers Listing queues ... default 0 1 celery@worker1.celery.pidbox 0 1 celeryev.d316d5d8-3a7c-4a35-9008-568844baec08 0 1 ...done. Also highly recommended is “flower” (pronounced flow-er), a web-based dashboard for reviewing workers, recent tasks, and performance metrics. To start flower, run the following command: ubuntu@jobs:/your_proj$ celery -A <your_proj> flower --address=0.0.0.0 --port=5555 Assuming you are running this command from an EC2 instance (and that the instance is able to receive external http requests), you can access flower (specifically, view the last 100 tasks) via a web browser via the following URI: http://<instance IP address>:5555/tasks?limit=100 Final Thoughts We’ve covered a lot of ground with this post, but as with everything in software, there’s miles more left to travel. Some things not discussed: Splitting RabbitMQ from Celery. Currently, we conceive of RabbitMQ and Celery as being a single unit, with separate instances isolated from each other. More sophisticated setups would seperate these, with one or more instances devoted solely to hosting RabbitMQ instances (which can be joined together to form a “cluster”, providing additional fascinating capabilities). Currently, messages are isolated to the jobs instance which first recieved them. If a jobs instance were to go down, all message already recieved (but not yet processed) by that instance would be lost. If your application can tolerate lost messages, then this may be alright. If you cannot, then you should pursue more advanced configurations in which messages are replicated across RabbitMQ instances in a cluster. Configuring flower to run continually, accessible with a username and password. It would not be particularly difficult to keep flower running constantly (perhaps under Supervisor control), accessible via a stable URI and requiring a username and password. This would make it much easier for the entire DevOps team to check on the health of the queue at any time. Hopefully this has been a helpful guide. Building infrastructure is a very, very exciting part of creating software – infrastructure defines the possibilities for what your app can do, and so new infrastructure unlocks possibilities in a way that code by itself rarely does. Please let me know in the comments or via email if there’s anything I’ve left out or you’d like me to expand upon.
http://kronosapiens.github.io/blog/2015/04/28/rabbitmq-aws.html
CC-MAIN-2017-17
refinedweb
3,873
54.12
A customer used the ReadDirectoryChangesW function to monitor a directory for changes, asking for notifications only for changes directly in the directory being monitored ( bWatchSubtree = false). But they found that the ReadDirectoryChangesW function reported a change even when they created a file in a subdirectory, rather than in the directory being monitored. For example, if they asked to monitor the directory C:\dir1, and a file was created at C:\dir1\dir2\file, the ReadDirectoryChangesW function reported a change, even though the file was created in a subdirectory, and the request was for a non-recursive monitor. What gives? We saw some time ago that the purpose of the ReadDirectoryChangesW function is to allow you to maintain a local copy of the contents of a directory: The idea is that you make an initial pass over the directory with FindFirstFile/ FindNextFile, and then you use the notifications from the ReadDirectoryChangesW function to make incremental updates to your local copy. And what happened here is that the contents of an enumeration of the C:\dir1 directory did in fact change. What changed is the last-modified date on C:\dir1\dir2! I actually guessed this answer before I got to the end of the article. I’ve noticed this in the past on sub-directory dates on my system. Two questions come to my mind: – What if something changes between FindFirstFile() and the first call to ReadDirectoryChangesW()? – Why is there no ReadDirectoryChangesA()? 1) Ideally you should call ReadDirectoryChangesW() first, kick off an update pass manually, then have ReadDirectoryChangesW() kick off the same update pass when it’s called, ideally with some locking mechanism in place to keep it from updating the same data simultaneously (unless your code doesn’t have that particular issue). 2) I sincerely doubt that ReadDirectoryChanges existed back in the days of FAT. That would’ve required the OS to implement its own polling mechanisms, which would’ve add complexity and consumed precious CPU, especially with DOS compatibility the way it was back then. It looks like this was introduced in Windows XP/2003 (maybe earlier, 2000 timeframe? MSDN isn’t always reliable for describing when functions were actually introduced). 😑 Why no auto-paragraph detection? Or edit button? Le sigh. There is paragraphs, I can see them perfectly fine for your post. The problem seems to be that if you are logged in, your own posts don’t seem to have paragraphs. Not sure why you’re saying the OS needs to poll to detect changes on FAT volumes, because any changes to FAT volumes came from the OS itself anyway. True. I think I meant to say “hooking” instead; I didn’t think too deeply into that particular sentence. This is a pattern you’ll see everywhere in computer science. If you’re watching incremental updates, begin subscribing BEFORE you make your base copy of whatever is being updated. I thought I read that ReadDirectoryChangesW could have spurious wakeups. Maybe not. Is there a shell equivalent of ReadDirectoryChangesW, to monitor an IShellFolder (or an IShellItem of a folder) for changes? Not everything in the Shell namespace corresponds to a file system directory. For example: my phone SHChangeNotifyRegister looks relevant. It requires a PIDL though, but I suppose you can get that from SHGetIDListFromObject if you have an IShellFolder.
https://blogs.msdn.microsoft.com/oldnewthing/20180712-00/?p=99225
CC-MAIN-2018-30
refinedweb
551
52.29
The special syntax for updating a map, %{var | field: value} is particularly useful with structs. With a plain map, the following gives a runtime erorr: saiyan = %{name: "goku"} saiyan = %{goku | pwer: 9001} because %{var | ...} can only be used to update an existing field. However, with a struct, you'll get a compile-time error: defmodule Saiyan do defstruct [:name, :power] ... end goku = %Saiyan{name: "goku"} goku = %Saiyan{goku | pwer: 9001} ** (CompileError) code.ex:17: unknown key :pwer for struct Saiyan Starting off, it can be a overwhelming to realize that Elixir has at least three ways of interacting with other modules. While there's a bit of overlap, they mostly serve distinct purposes. alias is the simplest to understand and the one you'll use the most. It lets you access a module via a shortened name rather than its full name: MyApp.Service.Auth.user(email, password) # vs alias Myapp.Service.Auth ... Auth.user(email, password) import takes this a step further: once imported, you can access functions directly as though they're defined in the current module: import Myapp.Service.Auth ... user(email, password) Personally, I think you should avoid importing. It makes things obscure: where is user defined? Also, because you lose the context provided by the [hopefully] meaningful module name, for the sake of readability, you'll often have you re-add that context to the function name, such as auth_user. Why bother? First, you have to import a module if you want to use its macros. As a beginner-safe-rule, you should only import when you need to use a module's macros. You can enforce this: import MyApp.Service.Auth, only: :macros You can also import only functions or specific functions or macros. I confess that we do occasionally import functions. Most notably in our tests, where a number of helpers are repeatedly needed. For example, all of our integration tests have access to an imported truncate function which is used to wipe a database clean. use isn't like alias or import but it's so powerful that it can be, and often is, used to inject an alias and/or import. When you use a module, that module's __using__/1 macro is executed. That macro can do anything, which means the behavious of use changes from module to module. defmodule MyApp.Controller.Base do # automatically called when you: use MyApp.Controller.Base defmacro __using__(_opts) do quote do # Gets injected into the calling module import MyApp.Controller.Base # ... probably does more things end end end Above is a somewhat common pattern where a use'd module imports itself. If you're just starting to learn elixir, use when a library / documentation tells you to, and take the opportunity to look at that module's __using__/1 macro to learn what it's doing. You can minimize the presence of __MODULE__ by aliasing it: defmodule DBZ.Saiyan do # Expands to alias DBZ.Saiyan, which means we can now use # Saiyan instead of __MODULE__ alias __MODULE__ def new(name) do %Saiyan{name: name} end end We often do this in our GenServers and give it the name of State (unless something more specific makes sense). This works well when combined with the special update syntax described in tip #1: defmodule Dune.Harvesters do use GenServer alias __MODULE__, as: State defstruct [:lookup, :dispatched] # ... def handle_cast({:destroyed, id}, state) do state = %State{state | lookup: Map.delete(state.lookup, id)} {:noreply, state} end end Elixir's with is useful for dealing with more complex flows, but did you know that you can omit the else clause? The default behaviour is to return whatever broke the flow (and would have triggered the else). In other words, any time you write: with {:ok, decoded} <- Poison.decode(data), {:ok, scores} <- extract_scores(decoded) do # do something with scores else err -> err end You can omit the else block: with {:ok, decoded} <- Poison.decode(data), {:ok, scores} <- extract_scores(decoded) do # do something with scores end Atom's aren't garbage collected. You should be weary of using String.to_atom/1. Doing this on user input, for example, is a good way to run out of memory. One option is to use String.to_existing_atom/1 which raises if the atom isn't already defined. Another option is to leverage matching: def planets("caladan"), do: :caladan def planets("ix"), do: :ix def planets("arrakis"), do: :arrakis def planets(_), do: nil Or less tedious and less readable: for {value, input} <- [caladan: "caladan", ix: "ix", ...] do def planets(unquote(input)), do: unquote(value) end def planets(_), do: nil IO.inspect takes an optional label value which is prepends to the output: IO.inspect("#{min} - #{max}", label: "debug") > debug: "10 - 100" Speaking of IO.inspect, it returns the parameter that you pass into it. This makes it injectable without having to change your code (say, by having to introduce a temporary variable or breaking a pipe chain): case IO.inspect(parse_input(input)) do ... end # or result = String.split(input, ",", parts: 3) |> Enum.map(&String.to_integer/1) |> IO.inspect() |> ... Add the path to the mix test command to run that specific file and optionally include :LINE to run a specific test: mix test test/users_test.exs mix test test/users_test.exs:24 List outdated dependencies by running mix hex.outdated; clean unused dependencies with mix deps.clean --unlock --unused If you find yourself using the same variable from conn.assigns, consider having it automatically injected into your actions: # turn def show(conn, params) do context = conn.assigns[:context] ... end # into def show(conn, params, context) do ... end This can be achieved by overriding action/2 within your controller, (as described in the documentation): def action(conn, _) do args = [conn, conn.params, conn.assigns[:context]] apply(__MODULE__, action_name(conn), args) end If you're new to elixir, you might see a function parameter which includes two backslashes: opts \\ []. This is how elixir defines a default value for a parameter. Default values are related to another strange thing you might spot: functions with no bodies (called function heads). Consider the implementation of Enum.all/2: def all?(enumerable, fun \\ fn(x) -> x end) # No body?! def all?(enumerable, fun) when is_list(enumerable) do ... end def all?(enumerable, fun) do ... end That first line is required by the compiler whenever you use default values and have multiple versions of the function. It removes any ambiguity that might arise from having default values and multiple functions. (Function heads are also useful in more advanced cases where documenting actual implementation(s) is messy or impractical, usually related to macros). Just like normal functions, anonymous functions can also do pattern matching: def extract_errors(results) do Enum.reduce(results, [], fn :ok, errors -> errors # don't do anything {:error, err}, errors -> [err | errors] other, errors -> -> [other | errors] end) end Any function in the Enum module can be implemented using Enum.reduce/3. For example, Enum.map/2 is implemented as a reduce + reverse (since it preserves ordering). You should always consider using the more readable versions, but if you're just getting started, it's a good mental exercise to consider how you'd implement each function using only reduce/3. Also, if performance matters and you have specific needs (like wanting to map but not caring about order), doing things in reduce/3 might be faster. Enum.reduce_while/3 is a powered-up version of reduce/3. It behaves almost the same, including taking the same parameters, but you control when it should stop enumerating the input. This makes it a more efficient solution for implementing Enum.find/2, Enum.take_while/2 and any custom partial enumeration behaviour you need. In the normal reduce/3 the supplied function returns the accumulator, which is passed to the next iteration. With reduce_while/3 the function returns a tuple, either: {:cont, acc} or {:halt, acc}. The values :cont and :halt control whether iteration should continue or halt. These values are stripped from the final return. For example, say we're dealing with user input. We're getting an array of strings. We want to convert them into integers and limit the array to 10 items: {_count, ids} = Enum.reduce_while(param["ids"], {0, []}, fn id, {11, ids} -> {:halt, {10, ids}} # or counter is > 10, stop processing id, {count, ids} -> case Integer.parse(id) do {n, ""} -> {:cont, {count + 1, [n | ids]}} _ -> {:cont, {count, ids}} end end) The most important thing to understand about processes is how they interact with their mailbox. Every process has a queue of pending messages called a mailbox. When you send a message to a process (say via send/2, GenServer.call/2 or GenServer.cast/2), that message is added at the back of the target process' queue. When you receive you dequeue the oldest message from the mailbox. For a GenServer receiving happens automatically; but the important point is that one message is processed at a time. It's not until you return from your handle_call/3, handle_cast/2 or handle_info/2 function that the next pending message will be processed. This is why your processes state is always consistent, it's impossible to have two concurrent threads of execution within the same process overwriting each other's changes to your state. Whether you're using GenServer.cast/2 or call/2 doesn't change anything from the target process' point of view. The difference between the two only impacts the callers behaviour. If you cast and then call, you're guaranteed that the handle_cast will fully execute before the handle_call and thus the handle_call will see any state changes made by the handle_cast A failure in your GenServre's init/1 will take down your entire app. The behaviour might surprise you at first, but it isn't without benefits: it provides a strong guarantee about the state of your app. This is particularly true given that supervisors and their workers are started synchronously. In other words, if you have a supervisor tree that places WorkerB after WorkerA, then WorkerB can be sure that WorkerA has been fully initialized (and thus can call it). If you absolutely need a database connection for your app to work, establish it in init. However, if you're able to gracefully handle an unavailble database, you should establish it outside of your init function. A common pattern is to send yourself a message: def init(_) do send(self(), :connect) {:ok, nil} end def handle_info(:connect, state) do ... {:noreply, new_state} end Because processes only handle one message at a time, you could simply block in the above handle_info/2 until a connection can be established. Any call/2 or cast/2 into this process will only be processed once the above function returns. Of course, by default, call/2 will timeout after 5 seconds (which is probably what you want: the app will startup, but trying to use the features that rely on this process will error). There are a couple properties of nil that you should be aware or. First, because nil, like true and false, is actually an atom, it participates in term ordering rules: nil > 1 > true nil > "1" > false nil > :dune > true nil > :spice > false Secondly the Access behaviour ( var[:key]) ignores nils. So while many languages would throw an exception on the following code, Elixir doesn't: user = nil user[:power] > nil user[:name][:last] > nil Strings that embed quotes can be messy to write and hard to read. Sigils are special functions that begin with ~ aimed at helping developers deal with special text. The most common is the ~s sigil which doesn't require quotes to be escaped: "he said \"it's over 9000!!\"" # vs ~s(he said "it's over 9000") The difference between the lowercase s and uppercase S sigils is that the lowercase one allows escape characters and interpolation: ~s(he said:\n\t"it's over #{power}") > he said: "it's over 9000" # vs ~S(he said:\n\t"it's over #{power}") > he said:\n\t\"it's over \#{power}\" The other popular sigil is ~r to create a regular expression: Regex.scan(~r/over\s(\d+)/, "over 9000") > [["over 9000", "9000"]] Finally, you can always create your own sigils. Lists in Elixir are implemented as linked lists. In the name of performance, this is something you should always be mindful of. Many operations that are O(1) in other languages, are O(N) in Elixir. The three that you'll need to be most vigilant about are: getting the count/length, getting a value at a specific index and appending a value at the end of the list. For example, if you want to know if a list is empty, use Enum.empty?/1 rather than Enum.count/1 == 0 (or match against []code>). While appending a value is O(N), prepending is O(1) - the opposite of what you'd see in languages with dynamic arrays. For this reason, when dealing with multiple values, you should favour prepending (+ reversing if order matters). There are also cases where Erlang's double-ended queue might prove useful. It has O(1) operation to get and add values at both ends of the queue. Sadly, it still doesn't have an O(1) length operation, but you could easily create your own wrapper. Many language us a buffered string when dealing building a string dynamically. While that isn't an option given immutable data structure, we do have a suitable alternative: iolists. An iolist is a list made of binaries (strings) or nested iolists. Here's a simple example, but keep in mind that iolists are often deeply nested: sql = ["select ", ["id", " ,name", " ,power"], " from saiyans"] Much of the standard library and many third party libraries can work with iolists directly: IO.puts(["it's", " ", ["over ", ["9000", "!!!"]]]) > it's over 9000!!! File.write!("spice", ["the", [" ", "spice", [" must", [" flow"]]]]) IO.inspect(File.read!("spice")) > "the spice must flow" In some cases functions that receive an iolist will first convert it to a normal binary then process it (which is what Poison.decode/1 does if you pass it an iolist). However, in other cases, processing happens on the iolist directly. Taking a step back, let's say we have a list of words: colors = ["red", "blue", "green", "orange", "yellow"] To append "grey" via the ++ operator, we need to create a new list and copy all the values into the new list. That's why we say it's O(N). Now consider what needs to happen if we do this as an iolist. The result would look like: colors = [["red", "blue", "green", "orange", "yellow"], "grey"] The original list doesn't change and so its values aren't copied. We do create a new list (the outer brackets). That new list references the original list at its head, and the new value at its tail. The cost of an iolist is no longer tied to the number of elements in the lists. Don't do single statement piping. It's the bad sort of clever. This: params = params |> Map.delete(:id) Is less readable than this: params = Map.delete(params, :id) It's never called for.
https://www.openmymind.net/Elixir-Tips-And-Tricks/
CC-MAIN-2019-13
refinedweb
2,533
64.71
I have a controller for customer. In the new action, I redirect to another page, which belong to the pages controller class CustomersController < ApplicationController def new redirect_to register_path end class PagesController < ApplicationController def registration @customer = Customer.new end end I believe the setup is something like this: you have models in your application for a Customer and, say, an Agent. Your website users register as either and the desire is to have a single HTML page (URL) with both options available. They choose which one they are and submit some fields, say name/email/password. To keep it simple, without bothering with JavaScript to hide things behind tabs, you have something like: **Customer** Name: ___________ Email: __________ Password: _______ [Submit] **Agent** Name: ___________ Email: __________ Password: _______ [Submit] You have a few options here to avoid your guilty feeling in the Rails controllers: newactions on the controllers. The JavaScript creates the page elements. The create action becomes a JSON API endpoint, thereby avoiding the problem in the Ruby application. This is obviously a significant architectural deviation from where I think you are today. newaction of its relevant controller. The downside is a page load to change between the two options. This is the simplest, plainest choice … if you can get the boss to agree to the UX. PS: if you are using turbolinks, then the 'feel' of this option in the browser will be not far from option (2). Keep in mind that you will have difficultly dealing with error conditions and messages with option (4). You can do it, but the code won't be simple or easy to maintain. If option (4) is a must, one simplification can be the create actions on each of the controllers rendering their own new in case of an error. If you submit the 'Agent' form from your starting page, with errors, to the Agents→create action, that action finishes with a render 'new' to show the user the Agents→new page. No 'customer' form is visible. You could then add a sprinkle of option (3) in there with a "Not an Agent? Register as a Customer." link under the form. Doing this greatly simplifies your error handling. Which then leads to a suggestion for your original problem. Cheat. Don't have an @customer instance variable for the new actions (or the registration action). Use partials for the customer and agent forms, and pass in a new object to form_for, e.g. pages/registration.html.erb <%= render 'customers/new_form' %> <%= render 'agents/new_form' %> customers/new.html.erb <%= render 'customers/new_form' %> customers/_new_form.html.erb <% form_for Customer.new do |f| %> <%# include the inputs shared with the edit action %> <%= render 'fields', f %> <%= f.submit %> <% end %> customers/_fields.html.erb <%# 'f' is one of the locals passed to the partial %> <% f.input_field :name %> <% f.email_field :email %> <% f.password_field :password %> customers/edit.html.erb <% form_form @customer do |f| %> <%= render 'fields', f %> <%= f.submit %> <% end %> … then you would follow the same pattern for:
https://codedump.io/share/03c2j1kvVveZ/1/would-it-be-ok-to-create-an-instantiate-an-object-in-another-controller
CC-MAIN-2017-39
refinedweb
495
66.84
2257! That's how many bookmarks I have in my Mozilla browser right now, all of which I upload to my web site every month. Uploading them is not a problem, but displaying them nicely on a web site without server-side support is. That simply rules out SQL, any JSPs, and other fancy stuff. Sure, DHTML is good, but it has its limitations. So, the only solution that remained was to download everything to the client's machine and run it there — an applet, that's it! But that presents its own challenges: the applet has to be small, the index must be pre-generated, and the applet should be able to read the index, retrieve the results, and then display them — all without having to make any calls back to the server. This looks like an ideal candidate for a three-tier web application. After four weeks of meddling with XML, XPath, Swing, and LiveConnect, I came up with SearchAssist, a portable search engine written in Java. It's a Java applet of 30KB, using a ternary search tree. The UI components are a Swing interface and HTML, as shown in Figure 1, and the input format is XML. Other cool features are: Figure 1. SearchAssist Let's go through the entire process of design and development of SearchAssist. When you consider the functionality that is expected, the potential applications of this project become obvious. For example, using XML (instead of the HTML format of Mozilla bookmarks) opens up new usage scenarios: a lightweight help system for another application, perhaps, or a photo album that can be searched using the person's name. The possibilities are endless. The only trick is designing a suitable data format able to support multiple nested levels of bookmarks and topics, such as Mozilla allows (see Figure 2). Figure 2. The Mozilla bookmark manager The XML will have a Category tag as the root. See Figure 3 for an example. A Category can have nested categories or Items as leaves. Both Category and Item have Title tags. Each Item has an additional Link tag that, as the name suggests, contains the link to the actual text, web site, or photo, as the case may be. Each Category or Item is uniquely addressable. Both Category and Item tags have an attribute called uniqueID that contains a string that does not repeat in the document. Such a format is also ideal for storing nested topics for a help system. Category Item Title Link uniqueID Figure 3. An XML input file generated from Mozilla bookmarks The Index, like a book's index, is a map of keywords to locations (much like a book's index points to page numbers where the index entries appear in the main text). In our XML file, the keywords are the text in the Title tags of Category and Item tags. Since each Category and Item tag carries a uniqueID, they are similar to the page numbers in our book index example. For a seasoned Java programmer, a HashMap should come to mind, as it can be serialized to a file. Although this is the right way of thinking, remember that the index must be compact and easily searchable in as few steps as possible. Although widely used (and sometimes overused), the HashMap does not completely satisfy the requirements at hand. It does not differentiate between an Integer, String, or Array, as long as the key is an Object. If there are three keywords words in the XML input file (such as "book," "bookmark," and "booklet"), then a HashMap will treat all three of them as just Objects and hence they will be hashed to completely different locations. Although all three words have a common prefix — "book" — the HashMap cannot use this pattern effectively, being unaware of the nature and content of its keys. HashMap Integer String Array Object A ternary search tree, on the other hand, is designed so that the nodes with the same prefix share the same parent in the search tree. Instead of treating a keyword as a single, unbreakable Object, it is split into an array of Characters. Keys that share common prefixes reuse the same characters. The remaining, unmatched part of the keyword branches off. This way of storing saves a lot of space, as the tree is aware of the keyword's content. Such a data structure automatically lends itself to providing another very useful UI feature — auto-completion. Character Since the index is aware of the keywords, the search program navigates the tree so that the string of characters that have been visited in the tree match the text that the user has typed. If the user has typed "boo", then the tree has seen b, o, and o. The tree can then guess that the user is typing book, bookmark, or booklet, if the tree contains only these three words starting with boo. The tree will supply the closest match that appears first in alphabetical order. If there is no match, there will be no auto-completion, so the user can stop without having to type the entire search word. b o book bookmark booklet boo The search results should be displayed if the user's typed text matches a keyword in the index. Because the actual information can be as varied as simple text, web sites, or photos, the display of search results must be customizable. To achieve this, the actual implementation must be kept separate from the interface — a simple programming idiom. Now that we've hammered out most of the challenges, it's time to design the UI layout. The layout is very minimal, as seen in Figure 4. The most crucial Swing components are a custom JTextField to do auto-completion, a JTextArea to display the list of nearest matches and a JPanel containing a custom JComponent to display the search results. JTextField JTextArea JPanel JComponent Figure 4. The layout of the UI Source Code Download the example source code for this article. The Mozilla bookmarks file must be converted to XML format. A careful observation of the HTML bookmarks file reveals a simple structure that can be easily transformed to the XML structure using SAX. The HTML file contains several attributes that are not required for the transformation, and so can be safely ignored. See MozillaBookmark2XMLConverter.java. MozillaBookmark2XMLConverter.java The resulting XML file, containing the Category, Title, Item, and Link tags, is fed to a small Java program that just echoes the XML tags and text content into another file. It is a simple SAX Handler. It also generates a uniqueID for each Category and Item, adding it as an attribute and value pair. The IDs are generated such that the parent's ID is also preserved in the child's ID. If the parent XML node has an ID of 1_2, its children will have IDs of 1_2_1, 1_2_2, 1_2_3, and so on, as shown in Figure 5. This makes it possible to provide a "Go to Parent" link beside each subtree in the search results. Since every node carries within itself the parent's ID as a prefix, it is very easy to navigate to the parent node. I haven't yet implemented the navigation, though. See XMLIDGenerator.java. 1_2 1_2_1 1_2_2 1_2_3 XMLIDGenerator.java Figure 5. The index-generation algorithm, illustrated The code uses a combination of Stacks and HashMaps to accomplish this. The Stack is used because the parent's ID is a prefix for the child's ID. So, it helps keep track of the depth of the tree. The HashMap keeps track of which sibling the current node is, for that level. A node could be 1_1_3 if it's the second sibling, or 1_1_3, if it's the third. Stack 1_1_3 A list of keywords and their corresponding uniqueIDs is required for the index. Since the uniqueIDs have been generated in the previous step, the next step is to generate the keywords that will point to the uniqueIDs, as shown in Figure 6. Figure 6. The XML input file with keywords Again, a simple SAX handler retrieves the text of the Title tags and tokenizes them. This list of tokens tag will contain non-keywords or stop words such as articles, pronouns, and prepositions that can be weeded out. The stop words are stored in a file that can be referred to by the SAX Handler. The filtered list of keywords is written back as a comma-separated list under a Keywords tag of the parent Category or Title tag. See KeywordTagAdder.java, excerpted here: Keywords KeywordTagAdder.java public void startElement( String namespaceURI, String lName, // local name String qName, // qualified name Attributes attrs) throws SAXException { indentLevel++; nl(); // element name String eName = lName; if ("".equals(eName)) { // namespaceAware = false eName = qName; } currTagName = eName; emit("<" + eName); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { String aName = attrs.getLocalName(i); // Attr name if ("".equals(aName)) { aName = attrs.getQName(i); } emit("\t"); emit(aName); emit("=\""); emit(attrs.getValue(i)); emit("\""); } } emit(">"); } public void characters(char buf[], int offset, int len) throws SAXException { String s = new String(buf, offset, len).trim(); if (!s.equals("")) { // nl(); emit(s); keywords = null; if (currTagName .equals(getTagNameContainingKeywords())) { keywords = s; } } } public void endElement( String namespaceURI, String sName, // simple name String qName // qualified name ) throws SAXException { // element name String eName = sName; if ("".equals(eName)) { eName = qName; // namespaceAware = false } nl(); emit("</" + eName + ">"); //if (currTagName.equals(getTagNameContainingKeywords())) //causes problems if (eName.equals(getTagNameContainingKeywords())) { nl(); emit("<" + getTagNameToPutKeywordsIn() + ">"); nl(); emit(convertToKeywords(keywords)); nl(); emit("</" + getTagNameToPutKeywordsIn() + ">"); } indentLevel--; } With the XML file containing both the Keywords and the uniqueIDs, the ternary search tree can be generated. As a keyword can occur in more than one Category or Item, the ternary search tree stores a List of uniqueIDs instead of just one. This List can provide another useful UI feature. The size() method on the List can determine the number of hits for the corresponding keyword, displayable in square brackets in the JTextArea. The ternary search tree thus populated is serialized into a file and stored on the disk. See TSTGenerator.java. uniqueIDs List size() TSTGenerator.java The steps preceding the actual index generation are required only if the Mozilla bookmarks file is used as the source of information. The index can be generated from any source — it is just a mapping of keywords to lists of unique IDs. The Mozilla bookmarks file may contain some characters that cause the XML parser to fail. Because HTML allows unclosed tags such as <P>, <BR>, <HR>, and <DT>, these unclosed tags must be replaced by their XHTML equivalents — <p />, <br />, <hr />, and <dt />. As URLs may contain ampersands (&) as part of HTTP GET requests, they too must be converted to an XML entity equivalent, such as &. A small Java class finds and replaces such troublemaking strings in the XML file before it is fed to the XML parser. <P> <BR> <HR> <DT> <p /> <br /> <hr /> <dt /> & HTTP GET & The steps described above constitute a simple information transformation pipeline. See SpecialCharactersFilter.java. SpecialCharactersFilter.java.
http://www.onlamp.com/pub/a/onjava/2003/10/01/searchassist.html
CC-MAIN-2014-42
refinedweb
1,845
62.38
The latest version of the book is P2.0, released almost (22-Sep-11) PDF page: All My ebook reader on android (aldiko) can't import the epub version into my library, because some information seems to be set like in the first edition.--abp - Reported in: P1.0 (16-Jan-16) PDF page: Safri (I'm viewing P1.0 on O'Reilly Safari, so I don't know what page number this error is on.) The "Recursion Revisited" section has an initial trampolining implementation of tail-fibo, saying, "You can take the code of tail-fibo and prepare it for trampolining by wrapping the recursive return case inside a function." The section goes on to say, "This requires adding only a single character, the #, to introduce an anonymous function" and "The only difference between this and the original version of tail-fibo is the initial # on line 7." Here is the relevant trampolining implementation that "Recursion Revisited" introduces: (defn trampoline-fibo [n] (let [fib (fn fib [f-2 f-1 current] (let [f (+ f-2 f-1)] (if (= n current) f #(fib f-1 f (inc current)))))] (cond (= n 0) 0 (= n 1) 1 :else (fib 0N 1 2)))) Though the text states that its implementation is similar to "the original version of tail-fibo", in fact it is completely different. This is the original version of tail-fibo, which is from the section "How to Be Lazy": (defn tail-fibo [n] (letfn [(fib [current next n] (if (zero? n) current (fib next (+ current next) (dec n))))] (fib 0N 1N n))) You can't get the implementation of trampoline-fibo from tail-fibo by "adding only a single character, the #". This isn't a simple typo: there are no implementations of fibo that look anything like trampoline-fibo - and certainly none that can be turned into it by adding a # character.--Walter Rader - Reported in: P1.0 (20-Jan-16) PDF page: Safri (I'm viewing P1.0 on O'Reilly Safari, so I don't know what page number this error is on.) The "Including Agents in Transactions" sub-section of chapter 5.4 ("Use Agents for Asynchronous Updates") includes the following text: "A Clojure transaction promises only to send/sendoff an action to the agent; it does not actually perform the action under the ACI umbrella." The correct name for the function is `send-off` - not `sendoff`.--Walter Rader - Reported in: P1.0 (30-Dec-12) PDF page: N/A .mobi version of the file does not contain index.--Hiro Asari - Reported in: P1.0 (15-Aug-12) Paper page: xxi I would lighten up the grey used in the background blocks, for readability.--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: xxii A newline is needed between "... with namespace prompt" and "-> 4 ...".--Rich Morin - Reported in: B3.0 (21-Nov-11) PDF page: 1 The cover on the epub version on page 1 on the nook touch is not scaled to the visible area of the nook.--Steven Proctor - Reported in: P1.0 (18-Apr-12) PDF page: 1 The ebook reader on my Android tablet shows an incorrect thumbnail, it shows "SQL Antipatterns", i.e. images/_covers/bksqla.jpg (the 1st within that directory) instead of images/cover.jpg . Rather, rather strange!--Jochen Hayek - Reported in: P1.0 (20-Jul-12) PDF page: 4 In the description of how the Clojure function blank? works, you don't describe what it does with an empty string. It seems obvious that if every character in the string returns true from the isWhitespace function that the entire expression would return true. But what happens when there are no characters? I would think that the isWhitespace function is never invoked. Does every? return undefined, or default to true or false if it has nothing to work on?--Kim Shrier - Reported in: P1.0 (15-Aug-12) Paper page: 7 I would indent the lines beginning "((> x ..." and "(> x ...".--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 9 The sentence beginning "Clojure provides a ..." contains four instances of a superfluous space following an opening parenthesis, eg: "( on page 115)".--Rich Morin - Reported in: B5.0 (11-Mar-12) PDF page: 10 In the book it states, "...but notice that in the following code the Clojure version has both fewer dots and fewer parentheses than the Java version: // Java "hello".getClass().getProtectionDomain() ; Clojure (.. "hello" getClass getProtectionDomain)" I count two dots in both sets of code. If there was one more function call in the example, then it would seem more accurate saying fewer dots and fewer parentheses. --Grant - Reported in: P1.0 (21-Apr-13) PDF page: 10 In: "but notice that in the following code the Clojure version has both fewer dots and fewer parentheses than the Java version: // Java "hello".getClass().getProtectionDomain() ; Clojure (.. "hello" getClass getProtectionDomain)" The Clojure version has the same amount of dots than the Java one, I see the authors' point, but this is a not-so-well chosen example ;).--J. D. - Reported in: P2.0 (14-Dec-17) Paper page: 11 "Clojure version has both fewer dots and fewer parentheses than the Java version", and the examples given are '"hello".getClass().getProtectionDomain()' in Java and '(.. "hello" getClass getProtectionDomain)' in Clojure. I see the same number of dots, not fewer. Another method call maybe? Extremely nit picky I know, sorry.--Jaihindh Reddy - Reported in: B4.0 (06-Jan-12) PDF page: 15 The hello user with memory example is incomplete and so is the associated source code. It seemed fine in the previous release (i.e. b3).--David Sweeney - Reported in: B5.0 (30-Mar-12) PDF page: 16 Link for the Github Repo in the footnote probably isn't the up to date code. Please update it with the latest or totally remove it. Wasted an hour on it when i saw that the repo was last update "6 months ago"--Suvash Thapaliya - Reported in: B3.0 (21-Nov-11) PDF page: 17 In the epub version on the nook touch, footnotes 3 and 4 on page 17 do not have the full url it stops after the "//".--Steven Proctor - Reported in: P1.0 (15-Aug-12) Paper page: 24 I would change "... for the dividend." to "... for the dividend or the divisor.".--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 25 The word "Namespaces" should be hyphenated as "Name-spaces", rather than "Names-paces".--Rich Morin - Reported in: B3.0 (20-Nov-11) PDF page: 26 URLs in footnotes (as on this page, but there are others) are missing the ':' after 'http'. The linked URL itself is correct, i.e. the hyperlink works, but the 'printed' URL lacks the semicolon. --Justin Forder - Reported in: B5.0 (02-Mar-12) PDF page: 29 Where is says “To run Clojure and the code in this book, you need two things:” I think it would be beneficial to say you need 3 things instead, with the third being a copy of the code repository for this book. I know this information is clarified shortly below where it says “See Section 6…” but when skim reading (like I was doing) it gives the appearance that section 6 is, in fact, much further down in the book as this is chapter 1 and thus the information won’t be needed until later. This caused some confusion for me later on in the book when I was trying the ”->Book” example in one of the later sections and it didn’t work because I hadn’t used leiningen to get the core dependences I needed. I believe by putting the repository for the code as a third dot point and by not referring to it as “Section 6” it would make the reader pay more attention that this process is essential to learning with the book; especially if they are skimming the first chapter as I was doing.--Adrian Tompkins - Reported in: P1.0 (22-Oct-12) PDF page: 30 Instantiating the record, (->Book "title" "author"), returns an error: "java.lang.Exception: Unable to resolve symbol: ->Book in this context" Instantiating the record with (Book. "title" "author") seems to work.--Robert Sutter - Reported in: P1.0 (15-Aug-12) Paper page: 30 The period (just before the colon) in "... a record with user.Book.:" seems out of place and is confusing. Please change and/or explain this.--Rich Morin - Reported in: P1.0 (22-Nov-13) Paper page: 31 Add index entry for #() anonymous-function notation--Phill - Reported in: P1.0 (22-Nov-13) Paper page: 31 Add index entry for #"" regular-expression notation--Phill - Reported in: B4.0 (21-Feb-12) PDF page: 32 I also tested the code and the following does not work (defrecord Book [title author]) (->Book "title" "author") I then tried the following and it worked. (Book. "title" "author") - Reported in: P1.0 (15-Aug-12) Paper page: 36 In the section "When to Use Anonymous Functions", I'd like to see some discussion of the benefits of named functions (eg, decomposition of code, documentation).--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 37 Change "... the var bound to ..." to "... the var that is bound to ...".--Rich Morin - Reported in: P1.0 (14-Nov-13) PDF page: 40 for destructuring forms, the ref to the `let` doc is misleading,since currently the special_forms documentation has a specific "Binding Forms (Destructuring)" section. - Reported in: P1.0 (15-Aug-12) Paper page: 42 The word "namespace" should be hyphenated as "name-space", rather than "names-pace".--Rich Morin - Reported in: B1.0 (16-Sep-11) PDF page: 42 Found another instance of a "word" being highlighted as if it were a function when it isn't being referenced as one in the require form just prior to the defn for ellipsize. str in the :as clause is highlighted, but I don't think it should be. It's subtle, but could be confusing. Might be worth doing a search for all instances of Clojure functions and confirm that they are actually being referred to as functions when highlighted as such?--Doug South - Reported in: P1.0 (15-Aug-12) Paper page: 43 In "... into a Clojure Var:", I do not think "Var" should be in monospace font, nor that the "v" should be capitalized.--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 43 It would be useful to clarify that nextInt is a _Java_ method, eg: "The . can call Java methods."--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 45 I would expand "... from REPL when exploring." to "... from the REPL when you are exploring."--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 45 The sentence "If the first argument to if is logically false, it returns nil:" is a bit awkward and potentially confusing. How about changing "it" to "if"?--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 46 "The Swiss Army knife of flow control in Clojure is loop:" seems awkward. How about "loop is the Swiss Army knife of flow control in Clojure:"?--Rich Morin - Reported in: B3.0 (22-Nov-11) PDF page: 48 In the epub version on the nook touch, Table 1, the underline of "Using Numeric Types" for the link is not under that part of the text, but spans the whole part of the line that is before that text.--Steven Proctor - Reported in: B3.0 (01-Dec-11) PDF page: 48 Can't turn past page 48 on the kobo ebook reader. Crashes the reader and forces a reboot. If I go to page 100, and then attempt to go to page 50, it reboots. Using Acrobat digital editions, it's the table on page 48 of the epub that it can't reach.--Graham - Reported in: B5.0 (28-Feb-12) PDF page: 49 The use of -> to represent the result of an evaluation is somewhat confusing as there is a macro that uses same symbol. So if you try searching the book to find what -> means you end up with a *lot* of matches. This is most confusing at the bottom of PDF page 48/top of PDF page 49 where you instantiate a Book instance with: (def b (->Book "Anathem" "Neal Stephenson")) Without explaining what the -> macro does (and neither is it defined in the index) . Hope this helps.--Aled Davies - Reported in: P1.0 (01-Aug-15) Paper page: 50 The last sentence of "Using numeric types": "Notice that only one BigInt literal is needed and is contagious to the entire calculation." is true only if the "N" is put "left enough" in the computation chain: (* 1000000N 1000000 1000000 1000000 1000000 1000000) is ok, where: (* 1000000 1000000 1000000 1000000 1000000 1000000N) will rise an exception. It's somewhat obvious from what you wrote about left to right evaluation (though I had to try in REPL to be sure), but It sorted of "jumped out" when I was reading, so I thought it might be worth reporting. Oh... and congratulations: great book so far! :)--Riccardo Di Meo - Reported in: P1.0 (13-Nov-13) Paper page: 52 the metadata tag attached to the argument `s` seems to make no visible difference, as :tag merely shows the tag attached to the retval. - Reported in: P1.0 (22-Nov-13) Paper page: 57 Add index entry for "inner class, notation for name of" --Phill - Reported in: P1.0 (15-Aug-12) Paper page: 58 The discussion of traversal order in maps and sets seems out of place. It _follows_ several examples which show (but do not explain) that the order in the definition may not be preserved.--Rich Morin - Reported in: B5.0 (01-Mar-12) PDF page: 60 Example on page 60 where you are explaining how maps can be treated as sequences too: (first {:fname "Aaron" :lname "Bedra"}) -> [:lname "Bedra"] // Should Be: -> [:fname "Aaron"] (rest {:fname "Aaron" :lname "Bedra"}) -> ([:fname "Aaron"]) // Should Be: -> [:lname "Bedra"] Looks like the results got mixed up--Joshua Niehus - Reported in: P1.0 (15-Aug-12) Paper page: 61 The bullet item "Sequence predicates" could be written as "Functions that test sequences".--Rich Morin - Reported in: P1.0 (14-Apr-12) PDF page: 61 Based on the result of (doc range), 'end' is optional, defaulting to infinity if not provided. The definition of 'range' in the pdf implies 'end' is a required argument.--Cameron Donaldson - Reported in: P1.0 (15-Aug-12) Paper page: 64 "its argument is vowel." should be "its argument is a vowel.".--Rich Morin - Reported in: P1.0 (10-May-12) Paper page: 67 I was using Clojure 1.4.0 with the book. Clojure 1.4.0 is a newer version so it could be the Clojure 1.4.0 run-time causing the error. For the code :- (sort-by :grade > [{:grade 83} {:grade 90} {:grade 77}]) If this code is run from the REPL, works fine, no problem. If however you run this code from a Clojure script, under Clojure 1.4.0 is generates an ArityException. The interpreter just doesn't like this code.--G R Smith - Reported in: P1.0 (10-May-12) Paper page: 67 PLEASE IGNORE ISSUE 49300. I MISTYPED SOME CODE. This was me being stupid.--G R Smith - Reported in: P1.0 (15-Aug-12) Paper page: 68 I would change "[according to format instructions]." to "[according to format instructions] [the] word."--Rich Morin - Reported in: B4.0 (26-Dec-11) PDF page: 69 at the end of the page "As an example of how much more general the functional index-of-any is, you could use code what we just wrote to find the third occurrence of “heads” in a series of coin flips:" the "use code what we just wrote" should probably be "use code that we just wrote"--Zev Blut - Reported in: P1.0 (15-Aug-12) Paper page: 73 The format of the example output "-> [Ljava.io.File;@..." does not match what I get from the REPL: "#<File[] [Ljava.io.File;@...>".--Rich Morin - Reported in: P1.0 (14-Nov-13) PDF page: 73 (import '(java.io File)) (.listFiles (File. ".")) -> [Ljava.io.File;@1f70f15e The syntax (Class. foo) to invoke a java ctor is used here for the first time, is elided and really should have been shown back where (new Foo) was discussed. - Reported in: P1.0 (08-Mar-14) PDF page: 76 (15-Aug-12) Paper page: 78 The drop/take combination also differs from subvec in that it takes different arguments and is called quite differently.--Rich Morin - Reported in: B3.0 (22-Nov-11) PDF page: 78 Page 78 on epub on nook touch. Table 2. is getting cut off. the table title stops after "functional", and the last column is "Variables". These may be the last things in the table, but the border is not showing so I am unable to tell if there are or not.--Steven Proctor - Reported in: P1.0 (15-Aug-12) Paper page: 80 I would change "... only the keys passed in." to "... only the pairs for the keys that were passed in.".--Rich Morin - Reported in: B4.0 (26-Dec-11) PDF page: 87 It might help clarify the power of "for" from map in the example by showing how map differs. user=> (map #(format "%c%d" %1 %2) "ABCDEFGH" (range 1 9)) ("A1" "B2" "C3" "D4" "E5" "F6" "G7" "H8") user=> (for [rank (range 1 9) file "ABCDEFGH"] (format "%c%d" file rank)) --Zev Blut - Reported in: P1.0 (04-Jan-15) PDF page: 87 The second footnote contains a broken link. You can easily find the correct link by Googling.--Marcus Russi - Reported in: P1.0 (15-Aug-12) Paper page: 92 In the tail-fibo code block, "next" is emboldened each time it appears. However, "next" is simply a parameter to the local function fib, not the Clojure next function. (This also occurs on p. 93 and possibly elsewhere; your formatting software may need some tweaks.)--Rich Morin - Reported in: P1.0 (21-Sep-14) PDF page: 94 Paper page: 76 The parse example on page 94 refers to parse without first telling the reader they should user or import xml. - Reported in: P1.0 (15-Aug-12) Paper page: 95 I would add a usage example after the fibo definition, eg: "(take 5 (fibo))".--Rich Morin - Reported in: B5.0 (17-Mar-12) PDF page: 96 Under the section Tail Recursion, in the code listing for the 'tail-fibo' function, the formatting rules appear to be that the bold magenta font is used for functions, special forms and macros... and normal black font for the rest. If this is the case, then the lexically bound formal parameter 'next' should not be in bold magenta font, as it's confusing for the reader. Initially it makes you think it's a function, when it's not.--Umesh Telang - Reported in: B4.0 (25-Feb-12) PDF page: 96 In the tail-fibo example: (fib 0N 1N n))) Causes this error in lein repl: java.lang.NumberFormatException: Invalid number: 0N java.lang.NumberFormatException: Invalid number: 1N java.lang.Exception: Unable to resolve symbol: n in this context (NO_SOURCE_FILE:0) java.lang.Exception: Unmatched delimiter: ) java.lang.Exception: Unmatched delimiter: ) java.lang.Exception: Unmatched delimiter: ) Changing to: (fib 0 1 n))) Makes the example work though you're not getting BigInt literals. System: Max OSX Snow Leopard Lein: Leiningen 1.6.2 on Java 1.6.0_29 Java HotSpot(TM) 64-Bit Server VM --Troy S Denkinger - Reported in: P1.0 (15-Aug-12) Paper page: 100 There is an extra space following the first :t in "[:h :t :t ...", three times on this page.--Rich Morin - Reported in: B3.0 (22-Nov-11) PDF page: 109 Page 109 in epub on nook touch. The section title for 3.5 is cut off from rendering, and does not wrap. It shows "3.5 Calling Structure-Specific Func-", the "tions" part is not displayed at all.--Steven Proctor - Reported in: P1.0 (22-Jan-14) PDF page: 111 The second paragraph makes this suggestion "Rebind m and f to memoized versions of themselves, using Clojure’s memoize function", but if I'm typing out all of the examples out of the book it doesn't work. I can memoize, but later when I try to invoke the memoized function I get the following error: "StackOverflowError clojure.lang.AFn.applyToHelper (AFn.java:155)" ... when I took a look at the example code from github I found that f/m are defined slightly differently using (defn-, which as I understand it--and I do thanks to you folks!--defines a function privately for just that namespace. Anyway, it was a bit confusing. Thanks!--Michael Avila - Reported in: P1.0 (15-Aug-12) Paper page: 114 I would change "... power into cores." to "... power into individual processing cores."--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 114 I think that "complect" deserves more than just a footnote. How about an explanatory block?--Rich Morin - Reported in: P1.0 (15-Aug-12) Paper page: 115 In the paragraph beginning "Clojure's model for ...", the word model is used several times with varying (though related) meanings. This seems needlessly confusing.--Rich Morin - Reported in: P1.0 (26-May-12) Paper page: 115 In the second paragraph, last sentence it says "...and not ask yourself...". That should be 'now' instead of 'not'.--Michael C - Reported in: P1.0 (15-Aug-12) Paper page: 116 It might be useful to show that the prior value persists after a ref-set call. For example, "(def snap current-track)" before the ref-set and "snap" afterwards.--Rich Morin - Reported in: P1.0 (16-Nov-13) PDF page: 116 I believe the description of "atomic" transactions is wrong. The description for atomic is actually roughly quivalent to the "isolated" property description. "atomic" means "all-or-nothing", while the description emphasizes the "all" guarantee which constitutes isolation. - Reported in: P1.0 (05-Jan-13) PDF page: 118 In my version of the text,`(alter ref update-fn & args...)` has the word `ref` typeset in bold purple, which makes it appear to be the Clojure `ref` function. But really you want `ref` to indicate an argument (e.g. a placeholder for the name of a ref). So, to fix, just remove the bold purple formatting.--David James - Reported in: P1.0 (05-Jan-13) PDF page: 119 My version of `(commute ref update-fn & args...)` has `ref` in bold purple. This is confusing because it makes it appear that `ref` is a 'built-in' Clojure function. It is clearer to make the formatting be plain. If automatic syntax highlighting is to blame, then perhaps use `ref-symbol` or `the-ref` instead of `ref`. You may want to check for additional examples of this happening -- I've already found one other (on the previous page).--David James - Reported in: P1.0 (11-Jul-12) PDF page: 125 I'm not sure if this is a change from 1.3 to 1.4, but I don't see a change-note in 1.4, so … See: After the agent tries to update itself on a pooled thread, it will enter an exceptional state. You will discover the error when you try to dereference the agent: @counter -> java.lang.Exception: Agent has errors This does not appear to be the case; user=> (send counter (fn [_] "boo")) #<Agent@6f93ee4 FAILED: 0> user=> @counter 0 user=> I get the pre-failed result. (agent-errors counter) works as advertised, though (clear-agent-errors counters) returns the value of the agent and not nil as shown in the book: (clear-agent-errors counter) -> nil @counter -> 0 Reality: user=> (agent-errors counter) (#<IllegalStateException java.lang.IllegalStateException: Invalid reference state>) user=> (clear-agent-errors counter) 0 user=> HTH!--Arlen Cuss - Reported in: P1.0 (15-Aug-12) Paper page: 127 "in the following tabler." should be "in the following table."--Rich Morin - Reported in: P1.0 (22-Nov-13) Paper page: 127 I think maybe the top row of the table is what the sentence below the table refers to with "the unified update model is the most important way...", while the succeeding rows are the "ancillary... optimizations"? But this is unclear. The table needs labels.--Phill - Reported in: P1.0 (16-Apr-12) PDF page: 127 Last word of the first paragraph under 5.4's "The Unified Update Model" "Tabler" should be "Table"--Cameron Donaldson - Reported in: P1.0 (17-Nov-13) PDF page: 128 the inclusion of metadata tag ^:dynamic in `(def ^:dynamic foo 10)` is distracting. it's not explained, nor even mentioned, it's unclear whether the inclusion or ommision of the tag makes any practical difference. - Reported in: B3.0 (23-Nov-11) PDF page: 130 The Sharp is not getting rendered after the C and the flat is not getting rendered after the D. Those are non-printable characters it would seem. In the PDF it is just showing a space, and when I look at it on the nook touch, it is showing a the non-printable unfilled rectangle. It is in the sentence: "The pitch will be represented by a keyword like :C, :C#, :Db, which represent the notes C, C (C sharp), and D (D flat), respectively."--Steven Proctor - Reported in: P1.0 (07-Sep-12) Paper page: 131 in manual has printed an old form for : ...... (startElement [uri local-name q-name #^Attributes atts] .......... the form #^..... is not found in any document (ver 1.3 or newer) The correct form shold be : (startElement [uri local-name q-name ^Attributes atts] or would it be useful to explain the meaning of #^ il text resume the source of xml.clj Ciao --Ugo Vierucci - Reported in: B4.0 (19-Feb-12) PDF page: 134 The sentence "When you call def or defn, you create a dynamic var, often called just a var." is somewhat misleading. A var is only dynamic if it has the :dynamic meta attribute set.--David Leung (@davleung) - Reported in: P1.0 (18-Apr-12) PDF page: 140 "Line 15 returns a vector with the snake, apple, and time" should read "Line 15 returns a vector with the snake, apple, and timer"--Cameron Donaldson - Reported in: P1.0 (13-Feb-13) Paper page: 147 (definterface IOFactory (^java.io.BufferReader make-reader [this]) (^java.io.BufferedWriter make-writer [this])) should be : (definterface IOFactory (^java.io.BufferReader make-reader []) (^java.io.BufferedWriter make-writer [])) --Yuexiang Zhang - Reported in: P1.0 (14-Sep-12) Paper page: 147 in (definterface IOFactory has an error in: (^java.io.BufferReader make-reader [this]) ...... correct in (^java.io.BufferedReader make-reader [this]) .....--ugo vierucci - Reported in: P1.0 (14-Sep-12) Paper page: 150 in make-writer[dst] for URL is wrong (->dst .getPath FileInputStream.) correct : (->dst .getPath FileOutputStream.) --ugo vierucci - Reported in: P1.0 (14-Sep-12) Paper page: 150 after : Now let's put it all together add the row src/examples/io.clj in reversed mode as in previous pages --ugo vierucci - Reported in: B3.0 (22-Nov-11) PDF page: 150 Page 150 in epub on nook touch. Chapter 5. The title of the chapter is cut off and not rendering the complete chapter name. It is rendering "Protocols and Data-".--Steven Proctor - Reported in: B5.0 (05-Apr-12) PDF page: 150 very very minor suggestion - I think the line "Clojure’s spit and slurp I/O functions are built on two abstractions, reading and writing." at the top of the page should read "Clojure’s slurp and spit I/O functions are built on two abstractions, reading and writing." , as in their minds, people would tend to implicitly order the abstractions the same as the I/O functions mentioned. Overall, the section clarifies this, but it would read better if the ordering of the I/O functions was the same as the abstractions mentioned associated with them.--Umesh Telang - Reported in: P1.0 (14-Sep-12) Paper page: 151 in make-writer [dst ] for URL has an error in: (-> dst .getPath FileInputStream.) correct in (-> dst .getPath FileOuputStream.) --ugo vierucci - Reported in: P1.0 (14-Sep-12) Paper page: 155 in (ns examples.cryptovault_complete (:require [clojure.java.io :as io] [examples.protocols.io :as proto]) ....................... has is wrong: 'examples.protocols.io' the correct form is: (ns examples.cryptovault_complete (:require [clojure.java.io :as io] [examples.io :as proto]) .................--ugo vierucci - Reported in: P1.0 (09-May-14) PDF page: 157 C (C sharp) should be C# (C sharp) D (D flat) should be Db (D flat) D half note should be D# half note--art g - Reported in: B3.0 (22-Nov-11) PDF page: 161 Page 161 of epub on nook touch. The cryptovault.clj code formatting is off with the line wraps weird. The "... define method body here ...)" is having wrapping or newline issues. It winds up displaying, with the '/n' for where the line breaks, "../n. define method body here ../n.)". It is doing that on the init-value, vault-output-stream, vault-input-stream method declarations.--Steven Proctor - Reported in: P1.0 (06-May-14) PDF page: 162 Paper page: 180 In section 6.6 - when calling reify on MidiNote there are a number of errors in the generator.clj implementation. All the functions defined in MidiNote that are implemented in the reify macro call, need to be called using the Java interop syntax of preceeding 'function' (method) calls with a dot. This is because MidiNote is imported rather than required/used so presumably it's used in the same manner as a Java interface. Also, as the 'perform' function is not part of the MidiNote protocol it needs to be fully qualified as 'examples.datatypes.midi/perform'. E.g. (ns examples.generator) ; START: midinote (import '[examples.datatypes.midi MidiNote]) (let [min-duration 250 min-velocity 64 rand-note (reify MidiNote (to-msec [this tempo] (+ (rand-int 1000) min-duration)) (key-number [this] (rand-int 100)) (play [this tempo midi-channel] (let [velocity (+ (rand-int 100) min-velocity)] (.noteOn midi-channel (.key-number this) velocity) (Thread/sleep (.to-msec this tempo)))))] (examples.datatypes.midi/perform (repeat 15 rand-note))) ; END: midinote --Chris Howe-Jones - Reported in: B4.0 (30-Dec-11) PDF page: 166 This may or may not be a technical error but even when copy-and-pasting sample code (and/or typing it manually from the book) I get the following message twice: user=> CompilerException java.lang.RuntimeException: Unable to resolve symbol: this in this context, compiling:(NO_SOURCE_PATH:21) --Kiyu Gabriel - Reported in: B5.0 (05-Mar-12) PDF page: 174 Paper page: 160 src/examples/cryptovault.clj (init-vault [vault] should read (defn init-vault [vault] --Ernesto Schirmacher - Reported in: B5.0 (05-Mar-12) PDF page: 175 Paper page: 161 The two method definitions in the code listings are missing the defn: (vault-output-stream [vault] SHOULD READ (defn vault-output-stream [vault] and (vault-input-stream [vault] SHOULD READ (defn vault-input-stream [vault]--Ernesto Schirmacher - Reported in: P1.0 (30-Aug-12) PDF page: 177 Paper page: 159 It's just the absence of the final closing parenthesis: (extend-type Note MidiNote (to-msec [this tempo] (let [duration-to-bpm {1 240, 1/2 120, 1/4 60, 1/8 30, 1/16 15}] (* 1000 (/ (duration-to-bpm (:duration this)) tempo)))) should be: (extend-type Note MidiNote (to-msec [this tempo] (let [duration-to-bpm {1 240, 1/2 120, 1/4 60, 1/8 30, 1/16 15}] (* 1000 (/ (duration-to-bpm (:duration this)) tempo))))) --Iván González Aguilar - Reported in: P1.0 (20-Nov-13) PDF page: 178 There's a distinction to be made between special forms hardcoded into the language evaluator, and macro invocation where args are evaulated differently then normal forms. the former are special by virtue of being part of the language , while the latter are different by virtue of the semantics of macros. You can *mimic* special forms with macros, but you can't create new ones except by modifying the language. - Reported in: P1.0 (30-Aug-12) PDF page: 179 Paper page: 161 Got this error with the dot syntax for a new instance: user=> (perform (for [velocity [64 80 90 100 110 120]] (assoc (Note. :D 3 1/2) :velocity velocity))) CompilerException java.lang.IllegalArgumentException: Unable to resolve classname: Note, compiling:(NO_SOURCE_PATH:12) just changing to Record syntax and works well: user=> (perform (for [velocity [64 80 90 100 110 120]] (assoc (->Note :D 3 1/2) :velocity velocity))) ->nil --Iván González Aguilar - Reported in: P1.0 (20-Nov-13) PDF page: 184 up to this point in the book, no discussion or mention of exceptions/try/finally has been made. the comment on "using a finally block" lacks the proper exposition. - Reported in: P1.0 (08-Mar-14) PDF page: 184 (17-Jun-13) PDF page: 190 prose concerns my-print, code example uses my-println instead: " Unsurprisingly, attempts to call my-print will fail: (my-println "foo") " --giles - Reported in: B4.0 (15-Jan-12) PDF page: 201 You use ::acc/Checking in the namespace corresponding to the one aliased to acc in namespace user. Besides this, I think it is confusing to use :: in namespace qualified keywords.--Juan Manuel Gimeno Illa - Reported in: P1.0 (12-Sep-15) PDF page: 205 Modify the existing my-println to add a new cond invoking the feature-specific helper. should be Modify the existing my-print to add a new cond invoking the feature-specific helper.--Jesper Rosenkilde - Reported in: P1.0 (12-Mar-14) Paper page: 217 (defn painstakingly-create-array [] ... (aset arr2 "fill) ---------^--Frei zhang - Reported in: P1.0 (26-Sep-12) PDF page: 232 Paper page: 217 There is a typo in the function: (aset arr2 "fill") (defn painstakingly-create-array [] (let [arr (make-array String 5)] (aset arr 0 "Painstaking") (aset arr 1 "to") (aset arr2 "fill") (aset arr 3" in") (aset arr 4 "arrays") arr)) It should be: (defn painstakingly-create-array [] (let [arr (make-array String 5)] (aset arr 0 "Painstaking") (aset arr 1 "to") (aset arr 2 "fill") (aset arr 3" in") (aset arr 4 "arrays") arr))--Iván González Aguilar - Reported in: P1.0 (02-Apr-13) PDF page: 235 3rd line: - How hard is it write a program should be: - How hard is it to write a program--Roman - Reported in: P1.0 (02-Apr-13) PDF page: 237 Last line is: (< 0 (matches score) (count secret))) Should be `<=` instead of `<`, as the range for the number of matches should include the edges.--Roman - Reported in: P1.0 (21-Nov-12) PDF page: 240 Paper page: 225 This does not work on windows "java -cp .:pinger-0.0.1-standalone.jar pinger.core". The classpath uses ';' semi colons on windows.--Robin Luiten - Reported in: P1.0 (02-Apr-13) PDF page: 240 First line: - test-namespaces takes on more namespaces should be: - test-namespaces takes one or more namespaces--Roman - Reported in: P1.0 (02-Apr-13) PDF page: 243 The command `lein plugin install lein-noir 1.2.0` no longer works. In Leiningen 2.x plugins should be specified in `project.clj` or `~/.lein/profiles.clj`--Roman - Reported in: P1.0 (02-Apr-13) PDF page: 243 `lein noir new clojurebreaker` should be `lein new noir clojurebreaker`--Roman - Reported in: P1.0 (15-Aug-12) Paper page: 249 The "Git" heading needs to be swapped with the paragraph "This will provide ...".--Rich Morin - Reported in: P1.0 (02-Oct-12) PDF page: 253 Paper page: 238 The name of the function is wrong: (scoring-is-bound-by-number-of-pegs secret guess (game/score secret guess)) This should be: (scoring-is-bounded-by-number-of-pegs secret guess (game/score secret guess)) --Iván González Aguilar - Reported in: P1.0 (22-Nov-13) Paper page: 260 Index entry for "extend" should also "see proxy"--Phill - Reported in: P1.0 (15-Aug-12) Paper page: 262 Add an index entry for load-file.--Rich Morin
https://pragprog.com/titles/shcloj2/errata/
CC-MAIN-2018-34
refinedweb
6,044
66.84
How to Trigger a Mule Flow From Java Triggering a Mule flow or a sub-flow by sending it a message payload and then using the response payload for your further processing is pretty straightforward. Join the DZone community and get the full member experience.Join For Free While working on an integration project in Mule ESB, there are various situations where you would like to trigger a Mule flow or a sub-flow by sending it a message payload and then using the response payload for your further processing. Doing this is pretty straightforward. Today, I will show you how to do it. However, before I move forward into all the code and XML involved in doing the flow calls from Java code, let’s first see some scenarios where we would require to do this. - Suppose you are creating a SOAP web-service using Mule CXF and now you want to use the Mule message process for XML-to-object or object-to-XML conversion. You create two sub-flows to do this. They work perfectly when you test them using a test flow with HTTP inbound. Now, the problem is how to call them in your service implementation class of the web-service. - You have created a super awesome DataWeave conversion for your two different kind of data sets and you don’t want to write the same logic in your some Java class. How to Do It To achieve calling a Mule flow in your Java code, the first thing we need to do is make our calling Java class aware of the Mule context. To do this, we will be using Spring's implementation of the aware pattern where if we implement a interface on our class (i.e., MuleContextAware), then Spring will automatically provide the MuleContext object to our class. - Don’t forget to create a variable for your MuleContext muleContext. - Don’t forget to generate setter method for your muleContextvariable. public class HelloWorldWSImpl implements MuleContextAware { MuleContext muleContext; @Override public void setMuleContext(MuleContext context) { muleContext = context; } } Once you are done with making your class MuleContext aware, the next step is to use this object and get reference to the flow or sub-flow using the name of flow that you created in mule-config.xml. @SuppressWarnings("deprecation") public Object triggerMuleFlow(String flowName, boolean isSubFlow, Object inputData, Object returnClass) { try { if (!isSubFlow) { Flow flow = (Flow) muleContext.getRegistry().lookupFlowConstruct(flowName); // Can be implemented in same way as below } else { MessageProcessor subFlow = muleContext.getRegistry().lookupObject(flowName); MuleMessage muleMessage = new DefaultMuleMessage(inputData, muleContext); MuleEvent inputEvent = new DefaultMuleEvent(muleMessage, MessageExchangePattern.REQUEST_RESPONSE, new DefaultMuleSession()); MuleEvent result = subFlow.process(inputEvent); returnClass = result.getMessage().getPayload(); } } catch (Exception e) { e.printStackTrace(); } return returnClass; } The code above is self-explanatory. What we are doing here is doing a looking up a flow from the Mule registry and then creating a MuleMessage to be sent to this flow with the payload data that our flow or sub-flow expects. Once we are done with the call, we get the result of the call by getting the payload out of MuleEvent, generated as a result of flow triggering. As you can see, it is very simple to trigger a flow or sub-flow from a Java class. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/trigger-mule-flow-from-java
CC-MAIN-2022-27
refinedweb
549
53.61
I'm making my way through "Programming in Scala" and wrote a quick implementation of the selection sort algorithm. However, since I'm still a bit green in functional programming, I'm having trouble translating to a more Scala-ish style. For the Scala programmers out there, how can I do this using Lists and vals rather than falling back into my imperative ways? As starblue already said, you need a function that calculates the minimum of a list and returns the list with that element removed. Here is my tail recursive implementation of something similar (as I believe foldl is tail recursive in the standard library), and I tried to make it as functional as possible :). It returns a list that contains all the elements of the original list (but kindof reversed - see the explanation below) with the minimum as a head. def minimum(xs: List[Int]): List[Int] = (List(xs.head) /: xs.tail) { (ys, x) => if(x < ys.head) (x :: ys) else (ys.head :: x :: ys.tail) } This basically does a fold, starting with a list containing of the first element of xs If the first element of xs is smaller than the head of that list, we pre-append it to the list ys. Otherwise, we add it to the list ys as the second element. And so on recursively, we've folded our list into a new list containing the minimum element as a head and a list containing all the elements of xs (not necessarily in the same order) with the minimum removed, as a tail. Note that this function does not remove duplicates. After creating this helper function, it's now easy to implement selection sort. def selectionSort(xs: List[Int]): List[Int] = if(xs.isEmpty) List() else { val ys = minimum(xs) if(ys.tail.isEmpty) ys else ys.head :: selectionSort(ys.tail) } Unfortunately this implementation is not tail recursive, so it will blow up the stack for large lists. Anyway, you shouldn't use a O(n^2) sort for large lists, but still... it would be nice if the implementation was tail recursive. I'll try to think of something... I think it will look like the implementation of a fold. Tail Recursive! To make it tail recursive, I use quite a common pattern in functional programming - an accumulator. It works a bit backward, as now I need a function called maximum, which basically does the same as minimum, but with the maximum element - its implementation is exact as minimum, but using > instead of <. def selectionSort(xs: List[Int]) = { def selectionSortHelper(xs: List[Int], accumulator: List[Int]): List[Int] = if(xs.isEmpty) accumulator else { val ys = maximum(xs) selectionSortHelper(ys.tail, ys.head :: accumulator) } selectionSortHelper(xs, Nil) } EDIT: Changed the answer to have the helper function as a subfunction of the selection sort function. It basically accumulates the maxima to a list, which it eventually returns as the base case. You can also see that it is tail recursive by replacing accumulator by throw new NullPointerException - and then inspect the stack trace. Here's a step by step sorting using an accumulator. The left hand side shows the list xs while the right hand side shows the accumulator. The maximum is indicated at each step by a star. 64* 25 12 22 11 ------- Nil 11 22 12 25* ------- 64 22* 12 11 ------- 25 64 11 12* ------- 22 25 64 11* ------- 12 22 25 64 Nil ------- 11 12 22 25 64 The following shows a step by step folding to calculate the maximum: maximum(25 12 64 22 11) 25 :: Nil /: 12 64 22 11 -- 25 > 12, so it stays as head 25 :: 12 /: 64 22 11 -- same as above 64 :: 25 12 /: 22 11 -- 25 < 64, so the new head is 64 64 :: 22 25 12 /: 11 -- and stays so 64 :: 11 22 25 12 /: Nil -- until the end 64 11 22 25 12
https://codedump.io/share/D5sR32UvbKDg/1/selection-sort-in-functional-scala
CC-MAIN-2016-50
refinedweb
652
61.87
Dependency injection and abstractions Testability is an important feature of any software product – game development is not an exception. To enable testability, all the components should be independent and testable in isolation. When we want to test something in isolation it means that we want to decouple it. Loose coupling is what we need. It is so easy to embed hidden dependencies into your game and it is so hard to break them. This article will help you understand loose coupling and dependency injection within a project in Unity, using the example project on github. Lets take handling input as an example. public class SpaceshipMotor : MonoBehaviour { void MoveHorizontally () { var horizontal = Input.GetAxis ("Horizontal"); // ... } } MoveHorizontally method uses static Unity API (Input class) without telling you. It considers this call to be his private business and you can’t control or influence the situation. It makes SpaceshipMotor class tightly coupled with Unity static API, and you can’t verify the behaviour of the SpaceshipMotor class unless you physically press the key on the keyboard. It’s annoying. Now lets take this situation under control. You are in charge here. The SpaceshipMotor class is using only horizontal axis, so we can define a short description what kind of functionality it expects from user input. public interface IUserInputProxy { float GetAxis(string axisName); } Then you can substitute the call to real Input with the call to our abstraction. public class SpaceshipMotor : MonoBehaviour { public IUserInputProxy UserInputProxy {get;set;} void MoveHorizontally () { var horizontal = UserInputProxy.GetAxis (“Horizontal”); // … } } Now you are in charge of the situation! The class can’t operate unless you provide it IUserInputProxy implementation. This is called Dependency Injection (DI). When the dependency (Input in our case) is passed to the dependant object(SpaceshipMotor class) and it becomes part of it’s state (a field in our case). There are several options of passing a dependency: constructor injection, property injection, method injection. Constructor injection is considered to be the most popular and the most robust approach as when the dependency is passed in the construction phase our chances to have object in uninitialized state is minimal. public class SpaceshipMotor : MonoBehaviour { private readonly IUserInputProxy userInputProxy; public SpaceshipMotor (IUserInputProxy userInputProxy) { this.userInputProxy = userInputProxy; } } But Unity engine is calling the constructors for MonoBehaviours and we can’t control this process. Still, property and method injection are both usable in this case. The easiest approach for manual Dependency Injection (DI) would be to use the script that will inject the dependencies. In “Growing Games Guided by Tests” we are using an interface to expose property dependency. public interface IRequireUserInput { IUserInputProxy InputProxy { get; set;} } And a script that allows us to set the parameters of fake input in the scene and inject it when the tests start. public class ArrangeFakeUserInput : MonoBehaviour { public GameObject Spaceship; public FakeUserInput FakeInput; void Start () { var components = Spaceship.GetComponents<MonoBehaviour> (); var dependents = components.Where(c=>c is IRequireUserInput) .Cast<IRequireUserInput>(); foreach(var dependent in dependents) dependents.InputProxy = FakeInput; } } How does this contribute to testability? We have lots of examples in “Growing Games Guided by Tests” where fake user input is injected with helper script and it lets us test the behaviour. On the other hand we can write unit tests for classes that depend on abstractions. [Test] public void ChangesStateToIsFiringOnFire1ButtnPressed() { // Arrange // Setting test double for user input IUserInputProxy userInput = Substitute.For<IUserInputProxy> (); // Telling GetButton method of test double to return true // if state of “Fire1” was requested userInput.GetButton(Arg.Is("Fire1")).Returns (true); // Passing the dependency to Gun object on creation Gun gun = new Gun(userInput); // Act gun.ProcessInput (); // Assert Assert.That(gun.IsFiring, Is.True); } Now you see that there is no magic to dependency injection. It is the process of substitution of concrete dependencies with the abstractions and making them external to the dependant object. To use DI on a large scale you need a tool to automate it . This will be the topic for our next blogpost. vitamin d June 26, 2014 at 7:10 pm / Hey I am so glad I found your web site, I really found you by error,. Steve Vermeulen June 4, 2014 at 4:41 am / Zenject was added to the Asset store this week to address this problem: Alan May 9, 2014 at 5:36 pm / @DIMITRY: Nice to know that there will be another article about this topic! I’ve had an idea lately, thinking about DI and Unity. Do you think it would be possible to integrate a DI framework directly into the Unity Engine? The reason for that is simple: each and every MonoDevelop is instantiated by Unity. If the engine would have control over the application context (or DI Container, depending on your background), then the ENGINE itself could do the injecting of [Inject]-Attributed fields in MonoBehaviours! Nicholas May 9, 2014 at 3:15 am / IOC and messenger come standard with unity foundation Avariceonline.com/foundation serpin May 8, 2014 at 4:53 pm / Please, help me understand why this would be better, then just having a separate SpaceShipInput class with methods for making the ship say, move and a public master ProcessInput() method and a separate SpaceShipLogic class which would have a single reference to SpaceShipInput instance and call its ProcessInput() method every frame? In this case within SpaceShipInput you have a bool “isFakeInput” attribute which determines which input each method processes – real GetAxis or a value from some attribute in the SpaceShipInput class itself, say, public int horisFakeInput which is exposed in the inspector. Granted, you will have to basically have a condition in each internal method to switch between real or fake input base on the “isFakeInput”, but you won’t depend on external interfaces and can go live by just setting isFakeInput = false. But surely if Unity API supported DI you wouldn’t need all this bull**t. Dmitriy Mindra May 8, 2014 at 2:24 pm / @ALAN, “universal cure” doesn’t exist. The purpose of the article was to give an introduction to DI. I’ve already promised to write another one about DI frameworks. DI is good for building both simple and complex systems. When you are using a framework, wiring complex hierarchies is not a problem. While loose coupling makes testing and reuse of your classes easier. Circular references in constructors do make problems which are easily solved in Java but might be an issue in C#. If you depend on interfaces they are quite resolvable, though. Dmitriy Mindra May 8, 2014 at 2:04 pm / @Nico, you are right regarding the shorter version. And yes blog engine eats this > < :) Nico de Poel May 8, 2014 at 12:52 pm / Okay I give up. >_< Nico de Poel May 8, 2014 at 12:51 pm / ^ … aaand the generic arguments in those code snippets got interpreted as HTML and filtered out. Let’s try that again: var dependents = components.Where(c=>c is IRequireUserInput) .Cast (); is the same as: var dependents = components.OfType (); Nico de Poel May 8, 2014 at 12:47 pm / Minor LINQ-related nitpick, but this: var dependents = components.Where(c=>c is IRequireUserInput) .Cast(); can be written shorter and simpler as this: var dependents = components.OfType(); Alan May 8, 2014 at 10:53 am / Nice article, but imho it doesn’t go far enough. Doing dependency wiring “by hand” is really an awful and error-prone task. Normally, you would employ a framework here. Examples include Zenject, Ninject and Spring4Net. Also, what you didn’t mention are the shortcomings of DI. DI works perfectly when wiring up singleton classes (e.g. UnityEngine.Input would be very nice, but since it only offers static methods, you need to do this artificial proxy thing as shown above), however DI really runs into problems when wiring non-static objects, ESPECIALLY if they have constructor arguments and cyclic dependencies. DI is great. But it’s not the “universal cure” for all architecture problems, as it appears to be from reading the article. Freezx May 8, 2014 at 9:01 am / I am using Zenject for dependency injection because it’s simple and you can make things quickly. Chris May 7, 2014 at 10:05 pm / @DMITRIY MINDRA I find that this way of thinking scales for my uses. The move script is a component that can be reused by anything that needs to move that particular way. The actual call to move may come from a Unity Input component script, from some AI component script or via a test class. In all cases move works the same without dependancy, although in this example move would depend on a Transform or Rigidbody to actually move. I guess I just don’t see where an interface fits into the Unity component way of doing things. Dmitriy Mindra May 7, 2014 at 10:01 pm / @RICHARD, you are absolutely right. The component is not usable without wiring code. I like the mechanism that is implemented in ASP.NET MVC, where you can provide your implementation of IDependencyResolver that would resolve dependencies for your application. Maybe we need something similar for Unity? Richard Fine May 7, 2014 at 8:57 pm / This is great right up until the point that SpaceshipMotor is now unusable without some other code to wire it up. It’s not even the case that we can just wire it up to a RealUserInput component in the Inspector and forget about it, because interface references aren’t serialised… Dmitriy Mindra May 7, 2014 at 6:16 pm / @JOSEPH, thank you for the link to Suice DI framework! It would be very useful for my next blogpost. @CHRIS, your approach is easy, but does it scale? Danyal May 7, 2014 at 6:16 pm / Probably the best description of DI I’ve ever read. Chris May 7, 2014 at 5:58 pm / My approach has been to make the function that moves public, then send in values using arguments from some other class. // Input managing class void HandleInput () { var horizontalValue = Input.GetAxis (“Horizontal”); moveInstance.MoveHorizontally(horizontalValue); } // Then in the move class public void MoveHorizontally (float hInput) { var horizontal = hInput; } This seems much easier than juggling interfaces? Joseph May 7, 2014 at 5:55 pm / We are stuck with an API with tons of static references. Resources.Load — Input.GetAxis — Screen The list goes on. Although, Unit tests is something that greatly benefits teams in creating clean, efficient, and less bug prone software. I have been wrapping all of Unity’s static classes so they can be testable, although – I follow one rule because about 2 years ago when I attempted DI for my first time in Dueling Blades, it is waaaayyy too inefficient to inject dependencies into a scene with tons of MonoBehaviours. So my rule is to Have MonoBehaviours be responsible for one thing: Managing Game Objects. There is 0 logic to my mono behaviours other than creating an API to doing specific tasks in regards to manipulating game objects/monobehaviours. I use Controllers and Services (Usually singletons) to instantiate, destroy and manage Mono Behaviours/Unity3d Objects. Following this rule and wrapping some of Unity’s APIs for unit testing has made life amazing with Unity. Feel free to check out the dependency injection framework I use (works on Unity 4.2+ for ios/android/pc) without any issues: Dmitriy Mindra May 7, 2014 at 5:48 pm / @MAT, thanks for the reference to StrangeIoC. Next blogpost would be about DI frameworks. @MARTIJN, I would be glad to see your refactoring and discuss it. @LIOR, I definitely agree with you that making Engine API mockable would make life easier. Peter Dwyer May 7, 2014 at 4:27 pm / Agree with Dmitriy here. Mocking is simply a way to mask the issues that actually exist in the code. While this allows you to test the code. If someone else comes along and doesn’t have your mocking suite they’re stuffed. Matt May 7, 2014 at 4:20 pm / Check out StrangeIoC. Great DI framework with a MVCS inversion of control system as well. Martijn Zandvliet May 7, 2014 at 4:13 pm / @VICTOR N. Having the input system as an object instance would allow you to switch it out with another one, as long as they adhere to the same interface. Kind of like the following: IInputDevice device = new UnityInputDevice(); // Use actual user input // IInputDevice device = new TestInputDevice(); // Use automated test input. float horizontal = device.GetAxis(“Horizontal”); Speaking of interfaces, and being a little pedantic, I’d refactor the example from the article to let SpaceshipMotor expose an interface for its functions and handling user input external to it. public interface ISpaceshipMotor { float ThrustInput { get; set; } } That way it is entirely decoupled from the input system, and can work with user input, test input, AI logic, or no logic at all. Lior Tal May 7, 2014 at 4:13 pm / @Dmitriy – I Agree, that’s exactly what i said. I only added that the API Unity provides for Input could’ve been one that allows easier injection by not being a static class in the first place. In this article you “simulate” an input API that is interface based that hides Unity’s static class to allow replacing those calls with fake calls. That could’ve been easier to do if (like i said above) the API was provided as some singleton or something like that. Then, You could’be substituted the returned instance with a fake one. If there are .NET tools that allow mocking calls on static classes. Then you could just fake Input.GetAxis(…) or any other static call. I am not sure NSubstitute could do that (although i think other .NET tools can, but are probably not compatible with Unity) Dmitriy Mindra May 7, 2014 at 3:58 pm / @Lior, mocking static classes is possible in .NET using proprietary libraries like Typemock Isolator or Microsoft Fakes. I don’t know any tools for Mono. In my opinion refactoring to abstractions is much better option. “Mocking static” lets you ignore your design issues while refactoring to abstractions solves them. Dmitriy Mindra May 7, 2014 at 3:53 pm / @Lior, @Victor – there are many situations where you depend on something you can’t control. Input is just one example of static class that can’t be inherited from and you can’t test the behavior of classes that depend on it. But when you create an abstraction for Input, the situation changes and you can pass any class that implement interface including wrapper that calls “real” system API. Depending on abstractions means that object knows nothing about concrete implementation of it’s dependency and should be able to work with any object that implements the interface (Barbara Liskov substitution principle). Lior Tal May 7, 2014 at 3:24 pm / @Victor – For example, instead of having a static Input class with static methods, e.g: Input.GetAxis(….) You would have a “singleton” like approach: var inputManager = Input.Instance; // As usual inputManager.GetAxis(…); When you test, you could fake the singleton instance using a mocking/fake framework such as NSubstitute to inject the instance you need for testing. In this article he presented a similar approach, but he had to define the interface for input himself so he could swap the implementation for testing purposes. Having the Input class already ready for substitution would’ve eased up on the process. * There may be mocking frameworks that allow mocking static classes (i can’t remember if .NET allows that or not). victor n. May 7, 2014 at 3:13 pm / @LIOR TAL how changing the API would solve the tight coupling issue ? can you elaborate ? Lior Tal May 7, 2014 at 2:54 pm / I think the problem is the Input API is a static class. The API should’be been built differently to support DI and testability.
http://blogs.unity3d.com/2014/05/07/dependency-injection-and-abstractions/
CC-MAIN-2014-42
refinedweb
2,641
55.13
C# Corner No unread comment. View All Comments No unread message. View All Messages No unread notification. View All Notifications * * Login using C# Corner TECHNOLOGIES Request a new Category | View All ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER Jobs IDEAS About OOP twitter google + Reddit Topics No topic found Content Filter Articles Videos Blogs News Complexity Level Beginner Intermediate Advanced Refine by Author [Clear] Ibrahim Ersoy (10) Akhil Mittal (8) Abdul Rasheed Feroz Khan (5) Pramod Thakur (4) Tahseen Jamil (3) Praveen Moosad (3) Vidya Vrat Agarwal (2) Suketu Nayak (2) Rahul Kaushik (2) Hussain Khawaja (2) Raghu Gurumurthy (2) Kuppurasu Nagaraj (2) Prakash Tripathi (2) Vignesh Mani (2) Mahesh Chand (2) Nisha Dwivedi (2) Ritesh Mehta (1) Sundar (1) Sandeep Mk Sharma (1) Syed Shanu (1) Yogendra Kumar (1) Vijai Anand Ramalingam (1) Manikandan Murugesan (1) Krishna Rajput Singh (1) Pradeep Yadav (1) David Mccarter (1) Sharad Gupta (1) Manish Agrahari (1) Vinodhini M (1) Rajesh Kumar Maurya (1) Amit Kumar (1) Prashant Bansal (1) Kirubashalini Velu (1) Anu V (1) Sujeet Sen (1) Sahil Sharma (1) Tanuj Khurana (1) Neha (1) Ananth G (1) Priyaranjan K S (1) Sourabh Somani (1) Ammar Shaukat (1) Shamim Uddin (1) Gaurav Singh (1) Abhishek Kumar Ravi (1) Sekhar Srinivas (1) Sr Karthiga (1) Shuhaib Pdn (1) Nitin (1) Pradeep Sahoo (1) Atul Kumar (1) Pankaj Kumar Choudhary (1) Saillesh Pawar (1) Sudeep Chourasia (1) Sumit Jolly (1) Rajesh Pawde (1) Ehtesham Mehmood (1) Dheeraj Kumar Jha (1) Ehsan Sajjad (1) Kins T (1) Anand Narayanaswamy (1) Manali Dangda (1) Sam Hobbs (1) Related resources for OOP No resource found SQL Engines Boost Hadoop Query Processing For Big Data Users 9/19/2017 4:39:54 PM. SQL engines help boost query processing in Hadoop for users of big data. There are many engines available, thus a business should choose which best fits its specific requirements. Swift Programming - Zero To Hero - Part Two 8/8/2017 9:26:18 PM. This is part two of Swift Programming Zero to Hero. In this article we will see loops in Swift. Introduction to Object-Oriented Programming 6/28/2017 4:23:48 AM. This article is a brief introduction to OOP. The basic building blocks of object-oriented programming are the class and the object. A class acts as a blueprint/template to create the instances/objects C# OOP in Details 6/28/2017 2:57:23 AM. In this article you will learn about OOPs in C#. Here we will learn about different pillars of OOPs like class, object, variables, Access Modifiers, Encapsulation, Abstraction, Inheritance, Polymorphi Explore Interface Vs Abstract Class 6/28/2017 1:44:38 AM. Here I explore an Interface Vs an Abstract Class. An interface can only have a declaration but not a definition. An interface can only have methods, properties, indexers and events whereas a class can How to Use For Each Loop in NINTEX Workflow 6/27/2017 4:43:23 AM. In this article you will see how to use a For Each loop in a NINTEX workflow. Why Hadoop Is Needed For Big-Data 6/26/2017 2:13:28 PM. In this blog , I am going to describe various reasons behind the Big-Data explosion and give a detailed view about Big Data OOP Series #2: Understanding Access Specifiers In C# 6/26/2017 2:50:34 AM. This article explains access specifiers in C#. Access modifiers and specifiers are keywords to specify the accessibility of a type and its members. C# has 5 access specifier or access modifier keyword OOPs Dynamic Binding Program Using C++ 6/22/2017 6:48:50 PM. In this program we will learn how to find squares and cubes and learn about what dynamic binding is in c++ programs Concept Of Factories In Object Oriented Programming 6/7/2017 12:04:29 AM. Concept Of Factories In Object Oriented Programming. Make Encapsulation Easy With dotNetTips.Utility 6/5/2017 1:33:29 PM. Encapsulation is the first pillar of Object Oriented Programming (OOP), yet most code that I see does not implement encapsulation correctly or not all. Like I say in many of my conference sessions &qu ForEach in TypeScript 5/22/2017 10:43:53 AM. In this article I am going to explain how to use forEach in TypeScript and how a for loop acts as a foreach in TypeScript Introduction to Object Oriented Programming Concepts in C# 5/22/2017 7:50:50 AM. This article defines the Abstraction, Encapsulation, Inheritance and Polymorphism concepts in C#. Introduction Of Big Data 5/1/2017 12:11:33 AM. In this article, I will discuss about Big data and where it is used and how it will perform in various applications in the world. Indexer In C# 4/20/2017 10:00:56 AM. Indexer and its uses in C#. Write A Query To Print 1 To 100 In SQL Server Using Without Loop 4/16/2017 9:25:16 AM. In this blog, we will print 1 to 100 numbers in SQL Server without using while loop. SharePoint 2013 - Disable Loopback Check 4/11/2017 7:27:20 PM. In this article, we will discuss how to disable loop back check for development VMs to avoid certain complexities during the development process. Decision Making And Looping Statement In Swift Programming Language 4/4/2017 6:29:21 PM. This blog provides an overview of decision making and looping statements in Swift programming language. Simple Example Of While Loop With Break And Continue In SQL Query 2/20/2017 10:50:53 AM. In this blog, you will learn a simple example of While lop with Break and Continue in SQL query. Object Oriented Programming Using C# .NET 1/31/2017 3:41:52 AM. The fundamental idea behind OOP is to combine into a single unit both data and methods that operates on that data; such units are called an object. OOPS Concept With Real Time Example 1/29/2017 12:44:05 PM. In this blog you will learn about the OOPS concept with a real time example. Diving Into OOP (Day 6) : Understanding Enums in C# (A Practical Approach) 1/24/2017 11:37:48 PM. This article of the series “Diving into OOP” will explain the enum datatype in C#. Diving Into OOP (Day 5): All About Access Modifiers in C# (C# Modifiers/Sealed/Constants/Readonly Fields) 1/24/2017 11:36:33 PM. In this article we will cover each and every concept related to access modifiers. Diving Into OOP (Day 3) : Polymorphism and Inheritance (Dynamic Binding/Run Time Polymorphism) 1/24/2017 11:33:31 PM. In this part of article we will focus more on run time polymorphism also called late binding or dynamic binding. Diving Into OOP (Day 2): Polymorphism and Inheritance 1/24/2017 11:32:09 PM. Here we will focus solely on inheritance concept in OOP. Diving Into OOP (Day 1): Polymorphism and Inheritance (Early Binding/Compile Time Polymorphism) 1/24/2017 11:30:17 PM. This article will cover almost every OOP concept that a novice/beginner developer might seek and not only beginners but this article's purpose is to be helpful to experienced professionals who als Diving Into OOP (Day 8) - Indexers in C# (A Practical Approach) 1/24/2017 11:25:01 PM. In this article you will learn about Indexers in the C# language. Abstract Class & Interface: Two Villains of Every Interview - Part 1 1/22/2017 4:32:03 AM. This article is the first part of the series "Abstract Class & Interface: Two Villains of Every Interview" and explains the important key points of Abstract Class. Object Oriented JavaScript 1/9/2017 12:30:14 PM. This blog explores object oriented programming in JavaScript. Loops In C# 12/21/2016 6:28:49 PM. In this blog, you will learn about loops in C#. Introduction To Hadoop Framework 12/19/2016 1:48:03 PM. In this blog, you will learn about Hadoop Framework. Installing Hadoop On Ubuntu 12/11/2016 12:38:05 PM. In this article you will learn how to install Hadoop on Ubuntu. Different Installation Modes On Hadoop 12/9/2016 1:32:13 PM. In this article, you will learn about different installation modes on Hadoop. Why We Need a Distributed Computing System And Hadoop Ecosystem 12/7/2016 6:19:50 PM. In this article, you will learn why we need a distributed computing system and Hadoop ecosystem. Workaround For Loop Back Check Issue In SharePoint 11/23/2016 11:22:31 AM. In this article you will learn about Loop Back Check Issue in SharePoint. Node.js - Event Loop 11/22/2016 3:25:10 PM. In this article, I will explain about Node.js Event Loop. An Overview Of Polymorphism, Inheritance And Encapsulation In OOP 11/18/2016 4:37:53 AM. In this article, you will learn an overview of polymorphism, inheritance and encapsulation in OOP. Get Started With Map Reduce Job On Hadoop Cluster In Azure Hdinsight 10/18/2016 11:11:31 AM. In this article, you will get started with Map Reduce Job on Hadoop Cluster in Azure HDInsight.. How To Use Cursors And While Loop In SQL Server 10/4/2016 7:07:40 PM. In this blog, you will learn how to use cursors and while loop in SQL Server. Create Storage And Hadoop Cluster From Azure Management Portal 9/17/2016 6:52:30 PM. In this article, you will learn how to create storage and Hadoop Cluster from Azure Management Portal. Concepts Of OOPS- Encapsulation And Abstraction 9/12/2016 4:02:12 AM. In this blog, you will learn the basic difference between Encapsulation and Abstraction. Kickstart Hadoop In HDInsight On Windows 9/10/2016 2:44:42 PM. In this article, you will learn about Hadoop in HDInsight on Windows. Loops In Swift Programming Language 8/28/2016 2:22:12 PM. In this blog, you will learn about loops in Swift programming language. Introduction to JDBC 8/2/2016 3:01:27 AM. In this video we will Understanding Introduction to JDBC.Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client m Using For Loop in Python 7/22/2016 1:36:22 PM. In this blog, you will learn how to use for loop in Python Tip To Improve Program Speed While Looping Through Arrays 7/11/2016 7:11:35 PM. In this blog, you will see a tip to improve the program speed while looping through arrays. Value And Reference Type In OOPS 7/8/2016 7:47:41 PM. In this blog, you will learn about value and reference type in OOPS. OOP Concepts - Part One 7/7/2016 12:14:14 PM. In this blog, you will learn about OOP Concepts. Reverse a String Using for Loop 6/19/2016 11:41:00 AM. In this blog we will see how to reverse a string using for loop. OnePlus 3 Launched 6/15/2016 12:02:02 PM. OnePlus has made its newest flagship, OnePlus 3, available for purchasing from OnePlus.net. Design Patterns In WinJS #5: Prototype 5/30/2016 12:56:29 AM. This article covers the implementation of Prototype Design Pattern. This is part five of the article series. Design Patterns in WinJS #6: Singleton 5/29/2016 3:26:30 PM. This article covers the implementation of Singleton Design Pattern. This is part six of the article series. Collection in C# 5/25/2016 3:05:39 PM. In this blog you will learn about Collections in C# language. Design Patterns in WinJS #4: Factory Method 5/24/2016 11:42:04 AM. This article covers the implementation of Factory Method Design Pattern. This is part four of the article series. Interface In C# 5/24/2016 10:40:51 AM. In this article you will learn about Interface in C# language. Base Class Constructor Gets Executed When Creating a Derived Class Object 5/23/2016 11:32:41 AM. In this blog we will learn how Base class constructor gets executed when creating a derived class object. Solution to General PIG Installation Problems 5/23/2016 11:31:38 AM. In this blog you will learn how to solve General PIG Installation Problems. Design Patterns in WinJS #1: Introduction to Series 5/19/2016 12:12:51 PM. With this blog, I'm going to make an introduction to the series of articles I'm planning to add in the following days. Understanding HDInsight In Microsoft Azure 5/16/2016 11:30:08 AM. In this article you will learn what is HDInsight in Microsoft Azure. Types Of Relationships In Object Oriented Programming (OOPS) 5/14/2016 2:50:41 PM. In this article you will learn about the types of Relationships in Object Oriented Programming (OOPS). Learn Tiny Bit Of C# In 7 Days - Day 1 5/12/2016 11:56:06 AM. As the title specifies learn C# in 7 days, this article intended focus is towards the beginners so that they can easily grasp the C# Language concepts.. OOP in WinJS #6 : Asynchronous Programming 5/10/2016 10:25:31 AM. In this last article of the series, we shall talk about Asynchronous Programming in WinJS Library. Getting Started With Azure HDInsight: Create Hadoop Clusters - Part One 5/9/2016 11:56:14 AM. In this article you will Create Hadoop Clusters in Azure HDInsight. This is part one of the article series. Basic OOPS Concept 5/2/2016 12:14:02 PM. In this blog I will tell you about OOPS concept Voice of a Developer: Part Eight - JavaScript OOP 5/1/2016 2:01:24 PM. In this article you will learn about OOP concepts in JavaScript. This is part eight of the series. Preparing for .NET Interviews - Part Seven (Abstract Class & Interface) 4/29/2016 3:26:04 PM. This article presents the common questions asked in .NET interviews related to Abstract Class & Interface and explains the answers in an easy way. OOP In WinJS #5 : Encapsulation 4/19/2016 11:04:37 AM. In this article, I'll be talking about how to use Encapsulation in WinJS library. This is Part 5 of the series. Diving Into OOP (Day 7) - Properties in C# (A Practical Approach) 4/13/2016 12:14:21 PM. This article explains properties in C# and OOP concepts. Preparing .NET Interview - Part Six (OOPs) 4/11/2016 11:59:44 AM. This article presents the common questions asked in .NET interview related to OOPs and explains the answers in an easy way. Pillars Of OOP/Overview Of OOP 4/8/2016 3:57:19 AM. In this article you will get an overview of OOP. A programming model which is mainly organized around the objects is called Object Oriented Programming. OOP In WinJS #4 : Inheritance 4/4/2016 10:36:16 AM. In this article, I'll be talking about how to derive classes in WinJS library. This is part 4 of the series. Diving Into OOP Book Available Now 3/31/2016 11:41:35 AM. Today, we are pleased to add one more ebook to the collection of C# Corner's free books library, "Diving Into OOP". This book is written by C# Corner author Akhil Mittal. OOP in WinJS #3: Classes 3/24/2016 10:53:43 AM. In this article, I'll be talking about how to use classes in WinJS library. We'll be using Universal Windows Apps for showing the demo. OOP In WinJS #2: Nested Namespaces 3/23/2016 9:26:54 AM. In this article, I'll be talking about how to use Nested Namespaces in WinJS library. We'll be using Universal Windows Apps for showing the demo. Inheritance With Example in C# 3/23/2016 6:46:31 AM. Today in this article I will show you OOP concepts in the C# language. OOP in WinJS #1: Namespaces 3/22/2016 10:09:49 AM. In this article, I'll be talking about how to use namespaces in WinJS library. We'll be using Universal Windows Apps for showing the demo. An Overview Of Class In OOPS 3/10/2016 9:55:17 AM. In this blog you will see an overview of Class in OOPS. Looping Statements In C# - Part Two 3/7/2016 10:00:45 AM. In this article you will learn looping Statements in C#. This is part two of the series. Install Hadoop on Windows: Part Three 3/2/2016 9:29:58 AM. In this article we will learn how to install Hadoop and some configuration settings in VM at local system. Learn Hadoop Free 2/29/2016 11:39:40 PM. Here is a list of free Hadoop tutorials. Difference Between Shadowing And Overriding in OOP Using C# 2/28/2016 11:22:31 AM. In this article you will learn about the difference between Shadowing and Overriding in OOP using C# Programming example.. Looping Statements In C#: Part One 2/27/2016 12:03:28 PM. In this article you will learn about some looping statements in C#. It will also include single as well as nested loops. Yahoo Open-Sources CaffeOnSpark 2/26/2016 9:09:08 AM. Yahoo has published the source code of its CaffeOnSpark AI engine. Google Announces Cloud Dataproc Service 2/24/2016 10:22:51 PM. Google recently announced its Cloud Dataproc service, a complete managed tool, based on Hadoop and Spark open-source big data software, is now available. OOPs Principle and Theory Book Available Now 2/21/2016 9:02:36 AM. Today, we are pleased to announce one more ebook has been added to the collection of C# Corner's free books library, "OOPs Principle and Theory." This book is written by C# Corner author Afzaal Ahmad Zeeshan. Oops, Twitter's Vine restrained by Facebook 2/21/2016 9:02:36 AM. Twitter reveals video sharing application called Vine and Facebook has decided to not support them. Free E-Book Object Oriented Programming Using C# Released 2/21/2016 9:02:36 AM. C# Corner released its new book on Object Oriented Programming Using C#. DOWNLOAD FREE.. Microsoft brings Hadoop to Cloud with HDInsight 2/21/2016 9:02:36 AM. HDInsight is Microsoft’s Hadoop-based service that brings an Apache Hadoop solution to the cloud. Microsoft announces availability of its Azure based Hadoop service 2/21/2016 9:02:36 AM. Microsoft's Windows Azure HDInsight service a cloud-based distribution of Hadoop is generally available. Microsoft Boosts Encryption To Prevent Snooping 2/21/2016 9:02:36 AM. Microsoft confirms encryption efforts across its cloud services and data centers to prevent the government spying. GooPhone i6, a clone of iPhone 6 hits the market before its launch 2/21/2016 9:02:36 AM. A clone handset maker, GooPhone has recently launched its GooPhone i6 which is a look alike of iPhone models. Samsung purchased LoopPay for mobile payments 2/21/2016 9:02:36 AM. Samsung has bought LoopPay for making mobile payments. Apache Hadoop 2.7.2 Version Available Now 2/21/2016 9:02:36 AM. Apache Hadoop 2.7.2 is a minor release in the 2.x.y release line, building upon the previous stable release 2.7.1. Install Hadoop On Windows: Part One 2/12/2016 2:11:56 AM. In this article we will learn how to install Hadoop on a local system. Install Hadoop On Windows: Part 2 2/2/2016 1:08:14 PM. In this article we learn how to install Ubuntu in Virtual Machine at local system. - Ebook C# Language Specification 5.0 This book provides a complete description of the C# language 5.0. Download
http://www.c-sharpcorner.com/topics/oop
CC-MAIN-2017-47
refinedweb
3,330
66.33
My thoughts on some code smells I’ve come across. These three are the ones that tend to turn my stomach the most. Here goes.. I often see a bunch of these duplicated in all templates, often disguised in a “#region Properties”, an obvious hint that I am in for a treat.. I have even seen code snippets in Visual Studio being used to generate these. This indicates the lack of sensible base classes. And if you want strongly typed Episerver properties, there are better ways.I have even seen code snippets in Visual Studio being used to generate these. This indicates the lack of sensible base classes. And if you want strongly typed Episerver properties, there are better ways. public string MainBody { get { if(IsValue("MainBody")) return (string) CurrentPage["MainBody"]; return String.Empty; } } When poking around a new project, one of the first things I generally do, is open up Web.config. I scroll down to the appSettings-element, and if I find 10+ custom keys, I can smell the lack of Admin tabs and/or Settings page. Usually goes something like: <add key="ContactFormPage" value="12312" /> <add key="ContactFormPageEN" value="54312" /> <add key="ProductModulePageTypeId" value="93" /> <add key="ModuleContactPageTypeId" value="38,39" /> <add key="ModulePageTypeId" value="3" /> <add key="MyCoolPageTypeId" value="42" /> <add key="CalendarEventPageType" value="11" /> <add key="DivisionStartPageTypeId" value="46" /> <add key="404PageId" value="78781" /> <add key="FileNotFoundPageId" value="12333"/> <add key="GenericErrorPageId" value="543"/> Episerver comes with a “Pagetype” property type. Use it. Everyone got them. At least some version of it, duplicated from one project to another, tweaked and refactored along the way. It usually contains the all familiar StripHtml(), Ellipse(), PreviewText(), MyGetPropertyWithFallbackValue(). Not really a smell perhaps, but I sort it into the DRY category. Thoughts anyone? I am sure you have experienced your fair share of smells, perhaps worse than mine…? I was worried you had found some smelly bits on EPiCode (). :-) As for smelly code in general, I think I have seen more than is healthy. I guess it comes with the territory, as many web devs don't think about architecture, code quality and reusability. Getting the job done quickly is first priority. Also, many newbies start with web development (and EPiServer), and are more concerned about why the html designer in Visual Studio does not work as well as shown on stage at the last Microsoft gig they attended. Not hardcoding page id's :-) Yes wasn't it a witty headline? ;-) Well many times it doesn't matter if the web dev thinks about quality and architecture, the project manager who rules the world doesn't care about things like that.
https://world.episerver.com/blogs/Thomas-Krantz-/Dates/2009/9/EPiCodeSmells/
CC-MAIN-2019-30
refinedweb
442
55.03
In this article we go over the Python file types .pyc, .pyo and .pyd, and how they're used to store bytecode that will be imported by other Python programs. You might have worked with .py files writing Python code, but you want to know what these other file types do and where they come into use. To understand these, we will look at how Python transforms code you write into instructions the machine can execute directly. Bytecode and the Python Virtual Machine Python ships with an interpreter that can be used as a REPL (read-eval-print-loop), interactively, on the command line. Alternatively, you can invoke Python with scripts of Python code. In both cases, the interpreter parses your input and then compiles it into bytecode (lower-level machine instructions) which is then executed by a "Pythonic representation" of the computer. This Pythonic representation is called the Python virtual machine. However, it differs enough from other virtual machines like the Java virtual machine or the Erlang virtual machine that it deserves its own study. The virtual machine, in turn, interfaces with the operating system and actual hardware to execute native machine instructions. The critical thing to keep in mind when you see .pyc, .pyo and .pyd file types, is that these are files created by the Python interpreter when it transforms code into compiled bytecode. Compilation of Python source into bytecode is a necessary intermediate step in the process of translating instructions from source code in human-readable language into machine instructions that your operating system can execute. Throughout this article we'll take a look at each file type in isolation, but first we'll provide a quick background on the Python virtual machine and Python bytecode. The .pyc File Type We consider first the .pyc file type. Files of type .pyc are automatically generated by the interpreter when you import a module, which speeds up future importing of that module. These files are therefore only created from a .py file if it is imported by another .py file or module. Here is an example Python module which we want to import. This module calculates factorials. # math_helpers.py # a function that computes the nth factorial, e.g. factorial(2) def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) # a main function that uses our factorial function defined above def main(): print("I am the factorial helper") print("you can call factorial(number) where number is any integer") print("for example, calling factorial(5) gives the result:") print(factorial(5)) # this runs when the script is called from the command line if __name__ == '__main__': main() Now, when you just run this module from the command line, using python math_helpers.py, no .pyc files get created. Let's now import this in another module, as shown below. We are importing the factorial function from the math_helpers.py file and using it to compute the factorial of 6. # computations.py # import from the math_helpers module from math_helpers import factorial # a function that makes use of the imported function def main(): print("Python can compute things easily from the REPL") print("for example, just write : 4 * 5") print("and you get: 20.") print("Computing things is easier when you use helpers") print("Here we use the factorial helper to find the factorial of 6") print(factorial(6)) # this runs when the script is called from the command line if __name__ == '__main__': main() We can run this script by invoking python computations.py at the terminal. Not only do we get the result of 6 factorial, i.e. 720, but we also notice that the interpreter automatically creates a math_helpers.pyc file. This happens because the computations module imports the math_helpers module. To speed up the loading of the imported module in the future, the interpreter creates a bytecode file of the module. When the source code file is updated, the .pyc file is updated as well. This happens whenever the update time for the source code differs from that of the bytecode file and ensures that the bytecode is up to date. Note that using .pyc files only speeds up the loading of your program, not the actual execution of it. What this means is that you can improve startup time by writing your main program in a module that gets imported by another, smaller module. To get performance improvements more generally, however, you'll need to look into techniques like algorithm optimization and algorithmic analysis. Because .pyc files are platform independent, they can be shared across machines of different architectures. However, if developers have different clock times on their systems, checking in the .pyc files into source control can create timestamps that are effectively in the future for others' time readings. As such, updates to source code no longer trigger changes in the bytecode. This can be a nasty bug to discover. The best way to avoid it is to add .pyc files to the ignore list in your version control system. The .pyo File Type The .pyo file type is also created by the interpreter when a module is imported. However, the .pyo file results from running the interpreter when optimization settings are enabled. The optimizer is enabled by adding the "-O" flag when we invoke the Python interpreter. Here is a code example to illustrate the use of optimization. First, we have a module that defines a lambda. In Python, a lambda is just like a function, but is defined more succinctly. # lambdas.py # a lambda that returns double whatever number we pass it g = lambda x: x * 2 If you remember from the previous example, we will need to import this module to make use of it. In the following code listing, we import lambdas.py and make use of the g lambda. # using_lambdas.py # import the lambdas module import lambdas # a main function in which we compute the double of 7 def main(): print(lambdas.g(7)) # this executes when the module is invoked as a script at the command line if __name__ == '__main__': main() Now we come to the critical part of this example. Instead of invoking Python normally as in the last example, we will make use of optimization here. Having the optimizer enabled creates smaller bytecode files than when not using the optimizer. To run this example using the optimizer, invoke the command: $ python -O using_lambdas.py Not only do we get the correct result of doubling 7, i.e. 14, as output at the command line, but we also see that a new bytecode file is automatically created for us. This file is based on the importation of lambdas.py in the invocation of using_lambdas.py. Because we had the optimizer enabled, a .pyo bytecode file is created. In this case, it is named lambdas.pyo. The optimizer, which doesn't do a whole lot, removes assert statements from your bytecode. The result won't be noticeable in most cases, but there may be times when you need it. Also note that, since a .pyo bytecode file is created, it substitutes for the .pyc file that would have been created without optimization. When the source code file is updated, the .pyo file is updated whenever the update time for the source code differs from that of the bytecode file. The .pyd File Type The .pyd file type, in contrast to the preceding two, is platform-specific to the Windows class of operating systems. It may thus be commonly encountered on personal and enterprise editions of Windows 10, 8, 7 and others. In the Windows ecosystem, a .pyd file is a library file containing Python code which can be called out to and used by other Python applications. In order to make this library available to other Python programs, it is packaged as a dynamic link library. Dynamic link libraries (DLLs) are Windows code libraries that are linked to calling programs at run time. The main advantage of linking to libraries at run time like the DLLs is that it facilitates code reuse, modular architectures and faster program startup. As a result, DLLs provide a lot of functionality around the Windows operating systems. A .pyd file is a dynamic link library that contains a Python module, or set of modules, to be called by other Python code. To create a .pyd file, you need to create a module named, for example, example.pyd. In this module, you will need to create a function named PyInit_example(). When programs call this library, they need to invoke import foo, and the PyInit_example() function will run. For more information on creating your own Python .pyd files, check out this article. Differences Between These File Types While some similarities exist between these file types, there are also some big differences. For example, while the .pyc and .pyo files are similar in that they contain Python bytecode, they differ in that the .pyo files are more compact thanks to the optimizations made by the interpreter. The third file type, the .pyd, differs from the previous two by being a dynamically-linked library to be used on the Windows operating system. The other two file types can be used on any operating system, not just Windows. Each of these file types, however, involve code that is called and used by other Python programs. Conclusion In this article we described how each special file type, .pyc, .pyo, and .pyd, is used by the Python virtual machine for re-using code. Each file, as we saw, has its own special purposes and use-cases, whether it be to speed up module loading, speed up execution, or facilitate code re-use on certain operating systems.
http://stackabuse.com/differences-between-pyc-pyd-and-pyo-python-files/
CC-MAIN-2018-26
refinedweb
1,617
65.12
Overview The SSH Monitoring ZenPacks include a unit testing framework that is easily extendable with the command output from various hosts. This extensibility can be used to add command output found in the field that triggered bugs in the parsers. The unittest Files that Drive the Tests Each SSH Monitoring ZenPack should have a testPlugins.py and testParsers.py file in its tests directory. These test scripts walk the plugindata and parserdata directories to find test data. If those files do not exist in the ZenPack you are working on, create them and add a class that extends BasePluginsTestCase or BaseParserTestCase. The subclass you create should include a single method named runTest. For plugins, runTest should call the super class's _testDataFiles method passing in the root data directory as os.path.join(os.path.dirname(__file__), 'plugindata') and a list of plugin classes that have been imported into the module. For parsers, runTest should call the super class's _testParsers method passing in the root data directory as os.path.join(os.path.dirname(__file__), 'parserdata') and a dictionary that maps commands to parser classes that have been imported into the module. Both types of test modules need the following function to be defined in them: def test_suite(): from unittest import TestSuite, makeSuite suite = TestSuite() suite.addTest(makeSuite( <YOUR TEST CASE CLASS NAME > )) return suite Adding Data to Create a New Test To create a new test you need to create a new folder with the name of the host under the appropriate testdata directory (e.g. tests/parserdata/linux/leak.zenoss.loc). In that new folder place two files. Both files share the same name; one has no extension and the other has a .py extension. The file with no extension must contain the command on the first line, and the output of the command on the subsequent lines. The file with the .py extension contains a Python dictionary with expected values that were manually parsed from the command output. The format of these dictionaries is slightly different depending on the type of test (modeling plugin or datapoint parser). The formats will be covered in sections later in this document. Note that if you are adding the first test data files for a parser, then you must edit testPlugins.py or testParsers.py to import the parser module and add the module to the list of tested modules. Dictionary Format for Modeling Plugin Tests Multiple modeling plugins can parse the same command. The first level of keys in the dictionary is the name of the modeling plugin class. Modeling plugins can return values of the following types (which are defined in Products/): - ObjectMap - RelationshipMap - list of the above data map classes The test data for each of these return types is in different formats. Test Data for an ObjectMap The test data is formatted as a simple dictionary that maps the attribute names of that ObjectMap to the expected values. Test Data for a RelationshipMap RelationshipMaps contain many ObjectsMaps. The test data is formatted as a two-level nested dictionary. The first level of keys is the ID that identifies the ObjectMap under test. The second level dictionary maps the attribute names of that ObjectMap to the expected values. Test Data for a List of Data Maps The test data is formatted as a list of dictionaries. The dictionaries are flat for ObjectMaps or two-level nested for RelationshipMaps. Dictionary Format for Datapoint Parser Tests Datapoint parsers differ in their return values. They can either return Device-level datapoints or component datapoints. The test data is formatted differently based on the return type of the parser. Test Data for Device-Level Parsers The test data for a device-level parser is formatted as a simple dictionary. The keys are the IDs of the datapoints returned by the parser. Test Data for Component Parsers The test data for a component parser is formatted as a two-deep nested dictionary. The first-level keys are the IDs of the components under test. The second-level dictionary maps the IDs of the datapoints to the expected values. Running the Tests To run all the tests in a ZenPack Use the last part of the ZenPack name runtests --type unit ZenPacks.zenoss.LinuxMonitor To run a single test runtests --type unit --name testLinuxPlugins ZenPacks.zenoss.LinuxMonitor
http://community.zenoss.org/docs/DOC-2360
CC-MAIN-2014-15
refinedweb
724
55.64
I want to read a file into an array - we will call it myArray1. I want to split the file at a certain point, and make the rest of the file go to myArray2. I have tried using while loop inside a for loop to do this, my attempt is show below. Please do note that I am new to java. Thankyou for your help. Note: There are 35 numbers in the file import java.util.*; import java.math.*; import java.io.*; class Test{ public static void main(String[] args) throws Exception{ Integer[] myArray1 = new Integer[20]; Integer[] myArray2 = new Integer[15]; //Reading Rectangle and Triangle address from file 3..... Scanner reader = new Scanner(System.in); System.out.println("Please specify file name:"); String fileName = reader.nextLine(); File inputFile = new File(fileName); reader = new Scanner(inputFile); /* IMPORTANT: We are splitting up File . The first 20 numbers of file will go to myArray1, and the next 15 goes to myArray2*/ for(int i = 0; i<35; i ++){ while (i<20){ myArray1[i] = reader.nextInt(); System.out.println("Rectangle is" +myArray1[i]); i++; } while (i>19){ myArray2[i] = reader.nextInt(); System.out.println("TTTTTTTTTT is" +myArray2[i]); i++; } } } } The first bit works - putting the first 20 numbers to myArray1, but the second bit doesn't. I can't work out why.
http://www.dreamincode.net/forums/topic/145111-splitting-a-file-up-and-putting-into-array/
CC-MAIN-2017-09
refinedweb
219
74.79
Learn how to boost ASP.NET performance and scalability with a distributed .NET Cache. Watch this webinar to learn about the five ways to boost ASP.NET performance for scalability in ASP.NET applications and how to use an In-Memory Distributed Cache to effectively resolve them. Co-delivered by our Senior Solutions Architect and Regional Sales Director, please join us to learn about: Today we're going to be talking about 5 ways to boost your ASP.NET application performance and scalability. It's a very hot topic, I would say it's something that is, it's high in demand. So, we're glad to bring this for you. Ron is going to talk about that in a minute and also, you have any questions during this presentation feel free to type them into the video and I'll be able to bring those up to Ron's attention. So, Ron what do you kind of get started? Thanks, Nick. Hi everybody, my name is Ron and I'll be your presenter for today's webinar and as Nick suggested the topic that we chose today is five ASP.NET performance boosters. So, we'll go through five different features. Initially, I will talk about five different problems, what you would typically see within an ASP.NET web application, these are day to day issues that actually slow down your applications, its performance degradation, then the scalability is another avenue, another aspect where we'll talk about these bottlenecks and then I'll talk about different solutions with the help of distributed caching system. How to resolve those issues within your ASP.NET applications? So, that's what we have lined up today, I will cover different features, I will have sample applications, I'll show you everything in action how to set up and get started with this. So, it's going to be a pretty interactive pretty hands-on webinar and as Nick mentioned, if there are any questions please feel free to jump in and I'll be very happy to answer all those questions for you. Alright assuming that everything looks good, I'm going to get started with this. So, first of all, I'll talk about ASP.NET platform in general. ASP.NET is a very popular platform for web applications. We see a lot of web deployments and it's increasing in its popularity. Nice thing about ASP.NET platform is that, it is based on the usage pattern it's something which scales out pretty nicely, you can handle thousands of concurrent users and their associated requests without having to change anything inside the application architecture. You can create a web farm, you could create a web garden, it gives you a lot of scalability options, you can put a load balancer in front and then you can route requests between different web servers and you can achieve linear scalability, horizontal scalability out of the ASP.NET web farm. A load balancer could have sticky load balancing or equal load balancing depend upon your architecture, depending upon the stateful nature of your web servers or app servers, and then you can scale out as you need to. So, this is a typical web farm deployment for ASP.NET applications, you have N number of clients going through the load balancer to set up web servers within a web farm and then you have ASP.NET session storage, that's one kind of data that you may see within your ASP.NET web applications. Then it will be database servers, relational databases or NoSQL databases you may be dealing with a lot of data back and forth and then it could be any other back-end data system mainframe file system where your applications are interacting with. So, this is pretty popular, pretty scalable, pretty fast and a lot of active deployments are using this platform. So, let's talk about the scalability bottleneck within ASP.NET. Where exactly is problem? It's something which scales out very nicely the scalability problem and let's quickly define what scalability is? Scalability is an ability within the application architecture or within the environment where your application is deployed. It is that ability where you can increase number of requests per second or given requests, concurrent requests without compromising on the performance. If you have certain amount of latency under say five users. How about you maintain that latency? You don't degrade performance and it's okay to not improve performance but at least you maintain the performance under 5000 users or 500,000 users that ability itself is called scalability, where you get maximum throughput out of the system, more and more request loads are being handled and then your latency does not grow as user loads grow. So, it's essentially performance under extreme load or extreme performance under extreme load. So, that ability is called scalability. Now, typically ASP.NET applications although the web farm is very scalable, they would now give you the scalability problems within the web farm but they can cause slowness under peak loads primarily because of backend data sources. So, if your application slows down, it chokes down because of a huge amount of load then that that application is a candidate for scalability, it needs to have scalable architecture within itself. Why application would feel your world or you would see situations like this where applications slow down under peak load, there could be different data storage rated bottlenecks or some bottlenecks within the application. So, from this point onwards we'll talk about five different bottlenecks within an ASP.NET application that limits your ability of scalability, that limits you to scale out. Alright. So, first of all, we have two data storage bottlenecks. We have application database which cannot scale up typically, you would have a relational database in the form of SQL Server, oracle or any other popular relational data source. It's very good for storage but it's not very good when it comes to handle huge amount of transaction load. It tends to choke down and, in some cases, it actually gives you time-out errors. So, or at least it actually slows down your performance you cannot add more database servers on the fly so, it's going to be single source. It's also single point of failure in some cases if you don't have replication and then the most important, the pressing issue here is that it's not very fast, it's slow under normal scenario and then under peak load and it actually worsens the situation where it's not able to accommodate the increased load and it further slows things down. So, that's our first bottleneck. Second bottleneck is around ASP.NET session state storage, now session state is a very important kind of data. It's something that has user information, for example, there could be an e-commerce application you have maintaining user information or the shopping cart for that matter, it could be booking system, it could be ticketing system, it could be your financial system. So, it could be any sort of front system where users log in and they have their very important data within this session object. Now, these are the three modes that ASP.NET platform offers, we have InProc where everything gets stored inside the worker process. So, everything sits inside the application process so your worker processes are not stateless, HTTP protocol itself is stateless but in this case, your worker processes would host all the user data themselves. Then we have StateServer that second option and then we have SQL Server. So, talk about these conventional session state storage options and let's talk about their Bottlenecks. First of all, InProc it's fast because it's in memory, there's no serialization deserialization but on the downside, first of all, you cannot handle a web garden scenario. On one web server you would only have single worker process for a given application because that's where your session data exists now if next request goes to another worker process, you don't have that session data anymore it has to be the same worker process and this is why it limits you, it technically it's not possible to run web garden with InProc session management, so that's one limiting factor here. Secondly, you need sticky session bit to be enabled on load balancer. So, first of all, you limited your performance or scalability or your resources on the web server and by having only single process for an application. Secondly, your web servers where the initial request got served, subsequent requests would always go to that same server. That is all sticky session load balancing works, it gets the job done but main issue with this is that it could be that one web server has a lot of users active but other web servers are sitting idle because those users have already been logged out and since the users are going to be sticky in nature, they would never go to this free server, they would always go to the same server where they have to go with data exists. So, that's another problem you have to have sticky session load balancing with InProc, and most importantly, if your worker process gets recycle and we've seen based on our experience ASP.NET worker processes do get recycle quite a lot you would lose all the data right, if it's a maintenance related task, if the server needs to go down you have to bring one web server down bring another web server up you lose all data as a result of that. So, that sums up all the problems, all the bottlenecks that you would see with InProc session management with an ASP.NET. So, it's clearly not an option and it's also not very scalable you have one server which you hit capacity of that server and with sticky is a load balancing it doesn't really help. Second option is StateServer, it's slightly better than InProc because it takes data out of your application process inside a state service, it could be a remote box or one of your web servers, it's entirely up to you but problem with this is that it's not scalable, it's single source, you can scale up on that server but scaling out is not an option. It's always going to be single server, one service hosting all your session data and that is going to manage all the requests load as well, if your request load grows, there are no options to add more resources. So, it's not going to scale out in comparison eventually your state service can choke down for example, if you have hundreds and thousands of users and their associated request makes it millions of requests per second or per day requester or within millions that's pretty heavy load. So, based on that StateServer would not scale out and it would not be able to cope up with increasing load, and then it's also a single point to failure. If StateServer itself goes down, you lose all your session data and session data is a very important kind of data you wouldn't want to lose your sessions while your user is about purchase something or it's about to make a decision and it's going to impact the business in return. The third option is SQL Server. SQL Server is again an out of process session management but again it's slow, it's not scalable, you cannot add more SQL Servers and it's not meant to handle transactional data alone, so you end up having the same problem that we discussed as part of our application database, that problem remains the same for data caching as well as for session caching. So, session state is not something which is going to be optimized with the default options that ASP.NET platform presents and this is primarily because of the data sources that it offers InProc, StateServer and SQL Server. I hope this has built some basic details around the bottlenecks and of course we'll talk about the solution, we're talking about distributed caching and its features in comparison and we'll talk about how to take care of these issues one by one, so I want to list down all the problems first and then we'll talk about solutions one by one. This diagram illustrates the same. We have data storage bottleneck database and then we have ASP.NET session storage or InProc or databases as a session manager and that also up clearly a bottleneck, where we have single sources in most cases, they're not scalable, they're not very reliable and then there's slow in general. Now third important bottleneck is ASP.NET view state. For ASP.NET web farms there is a view state, now those of you who want to know what view state is? I'm pretty sure everybody knows but view state is a client-side state management, it's a packet, it's a state of your controls widgets that you have on your web farms, it gets constructed on the server end and it becomes part of your response packet goes back to the browser that's where it's stored, it's never really used on the browser end and it's brought back to the server when you post back on that page as part of the dispersed request packet. So, it becomes bundled with the request and response packets, it goes back to the browser, it's never really used there and one pressing issue with view state is that is generally very heavy. It's hundreds of kilobytes in size and think on the scenario, where you have huge amount of transaction load, we have millions of transactions and then each transaction has a view state packet bundle to it or a request response packet for ASP.NET web application has view state part of it and if you have a hundreds of kilobytes of view state per request and you have millions of transactions, it is going to consume a lot of bandwidth and it would in general slow down your page responses because you're dealing with a lot of data back and forth and that data is heavy in size as well. So, that's another bottleneck which eats up your bandwidth, your cause increases significantly and then it slows down your page response times because view state is general heavy, you're dealing with heavier payload for requests in response. So, that is another kind of bottleneck which is part of ASP.NET web farms. If you have ASP.NET web farms application, there's no getting away from this problem. By default, you would have to deal with a lot of view state and this diagram covers it where view state goes back to the browser, it's a client-side state management gets constructed on the server end and goes back to the browser and bring it back on the server on your post backs. Now request and response packets are heavy, they eat up a lot of bandwidth, heavy payload slows things down as well. Now fourth bottleneck and this is second last, we have one more bottleneck after this is the extra page execution bottleneck. Now this is true for ASP.NET web farms as well as for ASP.NET MVC web applications. There are scenarios where either entire page output is same or portions within a dynamic page are same, right so, you're dealing with static content within application very frequently. So, page output does not change very frequently but you're still executing those requests. There could be a request and it involves some back-end databases that gets rendered and then you fetch some data from the back-end data sources, you read that data, make it meaningful apply some daily business logic layer, data access layer all the good stuff and after that you render a response and the response is sent back to the end user in the browser. Now whatever the same cycle has to go again and then the content is not changing, you would have to go through the same cycle again and again and again. This page executes regardless if it changes or not, by default you're dealing with a lot of static content and although the content is not changing but you're still executing the same request. Now this increases your infrastructure cost, extra CPU, extra memory, extra database resources it can hit capacity on the web server, it can also hit capacity on database site in general it's something which would waste a lot of expensive CPU and resources on executing something which has already been executed. So, that's another bottleneck and we'll talk about a solution with the help of page output caching how to take care of this as well. So, this covers our fourth bottleneck and the fifth and by the way this diagram it involves page execution on static output and made more databases we dealing with a lot of requests. And fifth bottleneck is SignalR backplane. Now this is a very specific use case you may or may not have SignalR but for those of you, who are familiar with SignalR and if you have set up a backplane, right a backplane is a common message bus and your web server send all their messages instead of sending pushing functionality on the client browsers. There could be a scenario where few client requests are dealt with other web servers. So, we're just broadcasted to the backplane and backplane in turn broadcast messages, SignalR messages to all the web servers and they in turn broadcast to all their connected clients. So, with WebSockets ASP.NET SignalR backplane is a pretty common set up, if you have a web farm. Now SignalR Backplane NCache or any other distributed caching product can be plugged in. It can also be a database or it could be also a message bus but idea here is that backplane should not have performance or throughput issues. It should perform very well, it should give you low latency, it gives you high throughput and at the same time, it should be very reliable if it goes down and you lose all the SignalR messages that would impact the business as well. Databases are slow, they're not very scalable, they're slow in performance, Redis is an option it's not native .NET so, you need something which is very scalable, which is very fast and it's also very reliable. So, that's another problem within an ASP.NET application if you are using SignalR backplane as a result of that. So, this completes our five bottlenecks, I know it's a lot of information but primarily its database being slow, being not very scalable, ASP.NET session state does not have very scalable or fast or reliable options by default. View State for ASP.NET web farm is also a bottleneck, its source of contention, over utilization of bandwidth, static pages within application are going to be executed regardless, if your application content is changing or not. It's going to be executed and then we have SignalR Backplane which is generally slow and it's not very reliable, it's not very scalable and you need something which is very scalable very reliable in comparison. So, this completes our five bottlenecks, on next few slides I will talk about solution and then we'll actually go through all of these bottlenecks one by one and I will present different solutions. Please let me know there any questions and I'll be very happy to answer those questions for you right now. I have some samples sample applications lined up right here, so I'll be using these alright. So, I think at this point there are no questions. So, I'm quickly going to get started with the solution because we have lot to cover in our next segment. We have in-memory distributed caching as a solution and I'll be using NCache as an example product. NCache is main distributed caching product, .NET based distributed cache, it's written for within .NET and is primarily for .NET applications and it's one of our main products. I'll be using NCache as an example product and we'll talk about five different features within NCache that will take care of this and you would see a performance booster within your ASP.NET application. It would just dramatically improve performance as well as scalability and this is just ASP.NET specific features, there are other server-side features which you can tune, there's a separate webinar on how to improve NCache performance, that will just take things to a whole new level, that will further improve performance but this webinar I'll talk about five different bottlenecks and then talk about five different solutions to those bottlenecks. So, what is an in-memory distributed cache and how it is faster and more scalable and in some cases it's more reliable in comparison? So, distributed cache is a cluster of multiple inexpensive cache servers which are pooled together into a logical capacity for their memory, CPU as well as their networking resources. So, if you have a team of severs and those team of servers are joined together into a cluster, it's a logical capacity for applications but it's a physical set of servers or VMs, so behind us in there are multiple resources and you have ability to add more servers on the fly. So, inexpensive cache servers, join together, came together and they pool their resources and that's what forms the basis of a distributed cache. Then we have synchronized cache updates cross cache servers, it's very consistent in terms of data than it was because there are multiple servers, multiple client applications connect to it, so any update made on one cache server has to be visible on other web cache servers and also to the clients which are connected to it and I have used term visible, which means it has to be consistent. I didn't use replication as a term here, replication is another concept. So, all the updates are applied in a sync manner or in a consistent manner on all the caching servers, so you have the same view of the data for all your client applications. Then it should scale out for transactional as well as for memory capacity and also for other resources. If you add more servers, it should just grow the capacity, if you have two servers and you bring the third server, previously you were handling say 10,000 requests with a third server it should bring it to 15,000 with two more servers doubling the capacity, it should handle 20,000 requests per second and that's our experience. It actually increases the capacity and overall request handling capacity increases as you add number of servers and I'll show you some benchmark numbers to support that. This is deployment architecture of typical distributed cache. You have a team of cache servers, all Windows environments are supported 2008, 2012 and all your applications connect to it in a client-server model and they use this fast, scalable and reliable source in addition to our relational database. Someday they're going to give this exists in the relational database, you can bring some or all of your data in out in the cache. Session state this becomes your main store, view state, output cache, SignalR backplane this becomes your main provider for that. Let me show you some benchmark numbers to support that it's very scalable. On our website these numbers are published. So, these are the test details and then if you look at the performance this is growing for reads not that linear for writes, but this is the topology that we'll be using in today's webinar, reads and writes are growing linearly and this has reads and writes growing linearly as well as backups. So, this also comes with backup support that's why writes performance or capacity is slightly less than partition doesn't have any backup, so this has an overhead of backup as well. So, this is our most popular topology for reads and writes and as you add more servers it actually scales out the capacity as well. Let me take you to our demo environment, set up a distributed cache and then get started with these features one by one and guys please I mean if there are any questions? I'll be using, I've already downloaded installed NCache, scope of this webinar is not around NCache configurations or setup. So, I'll skip through some of the details here but just to let you know, I've downloaded NCache from our website a fully working trial and then I have installed it on two of my cache server boxes and one machine on my end is going to be used as a client. You can install NCache on the client as well or you can use the NuGet packages as needed. I'll just create a cache, let's name it aspnetcache because that's what we have in focus today. I'll pick partition replica cache and all these settings are discussed in great details in our regular NCache architecture webinars. Asynchronous replication option and here, I specify the servers which are initially going to be part of my cache cluster. Keep everything same for TCP/IP port. NCache is a TCP/IP based communication, server- server communication and client-server is managed through TCP/IP and then size of the cache on each server, I'll keep everything default keep the evictions default and choose finish and that's it. That's how easy it is to set up the cache. On the right pane we have all the settings that are related to this cache and by the way you can also set up command lines as well as powerShell tools and then you can manage everything from command line or powershell as well. I’ll add mybox from where I plan to run applications. So, that we have client-side configurations are updated and I am able to connect to this cache I'll start and test this cache cluster and that's It. My server site setup is complete at this point. Guys, please let me know are there any questions? All right, so, this has started. I'll right-click and choose statistics. Ron, I have a question here real quick does NCache flows to support Java applications for JSP sessions a session caching or is it only ASP.NET apps? okay that's a very good question primarily this webinar was focused for ASP.NET so, I focused more on the ASP.NET site but yes to answer this question NCache fully support Java applications, we have a Java client and then for Java applications, if you have Java web sessions or JSP sessions, you could very well use NCache. So, our provider remains exactly the same, it's a no code change option and we have a sample application which comes installed with NCache as well. So, you just need to install NCache on Windows environment or you could also use containers and then the application could be on Windows or it could be on Linux UNIX environment as well, it fully supports Java applications. I've opened statistics just to see some monitoring aspects, I have opened a monitoring tool as well that comes installed with NCache. I'll quickly run a stress testing tool application to verify that my cache is configured fine and next I will actually get started with the sample applications, one client is connected, you should see some activity right here, there you go and we have counters showing value of requests per second from both servers and we have some graphs being populated already. So, that ensure that everything is configured properly and then we can get started with our sample applications. So, first sample application is, these are five different optimizations. I'll talk about these one-by-one and then I'll show you the sample applications. First of all, you can use NCache for data caching, we have our detailed API for database bottlenecks. You can use a fast in-memory distributed cache, it’s faster because it's in memory, it's more scalable because you can add more servers and then you increase the capacity at runtime by adding more servers. You can use it for session state this is a no code change option, sessions are very reliable in NCache because these are replicated, sessions are managed in a fast and scalable repository as well in comparison and you don't need sticky session load-balancing. I'll talk about more benefits once we actually show these sample applications but just let you know that these are some of the benefits that you get out of NCache right away as you as soon as you plug in NCache for these. For web farms you can use view state, you can store view state on server end, you don't need to send view state and it reduce your view state payload size as well, then you can use NCache for SignalR Backplane, that's our fourth option and then you can also use NCache for output caching as well for static content and this is also true for ASP.NET core. You can use it for session state within ASP.NET core and you can also use it for response caching in ASP.NET core applications. So, let's get started with ASP.NET session state storage. This is easiest of all, you can set this up within five minutes and you can quickly test it. As a matter of fact, I'm going to show you how to set it up and then get started with it. So, that's our first sample application, what I've done is this comes installed with NCache as well but I've slightly modified it. For session caching all you need to do is add an assembly tag, these two assemblies are redundant, these are for another use case for object caching but you only need Alachisoft.NCache.SessionStoreProvider assembly. Version 4.9 is the latest version and then you need culture and publicly token for this assembly as well. So, this is a typical reference to this session state assembly, after this you need to replace your existing session state tag with NCache. If you already have a session state tag you need to replace it, if you don't have one it was InProc, in that case you could actually replace it, you can add this as a new. Here the mode is custom and provider is NCacheSessionsProvider, timeout value is if a session object in NCache stays idle for more than twenty minutes, it would automatically expire remove from the cache. Then there are some settings such as exceptions to be enabled. So, this can be used as a sample tag, you can copy it from here and paste it in the application and then most important thing is the cache name, you just need to specify the cache name aspnetcache. I think i use the same name aspnetcache and it would resolve the configurations for this sample because you only specify the name. So, it would just read the configurations for this cache from the client.ncconf aspnetcache or this file can be made part of the project as well. If you have a NuGet package you could actually make this file part of your project as well and that's it. You just need to save this and let me just make this as a main page because we were using two pages here and I'll run this and this would launch the guest game sessions for provider and it would connect to NCache for session data. So, I'm expecting to create a session object in the cache and then I'll read some data back from the session and I'll show you the session object being created as well. This is a guessing game application, it allows you to guess a number between one and hundred and then it actually prints the previous guest from the session object. So, it guessed the number is between 0 & 23. So, I'll just guess 12, number is between 12 and 23. So, it read the last number as well. Let’s guess number is between 13 and 23. So, let's guess one more time. I'm not able to guess, hopefully I'll get there but just to let you know a session object must have been created on the server end. Let me just show you this with the help of a tool and there it is, NCache test is a keyword that I append it with this sample application. If I change it, this is to distinguish between sessions of different applications, there could be a scenario where you have two applications and you will use the same cache for both applications. So, in that case you can have an app ID appended to the session variable but typically one application should cache its session in a dedicated cache. So, it doesn't really matter, if you even specify it as an empty string but this has been created and this is your ASP.NET session ID, session right here is replicated right here. So, if this server goes down you have the session data made available automatically. Some more benefits of NCache session state in comparison to InProc hits out of process, so your web process either is completely stateless. So, that is as preferred by HTTP protocol, it's more scalable, you can add more resources, it's faster because it's in-memory, is comparable with in comparison to InProc and then it's very reliable. If a server goes down you don't have to worry about anything and most importantly you don't have to use sticky sessions or balancing anymore. You can have equal load balancing and request can bounce from one web server to another. You don't have to worry about anything because web servers are not storing anything, actual session objects are stored in NCache and this is an outer process store for your applications and comparisons of StateServer. It's not a single point of failure, if a server goes down or you bring it down for maintenance, you don't have to worry about anything, it would just work without an issue. Secondly, it's very scalable you can add more servers on the fly. It's very reliable, it's very scalable, it's fast in comparison. For database it's not slow, it's fast and it's very scalable and in some cases it's even better in terms of reliability where you don't have replication for databases. So, this covers it and one more important feature within NCache is our multi-site session support, that's another feature multi-region sessions, where you going to have sessions from two different regions stored in NCache and you can have fully synchronized sessions. If a session request bounces from one server to another or from one region to another, it were automatically fed session across the region and bring it here and vice versa. So, if you need to bring side down, you could route all your traffic's to the other side by keeping cache running for some period of time. So, that's another feature. One of our major airlines, airlines customer is actually using this feature for their location affinity. So, this covers our ASP.NET session state. This is a no code change provider, please let me know if there are any questions around it then I'm already answered a question around JSP sessions, you can use NCache for Java based web sessions as well. Assuming there are no questions. Next, I'll talk about view state, now NCache also has a view state provider, the way it works is that basically, we keep view state on the server end. It's again a provider, all you need to do is set up a section group right, it’s content settings, it's ContentOptimization.Configurations.ContentSettings. The name of the section group is nContentOptimization and then this has some settings where you take a cache name for example, I'm using mycache right now, the way we have designed our ASP.NET view state provider is that we keep view state on the server end right. So, first of all I'll run without caching although I have the prior provider plugged in but I've set up the view state caching to be false and I'll run this and I'll show you the actual view state going back to the browser. So, I'll show you the default option and then I'll show you the NCache view state and we'll compare the difference. So, there's a few pages web farm and I'll show you the view page source. This is the default view state, the value part, let me bring it here and let me just create a temporary document here. Now this is the default view state which is part of my response packet and when I push back on this page, it's going to be part of my request packet as well. That is an individual request and notice how many characters, it has appended to request and response headers right and this is same for all the requests that I will make. Let me just show you few more requests and let me show you the view page source of this one as well. So, it's almost similar you could see on the screen. Now with NCache what we have done is we intercept your view state with the help of our view state provider. We keep view state on the server end so, this value part we create a key and a value for a given page of web farm, we stored on the server end, now it is stored on the server end so, we send a small token back to the browser. So, that is a static size token, which is sent back to the browser. It never really changes, it's always going to be sent there and then brought back to be used again and when you post back, you actually make a call to NCache and fetch the extra view state from NCache and then use it on your web farm for actually view state and that's what we are doing behind the scenes. The benefits that you get your view state packet becomes smaller in size right because it's a token. So, that has overall impact of reducing the size of payload for request and response. So, this improves your performance and secondly, if you have hundreds of kilobytes of view state traveling back and forth for thousands of requests, it will eat up your bandwidth. S, this is not going to happen with NCache, NCache view state is a static token and I'll show you the token real quick. Ron, let me just jump in for the question, real quick does NCache have any bill security features such as the encryption for sessions and view state caching? yes it does, these are features that you can set up explicitly, these are general NCache features. So, all the view state is already an encrypted string but if you want to further encrypt and let me see if it's around yeah so, you can enable encryption on the cache itself you need to stop it, set up encryption, we have DES providers, we have AES providers, we have FIPS client, FIPS compliant, DES AES providers. So, yes you can simply set up this and all the payload from client-servers would be encrypted and decrypted on here in and fetch respectively. So, this is something that you can set up on demand and you can make things go and by this question, I also want to highlight that since NCache is not storing this is the view state after NCache has plugged in has been plugged in as a provider and notice the difference, it's these many characters versus these many characters. So, this is your default, this is with NCache and see the difference yourself this slows down, reduces the size of the payload over all performance increases, band virtualization costs go down. So, you see a lot of improvements in the architecture and most importantly your actual view state is never really sent back to the browser anymore. It's going to be stored on the server end, it's secure in general. So, based on this question thank you for asking this NCache view state is by default more secure than the default option because we store it on the server end that's where it's actually needed. So, I hope that helps. I'm going to close this down, any of the questions around view state, I will otherwise move on to our next segment. Let’s make me show you the object caching first because of time constraint. I think, I should cover this first. For database bottlenecks, anything that stores in the database that slows things down alternatively you can use a distributed cache like NCache. This is NCache API here.Cache Connection Fetching DataFetching Data Cache cache = NCache.InitializeCache("myCache"); cache.Dispose(); Writing DataWriting Data Employee employee = (Employee) cache.Get("Employee:1000"); Employee employee = (Employee) cache["Employee:1000"]; bool isPresent = cache.Contains("Employee:1000"); cache.Add("Employee:1000", employee); cache.AddAsync("Employee:1000", employee); cache.Insert("Employee:1000", employee); cache.InsertAsync("Employee:1000", employee); cache["Employee:1000"] = employee; Employee employee = (Employee) cache.Remove("Employee:1000"); cache.RemoveAsync("Employee:1000"); This is how you connect cache, this is how you dispose the handle towards the end you make operations, everything's stored in a key value pair, it's a string key value .NET permitted object you can map your data tables on to your domain objects and then you store your domain objects and then you deal with domain objects by storing individual objects or collections having relationships, SQL searches the list goes on but this is basic create, read, update, delete operation. I'll quickly run a sample application and demonstrate how you would actually use NCache for object caching. You need these two summary references Alachisoft.NCache.Web and Alachisoft.NCache.Runtime. Once you've done this, let me make this as a start up page and show you the code behind for this. This is a ASP.NET web farm but if you have controllers MVC you could also use the same approach and then I have this namespace right here and within this application, I'm initializing mycache, you need to specify the name of the cache and you could also specify servers here, using InitParams right cache InitParams right here or you could just specify the name and resolve the name through client.ncconf which I showed you earlier. There is an addObject, which adds a customer, name is David Jones, male, contact number, this is address and then I'm calling cache.Add. Similarly, I'm inserting this by changing the page or I could actually, also change the name as well just to ensure that this is updated and then I'm calling cache.Insert and then I'm getting the object back, getting the count of the object. I'm removing that object, I'm just running a load test. 100 items are going to be updated again and again. So, let's run the sample application, this is how intuitive it is to get started with it and it would just launch the application and I'll be able to perform all these operations for you and before I actually do this, I would also like to show you the view states which were cached in NCache. You could see the keys for the view state for three pages vs and this is the actual key of the object and then actual view status is on the value part. I forgot to mention this now assuming that we have let me just clear the contents. So, that we're only dealing with object caching data now, actually let me just do this from manager, it's convenient. So, I'll add an object, customer added I'll fetch this object back. So, we have David Jones, age 23. I'll update it and then add it, get it back now it's David Jones 2 and then we have 50 as age, again get it, items in the cache 1, I'll remove this object again items in the cache 0 insert it one more time, insert is in add as well get the object back and then I can show you this in the cache. So, I was dealing with one object at this point and the key was customer in the name of the customer appended to it and then I'll start the load, test now. You would see some activity on the cache, there are requests coming in and you have client requests dealing with the data. And if I simply run this dump cache keys again, it would just show me the hundred keys dumped together. So, these are the keys that I added. So, this is how simple it is to get started with the object caching, any data that belongs in the database and slows things down, limits your scalability you can bring it to NCache using our object caching. It could be anything domain objects, collections, datasets, images any sort of application related data can be cached using object caching model. I hope this helps, let me get started with this, all right this covers our data caching next there are SignalR Backplane. Let's talk about SignalR. With NCache we have a powerful pub/sub messaging platform. So, we have a sample application and this I'll also show you the NuGet packages. NCache libraries come installed with installation or you could use our NuGet packages. So, if you go to our online NuGet repository and you browse for NCache, you will see all the NuGet packages. Alachisoft.NCache.SDK is for object caching, Linq for linq query, we have session state provider, then we have open source and community as well. This is the NuGet package that I have included in this application. Just build it and let's see if it works fine because it should have a NuGet package added to it. All right, for SignalR Backplane all you need to do is make sure that you have SignalR NuGet package added, I mean this is install if it's not installed already, all right. So, you have a NuGet package added and after that you need to add, it added some SignalR assemblies as needed and some helping assemblies as well and after that if you go to the web.config, i've just added some settings in there myname of the cache is aspnetcache right and then the event key, which is the name of the topic that you like for this. So, you would actually like to provide a topic name based on which you would like to have SignalR chat messages or SignalR messages for this particular chat application transmitted and then all you need to do is, one line of code change inside where you specify the name of the cache and the event key and point towords NCache and run the sample application. It would automatically use NCache for SignalR Backplan, NCache becomes your backplan that's how simple it is to plug in NCache for SignalR application. Benefits that you get its native .NET unlike Redis it's fast, scalable, reliable in comparison to databases as well as message buses and then we have a fully functional fully supported pub/sub model, which is backing this up. So, you can use pub/sub messaging directly as well but one extension of that one use case of pub/sub messaging is our SignalR Backplane and it's pretty easy to set up as well. So, this application has started. There should be a key here, I think it's hard to find the key but just to show you the chat through NCache, this works and I'm going to transmit this to another browser by signing another user, let's say Nick. If I bring this back you could see that it actually broadcasted the message to the other connected client as well. So, that's how easy it is. Let me just ask one more time and then check if it's working as expected, so there you go. So, this is being driven through NCache and it's very easy to set up and this is how you set up and last feature within NCache, the fifth booster is output caching. Ron, I have a question regarding SignalR, our SignalR messages stored as a visual object within NCache or does NCache use notification for this? NCache uses pub/sub notification for this. So, we have a pub/sub messaging platform which is in the background, in the cache itself you would just see one object or you won't even seen object because it's a topic. So, there's a topic which gets created, it's a logical tunnel where multiple work processes are connected and they actually broadcast NCache, all the SignalR messages to that topic. So, it's a notification framework if you're asking, if you would see a lot of messages added in the cache, no you wouldn't, you would just see one topic and then there are messages within the topic. There are a few statistics in the popper encounters that you can visualize to see how many messages are there within the topic but as far as individual objects are concerned, you won't see those objects, you just see one object as a topic. I hope that helps. Final feature within this, I think we're also short on time as well, I'll quickly go through this. It's our output caching you just need to set up the output caching section, you need reference to NCache output cache provider dll. This is right here, you need these references Ncache.Adapters, web, runtime in cache and after that you simply refer the N output cache provider and then you set up the name of the cache to aspnetcache, version should be latest. The way it works is that it actually caches the output of static pages, you simply run it and then it would just cache the output of a static page. If it's the entire page or portions within the page which are static and you decorate your portion static pages with this directive output cache, specify a duration, location and VaryByParam. If these params are not changing that automatically means that this is same output. So, cached output is presented to your end users, you don't have to be execute the pages, you don't have to involve databases, take the load off of worker processes, off the database, save expensive CPU’s and machine resources and get a ready-made page output made available for your end clients. So, it overall improves your performance, ASP.NET provides this as a feature and NCache takes it to a distributed level where we have very scalable, very fast and very reliable page output stored in NCache without any code changes and this is true for ASP.NET core as well, you could use by the way you can use NCache within ASP.NET core web applications as well. We did a separate webinar on that and if we have idistributed cache, we have session storage and then we also have ASP.NET core response caching as well along with EF core caching. So, these are some of the features that I wanted to highlight, this completes our five performance boosters. I hope you liked it, please let me know if there are any other questions, I think we're very short on time as well. So, if there are any other questions now is it time to ask those questions, so please let me know. In general, I would also like to mention that NCache is a fully elastic hundred percent uptime dynamic cache cluster, no single point of failure. We have many topologies and features like encryption, security, compression, email alerts, database synchronization, SQL like searches, continuous query, pub/sub model, relational data in NCache, these are all covered as part of different features. So, if there are any specific questions around these please feel free to ask those questions as well otherwise, I'll just conclude it and hand it over to Nick. Thank you very much Ron one last question here is it possible to set up a custom provider for session caching in NCache? NCache already is a custom provider. NCache lies under a custom provider, default modes are InProc, State Server or SQL Server and then the fourth mode from ASP.NET is a custom. So, NCache provider itself is a custom provider. I'm slightly confused on the question if there are any specific requirements around this please let me know otherwise NCache itself is a custom provider for ASP.NET. Okay thanks a lot Ron, if there are no more questions, I like to thank everybody for coming and joining us today and thanks Ron again for your valuable insight into this and guys if you have any questions you can always reach us by sending us emails at support@alachisoft.com. You get in contact our sales team by dropping us an email at sales@alachisoft.com and somebody from sales team will be happy to work with you and to make sure that all your questions are answered, provide all the information that you need and with that I would also suggest that you can download a trial version from our website of NCache, comes with a 30-day trial. We also have a mediation which has a paid support option as well as free open source edition, thirteen years with that a lot of content. Thanks everybody for joining us and we'll see you next time thank you. +1 (214) 764-6933 (US) +44 20 7993 8327 (UK)
https://www.alachisoft.com/resources/webinars/ncache/five-asp-net-performance-boosters.html
CC-MAIN-2022-05
refinedweb
9,271
64.85
Routing is one of the most basic things your app must have to do anything meaningful. However, navigating between pages can quickly turn into a mess. It doesn't have to be so! There are multiple options for routing. Some create a lot of clutter, others cannot facilitate passing data between routes, and yet others require that you set up a third-party library. The option that you are going to learn about in this tutorial is the best of both worlds - first-party and yet clean to use. Initial setup Before we can do routing the right way, we first need to have some pages to navigate between. While setting them up, it's also not bad to showcase the most basic way of navigation from which we want to get away. There are 2 pages and the second page receives data from the first one. We push MaterialPageRoutes directly to the navigator which creates quite a lot of boilerplate code. The more pages your app has, the worse it gets, and it's easy to get lost in all these routes specified all over the place. main.dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), // Initially display FirstPage home: FirstPage(), ); } } class FirstPage extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Routing App'), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( 'First Page', style: TextStyle(fontSize: 50), ), RaisedButton( child: Text('Go to second'), onPressed: () { // Pushing a route directly, WITHOUT using a named route Navigator.of(context).push( // With MaterialPageRoute, you can pass data between pages, // but if you have a more complex app, you will quickly get lost. MaterialPageRoute( builder: (context) => SecondPage(data: 'Hello there from the first page!'), ), ); }, ) ], ), ), ); } } class SecondPage extends StatelessWidget { // This is a String for the sake of an example. // You can use any type you want. final String data; SecondPage({ Key key, this.data, }) : super(key: key); Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Routing App'), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( 'Second Page', style: TextStyle(fontSize: 50), ), Text( data, style: TextStyle(fontSize: 20), ), ], ), ), ); } } Now that you know what non-named navigation looks like, wouldn't it be simpler to just use the code below which uses named routes? ... // Pushing a named route Navigator.of(context).pushNamed( '/second', arguments: 'Hello there from the first page!', ); ... You have two options for navigating with named routes without needing a library. The first one is the simplest - just specify a map of routes on MaterialApp widget, its keys being the names of those routes. As soon as you want to pass some data between pages, and let alone run logic, this first option comes out of the equation. You cannot pass dynamic additional data in a map literal, after all! The second option is to specify a function returning a route. By doing this, you still get the benefits of using named routes, but you now have the option to pass data to pages. This is possible, because unlike with a map literal, you can add logic to a function. Creating a route_generator The function which you need to specify on the root widget MaterialApp is called onGenerateRoute. It's good to separate your code into multiple classes and stand-alone functions though, so let's create a RouteGenerator class to encapsulate the routing logic. route_generator.dart import 'package:flutter/material.dart'; import 'package:routing_prep/main.dart'; class RouteGenerator { static Route<dynamic> generateRoute(RouteSettings settings) { // Getting arguments passed in while calling Navigator.pushNamed final args = settings.arguments; switch (settings.name) { case '/': return MaterialPageRoute(builder: (_) => FirstPage()); case '/second': // Validation of correct data type if (args is String) { return MaterialPageRoute( builder: (_) => SecondPage( data: args, ), ); } // If args is not of the correct type, return an error page. // You can also throw an exception while in development. return _errorRoute(); default: // If there is no such named route in the switch statement, e.g. /third return _errorRoute(); } } static Route<dynamic> _errorRoute() { return MaterialPageRoute(builder: (_) { return Scaffold( appBar: AppBar( title: Text('Error'), ), body: Center( child: Text('ERROR'), ), ); }); } } function. main.dart ... class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( ... // Initially display FirstPage initialRoute: '/', onGenerateRoute: RouteGenerator.generateRoute, ); } } class FirstPage extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( ... RaisedButton( child: Text('Go to second'), onPressed: () { // Pushing a named route Navigator.of(context).pushNamed( '/second', arguments: 'Hello there from the first page!', ); }, ) ... } } ... With this done, run the app and test it! You can also intentionally mess up the name of the route to which you navigate or pass in an argument of a wrong type and see what happens. Conclusion You have learned how to navigate around your Flutter apps in a way suitable for larger apps. You've created a RouteGenerator which can encapsulate all of the routing logic - sparing you from code duplication. Creating many smaller classes with a certain purpose is always a good way to simplify your code and when it comes to routing, this principle still holds true. Be sure to check out the video tutorial for a more hands-on perspective of building this app. It will be nice to pass RouteSettings settings to MaterialPageRoute so that any reference to ModalRoute.of(context).settings continues to work. How to pass names parameters using onGenerateRoute How to pass names parameters using onGenerateRoute. How can I finish the first page and then go to second page so that I can exit the app when i hit back button on the second page? Any thing for that? How do you pass multiple arguments with this method? Arguments can be any object, you can make an array as you can see: Navigator.of(context).pushNamed(‘/nameroute’, arguments: {‘arg1’ : value, ‘arg2’ : value}); and access to the router class. Hello, How can I check which is the current Route, as of now I am facing issue in Notification route, below is the scenario. 1. Got a notification from FCM. 2. Tap on notification redirects to particular screen A. 3. As the time screen open in foreground other notification comes, 4. Open the Notification from the top and click on the notification. 5. That notification same as the previous screen so I need to redirect on the same screen 6. That redirect to the Screen A but now the route is Home -> Screen A -> Screen A So how can prevent to push the same screen multiple times?
https://resocoder.com/2019/04/27/flutter-routes-navigation-parameters-named-routes-ongenerateroute/
CC-MAIN-2020-24
refinedweb
1,086
56.35
Awesome! Thank you so much! Any idea how long it will take before the webIDE will work? I just tried it and I still get the SOS lights. !!! I'll have to test again! Make sure you pull the latest version in your app. i just got my RFID today and tested it with your new version and it definitly works on my photon (0.45). ... Good Timing i guess and Thank you for porting it! In case someone else could use a quick and easy code to just get the Card's ID as a string (i saw someone asking anywhere in this Thread) - this works fine for me: void loop() { // Look for new cards if ( ! mfrc522.PICC_IsNewCardPresent()) { return; } // Select one of the cards if ( ! mfrc522.PICC_ReadCardSerial()) { return; } String cardID = ""; for (byte i = 0; i < mfrc522.uid.size; i++) { cardID += String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : ""); cardID += String(mfrc522.uid.uidByte[i], HEX); } Serial.println(cardID); Particle.publish("pushover", cardID + " scanned", 60, PRIVATE); mfrc522.PICC_HaltA(); } How does one 'pull' the latest version in to an app? @anlek, if you are using the web IDE, remove the library and then re-add it again. Also make sure you are compiling for latest 0.4.5. latest 0.4.5 Understood, Thanks! So I created a new project (I also removed and re-added the MFRC522 library and still getting SOS lights (on the latest 0.4.5 firmware). MFRC522 0.4.5 #include "MFRC522/MFRC522.h" #define SS_PIN SS #define RST_PIN A1 MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance. Any other ideas? I'm quite lost... On the webIDE it still states: MFRC522 0.1.1 and not 0.1.2 MFRC522 0.1.1 0.1.2 I think I got it refreshed... sorry for the messages. Hi, I am working on a time-keeping project using an arduino uno, a lcd display and... a rfid reader RC522.But I have a problem because the rfid reader uses the same pins as lcd's . So I was wondering if I could connect RC522 using just the SOUT pin, or maybe there is another possibility to connect these two devices together. Hi guys, @peekay123, @korneelI am newbie to spark, i have found the library in the particle IDE and Pin are configure as per the in app comment.Could you please point me out how to see output data from the card which i place on the MFRC522 chip.also, Please point me some easy way to send this data to my server url as json data (something like webhook) for the card which i place on the MFRC522. Thanks in advance If you plug your Particle device into your computer via USB and open a serial monitor application (e.g. PuTTY) you can attach to the respective COM port an see the Serial output. Serial And if you have a line like this in your code Particle.publish("pushover", cardID + " scanned", 60, PRIVATE); You can go to and see the output there. If you want to use a webhook to relay this event to your server you'd best look at the webhooks docs first Thanks for reply. i will look this webhook docs BTW: If you were a bit quick with posting a reply, you don't need to delete the post and create a new one.You can just hit the pencil icon in the bottom line of the post to edit your own posts. @peekay123 I've been reading through this thread, and have downloaded your code from GitHub (RC522_RFID). But I'm getting errors when I compile. Admittedly, this is my first time using libraries and SPI...I'm new to Particle, but have experience with Arduino (you helped me on my first post in fact, Arduino vs. Particle...thank you!). Here are the errors: RFID.cpp: In member function 'void RFID::halt()':RFID.cpp:512:13: warning: variable 'status' set but not used [-Wunused-but-set-variable] uint8_t status; ^RFID.cpp: In member function 'uint8_t RFID::softSPITranser(uint8_t)':RFID.cpp:532:38: error: 'struct GPIO_TypeDef' has no member named 'BSRR' PIN_MAP[_mosiPin].gpio_peripheral->BSRR = PIN_MAP[_mosiPin].gpio_pin; // Data High ^ RFID.cpp:534:38: error: 'struct GPIO_TypeDef' has no member named 'BRR' PIN_MAP[_mosiPin].gpio_peripheral->BRR = PIN_MAP[_mosiPin].gpio_pin; // Data Low Any thoughts? I'm thinking maybe I'm not doing something right in the build.particle.io....my App shows the three files: RC522-RFID.INORFID.CPPRFID.H Am I missing something? Thanks so much, in advance!J- You can replace these calls with the respective commands pinSetFast() / pinResetFast() and pinReadFast() to get rid of the error messages. pinSetFast() pinResetFast() pinReadFast() for (uint8_t bit = 0; bit < 8; bit++) { if (data & (1 << (7-bit))) // walks down mask from bit 7 to bit 0 pinSetFast(_mosiPin); // Data High else pinResetFast(_mosiPin); // Data Low pinSetFast(_clockPin); // Clock High b <<= 1; if (pinReadFast(_misoPin)) b |= 1; pinResetFast(_clockPin); // Clock Low } Wow, thanks @ScruffR! That did it! What a quick response, and what an earlybird! Really appreciate it! Best-Jeremy That's the advantage of a global community - it's 2:10pm for me already
https://community.particle.io/t/getting-the-rfid-rc522-to-work-solved/3571?page=11
CC-MAIN-2017-17
refinedweb
857
68.06
Customizing Azure Search fields Eric Dugre — Oct 26, 2018 azure searchkentico 11event handler Kentico 11 introduces native Azure Search integration with a variety of customization options. In this article, we’ll learn how to change the data type of our Azure search fields. Azure Search integration is a powerful way to extend the search capability of your Kentico site, as well as incorporate your indexed content into other applications. Out-of-the-box, your Kentico fields will be converted into basic Microsoft data types like Edm.String, but your applications might expect a more specific data type. In this example, we will be indexing the DancingGoat.Cafe pages on the Dancing Goat sample site. To follow along with this guide, you can install the sample site using the web template provided by your Kentico installation:. 1. Creating the Azure Search service To create Azure Search indexes, you first need to have an Azure Search service running with your Azure subscription. You can find instruction on creating the service in Microsoft’s documentation:. 2. Adding a custom field in Kentico Once you have the Dancing Goat sample site installed, you may begin our customization. By default, the DancingGoat.Cafe page type contains fields such as CafeStreet and CafeCity, but what if you want to provide exact coordinates for use on a map or in a location search? Let’s add a new field to do this to the page type: While editing the DancingGoat.Cafe page type in the Page types module, click the Fields tab. Click the New field button and fill in the following properties: Field name: CafeGeolocation Data type: Text Field caption: Lat/Lng Field description: Enter the cafe's coordinates, separated by a comma. Click Save. On the Search fields tab, make sure Search is enabled is checked and click save. Check the Searchable box under the Azure section of the CafeGeolocation field, then click Save. Now, go to the Pages module and select the cafes from the content tree and enter coordinates in the Form tab for several of the pages. Here are some coordinates you can use for this example: Boston: 42.299744,-71.072383 Allendale: 42.978361,-85.916874 Los Angeles: 34.050518,-118.511553 New York: 40.749345,-73.996675 Ottawa: 45.415824,-75.689566 Toronto: 43.664006,-79.390779 Amsterdam: 52.359872,4.876509 Birmingham: 52.480798,-1.900119 Liverpool: 40.389553,-90.004861 London: 26.304427,50.169413 Madrid: 40.417313,-3.691632 Brisbane: -27.469309,153.026164 Melbourne: -37.814750,144.983066 Sydney: -33.879792,151.207440 3. Setting up the index in Kentico Go to Smart search > Azure indexes and click the New index button. Fill in the following properties: Display name: Dancing Goat Cafes Index type: Pages Service name: The name entered while creating the Azure Search service in the Azure Portal. This is the first part of the service’s URL, e.g. https://<servicename>.search.windows.net. Admin key: Either the Primary key or Secondary key found within your Azure Search service’s Keys tab. Click Save. In the Indexed content tab, click Add allowed content and fill in the following properties: Path: /Cafes/% Page types: DancingGoat.Cafe Click Save. 4. Our progress so far Don’t rebuild your index yet! If you did, you would see that the index in the Azure Portal has been updated to include your new CafeGeolocation field, but it is stored as an Edm.String object. This may be fine for your purposes, and if so, you’re done here! But, what if other applications accessing this index require the coordinates to be stored as Edm.GeographyPoint objects. How can we change the field in Azure Search? To do this, we will be using two events that can be found on the following page:. DocumentFieldCreator.CreatingField - Occurs when the system creates individual fields for a document within an Azure Search index. Triggered separately for each field of every indexed object. DocumentCreator.AddingDocumentValue - Occurs when the system sets the values of individual fields for documents within an Azure Search index. Triggered separately for each field of every indexed object. 5. Time to write some code! As the documentation explains, the event handlers we need to use can be registered using a custom Module class:. Although our recommendation is to add these types of customizations in a separate library project, for the sake of simplicity you can create your custom files and store them in the /App_Code folder (or /Old_App_Code for web applications). Create a new class for your custom Module, e.g. “CustomEventHandlers” and enter the following code: using CMS; using CMS.DataEngine; using CMS.Helpers; using CMS.Search.Azure; using Microsoft.Spatial; using System; [assembly: RegisterModule(typeof(CustomEventHandlers))] public class CustomEventHandlers: Module { public CustomEventHandlers(): base("CustomEventHandlers") { } protected override void OnInit() { base.OnInit(); } } Now, we need to change the automatically-generated “cafegeolocation” field in the Azure Search service from Edm.String to Edm.GeographyPoint. This is where the CreatingField event comes into play. Inside the OnInit() method, add an event handler: DocumentFieldCreator.Instance.CreatingField.After += CreatingField_After; Add the CreatingField_After method to the class: private void CreatingField_After(object sender, CreateFieldEventArgs e) { if (e.SearchField.FieldName == "CafeGeolocation") { e.Field = new Microsoft.Azure.Search.Models.Field("cafegeolocation", Microsoft.Azure.Search.Models.DataType.GeographyPoint); } } This code will run when the “cafegeolocation” field is created during index generation, and will change the field type to Edm.GeographyPoint. However, the value that is stored in that field will still be the plain comma-separated string that you entered in the Kentico interface, which will cause Azure to throw errors when the index rebuilds if we leave it that way. To account for this, we need to dynamically convert the lat/lng string into an Edm.GeographyPoint object every time the index is built. We register the AddingDocumentValue event handler in OnInit(): DocumentCreator.Instance.AddingDocumentValue.Execute += AddingDocumentValue_Execute; Then, add the method that will convert the string value into a GeographyPoint: private void AddingDocumentValue_Execute(object sender, AddDocumentValueEventArgs e) { if (e.AzureName == "cafegeolocation") { if (!DataHelper.IsEmpty(e.Value)) { string[] latlng = e.Value.ToString().Split(','); if (latlng.Length == 2 && !DataHelper.IsEmpty(latlng[0]) && !DataHelper.IsEmpty(latlng[1])) { e.Value = GeographyPoint.Create(Double.Parse(latlng[0].Trim()), Double.Parse(latlng[1].Trim())); } } } } At this point, you may get the following error message: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Visual Studio should be able to resolve this issue if you press CTRL+. and click the suggested fix, or you can add the following to your web.config’s <compilation><assemblies> section: <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> 6. Finishing up One more change needs to be made to the CustomEventHandlers.cs file for this to work. The C# type Microsoft.Spatial.GeographyPoint needs to be mapped to the Edm.GeographyPoint type, as described here:. To do this, you can add the following to the OnInit() method: DataMapper.Instance.RegisterMapping(typeof(GeographyPoint), Microsoft.Azure.Search.Models.DataType.GeographyPoint); You can now click the Rebuild button on your Smart Search index. It may take a few minutes, but eventually you will see the CafeGeolocation field is stored as an Edm.GeographyPoint object in the Azure Search service. Now that we are able to store Edm.GeographyPoint types in Azure Search it means we can use some of Azure’s built in functionality like calculating the distance between two points and filtering or ordering the results all on the Search Service. You can test this against your index by going into your Azure Search Service, into the Search explorer and use the following filter: $filter=geo.distance(cafegeolocation, geography'POINT(-71.071138 42.300101)') le 300 It should return all the cafés within 300 km from the given point. In this case it will return Boston and New York, since it is a Boston geolocation. We can also order the results by how far they are to that same point to get back a relevant list of cafes for our user by adding the following to the filter query: &orderby=geo.distance(cafegeolocation, geography'POINT(-71.071138 42.300101)') Using this index we could easily create a custom store locator web part to allow users to discover the closest cafés to their location. Share this article on Twitter Facebook LinkedIn Eric Dugre Please enable JavaScript to view the comments powered by Disqus.
https://devnet.kentico.com/articles/customizing-azure-search-fields
CC-MAIN-2019-30
refinedweb
1,417
50.23
Welcome to the fourth segment of the Epic PyObjC tutorial series. In the third part of the tutorial we focused on three smaller tasks: handling double clicks, caching to disk, and adding a progress indicator. This time we're going to focus on two slightly tricky, but extremely important patterns in Cocoa application development. We'll start out implementing some drag and drop functionality, and finish by looking at using a second nib file to create new windows while the application is running. In the third article I said that I would also include a list of resources in this segment, but after it occured to me to cover using a second nib (understanding which opens up your Cocoa horizons), I felt like that was a topic that would be genuinely beneficial to cover, and that covering drag and drop, additional nibs and the references would be a bit much material in one article. If you haven't been following along thus far, you can download the current zip of the project. Since this is our last dance together (in this series, at least), lets have some fun. Drag & Drop: A Philosophy, A Style I'd like to start out the discussion of drag and drop in Cocoa by mentioning my long term dedication to the concept, but that would be a lie. When I first was getting started with PyObjC and Cocoa--about a year and a half ago (don't tell the recruiters)--I put together my first fairly complex application and I was pretty proud of it. The two critiques I remember most closely were: don't use brushed metal (I still haven't recovered from the anti-brushed metal conspiracy yet), and "Wouldn't drag and drop work better to transfer things between two lists than double clicking?" I think I mumbled some lame excuse about not doing it, namely that it was more confusing than I could easily figure out, but damn it, who needs drag and drop anyway? Well, previous antics to the contrary, I need drag and drop, and so do you. Drag and drop is one of the few places where you can experiment with your user interface and really do something interesting without breaking so many conventions that your users curse your birth. Drag and drop is the wild west of Cocoa programming. So much of the potential of drag and drop isn't explored, simply because it doesn't need to be. Most applications can be implemented with no or minimal drag and drop, and thus they are implemented that way. But, I say, no longer! There are an unending number of intuitive, fun and useful ways to use drag and drop more. This isn't a complete list in any sense, just a starting point: Allow text and contents to be dropped on the dock icon. Its a great way of facilitating interapplication communication. In MetaWindow's case we might make it automatically search for strings dropped onto the dock icon. (I wrote a terse entry about implementation details here.) Make exporting data as simple as drag and drop. Lets say you wanted to email a report, wouldn't it be great if you could just drag the table into Mail.app, have it automatically convert into a PDF? But what if you dragged it into a text only email? Well, then it might export the data as text. Wouldn't it be great if exporting data was uniformly that simple and applications really cooperated? Be thoughtful about contextually dragging and dropping data. If the user is trying to enter a phone address, it would be great if you could use a regex to parse the phone number out of a paragraph. Even better if you dropped a list of telephone numbers and it identified and added all of them. We're used to strict standards for the input we give applications, but there is the real potential for users to fall in love with applications that let them throw data in indiscriminately and handles the details for them. Of course, we have to let our users know when they can be indiscriminate, since they've been trained to serve as the computer's secretary, and won't expect otherwise unless your app liberates them. To sum it up, drag and drop is the Unix pipes of Cocoa programming. It is the easiest and most seamless way for application to cooperate, and once we start getting creative, it'll open up a world of unexpected combination and utility. Drag & Drop: Search by Dropping In MetaWindow we're going to implement two kinds of drag and drop, starting with making it possible to search by dragging text into the search window. Not just the search textfield, but the entire window containing it. This creates a bigger sweet spot, and makes it quicker to use. The first thing we need to do is open up MWController.py and create a helper function that will accept a search string as a parameter and then perform the search (as well as update the textfield with the search string for visual confirmation). We need to do this, because we'll be subclassing NSWindow to listen for the drop operation, but if were handled searching in that subclass we'd have to re-implement the searching logic there. We avoid repeating ourselves by giving our NSWindow subclass an IBOutlet and connecting it to our MWController and its search_ method. Thus we're adding the dragSearch method to MWController. def dragSearch(self,searchString): self.textField.setStringValue_(searchString) self.search_(self) dragSearch really just loads the bullet in search_'s barrel and then fires it. Now, we need to create a new file. Go to the File menu, and then New File (Apple-N). We really want to subclass NSWindow, but there isn't a default template to do that, so we'll just create a Python NSObject subclass file and tailor it to our uses. Name the file MWDragWindow.py, and drag it into the Classes group in the outline view in XCode (strictly for organizational purposes). Then--the easy to forget but crucial step--open up main.py and add an import for MWDragWindow so that it looks like this: # import modules containing classes required to start application and load MainMenu.nib import metaweb import MetaWindowAppDelegate import MWController import MWDragWindow Now open up the MWDragWindow.py file and we can get to work. At the top you'll need to import * from AppKit and import objc, so that the imports are now: import objc from Foundation import * from AppKit import * Next we want to change MWDragWindow from subclassing NSObject to subclassing NSWindow. We also want to give it an IBOutlet named controller. class MWDragWindow(NSWindow): controller = objc.IBOutlet() Continuing, we begin to set it up to support drop operations. The first step is to register a class for the types of pasteboards it will respond to. In this case we just want to listen for the NSStringPboardType, which is the pasteboard type for text. To register for dragged types you call an object's registerForDraggedTypes_ method with a list of types to listen for. Its usually easiest to do this in the awakeFromNib method, which gets called as the object is initialized. For MWDragWindow the code is as simple as this: def awakeFromNib(self): self.registerForDraggedTypes_([NSStringPboardType]) Be careful to pass registerForDraggedTypes_ a list of types, not just pass it NSStringPboardType directly. A brief sidenote on user created pasteboard types. There are a number of different types of pasteboards already supported by Cocoa. We're using the NSStringPboardType, but there are many other existing pasteboards to choose from: NSUrlPboardType, NSColorPboardType, NSFilenamesPboardType, NSFileContentsPboardType and so on. Sometimes, however, you're trying to drag and drop something that falls outside of the purview of existing pasteboard types. In those cases, you can create your own pasteboard types. A pasteboard type is actually only a string, so creating a pasteboard type is as simple as creating a module level variable containing the string and importing it into any other modules that use the same pasteboard. ## Some Module A MWRowPboardType = u"MWRowPboardType" class MyWindow(NSWindow): def awakeFromNib(self): self.registerForDraggedTypes_([MWRowPboardType]) And using it in another module would be like this: from module_a import MWRowPboardType class AnotherWindow(NSWindow): def awakeFromNib(self): self.registerForDraggedTypes_([MWRowPboardType]) Typically you can only use user created pasteboard types within the application that declares it, simply because other applications won't know about it. However, if developers actively publicized the strings for their pasteboards, that wouldn't necessarily be the case. Now that MWDragWindow is registered for NSStringPboardType, we need to implement two more methods to tell it how to handle incoming drags. The first is draggingEntered_, and it is used for determining the type of imagery to use to represent the incoming drag. For example, if you were dragging text into a textfield, you would probably want to use NSDragOperationAdd, but if you were instead linking to objects together, you'd prefer NSDragOperationLink. Perhaps the most important operation, however, is NSDragOperationNone which you return when you refuse an incoming drag event. When you return NSDragOperationNone then there is no visual acknowledgement of the drag, and the object is refusing to handle the drag type. This provides a visual cue for users about which kinds of data an an application/window/field can accept. In MWDragWindow we'll implement draggingEntered_ as follows: def draggingEntered_(self,sender): pboard = sender.draggingPasteboard() types = pboard.types() opType = NSDragOperationNone if NSStringPboardType in types: opType = NSDragOperationCopy return opType If the pasteboard contains NSStringPboardType we'll handle it, otherwise we won't. We're using the NSDragOperationCopy imagery because that is the imagery the textfield uses to respond to the NSStringPboardType, and changing between drag imagery can be a bit unsettling (unless you're trying to indicate that different behavior will occur if you drop in different locations, in which case it's entirely appropriate). draggingEntered_ handles accepting or rejecting drags, and the visual imagery to display the drag, but so far we aren't handling the contents of an incoming drag. That is done by implementing performDragOperation_. def performDragOperation_(self,sender): pboard = sender.draggingPasteboard() successful = False if NSStringPboardType in pboard.types(): txt = pboard.stringForType_(NSStringPboardType) self.controller.dragSearch(txt) successful = True return successful If we return False from performDragOperation_ then the application will visually indicate that the drop was rejected--and if we return True then it will visually indicate the drop has succeeded--but actually handling the incoming data is up to us. Here we are simply calling the MWController method dragSearch with the string stored for type NSStringPboardType in the pasteboard, and having MWController handle things for us. The last thing we need to do is open up InterfaceBuilder and modify things a bit, so go ahead and open up MainMenu.xib. Open the Inspector, and select Window (Window), and go to the sixth tab. The Inspector's title will change to Window Identity when you are in the correct tab. At the top of the inspector in the segment named Class Identity, in the field named Class replace NSWindow with MWDragWindow. Then go to the window containing all the objects, hold down control, and drag from Window (Window) to Controller and release. Select controller from the popup menu. Now drag some text into the window, release it, and it will begin searching as if we had typed the text into the textfield and hit search. Drag & Drop: Export Data by Dragging Now that we're implemented drag and drop in our window, we're going to take a look at another common drag and drop scenario: drag and drop in an NSTableView. Traditionally drag and drop was handled in the NSTableView's datasource, but if remember back to segment two, we don't have a datasource specified yet, so we know things will work out a bit differently. In fact, we'll implement drag and drop by subclassing the NSArrayController class and reclassing the controller object in MainMenu.xib with our custom class. Let's start out by creating a new file in our project, subclassing from NSObject, named MWDragArrayController.py, and add the import to main.py so that the imports in main.py look like this: # import modules containing classes required to start application and load MainMenu.nib import metaweb import MetaWindowAppDelegate import MWController import MWDragWindow import MWDragArrayController Now, back in MWDragArrayController.py, lets change MWDragArrayController from subclassing NSObject to subclassing from NSArrayController, and also import NSStringPboardType from AppKit. from AppKit import NSStringPboardType from Foundation import * class MWDragArrayController(NSArrayController): pass Lets take a quick detour and open up MainMenu.xib in InterfaceBuilder. Select the Array Controller instance, open up the Inspector, select the Identity tab (the sixth one) and change the class from NSArrayController to MWDragArrayController. Then, and this step is easy to forget but very important, you need to select the tableview (not the scroll view that contains it, so click on it twice) and connect it to Drag Array Controller for both the delegate and datasource outlets. Save, close Interface Builder, and return to editing MWDropArrayController.py. Surprisingly enough we're almost finished! We just need to add this method to MWDropArrayController: def tableView_writeRows_toPasteboard_(self,tv,rows,pb): arranged = self.arrangedObjects() data = ",".join([ arranged[x]['name'] for x in rows ]) pb.declareTypes_owner_([NSStringPboardType],self) pb.setString_forType_(data,NSStringPboardType) return True Save and build the app, search for something and drag one of the rows out of the table. It's pretty neat, yeah, but somethings not quite right: you can't drag into other applications. Thats pretty inconvenient, and really cuts back on the utility of dragging. To fix that open up MWController, go to the awakeFromNib method, and add this line: self.tableView.setDraggingSourceOperationMask_forLocal_(NSDragOperationCopy, False) All together that means that ` MWController's awakeFromNib method looks like this: def awakeFromNib(self): if self.tableView: self.tableView.setTarget_(self) self.tableView.setDoubleAction_("open:") self.tableView.setDraggingSourceOperationMask_forLocal_(NSDragOperationCopy, False) Now save and trying building MetaWindow again. You should be able to drag content from rows into other applications as well. That sums up our look at drag and drop in MetaWindow. We're not going to look at dropping data into our tableview, mostly because I couldn't imagine a single way to even contrive a use for that given that we're displaying the results from Metaweb as if they were immutable. Perhaps if MetaWindow was extended to modify data, then such an operation might have some value (a way to import data, for example). Using a Second Nib Time to begin looking at our final topic in the Epic PyObjC tutorial series, and an important topic it is: using multiple nibs in one project. For many applications you can avoid using multiple nibs. For example, if you look at iTunes approach to playlists, by default when you click on a playlist it just displays in the list in the main window. You can do that with one nib. No problem. But if you double click on a playlist, it will open a new window. That, on the other hand, you can't do with one nib (unless you create and populate the window programatically, which is possible but will typically be far more work). Once you graduate from trivial applications, you will inevitable need to learn about using multiple nibs in one project, and--like everything we've looked at in this tutorial--it really isn't that hard once you decide to sit down and do it. Right now when you double click on a row it opens up the entry's page in a web browser, but it would be nice if instead it opened up a new window that showed us more details about that entry. So far we're just scratching the surface of the data stored returned by metaweb.py, and we could display a lot more of it with an entire window to dedicate to each result. There are three steps that we will take to integrate the additional nib into our project: Create a custom Python class that subclasses NSWindowController, and which is given the specific row's dictionary when initialized. Create a new nib, which we'll call RowWindow.xib, where we set the File's Ownerclass to be our custom subclass of NSWindowController. Update the open_method in MWControllerto create a new window using the RowWindow.xibnib instead of opening the row's entry in a web browser. Subclassing NSWindowController First, lets create a new file named MWRowWindowController.py. Initially it will be subclassed from NSObject, but lets change its parent class to NSWindowController, and also give it a field named rowDict. class MWRowWindowController(NSWindowController): rowDict = None Then import it in main.py like usual: # import modules containing classes required to start application and load MainMenu.nib import metaweb import MetaWindowAppDelegate import MWController import MWDragWindow import MWDragArrayController import MWRowWindowController And... thats it. Creating RowWindow.xib. Create a new file, this time choosing the Window XIB template, and naming it RowWindow.xib. Then open it in InterfaceBuilder. First, open the Inspector and select File's Owner, then go to the Identity tab and change its class from NSObject to RowWindowController. Next create an NSTextField in the nib's window, select it, and go to the Bindings tab. For the Value binding, bind it to File's Owner, and for Model Key Path type in rowDict.name. This is another example of using Cocoa bindings to avoid repetitive code. They are your friends. Finally, we need to click on File's Owner and connect its window outlet to Window (Window). Updating the open_ method The last step for us is to update the open_ method in MWController. To accomplish that we'll start by adding an import for the MWRowWindowController class to MWController.py. import objc, metaweb, webbrowser, pickle, datetime, md5, threading from MWRowWindowController import MWRowWindowController from AppKit import * from Foundation import * And then we turn to open_. Right now it looks like this: url = u"" % row['id'] webbrowser.open(url) Everything except for the last two lines is already perfect. Go ahead and delete the last two and replace them with this: rwc = MWRowWindowController.alloc().initWithWindowNibName_(u"RowWindow") rwc.rowDict = row rwc.showWindow_(self) rwc.retain() Now go ahead and Build and Go the application. Search for something then double click on the row and you'll see it opens up a new window with its name. Certainly we'd want to fill out the contents displayed in that window, but now you know enough to take care of that on your own. So we're done. Except For Two Big Problems Well... done might have been a strong word. There are two glaring problems with our current implementation. The first is that we're calling retain on rwc, but we're never calling release, so we're not allowing the garbage collector to release that window. The second problem is that if you click on the same row twice, then you'll open up two windows for that one row. It would be much slicker if it just brought the existing window for a row to the front instead of creating a second one. The good news is that the solutions to both these questions overlap, and won't take much time to deal with. First add a field to MWController named rowCache that initializes with an empty dict. class MWController(NSObject): tableView = objc.IBOutlet() textField = objc.IBOutlet() arrayController = objc.IBOutlet() indicator = objc.IBOutlet() results = [] rowCache = {} _cache = None We're going to use rowCache to keep track of the window controllers to allow us to reuse them. Now we'll redo open_ a final time: if self.rowCache.has_key(row): rwc = self.rowCache[row] rwc.showWindow_(self) else: rwc = MWRowWindowController.alloc().initWithWindowNibName_(u"RowWindow") rwc.rowDict = row rwc.showWindow_(self) rwc.retain() self.rowCache[row] = rwc The change is fairly simple: before we create a new MWRowWindowController we are check to see if we already have one stored in rowCache. You can Build and Go the application and gander at it properly reusing the windows. Hallelujah. Now to solve the 'not calling release' problem. Meeting dealloc So far in our journey into PyObjC and Cocoa we've touched on a lot of Cocoa topics and concepts: release, retain, Cocoa Bindings, NSArrayController, and drag & drop. The last tool I'll add to your armament is dealloc. dealloc is the method that is called when an object subclassing NSObject's memory is about to be released by garbage collection. It is your last chance to deattach any retained references before they turn into a memory leak. There are two steps (and the order is significant) in every dealloc method: - Release any retained objects. - Call the super class' deallocmethod. Its easy to forget the second step, but it's another common route to memory leakage. The dealloc method for MWController is going to look like this: def dealloc(self): for key in self.rowCache: value = self.rowCache[key] value.release() super(MWController,self).dealloc() At some point you'll want to read the Cocoa Guide to Memory Management, which is a thorough introduction to the sundry nuances that come up as you dig deeper into memory management. Ending Part Four You can download the current zip of the project, or retrieve the code from the repository on GitHub. We're finally done with the programming aspects of this tutorial. Its been a long, perhaps hellish for some, trip. The fifth and final entry will contain a variety of resources that can help you continue towards PyObjC and Cocoa mastery. The last topic I want to discuss is the future of MetaWindow, the application we built together in this tutorial. It is certainly a bit of a weird and not-fully-considered project, and shows that particularly when we consider just how damnably useless the currently iteration is. Still, I do think there is a useful application somewhere down there. The GitHub repository is in laughably bad repair, for which I humbly apologize. Insert some vague excuse about the inherent awkwardness of writing an application while you simultaniously try to tutorialize. I intend to clean up the repository, and would love to see others take a stab at turning it into something useful and interesting. I'd be glad to field questions or help with problem spots that arise. I'd love to devote more of my time to MetaWindow, but have been somewhat neglegent while writing this series, and won't have much time for developing MW in the near future. You can continue to the fifth section of the tutorial here. You say that we should select the File's Owner object, and "go to the Identity tab and change its class from NSObject to RowWindowController". Did you mean MWRowWindowController instead? I have to humbly disagree with the statement "now you know enough to take care of that on your own." I gave it some thought, and concluded that I haven't a clue -- I don't even understand how the current code works, let alone how I would make it do something different. Indeed, a big part of the problem is that most of the functionality doesn't seem to involve any code at all; it appears to be magic. Let's take the name appearing in the new window for starters. I have many questions. We bound the label's "Value" to "File's Owner" (which we previously defined as a MWRowWindowController), and then set the Model Key Path to rowDict.name. But what is that? How do I know that rowDict has a "name" property? I tried printing dir(row) in the open method, and it spewed out a bunch of items, none of which were 'name'. But even if I understood that, how would I get from there to displaying some more complex content, when there seems to be no code involved? I'll fiddle around and probably eventually figure it out, but it'd be great if you could at least point us in the right direction with another sentence or two.? Interface Builder, XCode, Python, Cocoa, and Cocoa Bindings are all substantial topics on their own. The pure way to approach learning them is to start learning Objective-C and work into Cocoa and XCode and IB and eventually Cocoa Bindings. The less pure approach here is to smash into all five more or less simultaneously. I think the thing you're most confused with is Interface Builder and Cocoa Bindings, which are simply confusing topics. I still screw them up occasionally, myself. In included some advice about continuing with PyObjC in the final entry in this series as well, which may be of some assistance. me again, thanks for this tutorial still getting errors on it though, with the first part of drag, after doing all de code and verifying i still get this uppon drag release : Canceling drag because exception 'OC_PythonException' (reason '<type 'exceptions.TypeError'>: argument of type 'objc.native_selector' is not iterable') was raised during a dragging session what could this be Is it possible to use PyObjC with garbage collected Objective C 2.0, thus eliminating the need to worry about Cocoa memory management? Reply to this entry
http://lethain.com/entry/2008/aug/26/epic-pyobjc-part-4-drag-drop-multiple-nibs/
crawl-002
refinedweb
4,221
54.12
I'm learning K&R's classic C programming book 2nd edition, here's an example on page 17: #include <stdio.h> /* copy input to output*/ main() { int c; // char c works as well!! while ((c = getchar()) != EOF) putchar(c); } it's stated in the book that int c is used to hold EOF, which turns out to be -1 in my Windows machine with GCC and can't be represented by char. However, when I tried char c it works with no problem. Curiously I tried some more: int a = EOF; char b = EOF; char e = -1; printf("%d %d %d %c %c %c \n", a, b, e, a, b, e); and the output is -1 -1 -1 with no character displayed (actually according to ASCII table for %c, c here there should be a nbs(no-break space) displayed but it's invisible). So how can char be assigned with EOF without any compiler error? Moreover, given that EOF is -1, are both b and e above assigned FF in memory? It should not be otherwise how can compiler distinguish EOF and nbs...? Update: most likely EOF 0xFFFFFFFF is cast to char 0xFF but in (c = getchar()) != EOF the the LHS 0xFF is int promoted to 0xFFFFFFFF before comparison so type of c can be either int or char. In this case EOF happens to be 0xFFFFFFFF but theoretically EOF can be any value that requires more than 8 bits to correctly represent with left most bytes not necessarily being FFFFFF so then char c approach will fail. Reference: K&R The C Programming Language 2e This code works because you're using signed chars. If you look at an ASCII table you'll find two things: first, there are only 127 values. 127 takes seven bits to represent, and the top bit is the sign bit. Secondly, EOF is not in this table, so the OS is free to define it as it sees fit. The assignment from char to int is allowed by the compiler because you're assigning from a small type to a larger type. int is guaranteed to be able to represent any value a char can represent. Note also that 0xFF is equal to 255 when interpreted as an unsigned char and -1 when interpreted as a signed char: 0b11111111 However, when represented as a 32 bit integer, it looks very different: 255 : 0b00000000000000000000000011111111 -127: 0b11111111111111111111111110000001 EOF and 0xFF are not the same. So compiler has to distinguish between them. If you see the man page for getchar(), you'd know that it returns the character read as an unsigned char cast to an int or EOF on end of file or error. Your while((c = getchar()) != EOF) is expanded to ((unsigned int)c != (unsigned int)EOF) User contributions licensed under CC BY-SA 3.0
https://windows-hexerror.linestarve.com/q/so32720934-confusion-about-int-char-and-EOF-in-C
CC-MAIN-2019-47
refinedweb
474
77.77
Checking. Setting everything up As usual, we have some Python modules to import before we get started, and we’re also going to define a main() function and a couple of useful variables. from __future__ import print_function import time import os import subprocess as sub def main(): clear = "\b"*300 keyword = 'AAA?' The top print_function line will allow us to use Python 3-style print statements, time will let us fetch the date and time, os is necessary to run tcpdump, and subprocess makes it possible to do this in the background and analyse the results as they are generated. Within our main() function, the clear variable contains a load of backspaces and will be used to update text on the screen to show progress. The keyword variable will be used to locate AAA DNS requests in the tcpdump output so we can find some domains. Getting domains from tcpdump It’s time to get tcpdump running! The top line uses the subprocess module to run tcpdump in the background and pipe the output to our Python script so we can analyse it. tcpdump = sub.Popen(('sudo', 'tcpdump', '-l'), stdout=sub.PIPE) for line in iter(tcpdump.stdout.readline, b''): if keyword in line: current_domain = line.split("AAA? ", 1)[1] current_domain = current_domain[:-7] The next section begins iterating over this data line by line (notice the readline attribute). If our keyword, “AAA?”, is in the line, the domain that comes after that text will be pulled into the current_domain variable, after which seven characters of extra data that comes afterwards is filtered out. After this, we’re left with a nice string like “google.com”. Checking domains against the blacklist Something to note here: You’ll likely realise that this section of code refers to a blacklist variable that does not yet exist. It’s a Python list containing known malicious domains – we’ll see how it’s set up (and where all that lovely data comes from) later. blacklist_detector = 0 for domain in blacklist: if domain in current_domain: current_blackliststatus = "Y" blacklist_detector = 1 else: pass if blacklist_detector == 0: current_blackliststatus = "N" else: pass So what’s happening here? The script takes each domain in the blacklist list and compares it to the current domain. If the blacklist entry is present, this is flagged in a variable and blacklist_detector is set to 1. If no blacklist entries match, blacklist_detector remains at 0 and the last if statement adds this information to current_blackliststatus. Adding log information and saving There’s a little more information we need to turn this data into a useful log entry, so this section grabs the current date and time and combines it with the current domain and the blacklist_status into a single event variable, with each field separated by commas and a return at the end so we can send the output to a CSV file. current_date = time.strftime("%d/%m/%Y") current_time = time.strftime("%H:%M:%S") current_log = current_date + "," + current_time + "," + current_domain + "," + current_blackliststatus + "\n" database_file.write(current_log) print (clear, current_domain, " added", end="", sep="") else: pass And that’s just what we do when the script appends the log event to the database_file (another variable we’ll set up in a moment). So we can be sure the script is working, it also prints data to the screen in the format “google.com added”. By removing the new line from the end attribute and printing the backspaces in our clear variable first, we can write over existing data on the screen on the same line rather than printing a huge list. Finally, we close up the line iteration for loop from the first section by including an else statement. If the line doesn’t contain our keyword, we’ll pass and move onto the next one. File and blacklist initialisation Here, outside of the main() function, we set up those variables we saw earlier. This is the first code that will run and handles some critical setup that allows the main function to work. database_file = open("weblog.csv", "a") blacklist_file = open("blacklist.txt", "r") blacklist = [] for line in blacklist_file: line = line[:-1] blacklist.append(line) blacklist = blacklist[:-1] main() The top section opens our log CSV file in append mode, to let us add new lines to it. Then we open the blacklist, which is a simple text file with one domain per line. There are a ton of ways you could gather data on malicious domains, but I found the resources at the SANS Internet Storm Center to be a useful place to start. Once we have our blacklist, the next part sets up a Python list and adds each malicious domain as an entry (minus the new line that comes afterwards). Now we’re set up and ready to go, we call our main() function and get to work on our tcpdump data. Output So what happens when we put all this together? To demonstrate, I’ve cleared my weblog file and have added a single domain – google.com – to my blacklist. Now I’m going to run the script, browse the internet, and see what happens. This is what we see while the script is running – tcpdump’s verbose output is suppressed, but the bottom line updates to show domains that are added to our log file. When we terminate the script, we can open weblog.csv to see every DNS request that was made. Here’s an excerpt from my own random browsing, and look – the script has flagged two visits to domains containing “google.com” that we might want to look into. Had I been running the script for longer and generated more data, I’d be able to filter by column D to more easily see whether any blacklisted malicious domains were accessed. The next step for this script? Once I have more than one computer to play with, I’d like to try running a tcpdump logger agent on one and sending the extracted domains across the network to be stored in a central log on the other. Watch this Pixabay (CC0). Cropped.
http://mattcasmith.net/2018/05/13/checking-dns-requests-against-a-domain-blacklist-in-python/
CC-MAIN-2018-34
refinedweb
1,011
69.01
06 April 2011 18:31 [Source: ICIS news] LONDON (ICIS)--A key German raw materials price index rose sharply in March from February because of higher oil prices due to the ongoing conflict in ?xml:namespace> The Hamburgisches Weltwirtschaftsinstitut (HWWI) said its raw materials price index rose 8.1% month on month in US dollar terms and 5.4% in euro terms. However, excluding energy, the index fell 1.5% in US dollar and was down 4.0% in euro as metal and agricultural commodity prices fell in March. Also, rubber prices fell 13.8% in US dollar and 16.0% in euro from February as many of As for the outlook, HWWI said oil would continue to trade at high price levels. Despite UN intervention, it remains unclear when the fighting in Even after the fighting ends, Libya’s oil production may not resume immediately because of damage to oil facilities and harbour infrastructure, it added. As for agricultural commodities, wheat, rice and corn (maize) prices are likely to rise, following a price decline in March from February, HWWI said..
http://www.icis.com/Articles/2011/04/06/9450537/germany+march+raw+material+price+index+jumps+on+libya.html
CC-MAIN-2013-20
refinedweb
181
65.42
I'm so sorry, Actually my problem is in another mpi program which is "sudoku game". But because of the fact I got inclusion error whenever I use MPI_Group_incl. For simplicity, I decided to put a simple program with MPI_Group_incl. Please take a look at the following lines of code, and please note that in this program I'm supposed to work just with 82 processes and I tried to divide the processes into 2 groups, namely "master" and "workers", master for "rank 0" process and workers for rest of processes(81 processes). Here is the codes: #include <string.h> #include "mpi.h" #include <stdio.h> #include <unistd.h> #include <time.h> #include <stdlib.h> int main(int argc, char *argv[]) { //Initializing the MPI world, rank, and size int size,rank,m,w,i; MPI_Group group,master,workers; MPI_Comm comm_world, comm_workers, comm_master; MPI_Status status; MPI_Request request; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (size != 82 ){ printf("Please run with 82 processors.\n"); fflush(stdout); MPI_Finalize(); exit(1); } comm_world = MPI_COMM_WORLD; MPI_Comm_group(comm_world, &group); MPI_Group_incl(group, 1, 0 , &master); MPI_Group_excl(group, 1, 0, &workers); MPI_Comm_create(comm_world, master, &comm_master); MPI_Comm_create(comm_world, workers, &comm_workers); MPI_Finalize(); } From: Jeff Squyres <jsquyres@cisco.com> To: Open MPI Users <users@open-mpi.org> Cc: maryam moein <maryam_moein2005@yahoo.com> Sent: Thursday, August 16, 2012 7:41 PM Subject: Re: [OMPI users] mpi_group_incl erros Further, if Neven is greater than 3, then you've got uninitialized values in the members array. That could be causing Open MPI to say "there's a bad rank number in there!", for example, if members[3] is randomly initialized to 1234. On Aug 16, 2012, at 10:01 AM, Ralph Castain wrote: > Well, one thing immediately leaps to the eye. You compute Neven based on the number of procs in the job, which you set when executing mpirun. However, the number of members you put in your group is fixed. Then you pass Neven to the MPI_Group call as the parameter telling it how many entries are in your member array! > > On Aug 16, 2012, at 5:07 AM, maryam moein < maryam_moein2005@yahoo.com > wrote: > >> I'm new memeber in this weblog, and I should deliver my assignment as soon as possible, but I have a big problem that I can't solve it. Please help me. In MPI I should divide my group into two groups. But all the time when I want to run a program I got error about mpi_group_incl. This is my error: >> >> [ubuntu:3346] *** An error occurred in MPI_Group_incl >> [ubuntu:3346] *** on communicator MPI_COMM_WORLD >> [ubuntu:3346] *** MPI_ERR_RANK: invalid rank >> [ubuntu:3346] *** MPI_ERRORS_ARE_FATAL (your MPI job will now abort) >> -------------------------------------------------------------------------- >> mpiexec has exited due to process rank 0 with PID 3345 on >> node ubuntu exiting without calling "finalize". This may >> have caused other processes in the application to be >> terminated by signals sent by mpiexec (as reported here). >> >> >> I should mention that I run this program with diffrent number of process but I got same errors. In below you can find my c program. >> >> #include <stdio.h> >> #include "mpi.h" >> #include <unistd.h> >> #include <time.h> >> #include <stdlib.h> >> #include <string.h> >> void main(int argc, char *argv[]) >> { >> int Iam, p; >> int Neven, Nodd, members[6], even_rank, odd_rank; >> MPI_Group group_world, even_group, odd_group; >> /* Starts MPI processes ... */ >> MPI_Init(&argc, &argv); /* starts MPI */ >> MPI_Comm_rank(MPI_COMM_WORLD, &Iam); /* get current process id */ >> MPI_Comm_size(MPI_COMM_WORLD, &p); /* get number of processes */ >> Neven = (p + 1)/2; /* All processes of MPI_COMM_WORLD are divided */ >> Nodd = p - Neven; /* into 2 groups, odd- and even-numbered groups */ >> members[0] = 2; >> members[1] = 0; >> members[2] = 4; >> MPI_Comm_group(MPI_COMM_WORLD, &group_world); >> MPI_Group_incl(group_world, Neven, members, &even_group); >> MPI_Group_excl(group_world, Neven, members, &odd_group); >> >> MPI_Barrier(MPI_COMM_WORLD); >> if(Iam == 0) { >> printf("MPI_Group_incl/excl Usage Example\n"); >> printf("\n"); >> printf("Number of processes is %d\n", p); >> printf("Number of odd processes is %d\n", Nodd); >> printf("Number of even processes is %d\n", Neven); >> printf("\n"); >> printf(" Iam even odd\n"); >> } >> MPI_Barrier(MPI_COMM_WORLD); >> >> MPI_Group_rank(even_group, &even_rank); >> MPI_Group_rank( odd_group, &odd_rank); >> printf("%d %d %d\n",Iam, even_rank, odd_rank); >> >> MPI_Finalize(); /* let MPI finish up ... */ >> } >> >> _______________________________________________ >> users mailing list >> users@open-mpi.org >> > > _______________________________________________ > users mailing list > users@open-mpi.org > -- Jeff Squyres jsquyres@cisco.com For corporate legal information go to:
http://www.open-mpi.org/community/lists/users/att-19951/attachment
CC-MAIN-2014-42
refinedweb
704
56.76
Rails in the Country - Home tag:blog.allen.com.au,2009:mephisto/ Mephisto Noh-Varr 2009-03-25T04:28:40Z Matt Allen tag:blog.allen.com.au,2009-03-24:42 2009-03-24T02:58:00Z 2009-03-25T04:28:40Z Prangz.com <p>Yes, another Friday night coding spree.</p> <p>I was itching to write an app that used real-time, location specific data and so <a href=""></a> was born.</p> <p>The whole app is 43 lines of code. It’s rails 2.3 and the scraper checks the <span class="caps">RTA</span> website every 2 minutes for new data.</p> <p.</p> <p>I’ve emailed the <span class="caps">RTA</span> to alert them to it, let’s see how long I last.</p> Matt Allen tag:blog.allen.com.au,2008-07-27:40 2008-07-27T00:41:00Z 2008-07-27T00:45:28Z Tweetbeer.com - Directors Cut <h3>Opening Credits</h3> <p>Here we see Matta doing the dishes on the night of Friday the 25th of July, 2008. As the music is streaming he pauses. He just thought up tweetbeer.com. He goes straight into the living room to IM <a href="">Lachie</a>, and so it began.</p> <h3>tweetbeer.com</h3> <p>At around 12 midnight of last night Lachie Cox and I launched a fun little app we wrote over the previous day, <a href="">tweetbeer.com</a>. Here’s some little tidbits of info</p> <ul> <li>Rails 2.1</li> <li>Mysql DB</li> <li>Haml for layout</li> <li>97 Lines of code</li> <li>Approx 6 hours of dev time</li> <li>git was used as our collabaration tool, worked <strong>so</strong> well</li> <li>All frontend <span class="caps">CSS</span> and the funky-ass logo done by Lachie</li> <li>Tweet parser uses search.twitter.com called via a cron every minute and run through script/runner</li> </ul> <p>So from idea to launch look about 18 hours of real time with about 6 hours of actual coding. Simple ideas are fun. If you could come up with a compelling way to monetize a simple idea like this, that’d be even cooler.</p> Matt Allen tag:blog.allen.com.au,2008-06-24:37 2008-06-24T22:53:00Z 2008-06-25T13:30:10Z Rails Camp, the Third <p>Here we are, a few days after the <a href="">Third Rails Camp</a> in Australia.</p> <p.</p> <p>Rails Camp was just awesome. The vibe was electric. It was great putting names to faces with the guys from the #roro <span class="caps">IRC</span> channel that I spend alot of time in. We asked people to blog about Rails Camp so we could get the word out, here is what I hacked on:</p> <h2>Twetter</h2> <p. <a href="">Lachie</a> had an example of the <span class="caps">XML</span> that the <span class="caps">API</span> returned and with a little help from Max M and his internet enabled CrackBerry we were able to read the twitter <span class="caps">API</span> docs and get the other bits and pieces. Once <a href="">Lincoln</a> woke up I had twitter.com resolving to a shiny new VM on Bigguns (the awesome server) and twitter was alive! There was no friending, everyone got the same stream. I did implement replies but left out direct messages. I think it was a hit.</p> <h2>Merb Caching</h2> <p>I met <a href="" title="hassox">Dan Neighman</a> for the first time in real life. We speak alot on <span class="caps">IRC</span> <a href="">background-tasks</a>. Dan wrote it up <a href="">here</a>. This is Uber exciting and I really want to start Merb Hacking.</p> <h3>Managing Expectations</h3> <p.</p> <p>So, to all you guys that read this and went, blog it up people! Get it out there. Let’s start a * Camp movement.</p> <p>—Matta</p> Matt Allen tag:blog.allen.com.au,2008-05-05:32 2008-05-05T21:49:00Z 2008-05-05T21:50:22Z Going Dark. Again <p><span class="caps">UPDATE</span>: <a href="">I reckon this article has nailed it</a></p> <p>This weekend was the Anzac weekend, a time for reflection and remembering the things our Grand Fathers and Great Grand Fathers (and possibly Mothers) did for us and our way of life. I miss you Pa.</p> <p>I had the opportunity on Friday night to sit down with some code, uninterrupted. No internet, therefore no Email, IM, <span class="caps">IRC</span>, Twitter, <span class="caps">RSS</span>. It was <strong>grand</strong>.</p> <p.</p> <p>So I have decided that my work day is now going to consist mostly of “off-line” time. 9 – Lunch will be offline, that is, working without distractions. No Email, <span class="caps">IRC</span>, IM, Twitter. At Lunch time i’ll surface again for a little while, probably an hour tops. After lunch i’ll hook back in. After the kids are in bed I may come back on, maybe not. Dunno yet.</p> <p>I tend to embrace things half-heartedly, this is one thing i’m going to try and stick to. If you need me urgently, <span class="caps">SMS</span> or Phone is where it’s at.</p> <p>The other side effect I hope this will address is my new level of bored-ness with the interwebs, seriously, I can’t find anything interesting out there atm.</p> <p>Apologies for the above brain dump, upon re-reading it wasn’t very well thought out. Oh Well.</p> <p>Matta</p> Matt Allen tag:blog.allen.com.au,2007-12-17:31 2007-12-17T22:21:00Z 2008-03-30T22:05:39Z Fluid.app <p>Have been using <a href="">Fluid</a> for the past week.</p> <p>It’s an <span class="caps">OS X</span> (Leopard only) app that lets you create standalone cocoa based web apps, basically a wrapper for web kit.</p> <p>I’ve got one for gmail and unfuddle setup. It’s nice to have them survive browser crashes normally due to unruley javascript.</p> <p><img src="" alt="" /></p> <p><img src="" alt="" /></p> <p><span class="caps">UPDATE</span>: Here’s a sexy big icon the UF guys sent me</p> <p><img src="" alt="" /></p> Matt Allen tag:blog.allen.com.au,2007-12-06:28 2007-12-06T08:23:00Z 2007-12-22T20:34:13Z Highly resposive Unfuddlers <p>To follow on from my last post, I have spent the day to-ing and fro-ing with the Unfuddle.com guys and I have come up with an <span class="caps">SVN</span> hook for non-UF-hosted svn repos.</p> <p><a href="">Here’s for code for anyone interested</a></p> Matt Allen tag:blog.allen.com.au,2007-11-30:27 2007-11-30T02:19:00Z 2007-12-22T20:34:03Z Move over lighthouse, Unfuddle it is <p>So, I blogged earlier about Lighthouse and how much I was in love it with. It has all the features I like but unfortunately for me, it missed a few critical ones my Boss wanted.</p> <p>Enter <a href="">Unfuddle</a></p> <p>We’ve been using this for a few months now and it works a charm. It’s a rails app and is run buy some very passionate dudes in Hawaii.</p> <p>The feature that really stands out for us is the work flow for tickets. See image below.</p> <p><a href=""><img src="" /></a></p> <p>Boss opens it, I accept it, I resolve it, boss closes it.</p> <p>Boss can reopen it if need be. So easy for me to see what tickets are left to work on in this release, also what tickets need to be verified by him before I can push the release live.</p> <p>Anyone who is dealing with a large ongoing site needs a decent bug tracker, this one is up there with the best i’ve used, both <span class="caps">OSS</span> and commercial.</p> Matt Allen tag:blog.allen.com.au,2007-11-27:26 2007-11-27T01:55:00Z 2007-12-15T02:39:52Z Print this out, give it to your boss <p>I don’t actually have to, he sent me the link.</p> <p>This made me a very happy programmer.</p> <p><a href="">Wide vs. Deep</a></p> Matt Allen tag:blog.allen.com.au,2007-10-17:23 2007-10-17T01:25:00Z 2007-10-17T01:25:37Z Going Dark <p.</p> <p>I don’t go completely off net as I need <a href="">my other brain</a> to remind me of things I constantly forget.</p> <p>I miss my <span class="caps">IRC</span> buddies from #roro on freenode.net heaps, they are a constant source of knowledge and entertainment but they are pretty good at posting to the <a href="">roro tumblr</a>, so that keeps me in the loop mostly.</p> <p>I actually jump on IM and <span class="caps">IRC</span> once or twice during the day, mostly at lunch, or in a lull between pushing out code.</p> <p>I’d like to hear how everyone else deals with the “always on” side of things?</p> Matt Allen tag:blog.allen.com.au,2007-10-15:22 2007-10-15T06:34:00Z 2007-10-15T06:35:22Z When Testing Caching ... <p>Don’t forget to set:</p> <p>config.action_controller.perform_caching = true</p> <p>in test.rb in environments. You’ll wonder why nothing is working until you do.</p> Matt Allen tag:blog.allen.com.au,2007-09-17:21 2007-09-17T11:21:00Z 2007-09-17T11:23:05Z -33.702635,151.099434 : Hornsby <p>So what does a north western Sydney suburb have to do with rails? Not very much, but it has lent it’s name to a very very cool app written by <a href="">Lachie Cox</a>.</p> <p>The main aim of <a href="">Hornsby</a>.</p> <p>I then started using Rspec, I love writing specs but fixtures were still making me swear at my <span class="caps">MBP</span>.</p> <p>Hornsby makes me an extremely happy Rails programmer. Here is <a href="">Lachie’s description</a>.</p> <p>Here’s my code. It’s an example of setting up a “scenario” that I used for testing my Equipment<>scenario <span class="sy">:equipment</span> <span class="r">do</span><tt> </tt> <span class="iv">@manufacturer</span> = <span class="co">EquipmentManufacturer</span>.create!(<span class="sy">:name</span> => <span class="s"><span class="dl">"</span><span class="k">Ben Hogan</span><span class="dl">"</span></span>)<tt> </tt> <span class="iv">@category</span> = <span class="co">EquipmentCategory</span>.create!(<span class="sy">:title</span> =><span class="s"><span class="dl">"</span><span class="k">Fairway Woods</span><span class="dl">"</span></span>)<tt> </tt> <span class="iv">@equipment</span> = <span class="co">EquipmentProduct</span>.new(<span class="sy">:name</span> => <span class="s"><span class="dl">"</span><span class="k">Edge CFT Ti Hybrid</span><span class="dl">"</span></span>,<span class="sy">:equipment_manufacturer_id</span> => <span class="iv">@manufacturer</span>.id,<span class="sy">:equipment_category_id</span> => <span class="iv">@category</span>.id)<tt> </tt> <span class="iv">@equipment</span>.save(<span class="pc">false</span>)<tt> </tt><span class="r">end</span></pre></td> </tr></table> <p>Here is the bit from Rspec test that loads it></pre></td> <td class="code"><pre>describe <span class="co">EquipmentController</span> <span class="r">do</span><tt> </tt><tt> </tt> before(<span class="sy">:each</span>) <span class="r">do</span><tt> </tt> hornsby_scenario <span class="sy">:equipment</span><tt> </tt> <span class="r">end</span><tt> </tt> ...<tt> </tt><span class="r">end</span></pre></td> </tr></table> .</p> <p>This software has made my testing life a joy yet again, knowing the exact state of your DB when testing is precisely what was missing from fixtures.</p> <p>Here’s those links again:</p> <p><a href="">Lachie’s write up</a></p> <p><a href="">Source Code</a></p> Matt Allen tag:blog.allen.com.au,2007-08-28:12 2007-08-28T21:56:00Z 2007-08-29T07:04:14Z Out of Bandwidth Cache Expiry <p?</p> <p>What I’ve done is started an extra mongrel in my pack but not included it in the standard mongrel pack, my (cut down) mongrel config looks like this:<>--- <tt> </tt>port: <span class="s"><span class="dl">"</span><span class="k">2222</span><span class="dl">"</span></span><tt> </tt>environment: production<tt> </tt>address: <span class="fl">127.0</span>.<span class="fl">0.1</span><tt> </tt>pid_file: log/mongrel.pid<tt> </tt>servers: <span class="i">7</span></pre></td> </tr></table> <p>As you can see there is 7 mongrels there. Next, setup a second cluster that contains only your 7th mongrel</p> <table class="CodeRay"><tr> <td title="click to toggle" class="line_numbers"><pre>1<tt> </tt>2<tt> </tt>3<tt> </tt></pre></td> <td class="code"><pre><<span class="co">Proxy</span> balancer<span class="sy">:/</span>/expirecluster><tt> </tt> <span class="co">BalancerMember</span> http<span class="sy">:/</span>/<span class="fl">127.0</span>.<span class="fl">0.1</span>:<span class="i">2228</span><tt> </tt><<span class="rx"><span class="dl">/</span><span class="k">Proxy></span></span></pre></td> </tr></table> <p>Next, tell apache to redirect any of your magic expiration URLs to that cluster</p> <table class="CodeRay"><tr> <td title="click to toggle" class="line_numbers"><pre>1<tt> </tt>2<tt> </tt></pre></td> <td class="code"><pre> <span class="co">RewriteCond</span> <span class="s"><span class="dl">%{</span><span class="k">QUERY_STRING</span><span class="dl">}</span></span> magic_url_expire_param=<span class="i">1</span><span class="er">$</span><tt> </tt> <span class="co">RewriteRule</span> ^<span class="rx"><span class="dl">/</span><span class="k">(.*)$ balancer:</span><span class="dl">/</span></span>/expirecluster%{<span class="co">REQUEST_URI</span>} [<span class="co">P</span>,<span class="co">QSA</span>,<span class="co">L</span>]</pre></td> </tr></table> <p>Restart apache and you’re done. Any cron triggered expire requests will now go through the out of bandwith mongrel and not slow down visitors to you site.</p> <p>This method can actually be used to segregate any URLs off to different clusters, I have a project coming up that will have a lot of slow processes that rely on an external <span class="caps">SOAP</span> service running. They’ll all be farmed off to a cluster running on a totally different machine with trimmed down, DB free mongrels.</p> Matt Allen tag:blog.allen.com.au,2007-08-21:10 2007-08-21T12:37:00Z 2007-08-21T12:53:20Z Seesaw, restarting your mongrels with zero downtime <p>Last weekend was the first Sydney Rails Group Hax Day, held by our very own <a href="">Lachie</a>. What a day! about 10 rails geeks showed up including a few guys we had either never met or only at the previous meet-up.</p> <p><a href="">Max</a> and I started the day talking about what we’d like to see in a web-based app that managed other rails apps. In discussing this I mentioned that over that <a href="">iseekgolf.com<.</p> <p.</p> <p>What we came up with was <a href="">Seesaw</a>. This does precisely what we needed including configuring the web server on the fly.</p> <p>This morning I installed it live at iseekgolf.com and after a few config tweaks it was working a treat. It brought a huge smile to my face as the logs kept rolling buy as the mongrels were restarting.</p> <p>One gotcha is that by default Seesaw names your mongrel cluster “mongrel_pack”, be sure to replace <strong>all</strong> instances of your mongrel cluster name in your apache config file to this new name, especially the <span class="caps">SSL</span> one ;)</p> <p>Hopefully some people may find a use for this plugin.</p> <p>We’ll be doing some minor changes to it over the coming days, including some definable pauses in between the cluster restarts and apache redirecting traffic to them to give them time to warm up.</p> <p>Max has written up an <a href="">awesome blog entry</a>, with pretty pictures and all!</p> Matt Allen tag:blog.allen.com.au,2007-08-12:9 2007-08-12T22:56:00Z 2007-08-12T22:56:30Z Lighthouse App, Svn and you <p.</p> <p>Enter <a href="">Lighthouse</a></p> <p>What a brilliant piece of software, it’s written by the <a href="">Active Reload</a> guys who also wrote <a href="">Mephisto</a> the blogging software this blog is written in. The brilliance of this software comes of it’s simplicity. It does the job I want it to do almost perfectly.</p> <p>It doesn’t make any assumptions about things like Bug Priority and such, however it does have a standard tagging system and you can save searches into “bins” that are available on the bug searching screen, we have settled on, low,normal,high,highest and <span class="caps">URGENT</span>. See below.</p> <p><a href=""><img src=""></a></p> <p>I also implemented the <span class="caps">SVN</span> integration, the <span class="caps">FAQ</span> can be found <a href="">here</a> Now all I do is put a proper comment in the <span class="caps">SVN</span> commit that explains the changes and has the lighthouse syntax in it, an example might be “Changes to log form [#15 state:resolved]”. A commit with that comment in it closes the ticket as well, brilliant.</p> <p>So the aim of this post was really just to send props to Rick and the team at Active Reload, it’s great to see an app by the geeks, for the geeks.</p> Matt Allen tag:blog.allen.com.au,2007-08-10:8 2007-08-10T08:28:00Z 2007-08-10T08:28:35Z The Caching Gap(tm) ... mixin' it with Cron <p>So the plugin i mentioned in my <a href="">last post</a> is alive and kicking, it has totally solved the problem we were having.</p> <p.</p> <p>Again, I was throwing the idea of using <span class="caps">DRB</span> around on <span class="caps">IRC</span> and <a href="">Lachie Cox</a> suggested good old cron. We are already using cron to expire the front page on the hour to keep the info fresh so I thought i’d expand it a little.</p> <p.</p> <p>The sweeper now looks like></pre></td> <td class="code"><pre><span class="c">## The Sweeper</span><tt> </tt><span class="r">class</span> <span class="cl">TournamentSweeper</span> < <span class="co">ActionController</span>::<span class="co">Caching</span>::<span class="co">Sweeper</span><tt> </tt> observe ...models...<tt> </tt><tt> </tt> <span class="r">def</span> <span class="fu">after_save</span>(record)<tt> </tt> ... <tt> </tt> <span class="co">CacheQueue</span>.create({<span class="sy">:cache_type</span> => <span class="s"><span class="dl">"</span><span class="k">url</span><span class="dl">"</span></span>, <span class="sy">:cache_data</span> => <span class="s"><span class="dl">'</span><span class="k">/?special_param_to_hose_cache=1</span><span class="dl">'</span></span>})<tt> </tt> <span class="co">CacheQueue</span>.create({<span class="sy">:cache_type</span> => <span class="s"><span class="dl">"</span><span class="k">regex</span><span class="dl">"</span></span>, <span class="sy">:cache_data</span> => <span class="s"><span class="dl">"</span><span class="k">tournaments/</span><span class="il"><span class="dl">#{</span>tournament.id<span class="dl">}</span></span><span class="k">-*</span><span class="dl">"</span></span>})<tt> </tt> ...<tt> </tt> <span class="r">end</span></pre></td> </tr></table> <p>So we’re creating lots of entires in the cache_queues table, all having an expired = 0 column by default.</p> <p>The next step was to write a method that could be called from a rake task that expires the caches, here it>15>25>35>45<tt> </tt>46<tt> </tt>47<tt> </tt>48<tt> </tt></pre></td> <td class="code"><pre><span class="c">## The CacheQueue Class</span><tt> </tt><span class="r">class</span> <span class="cl">CacheQueue</span> < <span class="co">ActiveRecord</span>::<span class="co">Base</span><tt> </tt> <span class="r">def</span> <span class="pc">self</span>.expire<tt> </tt> <span class="r">begin</span><tt> </tt> require <span class="s"><span class="dl">'</span><span class="k">action_controller/integration</span><span class="dl">'</span></span><tt> </tt> <span class="c"># wite a disc lock</span><tt> </tt> lockfile = <span class="co">RAILS_ROOT</span> + <span class="s"><span class="dl">"</span><span class="k">/log/cache.expire</span><span class="dl">"</span></span><tt> </tt> <span class="r">if</span> <span class="co">File</span>.exists? lockfile<tt> </tt> <span class="gv">$stderr</span>.puts <span class="s"><span class="dl">"</span><span class="k">Locked since </span><span class="dl">"</span></span> + <span class="co">File</span>.open(lockfile,<span class="s"><span class="dl">"</span><span class="k">r</span><span class="dl">"</span></span>).atime.to_s<tt> </tt> <span class="r">return</span><tt> </tt> <span class="r">end</span><tt> </tt> <span class="co">FileUtils</span>.touch lockfile<tt> </tt> caches_to_be_hosed = <span class="co">CacheQueue</span>.find(<span class="sy">:all</span>,<span class="sy">:conditions</span> => {<span class="sy">:expired</span> => <span class="pc">false</span>}, <span class="sy">:order</span> => <span class="s"><span class="dl">"</span><span class="k">cache_type DESC, id ASC</span><span class="dl">"</span></span>)<tt> </tt> hosed_url_caches = []<tt> </tt> hosed_regex_caches = []<tt> </tt> sess = <span class="co">ActionController</span>::<span class="co">Integration</span>::<span class="co">Session</span>.new<tt> </tt> sess.host! <span class="co">LIVE_HOST</span><tt> </tt> c = <span class="co">ActionController</span>::<span class="co">Base</span>.new <tt> </tt> skipped = <span class="i">0</span><tt> </tt> caches_to_be_hosed.each <span class="r">do</span> |cache|<tt> </tt> <span class="c"># update the db</span><tt> </tt> cache.expired = <span class="pc">true</span><tt> </tt> cache.save!<tt> </tt> <span class="r">case</span> cache.cache_type<tt> </tt> <span class="r">when</span> <span class="s"><span class="dl">"</span><span class="k">url</span><span class="dl">"</span></span><tt> </tt> <span class="r">if</span> hosed_url_caches.include? cache.cache_data<tt> </tt> skipped += <span class="i">1</span><tt> </tt> <span class="r">next</span> <tt> </tt> <span class="r">end</span><tt> </tt> sess.get cache.cache_data<tt> </tt> hosed_url_caches << cache.cache_data<tt> </tt> <span class="r">when</span> <span class="s"><span class="dl">"</span><span class="k">regex</span><span class="dl">"</span></span><tt> </tt> <span class="r">if</span> hosed_regex_caches.include? cache.cache_data<tt> </tt> skipped += <span class="i">1</span><tt> </tt> <span class="r">next</span><tt> </tt> <span class="r">end</span><tt> </tt> c.expire_fragment(<span class="co">Regexp</span>.new(cache.cache_data))<tt> </tt> hosed_regex_caches << cache.cache_data<tt> </tt> <span class="r">end</span><tt> </tt> <span class="r">end</span><tt> </tt> <span class="co">FileUtils</span>.rm lockfile<tt> </tt> <span class="r">rescue</span><tt> </tt> <span class="co">FileUtils</span>.rm lockfile<tt> </tt> <span class="r">end</span><tt> </tt> <span class="gv">$stderr</span>.puts ((hosed_regex_caches.size + hosed_url_caches.size).to_s + <span class="s"><span class="dl">"</span><span class="k"> caches removed</span><span class="dl">"</span></span>) <span class="r">if</span> (hosed_regex_caches.size + hosed_url_caches.size > <span class="i">0</span>)<tt> </tt> <span class="gv">$stderr</span>.puts skipped.to_s + <span class="s"><span class="dl">"</span><span class="k"> caches skipped</span><span class="dl">"</span></span> <span class="r">if</span> skipped > <span class="i">0</span><tt> </tt> <span class="r">end</span><tt> </tt><span class="r">end</span></pre></td> </tr></table> ><span class="c">## The Rake task</span><tt> </tt>namespace <span class="sy">:cache</span> <span class="r">do</span><tt> </tt> task <span class="sy">:expire</span> => <span class="sy">:environment</span> <span class="r">do</span><tt> </tt> <span class="co">CacheQueue</span>.expire<tt> </tt> <span class="r">end</span><tt> </tt><span class="r">end</span></pre></td> </tr></table> <p>This write out to $stderr, when it actually does something it send me an email. It also implements locking so it doesn’t run over itself.</p> <p.</p>
http://feeds.feedburner.com/RailsInTheCountry
crawl-002
refinedweb
4,188
65.83
16 July 2012 08:21 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The DES (delivered ex-ship) prices for August LNG into Demand in China National Offshore Oil Corp (CNOOC), China’s biggest LNG importer, had to swap a term contract cargo supplied by France’s Total with South Korea’s KOGAS, as LNG stocks at CNOOC’s Putian terminal in Fujian province were too high, an industry source in Singapore said. The cargo, due to arrive in Fujian in late July, was re-routed to South Korea in exchange for a cargo in early August, when stock levels are expected to decline, the source added. LNG demand in the Asian spot market is expected to continue weakening until the end of August, as inventory levels are high and downstream demand is soft amid economic slowdowns, market sources said. Demand is likely to rebound in September when regional buyers begin to restock,
http://www.icis.com/Articles/2012/07/16/9578365/chinas-lng-import-price-falls-for-august-on-high-inventory.html
CC-MAIN-2015-11
refinedweb
152
50.91
1. Charm++ Quickstart¶ This section gives a concise overview of running your first Charm++ application. 1.1. Installing Charm++¶ To download the latest Charm++ release, run: $ wget $ tar xzf charm-latest.tar.gz To download the development version of Charm++, run: $ git clone To build Charm++, use the following commands: $ cd charm $ ./build charm++ netlrts-linux-x86_64 --with-production -j4 This is the recommended version to install Charm++ on Linux systems. For MacOS, substitute “linux” with “darwin”. For advanced compilation options, please see Section 2.6.1 of the manual. 1.2. Parallel “Hello World” with Charm++¶ The basic unit of computation in Charm++ is a chare, which is a C++ object. Chares have entry methods that can be invoked asynchronously. A Charm++ application consists of collections of chares (such as chare arrays) distributed among the processors of the system. Each chare has a proxy associated to it, through which other chares can invoke entry methods. This proxy is exposed through the thisProxy member variable, which can be sent to other chares, allowing them to invoke entry methods on this chare. Each Charm++ application consists of at least two files, a Charm interface (.ci) file, and a normal C++ file. The interface file describes the parallel interface of the application (such as chares, chare arrays, and entry methods), while the C++ files implement its behavior. Please see Section 2.2.1 of the manual for more information about the program structure. In this section, we present a parallel Hello World example, consisting of the files hello.ci and hello.cpp. 1.2.1. The hello.ci File¶ The hello.ci file contains a mainchare, which starts and ends execution, and a Hello chare array, whose elements print the “Hello World” message. Compiling this file creates C++ header files ( hello.decl.h and hello.def.h) that can be included in your C++ files. mainmodule hello { mainchare Main { // Main's entry methods entry Main(CkArgMsg *m); entry void done(); }; array [1D] Hello { // Hello's entry methods entry Hello(); entry void SayHi(); }; }; 1.2.2. The hello.cpp File¶ The hello.cpp file contains the implementation of the mainchare and chare array declared in the hello.ci file above. #include "hello.decl.h" // created from hello.ci file above /*readonly*/ CProxy_Main mainProxy; constexpr int nElem = 8; /*mainchare*/ class Main : public CBase_Main { public: Main(CkArgMsg* m) { //Start computation CkPrintf("Running Hello on %d processors with %d elements.\n", CkNumPes(), nElem); CProxy_Hello arr = CProxy_Hello::ckNew(nElem); // Create a new chare array with nElem elements mainProxy = thisProxy; arr[0].SayHi(0); }; void done() { // Finish computation CkPrintf("All done.\n"); CkExit(); }; }; /*array [1D]*/ class Hello : public CBase_Hello { public: Hello() {} void SayHi() { // thisIndex stores the element’s array index CkPrintf("PE %d says: Hello world from element %d.\n", CkMyPe(), thisIndex); if (thisIndex < nElem - 1) { thisProxy[thisIndex + 1].SayHi(); // Pass the hello on } else { mainProxy.done(); // We've been around once -- we're done. } } }; #include "hello.def.h" // created from hello.ci file above 1.2.3. Compiling the Example¶ Charm++ has a compiler wrapper, charmc, to compile Charm++ applications. Please see Section 2.6.2 for more information about charmc. $ charm/bin/charmc hello.ci # creates hello.def.h and hello.decl.h $ charm/bin/charmc hello.cpp -o hello 1.2.4. Running the Example¶ Charm++ applications are started via charmrun, which is automatically created by the charmc command above. Please see Section 2.6.3 for more information about charmrun. To run the application on two processors, use the following command: $ ./charmrun +p2 ./hello Charmrun> scalable start enabled. Charmrun> started all node programs in 1.996 seconds. Charm++> Running in non-SMP mode: 1 processes (PEs) Converse/Charm++ Commit ID: v6.9.0-172-gd31997cce Charm++> scheduler running in netpoll mode. CharmLB> Load balancer assumes all CPUs are same. Charm++> Running on 1 hosts (1 sockets x 4 cores x 2 PUs = 8-way SMP) Charm++> cpu topology info is gathered in 0.000 seconds. Running Hello on 2 processors with 8 elements. PE 0 says: Hello world from element 0. PE 0 says: Hello world from element 1. PE 0 says: Hello world from element 2. PE 0 says: Hello world from element 3. PE 1 says: Hello world from element 4. PE 1 says: Hello world from element 5. PE 1 says: Hello world from element 6. PE 1 says: Hello world from element 7. All done [Partition 0][Node 0] End of program 1.3. Where to go From Here¶ - The tests/charm++/simplearrayhellofolder in the Charm++ distribution has a more comprehensive example, from which the example in this file was derived. - The main Charm++ manual () contains more information about developing and running Charm++ applications. - Charm++ has lots of other features, such as chare migration, load balancing, and checkpoint/restart. The main manual has more information about them. - AMPI () is an implementation of MPI on top of Charm++, allowing MPI applications to run on the Charm++ runtime mostly unmodified. - Charm4py () is a Python package that enables development of Charm++ applications in Python.
https://charm.readthedocs.io/en/latest/quickstart.html
CC-MAIN-2020-16
refinedweb
841
60.72
Note The N@ classifier cannot be used in compound matches within the CLI or top file, it is only recognized in the nodegroups master config file parameter.. A simple list of minion IDs would traditionally be defined like this: nodegroups: group1: L@host1,host2,host3 They can now also be defined as a YAML list, like this: nodegroups: group1: - host1 - host2 - host3 New in version 2016.11.0. To use Nodegroups in Jinja logic for SLS files, the pillar_opts option in /etc/salt/master must be set to True. This will pass the master's configuration as Pillar data to each minion. Note If the master's configuration contains any sensitive data, this will be passed to each minion. Do not enable this option if you have any configuration data that you do not want to get on your minions. Also, if you make changes to your nodegroups, you might need to run salt '*' saltutil.refresh_pillar after restarting the master. Once pillar_opts is set to True, you can find the nodegroups under the "master" pillar. To make sure that only the correct minions are targeted, you should use each matcher for the nodegroup definition. For example, to check if a minion is in the 'webserver' nodegroup: nodegroups: webserver: 'G@os:Debian and L@minion1,minion2' {% if grains.id in salt['pillar.get']('master:nodegroups:webserver', []) and grains.os in salt['pillar.get']('master:nodegroups:webserver', []) %} ... {% endif %} Note If you do not include all of the matchers used to define a nodegroup, Salt might incorrectly target minions that meet some of the nodegroup requirements, but not all of them.
https://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
CC-MAIN-2017-17
refinedweb
268
63.59
What is MultiCollinearity and how to resolve it? Q1: What is MultiCollinearity? If any of our Independent Feature(x1,x2) is internally co-related more than 90%. Q2: How multicollinearity works and how to resolve it? lets say we are solving Regression/classification problem where we have 10–15 features. i.e (n rows, 15 features) n x 15. Step 1: we plot correlation heat map by comparing each feature with each other. Step 2: So,lets say after doing step 1 we got features[f3,f4] which are highly correlated with more than 90%. Step 3: So, what we can do is remove any one of the feature which has [p-value > 0.05] Important Note: It is not Possible for finding correlation for each feature if we have large amount of features such as , eg: (n rows,200 features) n x 200. So to solve that issue we use something called Ridge and Lasso Regression. Lets take example: 1: df = pd.read_csv(“Advertising.csv”) X = df[[‘TV’, ‘radio’, ’newspaper’]] #Independent Features y = df[‘sales’] #Dependent Features df.head() y = b0 + b1x1 + b2x2 + b3x3 x1 = TV , x2 = radio , x3 = newspaper , y = sales b0 = Intercept b1,b2,b3 = Slopes or Coefficient So in order to check if there is Multi Collinearity issue or not we will use OLS MODEL : Ordinary Least square. import statsmodels.api as sm X = sm.add_constant(X) # add B0 with all const values X.head() model= sm.OLS(y, X).fit() model.summary() import matplotlib.pyplot as plt X.iloc[:,1:].corr() Conclusion: None of Features are internally corelated, all features(Tv, Radio,Newspaper) having values nearer to zero,i.e. all independent features are not correlated to each other. 2: df1 = pd.read_csv(‘Salary_Data.csv’) df1.head() X = df1[[“YearsExperience”,”Age”]] y = df1[‘Salary’] Using OLS model import statsmodels.api as sm X = sm.add_constant(X) # add B0 with all const values X.head() model= sm.OLS(y, X).fit() model.summary() import matplotlib.pyplot as plt X.iloc[:,1:].corr()
https://niharjamdar.medium.com/what-is-multicollinearity-and-how-to-resolve-it-35bef9b31fc4
CC-MAIN-2022-40
refinedweb
336
61.33
Files/Folders One they’d be in seperate files even though they are very closely related. If they share a base class, or a class they both compose, then that would be in yet another class (presumably). - Multiple classes per file – As an example you might group the Order addition contexts into a file called OrderPlacementSpecifications, the file could also contain the shared base class (if you went down that road). To me the second approach has a couple of advantages: - Gives the reader extra information – By grouping the two order placement classes we tell the reader that they are quite closely related. - Simplifies folder structure – If we go for the other approach, one class in each file, then we’re probably going to have to have more folders. The addition of the extra files and folders definitely makes the solution file harder to structure. To give you an idea here’s a screen shot of a part of the folder structure for a sample app we’re doing: In addition to files/folders I’ve tried a few approaches to structuring namespaces but the approach I’m trying now groups related artifacts. For example: - Specifications.Users.Domain - Specifications.Users.Domain.Contacts - Specifications.Users.Services - Specifications.Users.Domain.Repositories - Specifications.Users.UI.Controllers The “Specifications” bit adds very little but I think grouping all specifications related to users is useful, not least as R# makes it easy to run all the specifications in a namespace. This can be useful if you have a big solution and only want to run the specifications for the area your working on. Its also worth saying that its “Users” to avoid clashing with the “User” class. Folder wise however we’re using a standard approach where your Repositories are in a completely seperate folder from your controllers, even though they might both relate to a particular entity. To me the lack of relationship between our folders and namespaces isn’t a problem though, with R# its easy to find a file/type and in addition the folder/namespace tell you two different things about your codebase (one by “layer”, one by “feature”). So I’m interested in peoples views? I’m guessing you’ll all dislike it though because from what I’ve seen no matter what you do people will be unhappy with your file/folder/namespace scheme. Pluse we’ll probably turn against this approach next week…. Post Footer automatically generated by Add Post Footer Plugin for wordpress. I’ve tried all sorts of ways and I’m not trilled about any of them. We’re currently doing #1 but we expand out the namespaces more. We have folder names like UserContacts.when_doing_some_action and then we’ll have classes with names like when_doing_some_action_in_some_context. Then main reason for doing this was to not have files 1000 lines of spec code in there for all the different contexts. Like you, I’ll probably change my mind next week. I’ve also tried different approaches. The one we are using now is sligthly different and at first sight a bit weird, but it made a lot of sens after a short while: We are having each specs file(with one or more classes) live beside the code it is testing (i.e. in the same project!). We then use an Nant skript to deploy the application, that among other things, removes the “*specs” file from the assembly. Works like a charm. A bonus with this approach, is that you have also access to internal methods of your sut. @Ray Nice suggestion, will definitely give that a shot. @Michael The whole tests with code under test things always been a little radical for me but I can definitely see the value. I’m always behind the times on these sorts of things I’m curious about this as well, as the specs I’ve written quickly get numerous and hard to navigate. This is still a problem with my “legacy” tests, even more so actually. I like the nice view that I get when running my specs in R# or NUnit’s runner, but when browsing around code it’s not nearly as easy. What if I’m currently writing code for a component, and I need to add a new tests. R#’s CTRL+N brings up the type dialog and I type “when_” and I get a barrage of unrelated specs. @Ben Yeah the whole search for when_ is a big annoying, I tend to find the SUT then do a find usages and then see all the specs for it. If our test classes are attributed with something like [Conerning(typeof(Account))] then we can search on that (and hope that at some point R# or whatever will take advantage of this sort of metadata. Not great solutions though. @Ben You could browse by file instead with R# using CRTL+SHIFT+N which allows you for example to find the OrderSpecs file, which contains all tests for an Order. I tend to use CustomerSpecs.cs as the file name and have multiple classes in each file. I then use what Ben suggested, R# Find by file name. This was been the easiest so far. If I have a ton of test for Customer then I think about breaking the file up into two or three files and keep the classes orgainzed logically within those.
http://lostechies.com/colinjack/2008/10/28/context-specification-files-folders-namespaces-bdd/
CC-MAIN-2014-41
refinedweb
901
69.31
Preparing your Python code for Perlmutter's GPUs¶ NERSC's next system is Perlmutter. 1) The Perlmutter GPU partition will have approximately 1500 GPU nodes, each with 4 NVIDIA A100 GPUs and 2) the CPU partition have approximately 3000 CPU nodes, each with 2 AMD Milan CPUs. You can find some general Perlmutter readiness advice here. The majority of the Perlmutter FLOPS will come from the GPU partition. Python users who wish to take advantage of this will need to adjust their code to run on the GPUs. For more information about running Python on Perlmutter's AMD CPUs, please see this page. This page is focused on considerations and GPU porting advice for potential Python GPU users. Here are some questions to ask yourself to help determine if your code would benefit from running on a GPU and if so, which options may be a good fit for your application. Question 0 -- Is my code a good fit for a GPU?¶ This is an important question to consider. Moving code from a CPU to a GPU can be a lot of work. Expending this developer time and energy only makes sense if you can be reasonably sure that a GPU will provide some speedup. GPUs are best at the type large matrix operations, like those in graphics processing, that they were initially created to do. If a scientific Python application can leverage large matrix operations, GPUs are likely a good fit. Other applications that can't employ massively parallel operations, like Monte-Carlo calculations, will like struggle to use the GPU effectively. If you aren't sure what kinds of operations you are doing or where your code spends most of its time, the best solution is to profile your code. Even basic profiling will give you some sense of whether moving to the GPU is worth your time. It may not be-- and that's ok! Question 1 -- How much data do I need to move between the CPU and GPU?¶ Moving data between a CPU and GPU is expensive. In many cases it can be much more expensive than the GPU computation itself. A Python developer should ask themselves if the amount of data they have to move outweighs the number of calculations they expect to perform on the GPU. A general rule of thumb is that the GPU should perform 10 operations on a dataset before it makes the cost of data movement worthwhile. If you only have one matrix to solve, a GPU may not be that helpful. If you want to operate on the same matrix 100 times, then it may be much more useful. Basic profiling may also help shed some light on the data needs and usage patterns in your application. Question 2 -- What if my code doesn't meet these requirements?¶ This is actually a common question. It is very unlikely your code is a great fit for GPUs without doing any work. Many of the codes that will use the Perlmutter GPU partition have been actively redesigned with GPUs in mind. If you are willing to redesign your code, you'll want to focus on the areas we discussed in Question 0 and Question 1-- massive parallelism and minimizing eventual data movement between the CPU and GPU. You may find that these changes may improve the CPU version of your code. Once your code meets these requirements, you can move forward. Question 3 -- Okay, my code is suitable for a GPU, now what?¶ If your code meets the first two criteria we listed-- contains massive parallelism and has a reasonably high GPU compute to data movement ratio-- the next question is how best to start porting your code to the GPU. import gpu #this will not work :) Python users have become somewhat spoiled due to well-established libraries like NumPy and SciPy that make performing sophisticated calculations easy on a wide variety of CPU hardware. On GPUs however, Python users can not use familiar libraries like NumPy and instead will have to choose from newer GPU-enabled libraries and frameworks. Each of these options has its own pros and cons. You should select a library (or libraries) depending on the needs of your application. We will provide a brief overview of several current options below. The only constant is change It is important to note that the Python GPU landscape is changing quickly. Most likely by the time you are reading this page some information will be out of date. We encourage anyone interested in the current Python GPU landscape to continue checking project repositories and reading the documentation for the framework(s) in which they are interested. Question 4 -- How should I replace NumPy/SciPy?¶ CuPy¶ CuPy, developed by Preferred Networks, is a drop-in replacement for NumPy. Many NumPy and SciPy functions have been implemented in CuPy with largely the same interface as their original counterparts. CuPy does not come with its own JIT compiler. It does however interface well with Numba which will be described below. Users who require a function which is not currently implemented in CuPy are advised to write a custom kernel in a framework like Numba. At present CuPy is predominately supported on NVIDIA GPUs, although AMD ROCm support is also in development. JAX¶ JAX, developed by Google, is also a NumPy/SciPy-like library, although it cannot be used as a drop-in replacement due to syntax differences. The JAX framework includes many implemented versions of NumPy and SciPy functions, a JIT compiler, and some other deep learning specific functionality. JAX has its own JIT compiler in contrast to CuPy. While this native JIT functionality is nice, the syntax required for the JIT compiler can be somewhat alien to NumPy users. For example, traditional NumPy index slicing is not supported. These small changes can make it difficult to translate existing code into code suitable for JAX's JIT compiler. JAX uses Google's XLA compiler. At the moment XLA supports many CPUs, Google TPUs, NVIDIA GPUs, and recently AMD ROCm. However JAX does not yet support AMD GPUs. Deep Learning Libraries like PyTorch and TensorFlow¶ PyTorch and TensorFlow aren't just for deep learning! They both have implemented many of the most common NumPy functionality (and even some SciPy functionality) in their tensor arrays. PyTorch and TensorFlow have been supported by more development effort than smaller Python frameworks like JAX, and as a result, they are very well-optimized. They also have very large user communities, making it easier to find answers to problems. Question 5 -- How should I replace pandas/scikit-learn?¶ NVIDIA RAPIDS¶ NVIDIA RAPIDS provides libraries like pandas (RAPIDS CuDF) and scikit-learn (RAPIDS CuML) implemented with CUDA library backends. Question 6 -- How can I write my own custom GPU kernels?¶ If you are using other domain specific libraries-- for example, AstroPy-- that do not yet provide any GPU support, you will likely need to write some GPU kernels yourself. You may also find that CuPy, JAX or RAPIDS have not implemented the function that you require. In both of these situations your only option is to write your own GPU kernel. There are several options for this. Your choice should depend on your skill-level and your needs. Numba¶ Numba, part of the Python ecosystem, is a JIT-compiler for Python. It can compile Python for CPUs and also generate GPU code for both CUDA and ROCm architectures. Numba CUDA is more Pythonic, less powerful, and less complex than writing kernels in PyCUDA. For users who would prefer not to deal with raw CUDA, Numba offers a more friendly alternative. It does however still require users to be aware of the basics of CUDA-style GPU programming, including threads, blocks, and kernels. We have found that CuPy and Numba compliment each other and have used both together-- CuPy for the drop-in NumPy replacements, and Numba in situations where the functions are not available in CuPy. Numba and CuPy objects are able to interface directly. PyCUDA¶ PyCUDA was written by Andreas Kloeckner. PyCUDA is much more powerful than Numba. It provides a wrapper for CUDA that is cleanly accessible within Python. It is straightforward to install and run. However for most Python users, PyCUDA and PyOpenCL are likely the most challenging frameworks to use. Where Numba abstracts away some of the more complex parts of writing CUDA code (using pointers, for example), Python users will need to write and understand enough of C/C++/CUDA in order to write the PyCUDA kernel they require. The same is true for PyOpenCL. PyOpenCL¶ PyOpenCL was also written by Andreas Kloeckner. It is similar to PyCUDA in that it wraps OpenCL, another C/C++ like language that is most likely not familiar to most Python users. Installing and using PyOpenCL is more challenging than using PyCUDA (at least on our Corigpu NVIDIA testbed). It is supported by fewer profiling tools and in general is more difficult for which to find resources. However, the true strength of OpenCL is its portability. It should run on all CPUs and all current GPUs. Question 7 -- How do I scale up?¶ We anticipate that many NERSC users would like to run on more than one GPU and maybe even more than one GPU node. We will briefly summarize several options for scaling up with Python GPU frameworks: - Familiar options like mpi4py will still work on CPUs and can be used to coordinate work on multiple nodes and multiple GPUs. - CuPy can run on more than one GPU via CuPy streams. It can also scale to multiple GPUs and many nodes via Dask. - JAX can extend from a single GPU to multiple GPUs (on the same node) via the Parallelization/pmap subpackage. Based on the JAX docs it appears that these areas still under active development. - Libraries in NVIDIA RAPIDS also use Dask to scale to multiple GPUs and multiple nodes. - Other libraries like Legate that are currently in development may also provide a user-friendly way to scale NumPy operations to many nodes. If you have questions about porting your Python code to Perlmutter, please open a ticket at help.nersc.gov. We can provide some guidance to help you decide if GPU porting is a good fit for your application, give you some advice to get started, and help you choose a framework (or combination of frameworks) that will suit your needs.
https://docs.nersc.gov/development/languages/python/perlmutter-prep/
CC-MAIN-2021-17
refinedweb
1,738
62.98
Bjarne Stroustrup Reveals All On C++ 371 An anonymous reader writes ." Oh... my... god... (Score:3, Funny) C++ is a woman?! I didn't see this coming. Re: (Score:2) Sorry, but we're talking about C++ here. You may have this confused with an earlier slashdot story [slashdot.org]. Re:Oh... my... god... (Score:5, Funny) It shouldn't be that surprising. The new operator should have given it away. After all, in C++ you can create objects (children) that consume resources and don't clean up their garbage. The secret to how it works is that C is a man. Re: (Score:3, Funny) Is that you, Verity Stob? Re:Oh... my... god... (Score:5, Funny) C++'s social life is a bit weird as well: I hear that friends have access to your privates. Normal Read (Score:5, Informative) Re: (Score:3, Funny) Where is the printf() version? Re:Normal Read (Score:4, Funny) You mean the cout version, noob! Interesting Read (Score:5, Informative) It's always cool to see this kind of interview. It's even cooler when you can read it all on one page [computerworld.com.au] rather than 8. I suggest that anyone who uses C++ or is interested in the history of programming read this. Some of it is a bit banal, like how they chose the name, but some of it is really intersting. RTFA for once, you lazy clods! Re:Interesting Read (Score:5, Funny) Re:Interesting Read (Score:5, Funny) Hey! I'm illiterate, you insensitive clod! As are most c++ programmers. Re: (Score:3, Funny) Oh know were not. Re:Interesting Read (Score:5, Interesting) Re:Interesting Read (Score:4, Informative) Early C++ "compilers" usually did more than just macro processing, but only just; most of them were implemented in terms of translating C++ to equivalent C code and then compiling the resulting C. Not so elegant, but it allowed compiler vendors to pick the low-hanging fruit and get something on the market ASAP. It wasn't just commercial compilers, either. g++ worked that way. Of course, it goes without saying that these early C++ compilers sucked hard. c. Re: (Score:3, Informative) Re: (Score:3, Interesting) It's the real reason that D hasn't taken off yet. Well, that and the fact that it has 90+ (!) keywords. The guys at digital mars are doing what Sun tried to do with java; it's ours, ours, and ours alone ! Yes, there is a spec, and yes you can build compilers, but wait - not so fast. You have to let us test your stuff, or you can't call it D. And maybe pay us a little. Or at least remember us in any code that you write. . Whenever I go to digital mars' website, I'm reminded of my Corba days and that inst Re:Interesting Read (Score:4, Interesting) > Aren't you just a bit biased? If you're gonna be pedantic, it's a lower-case 'c'. But I'll freely admit to being biased. I've spent my time in the C++ trenches. C isn't a terribly good language, but when you shoot yourself in the foot it's usually a clean wound. c. Re: (Score:3, Informative) C isn't a terribly good language, but when you shoot yourself in the foot it's usually a clean wound. From TFA: "C++ makes it harder to shoot yourself in the foot; but when you do, it takes off the whole leg" is sometimes quoted in a manner hostile to C++. That just shows immaturity. Every powerful tool can cause trouble if you misuse it and you have to be more careful with a powerful tool than with a less powerful one: You can do more harm (to yourself or others) with a car than with a bicycle, with a power saw than with a hand saw, etc. What I said in that quote is also true for other modern languages; for example, it is trivial to cause memory exhaustion in a Java program. Modern languages are power tools. That's a reason to treat them with respect and for programmers to approach their tasks with a professional attitude. It is not a reason to avoid them, because the low-level alternatives are worse still. -metric Re: (Score:2) I don't know about many, but I used at least one that was C++ implemented mainly with the preprocessor -- if I recall, it even did templates using name mangling. It worked, but it made debugging a challenge because the debugger was basically an OK C debugger that wasn't completely up to speed on unmangling C++ symbol It was never a preprocessor (Score:3, Interesting) If you're thinking along the lines of a bunch of #defines making C into proto-C++ then you're completely wrong. The early compilers produced C as a sort of "assembly language" so that it could be used on many different targets (C was widely available). But it you looked at the C it produced you'd have a hard time relating it to the original C++ source code. Cfront (Score:3, Insightful) And in fact, Cfront was a compiler, not just a preprocessor; it was just a compiler that compiled C++ into C. Re: (Score:3, Interesting) "that's no longer possible." Remember... This is Slashdot. Comments like these may have unintended consequences when made here. It's, of course, possible to build a CFront-like preprocessor that converts current C++ code into C. It's not easy and the C code would probably be even less readable than what CFront wrote. It's not practical either. Or wise. But it's certainly possible. Re: (Score:2) The early versions compiled C++ into C--this was a compilation, not a translation. What's the difference? The name (Score:2, Funny) FTA they tried calling it C with Classes, but that didn't stick, so they asked for suggestions and got C++ I think they should have called it Class-C. Much more fun to pronounce. Humour (Score:2, Funny) (C'mon KDE guys, it's funny. Laugh.) Re:Humour (Score:4, Insightful) The pun seems to be that KDE isn't structured, efficient, portable or serious, despite being written in C++. I can't blame you for missing it, or finding it not funny. yawn (Score:4, Insightful) C++ is a language of a million gotchas. The moment I start having to think about implementation detail and I'm not writing an operating system or compiler, I know I'm using the wrong language. Re: (Score:3, Insightful) then you're going to have a hard time of programming, perhaps you'd be happier being the Boss. [urbandictionary.com] All languages have "implementation details" and various gotchas. Look on any programming forum for any language and you'll see tips and tricks in using it. I think you're in the wrong job. Re:yawn (Score:4, Informative) Re: (Score:3, Insightful) > C++ is a language of a million gotchas. Whenever you want to use a language, you must learn it first. That's true even of Visual Basic. The reason you see those problems of yours as "gotchas" is that you don't understand how the language (and, in the case of C++, the computer) works. If you let the language shape your thoughts instead of trying to cram your crummy thoughts into C++, it would have been much easier and simpler for you. > The moment I start having to think about implementation detail, I Re: (Score:2, Insightful) You evidently either (A) don't know thing one about C++ or (B) FAR FAR FAR worse, you do think you know about it. Next time you're in a bookstore, browse through Scott Meyer's "Effective C++" books. They're basically a huge list of comments to the effect of, "Gee, you THINK you can do X because it's perfectly legal syntax and it makes sense because you do X in other object-oriented languages, but in C++ it either fails outright or its undefined behavior in the language, so it will fail at the worst possible t Re: (Score:3, Informative) I don't know where you got this idea. If you have virtual member functions, you probably want a virtual destructor, but it's neither a requirement, nor a given. From the C++ FAQ lite, read [20.7] When should my destructor be virtual? [parashift.com] Re:yawn (Score:4, Insightful) This is the problem with people who don't know how to appreciate C++ capabilities. Do you even know why a "virtual" declaration on a method may be useful, or what it does internally? The whole idea is that you write code that can call methods named in a base class but defined in a derivative (child), via pointers. So, if you want to keep your code clean, you just have one line like: Parent *p = new Child(); and the rest of the "user" code stays the same. You change the one line above to change functionality of every virtual method. Now since destructors are called implicitly most of the time, and since you OBVIOUSLY DECLARED VIRTUAL METHODS FOR A REASON, the compiler will warn you if the destructor is not virtual too, because then the object will be destructed as if it is a Parent object. It is a very valid warning, and will save you memory leaks(child objects contain more stuff to be freed..etc). It all makes sense now, see. The compiler is being nice, yes? Do you not agree that you should be blushing, after accusing the heavenly father Stroustrup of psychosis? Advice for life in general: If you don't know how to use something, don't use it ;) Re: (Score:3, Insightful) >> The moment I start having to think about implementation detail, I know I'm using the wrong language. > In other words, you don't want to know how your program really works. A fine attitude for a PHB. I suggest you switch to english. steerin Re: (Score:3, Insightful) steering wheel, the tighter I turn, but that should be it. Why should a programming language force me to think about low level implementation details that are nothing to do with the algorithm I'm trying to write? It is nice to know when you are driving the car that if there is snow or an oil slick or a flat your turning response would be different. You don't have to know how the steering works, but know a few things more than just rotate the wheel right are useful when you want to do anything non-trivial. And just like programming you will learn these things by experience (if u don't get into any serious crashes). Re:yawn (Score:4, Funny) Re: (Score:3, Funny) Be careful - you should Turn Left. Turning right may make you dissolve into little fat monsters. Re: (Score:3, Insightful) > When I'm driving my car and I turn the steering wheel right, I expect the car to run right, without having to think That's what I would expect when using your software, because that is the proper analogy to driving the car. Programming is more like designing the car, and yes, you do want to know what the steering wheel does. What if car designers just had little modules described as "this thingy makes the car turn right"? Then they would just snap the parts together and secure them with duct tape. Would Re:yawn (Score:4, Insightful) Because a programmer is a car designer, assembler or a mechanic, depending on his specific job description. The user of the program is analogous to the driver of a car. If you want to be a car mechanic, you'd better learn how cars work. If you want to be a programmer, you'd better learn how programs work. You'd think this would be bloody obvious, but oh well... Re: (Score:2) It is used to solve the diamond problem in singletons where the base class is abstract (pure virtual), though making the base protected isn't too useful. DOM implementations with multiple inheritance where each node is created by the document object come to mind. This kind of design is used e.g. in Inkscape's Inkscape::XML::Node class. Re: (Score:3, Insightful) Oh, java must be crap because you can't tell, right? It's pretty damned easy to tell what should happen. f(foo(a)); should run f on the return value of foo(a). f(a); foo(a); will depend on the specific functions involved (and whether a is passed by reference or value), so it isn't the language's fault if your example is bad. In the c++ example, the expected behavior is clear: f(a++) should be the same as f(a); a++; because it's a postfix increment. If the actual behavior doesn't match that, that's C++'s fault. Likewise, if the Java behavior doesn't match wha everything programmers should know about C++? (Score:5, Funny) in an 8 page interview? I feel like a sucker for buying the 900 page book [amazon.com] Re: (Score:2, Funny) [amazon.com] Re: (Score:3, Funny) Yeah, he is apparently very good at refactoring. Re: (Score:3, Funny) Yeah, but that's 8 pages of pointers into said book ;) And ... (Score:4, Informative) ... for an equally partisan view from another perspective, the C++ FAQ [yosefk.com]. Re: (Score:3, Informative) Re: And... (Score:2) The FQA. One of my favourite extended rants. I cant speak as to how accurate it is (never really have done much in C++), but there are many eye openers in there. (C++ grammar is undecideable-what?) Re:And ... (Score:4, Insightful) ...it's largely a waste of time. The author spends an inordinate amount of time complaining that C++ prefers compile-time overhead to run-time overhead, and has no understanding that C++ is designed to have no unnecessary performance penalty relative to C. It would be nice if he did, as whatever insights the FQA author has concerning OO languages could be gleaned without wading through a few thousand lines of whining over the lack of things like garbage collection, heap compaction, run time bounds-checking, etc. He also has apparently never heard of Boost. The FQA is "equally" partisan? (Score:5, Insightful) I'm afraid that web site is one of those things that gets way too much attention in some on-line communities because of its controversial nature. The reason the two sides are far from equally partisan is that Stroustrup freely admits there is another side to the debate and that C++ has its flaws, and he is making efforts to improve the situation. The FQA, on the other hand, just makes blanket statements like "For example, the lack of garbage collection makes C++ exceptions and operator overloading inherently defective", which simply isn't true (and neither are many of the statements made in the FQA under those particular headings). If you read the comments the guy who wrote the FQA makes on forums like reddit, as well as throughout the FQA itself, it's pretty obvious that unlike Stroustrup, he has little interest in any balanced discussion on the subject. He's just out to prove the other side wrong — where "wrong" often means "not agreeing with him" — and perhaps, the cynic in me suspects, to make a reputation for himself in the process. Favorite line... (Score:4, Funny) programs in C++ could be simultaneously elegant ... and efficient for systems programming... Obviously, not every program can be both and many are neither Many are neither. Ain't that the truth. The Truth about C++ (Score:5, Funny) - re Re: (Score:3, Interesting) What a wonderful bit of fiction. I did find it entertaining, so thank you. I have worked with some very good programmers, and some mediocre ones. The very good ones usually liked C++, and often preferred it when given a choice. The younger (good) ones tend to go with C# these days, though they don't bad-mouth C++. It is always the mediocre ones who badmouth C++. That has just been my experience, I don't know if this is true across the board, but I do encounter this a lot. Average and below-average programm Re: (Score:2) Er, hardly a Troll there mods. It's definitely personal opinion, (And one that I would have to agree with from personal experience), but not a troll. Re:The Truth about C++ (Score:4, Interesting) Nice. If you don't like C++, it must be because you're a bad programmer. It's much harder to write C++ code that, for example, will never leak memory no matter what goes wrong than in the assorted garbage collected languages, or even vanilla C. That, I don't see how anyone could even reasonably argue. C++ was an important step on the way to better languages (for the problems it was trying to solve -- not for everything), but that doesn't mean that given today's alternatives it should be considered good. Being a good programmer is about being good at solving the problem at hand in a clean, maintainable way. It's not about being able to memorize the weird inconsistencies in a language or fight a better fight with a difficult language. Even for a project that has to be done close to the machine, you'll almost always get in less trouble using C. (Or, if you must, using C++ but generally ignoring the C++ features.) Re: (Score:2) I'm not sure why this garbage is not being collected, but honestly, C++ making it easier to leak memory than C? What are you smoking, and can I have some? Re:The Truth about C++ (Score:5, Insightful) Yawn. If you don't like C++, you probably just don't understand it [emptycrate.com]. Yes, it's a complex language. However, if you use RAII (a fundamental tenant of C++) you will not. leak. memory. ever. Same arguments about C++ are used over and over again by people who don't grok the language. Is it the end-all be-all language? No. But it is darn good at what it does (performance minded system level code) with almost none of the problems C has (memory leaks and weak typing). Re: (Score:3, Insightful) It's much harder to write C++ code that, for example, will never leak memory no matter what goes wrong than in the assorted garbage collected languages, or even vanilla C. That, I don't see how anyone could even reasonably argue. Probably true. But what does that tell us about general language fitness really since it's equally as easy to hog resources in a language with GC? Database connections for example. When you absolutely need deterministic release of resources you end up having to approach the problem in a similar fashion to c++ memory management anyway. Many people believe seem to believe GC allows you to forget about resource management when it doesn't at all. It's a great tool for a certain class of problems but not a "What good progammers should think" (Score:3, Funny) Language stability (Score:3, Interesting) Re: (Score:3, Insightful) Stoustrup probably means the binary still runs on the now antiquated system it was originally compiled for. I very much doubt he means that the 20 year old source code still compiles with a modern compiler, as the language has changed way too much. So, Stoustrup's probably being a little bit disingenuous as usual. Re: (Score:2) Unless that C++ program was statically linked, it's ridiculously unlikely a 20 year old binary will still run. Even then, some kernels don't even bother supporting a.out at all. Hell, even Windows doesn't run a good chunk of 20 year old code, especially not Vista. Re: (Score:2) I have C++ code from 20 years ago that is still used in the products my company sells. I imagine most C++ will work, unless some relatively obscure (for the time) features were used. Most of the language hasn't changed at all. OK, it is somewhat "better C" than a full-on templated metaprogram. Non Geeks (Score:3, Interesting) Re: (Score:2) Uh, how about Management types (PHBs) Book Store workers Publishers Librarians You may even have issues with some file systems. When it comes to computing, ignorance rules the masses - I'm still amazed at how many people still call / backslash (which I heard on the radio today when a DJ was giving a URL). If you liked that, read "Design and Evolution"... (Score:3, Informative) The interview just seems like a very brief sampling of "The Design and Evolution of C++ [amazon.com]". Even if you do not care much about C++, it's an excellent look into the philosophy and thought that goes into language design. Use this link to read article on one page (Score:5, Interesting) First, read the printable version of the article on one page. [computerworld.com.au] The original version is one paragraph per page, surrounded by ads and related dreck. There's really nothing new there. It's the usual Strostrup stuff. He's still in denial about C++ being the cause of most of the buffer overflows, system crashes, and security holes in the world. The fundamental problem with C was the "array=pointer" concept. If array sizes were carried along with arrays, we'd have far less trouble. Even FORTRAN has conformant array parameters. That should have been fixed in C++, but it wasn't, and as a result, we had two more decades of buffer overflow problems. This isn't a performance issue, by the way; Modula 3 got it right, but Modula 3 disappeared for non-technical reasons - Compaq bought DEC and closed down the software R&D operation. C++ is also the only language that has hiding ("abstraction") without memory safety. C has neither; almost all later languages (Java, Delphi, all the scripting languages) have both. C++ stands alone in this unsafe place. Nobody ever repeated that mistake. So subtly incorrect calls to objects can result in the object overflowing. Yes, some of these problems can be papered over with templates. The C++ committee is full of templateheads, focused on template features that few will use and fewer will use correctly and productively. That crowd is still struggling to make auto_ptr work. Re:Use this link to read article on one page (Score:5, Informative) The developer should know if he'll need the size of an array or not. Which is why there is a convenient std::vector and std::tr1::array for when you do want the size. Not forcing you to carry around a size is a feature, not a bug - if you don't need the size, it's just a waste of space. And auto_ptr is likely to be depreciated in C++0x, with unique_ptr and shared_ptr replacing it. Re: (Score:3, Informative) Delphi is no more memory-safe than C++ is. For that matter, Delphi actually requires you to call destructors for all objects explicitly, and woe be on you if you forget to, or, wors Tell it like it is (Score:2) but the intent was (and is) that a competent programmer should be able to express just about any idea directly and have it executed with minimal overheads (zero overheads compared to a C version). Possibly the most important part of the article. non-competent programmers, go find a language more suited to your skills, preferably one with an IDE that does it all for you. Convincing the systems programming community of the value of type checking was surprisingly hard. The idea of checking function arguments against a function declaration was fiercely resisted by many - at least until C adopted the idea from C with Classes And today, we have script languages like this. Just shows things never change, they just go quiet before returning to fashion. (unlike bell-bottom flares which really should never return)(ask your dad) Re: (Score:2) And today, we have script languages like this. Just shows things never change, they just go quiet before returning to fashion. To be fair, the non-type-checking of old C compilers (or new C compilers if you do something wrong and don't follow good conventions) is an entirely different animal than the non-type-checking of today's Python or Perl. In the former, the function you're calling expects certain types in particular register and/or memory locations, and runs as if they are there. If it's wrong, and the Love C++, but it still sucks... (Score:5, Informative) * No standardized pragmas * Macros after-thought and not type safe * No 24, and 32 bit (unicode) chars * Still has float / double crap, instead of being properly deprecated and f32, f64, f80 used instead * Still has short / long crap, instead of being properly deprecated, and i8, i16, i32, i64, i128, u8, etc... * No distinction between typedefs and aliases * Inconsistent left-to-right declarations * Compilers still limited to ASCII source * No binary constant prefix (even octal has one?!) * No standard way to assign NaN, +Inf, -Inf to floating point constants at compile time Re:Love C++, but it still sucks... (Score:5, Informative) * Pragmas are made specifically for non-standard compiler extensions. There can be no "standard" pragmas. * C++0x is adding support for UTF-8, UTF-16, and UTF-32 character types and literals. * TR1 adds cstdint which includes int32_t etc. types. * NaN and +Inf (not -Inf, though) can be had from std::numeric_limits alas, if those are the first complaints you think of, you haven't been using C++ long enough to really know the painful bits. Re:Love C++, but it still sucks... (Score:5, Informative) Most of your complaints seem aimed at C and not C++. Let's see: * No standardized pragmas They standardized the extension mechanism. That sounds good for a start, but I don't see how you could go farther. * Still has short / long crap, instead of being properly deprecated, and i8, i16, i32, i64, i128, u8, etc... Also, short/int/long give you the sizes optimized for the specific processor, so you can use that if that's what you want. You can't really deprecate them because of that I've never used them though. For double: #include <limits> const double inf = std::numeric_limits<double>::infinity (); const double minf = -std::numeric_limits<double>::infinity (); const double nan = -std::numeric_limits<double>::signaling_NaN(); See more here [unc.edu] for example. There are has_infinity() and related functions to check for a type's capabilities (say, in a template) Bitmasking (Score:3, Insightful) Hex is close enough and less error-prone When you're actually bitmasking, it's nice to see the bits rather than having to accumulate them in your head. Re: (Score:2, Informative) * No standardized pragmas Pragmas were meant to be OS and compiler specific. If your OS or compiler doesn't provide a standard then it's the language is not at fault. * Macros after-thought and not type safe Macros weren't meant to be type safe. You should use templates if you need type safety. * No 24, and 32 bit (unicode) chars What about std::wstring and cwchar? * Still has float / double crap, instead of being properly deprecated and f32, f64, f80 used instead * Still has short / long crap, instead of being properly deprecated, and i8, i16, i32, i64, i128, u8, etc... Use cstdint [die.net] and cfloat [cplusplus.com] * No distinction between typedefs and aliases * Inconsistent left-to-right declarations I don't have much experience with those in C++ so maybe someone else should elaborate. Could you provide examples where these two would be a problem? * Compilers still limited to ASCII source This is true but hard-coding unicode strings is considered a no-no. * No binary constant prefix (even octal has one?!) This and worst of all... (Score:4, Interesting) Re:Love C++, but it still sucks... (Score:4, Funny) ... +Inf, -Inf... Everything has its limits, you know. Sand-bagger (Score:4, Funny) Bjarne Stroustrup Reveals All On C++ You mean... He's been holding back? Want to know more? Read the book (Score:4, Insightful) "The Design and Evolution of C++" by Stroustrup is a must-read if you are interested in why C++ is the way it is. After reading it, I really hated C++. It's the classic example of a project that gets ruined by too many people working on it, all with their own goals, and the book tells you exactly why this happened. C++ now is a hideously complex monstrosity that is popular because it is all things to all people, not because it is a good language. Anyway, if you disagree with me, have a look at the book. It is a testament to Stroustrup's objectivity that I came to the conclusion I did, and that you may come to the exact opposite conclusion as me after reading it. Anyone trying to defend C++ as a language (Score:4, Informative) Anyone trying to defend C++ as a language should read this [yosefk.com]. And I speak as a programmer who has used C++ since cfront 1.0 was released to the world. Useful, yes. Pragmatic, maybe. Design heavily rationalized ex post facto by its creator and its proponents, most certainly. But a well-designed programming language, it is not. C++ Debuggers (Score:4, Funny) His answer was along the lines of: "Oh, I never use a debugger. If something's not working right I just think about it...maybe I'll add a printf once in a while if I need to check something." Now you know why utterly un-debuggable features like templates went into the language... Re: (Score:3, Insightful) That's just the point. Your code isn't the problem for you to understand. In the real world where people have to look at other people's code, you often need all the debugging help you can get. Stroustrup is being very smug in his response here. He lives in an ivory tower, how much real-world code written by other people (to a deadline or management constraints) has he ever dealt with? My feeling is, very little.. Stroustrup seems to say (don't use exceptions!) (Score:3, Informative) Here is a real eye opener: Bjarne Stroustrup cited the JSF coding standard as an example of C++ usage: "Also, embedded systems programming is a major area of use and growth of C++; for example, the software for the next generation US fighter planes are in C++ (see the JSF++ coding rules on my home pages).";408408016;pp;5;fp;16;fpid;1 [computerworld.com.au] I particular like the following statement in the JSF++ coding rules that the creator of C++ holds up as an example of how to use C++: AV Rule 208 C++ exceptions shall not be used (i.e. throw, catch and try shall not be used.) Rationale: Tool support is not adequate at this time. Re: (Score:2) Re: (Score:2) Re: (Score:3, Funny) Inaccurate. You forgot COBOL. But that's understandable, I want to forget it, too. Re: (Score:2) Re: (Score:2, Insightful) If the messages are the same, no one has any reason to see both, so scoring one out of the default view is the Right Thing. If you're pathetic enough to care about karma and this happens so often that it even matters, complain to the admins that the author of a redundant comment hasn't done anything wrong. Re:managed code (Score:4, Interesting) And I suppose your shop used to say "COM only", and now says "ugh, COM, who'd want to code those things up". You seem to have swallowed the Microsoft marketing man's sales spiel wholesale. When you find out how slow some parts of .NET is (eg DB access), or how much memory it uses when you don't want it to, or how to find the object you expected to be GCd but hasn't been.. then you'll think about writing a chunk of your code in old C++. MS did do a lot of work (pretty poor IMHO though) with C++/CLI to get some interop going between C++ and C#/VB. Poor because of the somewhat contrived bodges to the language they put in that they could have hidden behind the compiler, and also because there isn't any real interop with old unmanaged C++ except by wrapping it with a managed dll (or recompiling with the /clr flag set). Its also a poor implementation - eg STL/CLR is a lot slower than the .NET containers surprisingly. Re: (Score:3, Insightful) Re:useful but oh so flawed (Score:4, Informative) Re:useful but oh so flawed (Score:4, Insightful) Basically when you have rules you ought to (or "must" unless you want magical bugs) follow that are not enforced by the compiler, the language is flawed. Like when you oveload new but not delete and thus have incompatible memory management. Or you return a reference to a method-local (auto) string object. It does however give rise to a market for code analysis tools that checks all the stuff the compiler will let you get away with. But you can save the cost of these tools (or the alternative manual hunt for bugs) by using more modern and productive languages like Java or Ruby, leaving C++ for operating systems and games. And the latter is moving into other lanbguages as well, i.e. Microsofts push for C# in game development, and the widespread use of Python in e.g. EVE Online, ToonTown, Civ IV and other games. Re:useful but oh so flawed (Score:5, Insightful) Well, there's no doubt in my mind that C++ is a language design tour de force. The question is whether its design objectives are the right ones. They were probably the right objectives for the place (Bell Labs) and time (1979) it was conceived. At the time, computers were inconceivably slow by today's standards. I worked at a small developer that had a very nice AT&T 3B2-400, which had a WE32000 microprocessor, which probably ran at about 10-15MHz; a half dozen programmers shared it. As for the place, well, it was crawling with C programmers and C libraries, doing rather complex and important systems programming. Compatibility with C and proven C libraries would have been a huge thing. So, an efficient, object oriented version of C was probably exactly what was needed. I think that if there was any fault, it was the attempt to meet the goals of efficiency and compatibility with a language that implemented everything that (at the time was thought to be) necessary for programming in an object oriented style. Multiple inheritance carries too much baggage when all you want to do is to guarantee objects have a certain interface. Likewise, I think operator overloading is another example of trying to do too much. Yes, it makes programmer classes "first class citizens", but it really has no demonstrable practical benefit in my opinion. In situations where you need a special purpose language, it's probably better just to create one. Still, that's hindsight. If you really understand all the things Stroustrup was trying to do, C++ is quite awe inspiring. Re:useful but oh so flawed (Score:4, Insightful) I write math codes for fun and for a living. I have this discussion on an infrequent basis with a Java buddy of mine. Now granted I'm a dumb mechanical engineer and he's a smart CS major, but when I need some custom math classes that aren't provided by the language (tensors, vectors, Jacobians, Quaternions, etc.) and evaluating long math expressions, it is so much easier to view it using the native math symbols than to nest it all in member functions Re: (Score:3, Interesting) Of course that might depend on what the 10% is. Re: (Score:3, Insightful) Re:useful but oh so flawed (Score:4, Insightful) I write code for clusters, now specifically CFD. Lots of math, lots of parallel processing. Matlab and Octave isn't gonna cut it, and you really desire the close to the metal aspects of c++. It may be a narrow range, but there's a lot of people in this narrow range. Specifically, (mechanical/aerospace/etc.) engineers. C++ isn't sexy like Java or Python, but we do a lot of things you just can't do in Python, and can't do fast in Java. Re: (Score:3, Insightful) Altogether, I'd rather do the kind of work you're talking about in Matlab or Octave. Or you could do something like Beanshell -- have an interpreted language that is closely tied to the underlying language and its libraries. Matlab (and its clones) are mostly useless in the numerous areas of math outside of a standard undergrad curriculum, even for "profiling" since the data structures aren't even in the language. It's a zillion times easier to write these in C++. This never gets mentioned on forums like this, but C++ provides the right balance of power and flexibility (especially with memory managament) for people who do specialized math/science. And even in not-so-specialized areas, sometimes objects in Matlab clones are Re:Operator overloading... (Score:4, Interesting) The people using C++ for engineering, mathematical, and scientific applications may be a minority, but not a tiny minority. No one has to deal with operator overloading if it is not applicable to their application. If a developer is too immature to recognize when a feature is a bad choice, then operator overloading is the least of his problems.
https://developers.slashdot.org/story/08/06/25/139219/bjarne-stroustrup-reveals-all-on-c
CC-MAIN-2017-39
refinedweb
6,370
71.14
Angular is a mature technology with introduction to new way to build applications. Think of Angular Pipes as modernized version of filters comprising functions or helps used to format the values within the template. Pipes in Angular are basically extension of what filters were in Angular v1. There are many useful built-in Pipes we can use easily in our templates. In today’s tutorial we will learn about Built-in Pipes as well as create our own custom user-defined pipe. Angular Pipes – overview Pipes allows us to format the values within the view of the templates before it’s displayed. For example, in most modern applications, we want to display terms, such as today, tomorrow, and so on and not system date formats such as April 13 2017 08:00. Let’s look more real-world scenarios. You want the hint text in the application to always be lowercase? No problem; define and use lowercasePipe. In weather app, if you want to show month name as MAR or APR instead of full month name, use DatePipe. Cool, right? You get the point. Pipes helps you add your business rules, so you can transform the data before it’s actually displayed in the templates. A good way to relate Angular Pipes is similar to Angular 1.x filters. Pipes do a lot more than just filtering. We have used Angular Router to define Route Path, so we have all the Pipes functionalities in one page. You can create in same or different apps. Feel free to use your creativity. In Angular 1.x, we had filters–Pipes are replacement of filters. Defining a Pipe The pipe operator is defined with a pipe symbol (|) followed by the name of the pipe: {{ appvalue | pipename }} The following is an example of a simple lowercase pipe: {{"Sridhar Rao" | lowercase}} In the preceding code, we are transforming the text to lowercase using the lowercase pipe. Now, let’s write an example component using the lowercase pipe example: @Component({ selector: 'demo-pipe', template: ` Author name is {{authorName | lowercase}} ` }) export class DemoPipeComponent { authorName = 'Sridhar Rao'; } Let’s analyze the preceding code in detail: - We are defining a DemoPipeComponent component class - We are creating string variable authorName and assigning the value ‘Sridhar Rao’. - In the template view, we display authorName, but before we print it in the UI we transform it using the lowercase pipe Run the preceding code, and you should see the screenshot shown as follows as an output: Well done! In the preceding example, we have used a Built-in Pipe. In next sections, you will learn more about the Built-in Pipes and also create a few custom Pipes. Note that the pipe operator only works in your templates and not inside controllers. Built-in Pipes Angular Pipes are modernized version of Angular 1.x filters. Angular comes with a lot of predefined Built-in Pipes. We can use them directly in our views and transform the data on the fly. The following is the list of all the Pipes that Angular has built-in support for: DatePipe - DecimalPipe - CurrencyPipe - LowercasePipe and UppercasePipe - JSON Pipe - SlicePipe - async Pipe In the following sections, let’s implement and learn more about the various pipes and see them in action. DatePipe DatePipe, as the name itself suggest, allows us to format or transform the values that are date related. DatePipe can also be used to transform values in different formats based on parameters passed at runtime. The general syntax is shown in the following code snippet: {{today | date}} // prints today's date and time {{ today | date:'MM-dd-yyyy' }} //prints only Month days and year {{ today | date:'medium' }} {{ today | date:'shortTime' }} // prints short format Let’s analyze the preceding code snippets in detail: - As explained in the preceding section, the general syntax is variable followed with a (|) pipe operator followed by name of the pipe operator - We use the date pipe to transform the today variable - Also, in the preceding example, you will note that we are passing few parameters to the pipe operator. We will cover passing parameters to the pipe in the following section Now, let’s create a complete example of the date pipe component. The following is the code snippet for implementing the DatePipe component: import { Component } from '@angular/core'; @Component({ template: ` Built-In DatePipe `, })`, }) - DatePipe example expression Today is {{today | date}} {{ today | date:'MM-dd-yyyy' }} {{ today | date:'medium' }} {{ today | date:'shortTime' }} Let’s analyze the preceding code snippet in detail: - We are creating a PipeComponent component class. - We define a today variable. - In the view, we are transforming the value of variable into various expressions based on different parameters. Run the application, and we should see the output as shown in the following screenshot: We learned the date pipe in this section. In the following sections, we will continue to learn and implement other Built-in Pipes and also create some custom user-defined pipes. DecimalPipe In this section, you will learn about yet another Built-in Pipe–DecimalPipe. DecimalPipe allows us to format a number according to locale rules. DecimalPipe can also be used to transform a number in different formats. The general syntax is shown as follows: appExpression | number [:digitInfo] In the preceding code snippet, we use the number pipe, and optionally, we can pass the parameters. Let’s look at how to create a DatePipe implementing decimal points. The following is an example code of the same: import { Component } from '@angular/core'; @Component({ template: ` state_tax (.5-5): {{state_tax | number:'.5-5'}} state_tax (2.10-10): {{state_tax | number:'2.3-3'}} `, }) export class PipeComponent { state_tax: number = 5.1445; } Let’s analyze the preceding code snippet in detail: - We defie a component class–PipeComponent. - We define a variable–state_tax. - We then transform state_tax in the view. - The first pipe operator tells the expression to print the decimals up to five decimal places. - The second pipe operator tells the expression to print the value to three decimal places. The output of the preceding pipe component example is given as follows: Undoubtedly, number pipe is one of the most useful and used pipe across various applications. We can transform the number values specially dealing with decimals and floating points. CurrencyPipe Applications that intent to cater to multi-national geographies, we need to show country- specific codes and their respective currency values. That’s where CurrencyPipe comes to our rescue. The CurrencyPipe operator is used to append the country codes or currency symbol in front of the number values. Take a look the code snippet implementing the CurrencyPipe operator: {{ value | currency:'USD' }} Expenses in INR: {{ expenses | currency:'INR' }} Let’s analyze the preceding code snippet in detail: - The first line of code shows the general syntax of writing a currency pipe. - The second line shows the currency syntax, and we use it to transform the expenses value and append the Indian currency symbol to it. So now that we know how to use a currency pipe operator, let’s put together an example to display multiple currency and country formats. The following is the complete component class, which implements a currency pipe operator: }} Let’s analyze the the preceding code in detail: - We created a component class, CurrencyPipeComponent, and declared few variables, namely salary and expenses. - In the component template, we transformed the display of the variables by adding the country and currency details. - In the first pipe operator, we used ‘currency : USD’, which will append the ($) dollar symbol before the variable. - In the second pipe operator, we used ‘currency : ‘INR’:false’, which will add the currency code, and false will tell not to print the symbol. Launch the app, and we should see the output as shown in the following screenshot: In this section, we learned about and implemented CurrencyPipe. In the following sections, we will keep exploring and learning about other Built-in Pipes and much more. }} The LowercasePipe and UppercasePipe, as the name suggests, help in transforming the text into lowercase and uppercase, respectively. Take a look at the following code snippet: Author is Lowercase {{authorName | lowercase }} Author in Uppercase is {{authorName | uppercase }} Let’s analyze the preceding code in detail: - The first line of code transforms the value of authorName into a lowercase using the lowercase pipe - The second line of code transforms the value of authorName into an uppercase using the uppercase pipe. Now that we saw how to define lowercase and uppercase pipes, it’s time we create a complete component example, which implements the Pipes to show author name in both lowercase and uppercase. Take a look at the following code snippet: import { Component } from '@angular/core'; @Component({ selector: 'textcase-pipe', template: ` Built-In LowercasPipe and UppercasePipe ` }) export class TextCasePipeComponent { authorName = "Sridhar Rao"; }` }) export class TextCasePipeComponent { authorName = "Sridhar Rao"; } - LowercasePipe example Author in lowercase is {{authorName | lowercase}} - UpperCasePipe example Author in uppercase is {{authorName | uppercase}} Let’s analyze the preceding code in detail: - We create a component class, TextCasePipeComponent, and define a variable authorName. - In the component view, we use the lowercase and uppercase pipes. - The first pipe will transform the value of the variable to the lowercase text. - The second pipe will transform the value of the variable to uppercase text. Run the application, and we should see the output as shown in the following screenshot: In this section, you learned how to use lowercase and uppercase pipes to transform the values. JSON Pipe Similar to JSON filter in Angular 1.x, we have JSON Pipe, which helps us transform the string into a JSON format string. In lowercase or uppercase pipe, we were transforming the strings; using JSON Pipe, we can transform and display the string into a JSON format string. The general syntax is shown in the following code snippet: {{ myObj | json }} Now, let’s use the preceding syntax and create a complete component example, which uses the JSON Pipe: import { Component } from '@angular/core'; @Component({ template: ` Author Page{{ authorObj | json }}` }) export class JSONPipeComponent { authorObj: any; constructor() { this.authorObj = { name: 'Sridhar Rao', website: '', Books: 'Mastering Angular2' }; } } Let’s analyze the preceding code in detail: - We created a component class JSONPipeComponent and authorObj and assigned the JSON string to the variable. - In the component template view, we transformed and displayed the JSON string. Run the app, and we should see the output as shown in the following screenshot: JSON is soon becoming defacto standard of web applications to integrate between services and client technologies. Hence, JSON Pipe comes in handy every time we need to transform our values to JSON structure in the view. Slice pipe Slice Pipe is very similar to array slice JavaScript function. It gets a sub string from a strong certain start and end positions. The general syntax to define a slice pipe is given as follows: In the preceding code snippet, we are slicing the e-mail address to show only the first four characters of the variable value email_id. Now that we know how to use a slice pipe, let’s put it together in a component. The following is the complete complete code snippet implementing the slice pipe: import { Component } from '@angular/core'; @Component({ selector: 'slice-pipe', template: ` Built-In Slice Pipe ` }) export class SlicePipeComponent { emailAddress = "[email protected]"; }` }) export class SlicePipeComponent { emailAddress = "[email protected]"; } - LowercasePipe example - LowercasePipe example Sliced Email Id is {{emailAddress | slice : 0: 4}} Let’s analyze the preceding code snippet in detail: - We are creating a class SlicePipeComponent. - We defined a string variable emailAddress and assign it a value, [email protected]. - Then, we applied the slice pipe to the {{emailAddress | slice : 0: 4}} variable. - We get the sub string starting 0 position and get four characters from the variable value of emailAddress. Run the app, and we should the output as shown in the following screenshot: SlicePipe is certainly a very helpful Built-in Pipe specially dealing with strings or substrings. async Pipe async Pipe allows us to directly map a promises or observables into our template view. To understand async Pipe better, let me throw some light on an Observable first. Observables are Angular-injectable services, which can be used to stream data to multiple sections in the application. In the following code snippet, we are using async Pipe as a promise to resolve the list of authors being returned: The async pipe now subscribes to the observable (authors) and retrieve the last value. Let’s look at examples of how we can use the async pipe as both promise and an observable. Add the following lines of code in our app.component.ts file: getAuthorDetails(): Observable { return this.http.get(this.url).map((res: Response) => res.json()); } getAuthorList(): Promise { return this.http.get(this.url).toPromise().then((res: Response) => res.json()); } Let’s analyze the preceding code snippet in detail: - We created a method called getAuthorDetails and attached an observable with the same. The method will return the response from the URL–which is a JSON output. - In the getAuthorList method, we are binding a promise, which needs to be resolved or rejected in the output returned by the url called through a http request. In this section, we have seen how the async pipe works. You will find it very similar to dealing with services. We can either map a promise or an observable and map the result to the template. To summarize, we demonstrated Angular Pipes by explaining in detail about various built-in Pipes such as DatePipe, DecimalPipe, CurrencyPipe, LowercasePipe and UppercasePipe, JSON Pipe, SlicePipe, and async Pipe. Read Next Get Familiar with Angular Interview – Why switch to Angular for web development Building Components Using Angular
https://hub.packtpub.com/angular-pipes-angular-4/
CC-MAIN-2020-05
refinedweb
2,268
51.68
.2: Robots and Options About This Page Questions Answered: How can I use Option more deftly? Let’s keep working on the Robots app of Chapter 8.1, shall we? Topics: Higher-order methods on Options. The robot simulator. What Will I Do? Read and program. There’s a slew of multiple-choice questions to practice on at the end. Rough Estimate of Workload:? Under two hours. Points Available: B45. Related Projects: Robots. Robot Turns The methods advanceTurn and advanceFullTurn in RobotWorld are supposed to let the robots take their turns in a round-robin fashion. They can do that by calling takeTurn in class RobotBody, which instructs a specific robot to act. First, let’s see how we can implement the latter method. There’s a draft in the given RobotBody code: def takeTurn() = { if (this.isMobile) { // TODO: call the brain's moveBody method (if there is a brain) } } The following mini-assignment serves both as a recap and as an introduction to the upcoming topics: When our program needs to do something simple, it would be nice if we could express that behavior simply. That’s one of the reasons why we now take a little break from the robots and learn some new techniques. A Number-Finding Problem Consider a simple, separate example. Let’s say we have a vector of integers and we mean to find the first “big” number (defining big as “over 10000”, for example) as well as the first negative number; moreover, our goal is to determine whether or not those numbers are even. We can use find to locate the numbers in the vector. It returns a result as an Option: val numbers = Vector(10, 5, 4, 5, -20)numbers: Vector[Int] = Vector(10, 5, 4, 5, -20) val possibleBigNum = numbers.find( _ > 10000 )res0: Option[Int] = None val possibleNegativeNum = numbers.find( _ < 0 )res1: Option[Int] = Some(-20) We can’t use the modulo operator % on an Option[Int], which is “a number that may not exist”: possibleNegativeNum % 2 == 0<console>:10: error: value % is not a member of Option[Int] The problem is the same as in takeTurn above: we mean to perform out an operation only in case a particular value exists. Choosing a result type There are three different cases: the number was found and is even; the number was found an is odd; or the number wasn’t found so we can’t say anything about its evenness. We need our program to attend to each of these three possible outcomes. Option[Boolean] works for representing the result. Let’s use it like this: - If findreturns None, the result is Noneas well. - If findreturns a Somethat contains an even number, the result is Some(true). - If findreturns a Somethat doesn’t contain an even number, the result is Some(false). One way to implement this scheme is to use match: An okay solution with match val possibleBigNum = numbers.find( _ > 10000 ) val bigIsEven = possibleBigNum match { case Some(firstBig) => firstBig % 2 == 0 case None => None } Like our takeTurn implementation earlier, this code is a bit verbose considering how simple our goal is. We can do better. Let’s adopt a new perspective on the Option class. Option as a Collection An Option object is a collection: it contains a number of elements of a specific type. It’s just that it’s a very simple sort of collection: the number of elements is either zero or one. None is a collection with zero elements and Some(x) is a collection whose only element is x. The authors of the Scala API, too, have treated Option as a kind of collection. The Option class is designed so that it has the same methods as other collections do! Let’s try some methods on a Some object, a single-element collection. Some as a collection We can call foreach on a Some: the parameter function is then executed on whichever value is wrapped therein. val experiment = Some("Here I am")experiment: Some[String] = Some(Here I am) experiment.foreach(println)Here I am filter returns either the original Some, or None: experiment.filter( _.length < 100 )res2: Option[String] = Some(Here I am) experiment.filter( _.length >= 100 )res3: Option[String] = None exists and forall work as you might expect: experiment.exists( _.length >= 100 )res4: Boolean = false experiment.exists( _.length < 100 )res5: Boolean = true experiment.forall( _.length < 100 )res6: Boolean = true map produces another Some object that contains a value computed from the value in the original Some: experiment.map( _.toUpperCase + "!!!" )res7: Option[String] = Some(HERE I AM!!!) None as a collection Now let’s try these methods on None, a zero-element collection. As with other empty collections, foreach simply doesn’t do anything: val experiment2: Option[String] = Noneexperiment2: Option[String] = None experiment2.foreach(println) filter and map always return None since there’s no element to work with: experiment2.filter( _.length < 100 )res8: Option[String] = None experiment2.map( _.toUpperCase + "!!!" )res9: Option[String] = None Similarly, exists returns false: experiment2.exists( _.length >= 100 )res10: Boolean = false experiment2.exists( _.length < 100 )res11: Boolean = false forall, on the other hand, always returns true since any given condition holds for all of the collection’s zero elements. Or, if you prefer: since there are zero elements, there exists no value for which the given condition does not hold. experiment2.forall( _.length >= 100 )res12: Boolean = true A Niftier Solution to the Number-Finding Problem Let’s start again from the following code: val numbers = Vector(10, 5, 4, 5, -20)numbers: Vector[Int] = Vector(10, 5, 4, 5, -20) val possibleBigNum = numbers.find( _ > 10000 )res13: Option[Int] = None val possibleNegativeNum = numbers.find( _ < 0 )res14: Option[Int] = Some(-20) Let’s write a function that checks a given number’s parity and pass that function to map. In other words, let’s issue this command: “Check the evenness of any element within the Option that find returned.” possibleBigNum.map( _ % 2 == 0 )res15: Option[Boolean] = None Now, if it happens that the Option is empty, as above, the result is also None. On the other hand, if the Option wrapper contains a value, our code applies the parity-checking function to that value and gives us the result in a Some: possibleNegativeNum.map( _ % 2 == 0 )res16: Option[Boolean] = Some(true) This solution attends to all three scenarios: we either find an even number, find an odd number, or find nothing. Above, we used a variable for illustration, but of course the shorter versions below work, too. numbers.find( _ > 10000 ).map( _ % 2 == 0 )res17: Option[Boolean] = None numbers.find( _ < 0 ).map( _ % 2 == 0 )res18: Option[Boolean] = Some(true) Example: The tempo Function For another example of map on an Option, consider this implementation for the tempo function of Chapter 4.5: def tempo(music: String) = music.split("/").lift(1).map( _.toInt ).getOrElse(120)tempo: (music: String)Int tempo("cccedddfeeddc---/150")res19: Int = 150 tempo("cccedddfeeddc---")res20: Int = 120 split(Chapter 4.5) and lift(Chapter 4.2). The first method call returns the two substrings on either side of the slash character. The second gives us an Option[String]that contains the substring that follows the slash, if it exists. liftgives us a possible string, we can use combination of mapand toIntas turn it into a possible integer. Example: Preferences Our goal: optional settings in user profiles Imagine we’re working on an application that uses the simple class below for representing the app’s users’ personal preference settings. As things stand, the application has only two different settings: 1) the user’s preferred language and 2) whether or not the user prefers the metric system of units. Each of those settings is optional: a user may have recorded their preference on them or not. That fact has been modeled with Options: class Preferences(val profileName: String, val language: Option[String], val metricSystem: Option[Boolean]) { // add toString etc. here } A couple of usage examples: val test = new Preferences("My preferred settings", Some("English"), None)test: Preferences = lang: English, metric: NOT SET val test2 = new Preferences("Some other settings", Some("Finnish"), Some(true))test2: Preferences = lang: Finnish, metric: true Let’s also assume that each user either has or hasn’t created a profile for themselves. That is, each user either has or doesn’t have a Preferences object associated with them, which we can represent as an Option[Preferences]. See below for three instances: Tiina has created a profile and set their preferences, Fang also has a profile but hasn’t stated their language preference, and Ben has no profile at all: Given that information, how can we generate a String that tells us which language the app’s GUI should use for each of these users? If a user has a profile that names a language, we’d like to use that. If the user either doesn’t have a profile or their profile doesn’t specify a preferred language, we’d like to use English as the default language. Let’s sketch out a solution in the REPL. Towards a solution To determine which language to use for Tiina, we might try this first: tiinasPreferences.language<console>:20: error: value language is not a member of Some[Preferences] tiinasPreferences.language ^ That doesn’t work, since a user may not have a profile. A Some doesn’t have a language, but its contents do. Let’s use map, just like we did in the number-finding example: tiinasPreferences.map( _.language )res21: Option[Option[String]] = Some(Some(Finnish)) Option[Option[String]]. tiinasPreferencesisn’t Nonebut a Preferencesobject wrapped in a Some. That object’s languageisn’t Noneeither but the string "Finnish"wrapped in a Some. Therefore, when you mapfor the languageof a Preferencesobject, you get a Someinside another. flatten eliminates the nesting: tiinasPreferences.map( _.language ).flattenres22: Option[String] = Some(Finnish) In what is hopefully a familiar maneuver by now, we can combine map and flatten into flatMap: tiinasPreferences.flatMap( _.language )res23: Option[String] = Some(Finnish) This gives us Tiina’s language preferences within an Option[String]. Some(Finnish) informs us that there is a language preference and it is for Finnish. Our goal was to use the user’s preferred setting if available and a default language otherwise. getOrElse does the job: val tiinasLanguage = tiinasPreferences.flatMap( _.language ).getOrElse("English")tiinasLanguage: String = Finnish The solution as a function Let’s abstract our example into a function that uses a (possibly missing) user profile to determine the GUI language: def chooseLanguage(prefs: Option[Preferences]) = prefs.flatMap( _.language ).getOrElse("English")chooseLanguage: (prefs: Option[Preferences])String We can apply this function to each of our three example users: val tiinasLanguage = chooseLanguage(tiinasPreferences)tiinasLanguage: String = Finnish val fangsLanguege = chooseLanguage(fangsPreferences)fangsLanguege: String = English val bensLanguage = chooseLanguage(bensPreferences)bensLanguage: String = English An additional example Here’s the toString method for Preferences. It contains an additional example of calling map on an Option. class Preferences(val profileName: String, val language: Option[String], val metricSystem: Option[Boolean]) { override def toString = { def describe(name: String, value: Option[String]) = name + ": " + value.getOrElse("NOT SET") describe("lang", this.language) + ", " + describe("metric", this.metricSystem.map( _.toString )) } } Yes, we could have used match, but not as neatly This works: def chooseLanguage(prefs: Option[Preferences]) = { val languagePref = prefs match { case Some(existingPrefs) => existingPrefs.language case None => None } languagePref match { case Some(pref) => pref case None => "English" } } Example: Passenger In Chapter 4.4, you wrote a Passenger class that relied on another class, TravelCard. Passenger’s canTravel method was implemented using match: class Passenger(val name: String, val card: Option[TravelCard]) { def canTravel = this.card match { case Some(actualCard) => actualCard.isValid case None => false } } Now you know that it’s also possible to write: class Passenger(val name: String, val card: Option[TravelCard]) { def canTravel = this.card.exists( _.isValid ) } More generally, we can say that these two snippets of code accomplish the same thing: x match { case Some(content) => someCondition(content) case None => false } x.exists(someCondition) xrefers to some object of type Option. someConditionis a function that operates on the Option’s contents and returns a Boolean. exists is just one Option method that you can use instead where you might otherwse use match. You’ll find opportunities to use these methods as we now return to the Robots project: Robot Movements In Chapter 8.1, you did the first two parts of the Robots assignment. Now on to the next two. Here are couple of hints that are useful both now and in later parts of the assignment: Optionis a collection.” It really helped. exists, forall, and foreachare fantastic on Options. Try to solve the assignments in this chapter and the next without matching on Options. Use the higher-order methods instead. Robots, Part 3 of 8: turns and Spinbots - Implement takeTurnas outlined at the top of this chapter. This should be quite simple as long as you pick the right tool for dealing with the optional robot brain. RobotBodyalso needs the spinClockwisemethod. Implement it. - In class Spinbot, the moveBodymethod doesn’t do anything. Implement it. - In class RobotWorld, the methods nextRobot, advanceTurn, and advanceFullTurnare missing. Implement them. Use higher-order methods on collections where appropriate. - Run your code and see if Spinbots work now. Also try breaking down a robot in the GUI and make sure the robot no longer spins. Robots, Part 4 of 8: restrictions on movement Some methods are still missing from RobotBody. - Implement neighboringSquare, canMoveTowards, and isStuck. - Submit your solution to Parts 3 and 4. A+ presents the exercise submission form here. We’ll continue with the robots in the next chapter. First, though, use the questions below to practice on and check your understanding of Options. Practice on Options What was the lesson there? Most of the things you might wish to do with an Option are simple if you pick the right method for the task. You can use higher-order methods on Options to write code that is compact and yet understandable — at least if you can expect the reader to be familiar with these common methods. Whether you select with if and match or use these higher-order methods is up to you. Either way, you should be aware of both alternatives. Using a for loop to process an Option, as in the last question above, is often convenient, too. How are your robots? If you didn’t yet use the Option methods in your Robots implementation, do that know; you’ll learn something. Can you eliminate all matches? Additional practice questions If you didn’t get your fill yet, you can continue practicing Optional thinking by answering the following questions that again ask you to pick the method that corresponds to the given piece of code. Each of these code snippets features the get method, which simply returns the contents of an Option wrapper, or crashes at runtime in case of None. As mentioned near the end of Chapter 4.3, you should abstain from using this method, which is just calling out for a careless mistake. We’ve used get below not to suggest that you do so but the opposite: to show you that you don’t need this method. More questions to read and think about - So, Optionis a collection. How about using a regular collection instead? For instance, you might use a buffer with at most one element. Why or why not do that? - Find out what Scala’s Eitherclass is and how it is similar to and different from Option. Also look up the this trio of classes: Try, Success, Failure. - Perhaps you’d like to read what has been said about the possible overuse of Option. Can you find any example code in this chapter that might be better expressed differently? On a related note, you may find the Null Object design pattern interesting. Summary of Key Points - An Optionobject is a collection of elements. It contains zero or one elements. Optionobjects have the methods you know from other collection types: foreach, exists, map, flatMap, etc. With these methods, “values that are maybe there” are easier to work with. - Sure, you can use match, too, but you’ll probably prefer the methods once you get to know them. - You can also process an Optionwith a forloop. - Glossary: Option, collection, higher.
https://plus.cs.aalto.fi/o1/2018/w08/ch02/
CC-MAIN-2020-24
refinedweb
2,740
56.55
Discord is now Scala’s main chat platform. Please join us at @prayagupd Well surely I can, and it does what I wanted, I just was expecting some nicer DSL... I think I had a similar problem a few months ago and I solve it that way, so I was thinking it was a repetitive enough requirement to have an especial treatment. Anyways, Thanks a lot :+1: def earliestFilm = mcTiernan.films.foldLeft(Int.MaxValue) { (current, film) => math.min(current, film.yearOfRelease) val films = directors.flatMap(director => director.films) def averageScore:Int = films.foldLeft(0)((a, b) => a.imdbRating + b.imdbRating) / films.length
https://gitter.im/scala/scala?at=5b99f0c6fcba1254faaa9ae0
CC-MAIN-2022-40
refinedweb
102
60.82
Distribute is a project that tries to think about how distutils can evolve Interesting discussion are happening in distutils-SIG. You can read the threads This page tries to synthetizes these threads and see what could be done to improve package managment in Python. It is not clear right now if a new development will happen outside distutils or not. But this page can be the place where we structure things and decide of the best plan. Another great ressource to get the whole picture is Kevin Teague's post in Django Mailing list. Chris Withers made a presentation called Python Package Management Sucks at PyCon Uk in september 2008. Related Docs DistributeSprint #1 : Starting a PEP series Packaging Survey : Survey for the Python Language Summit 2009 distutils-autoconf : Proposal by David Defend Against Fruit Docs: Continuous Deployment considerations and Python package management Related PEPs What do we have today ? Distutils This is a really high-level view of Distutils. It is just made to understand its mechanisms, so if you are not used to it you can get it. Right now in Python, Distutils provides a set of commands to create a distribution of your package. It uses a set of metadata that describes the package and build an archive with the source code. These metadata are described in PEP 345. Distutils uses "commands" that can be combined to build various distributions. These commands are invoked through the command line, as long as the package provides the distutils-enable setup.py file, but that is conventionnaly the case: $ cd my_python_package $ python setup.py COMMAND So basically, building a source distribution is done by calling "sdist": $ cd my_python_package $ python setup.py sdist "sdist" calls other commands ("low level" commands) and builds an archive in the "dist" directory. From there, someone who wants to install a package can get the source distribution, and run the "install" command: $ wget $ tar -xzvf my_python_package.tgz $ cd my_python_package $ python setup.py install This command will inject the package into Python's site-packages so it is installed. There are other commands available to make various flavors to distribute your package. Binary distributions, and even OS-specific distributions, like RPM, that maps some metadata to the RPM system ones. Distutils is also used to upload you package to PyPI or any website that implements the protocol. Some PyPI-enabled websites are starting to be launched. For instance plone.org is about to switch its products center to a PyPI-enabled system. So developers sends their package like this $ python setup.py register sdist upload This command registers the package to PyPI, builds a source archive, and upload it. Python 2.6 has been changed so you can do it with any website and several accounts, like this for instance: $ python setup.py register sdist upload -r plone.org Setuptools Setuptools can be seen as an enhancement of Distutils. It does a lot of things, and this section will not present everything. You might want to read Phillip's page on the project. But basically it adds 4 major features a lot of people use: - a new metadata called install_requires where you can list the names of the packages the package uses - a namespaced package feature à la Java, that let you create several package under the same namespace, without having to distribute them in the same package. - some new commands like: - "develop", that will let you link a package you are currently working in into you Python environnement - without having to install it for real. See it as a special symbolic link inside Python site-packages. - "test", that will let you link a tets runner to the package tests - easy_install (described later) real-world example Zope used setuptools namespace feature to split its huge code base into small packages. For instance zope.interface is distributed as a single package and has its own developement cycle. In a way, Instead of downloading one 100MB package called Zope that contains the whole zope.* source tree, you download 100 packages of 1MB. And zope.whatever can use the new version of zope.interface, without having to wait for a 6 months-based release of Zope. So zope.whatever, declares in its setup.py environment zope.interface, with the right version: setup(name='zope.whatever', ... install_requires=['zope.interface>=1.2.4'] ... ) This will tell Setuptools that zope.whatever needs zope.interface 1.2.4 or higher to work. And if you try to install it, Setuptools will check if it is installed. If not it will try to get it at PyPI and instal it. Paver Paver subsumes the build tool portion of distutils/setuptools. It allows python programmers to use all of the setuptools/distutils commands but makes it easy to add new commands and modify the existing ones. Extensibility is easy in both the declarative portion of the files (adding new pieces of information about a package) and the imperative portion (adding new commands to perform.) Converting a simple setup.py that only has declarations to a pavement.py file is trivial. Defend Against Fruit Defend Against Fruit is focused on providing a pragmatic, continuous deployment style build system for Python. Current Python build systems do not properly account for the needs of effective continuous deployment. This package extends the Python tooling to add the missing pieces. With an eye to agile development principles and fast-feedback, we want a build system which satisfies the following goals: - Every SCM change-set committed should result in a potentially shippable release candidate. - When a defect is introduced, we want to immediately detect and isolate the offending SCM change-set. This is true even if the defect was introduced into a library we depend upon. - Library management should be so easy as to never impede code changes, even in multi-component architecture. For in-depth documentation with lots of pretty diagrams, take a look at the wiki. Other tools xxx What is good ? Distutils xxx Setuptools xxx Other tools xxx What is wrong ? Distutils The problems in distutils that where listed by people: - the code is old, and undertested - It does too many things ! - The layout and the metadata are not complete enough. For instance, it is not clear for an OS vendor what files should be put where in a FHS PoV - when you distribute your application with distutils, you have to prepare yourself all the binary and os-specific versions. You can't just give a source distribution that can be understood by everyone. Either it is push completely inside the Python installation, either you provide OS-specific installers. - documentation is weak and the code is hard to reverse engineer - hard for end user to override dynamically selected defaults; e.g. it finds the "right" compiler, flags, libraries, and so on, but it is not always right - no un-install - No provisions for installing applications or "private libraries". private libraries are libraries meant to be used by an application but not wanting to export a public API. Setuptools xxx Other tools xxx What can we do today ? Distutils - remove the log module and use logging - remove old-style Python code (work in progress, see latest patch in bugs.python.org) - finish the test coverage - propose an independant tool in a PEP, that knows how to register and upload a package at a PyPI compatible server this is started here: A new pypi module Setuptools xxx Other tools xxx What's next ? BUILDS is the code name of project for a "Build Utilities, Installation Locations, & Distribution Standards" (BUILDS) specification. As part of this specification, the PythonPackagingTerminology page documents the terms used in the Python packaging ecosystem. Create a web resource that documents the existing Python packaging ecosystem, tools and practices to make it easier for people to learn about how they can better manage their Python packaging needs. Design discussions: - Split the concerns
https://wiki.python.org/moin/Distribute?action=fullsearch&context=180&value=linkto%253A%2522Distribute%2522
CC-MAIN-2017-17
refinedweb
1,313
55.95
Okay I've got a homework assignment to write a program that reads integers, finds the TWO (2) largest of them, and counts their occurrences. I've managed to get the largest number but can I get any tips on how to find the second largest? Here is my code so far and thanks in advance! import java.util.Scanner; public class Unit4PT1 { public static void main (String [] args){ Scanner in = new Scanner(System.in); System.out.print("Enter numbers: "); int max = -1; int count = 0; int number; while((number = in.nextInt()) != 0){ if(number > max){ max = number; count = 1; } else if (number == max){ count++; } } System.out.println("The largest number is " + max); System.out.println("The occurence count of the largest number is " + count); } }
http://www.javaprogrammingforums.com/whats-wrong-my-code/29003-homework-help-using-max-method.html
CC-MAIN-2014-15
refinedweb
125
66.33
Ads Via DevMavens Metification – verb Pick one. Pick one. Service Pack 1 for Visual Studio 2008 has just arrived with new features, including version 1.0 of ADO.NET Data Services (a.k.a Astoria). From the description (highlighting is mine):. Compared to the traditional SOAP approach, the REST-style is a different model for exposing functionality over a web service. Instead of defining messages and exposing operations that act on those messages, you expose resources and act on the resources using common HTTP verbs. I’ve lately been thinking of SOAP based web services as “verb oriented” (exposing GetOrder and UpdateCustomer), while REST style web services are “noun oriented” (exposing Orders and Customers). Both models have advantages and disadvantages, but I’ve felt that REST partners well with rich, Internet applications that need to retrieve a variety of resources using the same filtering and paging parameters. Creating a heap of GetThisByThat operations is tedious. Noun and verbs aren’t the only difference between REST and SOAP. One of the primary strengths of REST is its inherent simplicity. The simplicity not only facilitates broad interoperability, but encourages an acceptance of REST from many who feel overwhelmed by the complexities of WS-*. There are no tools required for REST - all you need is the ability to send an HTTP request and read the response. WS-*, on the other hand, is great when you need a digitally signed message including double-secret user credentials routed through an asynchronous and distributed, two-phase commit transaction with an extended buyer protection. Not everyone needs that flexibility, but you still pay the price for the flexibility when using the tooling and the API, and when configuring the service. Although we could continue talking about differences in REST and SOAP, I wanted to talk about metadata, and Astoria. REST proponents, as a rule of thumb, shun metadata – but not all forms of metadata. Metadata in prose or written documentation is fine. Metadata in a self-describing response format is fine. However, metadata for tooling is seen by many as pure evil. Part of the complexity in WS-* is in the quirky and convoluted folds of metadata formats like WSDL and XML Schema. REST has seen some attempts at standardized metadata (WADL, WSDL 2.0, XSD), but still resists all attempts for the most part. I like metadata. Maybe I’ve been in the .NET ecosystem for so long that I expect tooling, but I still remember the first time I tried to write a program for the Flickr web service (which is technically just POX). I was shocked when I coudn’t find a WSDL file. Then I was surprised at how easy it was to craft the correct URL for an HTTP request, and shred apart the XML response to find photographs. It was so easy that ... well, it was just too easy. It reminded me of writing data access code from scratch. Data access code is so predictable and repetitive that we have tools, frameworks, and code generators to take care of the job. But those tools, frameworks, and code generators rely on metadata defined by a database schema, so their job is relatively straightforward. REST is a bit different, unless you are working with Astoria on the server and a CLR client. Let’s say you have some DTOs for employees, orders, and other objects you want to send over the wire. You’ll need to decorate them with enough information for the service to understand the primary key. [DataServiceKey("ID")]public class Employee{ public int ID { get; set; } public string Name { get; set; }}[DataServiceKey("ID")]public class Order{ // …} Next, define a class with public IQueryable<T> properties for each “entity set” (Employees and Orders). IQueryable<T> is easy to conjure up, and the class below represents a read-only data source with some fake in-memory data. If you need create, update, and delete functionality the class will need to implement IUpdateable, too. Sean Wildermuth has a three series blog post about IUpdateable that he wrote when implementing IUpdateable for the NHibernate LINQ project. public class AcmeData { public IQueryable<Employee> Employees { get { return new List<Employee> { new Employee() /* ... */, new Employee() /* ... */, new Employee() /* ... */ // ... }.AsQueryable(); } } public IQueryable<Order> Orders { // ... } // ...} Then you need an .svc file… <%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory, System.Data.Services, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Service="AcmeDataService" %> … and you’ll also need a code-behind file for the .svc (which is all setup for you using an ADO.NET data service template, you just add some configuration): public class AcmeDataService : DataService<AcmeData>{ public static void InitializeService(IDataServiceConfiguration config) { config.SetEntitySetAccessRule("Employees", EntitySetRights.AllRead); // ... more rules }} At this point you can start testing the service using a web browser and looking at, for example,. What is more interesting is looking at, because there you’ll find service metadata, which is where the magic starts. To consume the service, right-click on a project in Visual Studio and select “Add Service Reference…”. Yes – the same “Add Service Reference” command you might have seen in the hit motion picture “SOAP and WSDL – an XML Love Story”. This feature blurs the lines between REST and WS-*. Enter the root URL to the service and Visual Studio will generate a proxy – but not the type of proxy you receive when using SOAP based web services. This proxy will derive from DataServiceContext class and you can use it like so: var employees = new AcmeData(serviceRoot) .Employees .Where(e => e.Name == "Scott") .OrderBy(e => e.Name) .Skip(2) .Take(2) .ToList(); DataServiceContext does a little bit of magic to turn the LINQ query into the following HTTP request. It’s LINQ to REST: GET /AcmeDataService.svc/Employees() ?$filter=Name%20eq%20'Scott'&$orderby=Name&$skip=2&$top=2 HTTP/1.1User-Agent: Microsoft ADO.NET Data ServicesAccept: application/atom+xml,application/xml The data service will respond with some XML that the data context uses to create objects that look just like the server side DTOs. I’m sure some are horrified at this metification of REST, but. Beauty!
http://odetocode.com/blogs/scott/archive/2008/08/14/12239.aspx
crawl-002
refinedweb
1,018
55.64
Customizing Tilt Brush Part Two — Custom Tools: Flight Series So Far: Welcome back to my series of tutorials on how to customize Tilt Brush, which is now an open-source VR creativity suite. In this part, we’re going to go beyond simply creating new brushes and add completely new functionality to Tilt Brush with a custom tool! In Tilt Brush, almost everything we do is done with the help of tools. A tool can be something like the Straight Line tool, which applies a modifier to any new brushes created with the Free Paint tool, or it can be something like the Teleport tool, which moves the player. At the end of the day, a tool is simply a way for us to run some code in a nice compartmentalized way. For now, let’s add in a tool that will let us fly around, rather than using the default teleportation or translation tools. This tutorial will require some C# programming knowledge, so be ye warned! First, let’s actually create the button in the menu that will eventually be used to access our tool. We’ll place the tool in the advanced tools panel so that we have a bit more room. This panel is a prefab, contained in the Assets/Prefabs/Panels folder, and is named “AdvancedToolsPanel”. If you want to build for Quest, you’ll also need to perform the following operations on the “AdvancedToolsPanel_Mobile” prefab. Double-click it to open it, and notice that there’s totally space for one more tool in there. We could make the panel bigger easily enough, but for now let’s use that empty space. Move the two bottom buttons to the left to create some space, and then duplicate one of the other buttons to create a new button. Note that the mirror and straight edge buttons are not tool buttons! The mirror button is a ‘long press button’ and the straight edge button is an ‘option button’. So don’t duplicate either of those. Make sure that your new button has an ‘Option Button’ component on it. Name your new button object “Button_Fly” and make sure that it’s right underneath the “Button_Straightedge” object in the hierarchy. It’s good to keep things neat! Take a look at the Tool Button component on your new object. We’ll need to change the Description Text to read “Fly” — we’ll also need a 128x128 black and white image to use as the button texture. Feel free to create one, or use this one I’ve already created: Place this image in the Assets/Resources/Icons folder and name it “fly.png”. Now you can drag it on to the “Button Texture” property of your new button object. Finally, we need to change the “Tool” dropdown. But “Fly” isn’t an option! So we’ll need to add it. If you look at the code for ToolButton.cs, you’ll see that m_tool is of type BaseTool.ToolType. So head over to that file (Assets/Scripts/Tools/BaseTool.cs), find the ToolType enum and add a new line to the bottom — FlyTool! public class BaseTool : MonoBehaviour { public enum ToolType { SketchSurface, Selection, ColorPicker, BrushPicker, BrushAndColorPicker, SketchOrigin, AutoGif, CanvasTool, TransformTool, StampTool, FreePaintTool, EraserTool, ScreenshotTool, DropperTool, SaveIconTool, ThreeDofViewingTool, MultiCamTool, TeleportTool, RepaintTool, RecolorTool, RebrushTool, SelectionTool, PinTool, EmptyTool, CameraPathTool, //Custom FlyTool, } ..... Once we’ve done that, we can go back to our component and finally select “Fly Tool” as the tool type for our button! Save the prefab and go back to the main scene. Now it’s time to add our tool to the scene. In the main scene (Assets/Scenes/Main.unity), find the object SketchSurface, which is a child of SketchControls. Inside, you’ll see all the tools available, deactivated. Add a new empty child to this object, give it a scale of (0.5, 0.5, 0.5) and call it FlyTool — placing it just above the EmptyTool object. Any children of this object will be the 3D content that appears on the controller when the tool is activated. I chose to take the line renderer from the ‘bad teleport’ object in the teleport tool and to add a small sphere with the ‘pointer’ material to the end of it. To make things easier on ourselves, let’s place all the visual content as children of an empty ‘DirectionIndicator’ object which is a child of our tool. That will make it easier to turn on/off the indicator objects. Once you’re finished creating the tool, deactivate it. Now it’s time to actually create our tool’s functionality. Notice that all the other tools have their own custom components. These components live in the Assets/Scripts/Tools folder. These tools all inherit from the class BaseTool and override a few key methods to do what they need to do. So let’s create a new script in this folder and call it FlyTool.cs. Before we worry about actually making the user fly, let’s make sure that our tool is integrated and receiving controller input. Here’s a nice template tool script to get you started. It includes all the code necessary to show/hide the tool at the appropriate times and to ensure the tool stays attached to the controller: Now we can add this new component to our FlyTool object in the scene, ensure that that tool type is set to FlyTool and press play! You should see your new custom tool in the advanced tool panel, and when you select it, you should see the tool geometry you built appear attached to your hand. From here, we could add any functionality to the tool that we want, but let’s keep going and add the flight functionality that we’re after. We’d like our flight to be smooth and comfortable, but just to get things up and running, let’s do things in the simplest possible way just so we can see how controller input works in Tilt Brush. All of this code was extracted by looking at how the TeleportTool works — if you want to get something done ‘the Tilt Brush way’, take a look at the most-similar functionality built into the original app! Modify your UpdateTool function to look like this: We ask the Tilt Brush input manager to tell us whether the Fly command is currently true or not, and if it is we apply a scene translation equal to the reverse of the tool controller’s forward direction (making it feel like the player is moving in the controller’s forward direction) Right now there’s an error — there is no “Fly” command in the InputManager SketchCommands! So let’s go and add it. Head to the file Assets/Scripts/InputManager.cs and look for the SketchCommands enum — you simply need to add “Fly” at the bottom! That removes the error, but right now that command will always be false, since there’s never anything telling it to be true! So now, scroll down (still in InputManager) until you find the GetCommand function. We need to pass the command through to the Brush (which is the hand that does the drawing. Update the function to look like this (note lines 37 and 38): Finally, we can find the Brush.GetCommand function in the file Assets/Scripts/Input/ControllerInfo.cs and update it to look like this (note lines 27 and 28): Also note that we didn’t need to choose the trigger button here! As you can see, we could easily have chosen a different one! If you now press play, you should be able to fly around in the direction the tool is pointed while the trigger is pressed! At this point we’re more-or-less done with the lesson on how to add new tools to Tilt Brush. You should be able to imagine how you could poll different controller buttons, use button combinations to enable different kinds of behaviours, show different visual indications of tool state and inspect existing Tilt Brush tools to investigate ways to use the Tilt Brush API to make changes to your scene. In later tutorials, we’ll investigate how to create tools to let us modify the sketch itself. You might now like to try adding some more features to your flight tool — acceleration / deceleration would be a nice way to make the flight a little more comfortable, and it would be nice to be able to change the speed using some other controller inputs! This tutorial is just about how to make the tool itself, so I’ll leave it up to you to experiment. If you’d like to download a complete FlyTool script which includes acceleration, deceleration and an audio effect, you can find it at the gist linked here. Until next time, happy modding!
https://lachlansleight.medium.com/customizing-tilt-brush-3407f5ceb4ea?source=post_internal_links---------3----------------------------
CC-MAIN-2021-49
refinedweb
1,478
69.62
Exception does not show which line raised it Hi there, I'm new to sage, and made some sage scripts to improve my python scripts' performances. Then I load my script into a sage session, and run a test function. When I get exception, it shows me the traceback with functions names only, without the instruction that triggered it. For example : sage: f.runtest() Generating keys ... --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-3-abdb981a9bdb> in <module>() ----> 1 f.runtest() <string> in runtest(self) <string> in KeyGen(self) /home/hack4u/Download/SageMath/src/sage/rings/rational.pyx in sage.rings.rational.Rational.__mod__ (/home/hack4u/Download/SageMath/src/build/cythonized/sage/rings/rational.c:22716)() 2541 n = rat.numer() % other 2542 d = rat.denom() % other -> 2543 d = d.inverse_mod(other) 2544 return (n * d) % other 2545 /home/hack4u/Download/SageMath/src/sage/rings/integer.pyx in sage.rings.integer.Integer.inverse_mod (/home/hack4u/Download/SageMath/src/build/cythonized/sage/rings/integer.c:38530)() 6169 sig_off() 6170 if r == 0: -> 6171 raise ZeroDivisionError, "Inverse does not exist." 6172 return ans 6173 ZeroDivisionError: Inverse does not exist. And I have no idea which line in KeyGen does trigger that ZeroDivisionError. Any idea ? I think it's interesting that the traceback isn't longer (maybe use pdb or...). As to your specific question, maybe knowing what the code is would help find where your problem is. You seem to be looking for an inverse modulo a non-prime for something not in the ring of units, maybe you can see where you do that? In fact you didn't read my question. I don't want to resolve the exception, but I want to know which line raised it in my script. As you can see, I'm forced to make prints all along the code to search to place where there is an error. With the classic Python traceback, I can directly see where the error is : I did read the question, I'm just saying that as a practical matter that is all I can suggest. I don't know why there isn't a longer traceback, and I agree that is very annoying. Normally it should tell the line but perhaps something about .sageversus .pyscripts is the issue.
https://ask.sagemath.org/question/32811/exception-does-not-show-which-line-raised-it/?sort=oldest
CC-MAIN-2021-31
refinedweb
379
59.3
Revision history for Perl extension Plack-Middleware-Debug 0.18 2020-05-03 13:12:56 PDT - Fix the use of global jQuery function to allow loading multiple jQuery.js #43 0.17 2018-02-22 06:11:23 JST - Added support for loading debug middleware outside of the Plack::Middleware::Debug::* namespace, by prefixing the name of middleware with a "+", e.g. "+My::Plack::Middleware::Debug::Something". - Debug.pm no longer injects inline JavaScript 0.16 2013-09-06 11:41:25 PDT - Merge with upstream 0.15 2013-09-06 11:37:24 PDT - Convert to Milla - Fix broken latin-1 META.yml 0.14 Sun Sep 18 12:51:49 PDT 2011 - Fixed warnings (chiselwright) 0.13 Mon Jul 18 13:57:27 PDT 2011 - Fixed the way $spec mangling works (Jon Swartz) 0.12 Mon Mar 28 16:20:54 PDT 2011 - Added experimental TrackObjects panel - Fixed UUV warnings for Catalyst (jjn1016) 0.11 Fri Jan 14 10:54:53 PST 2011 - Fixed memory leaks in Parameters panel (jnap) - Fixed memory leaks in responses not HTML/XML (forwardever) 0.10 Wed Aug 25 12:43:54 PDT 2010 - Support panels in non-200 responses as well since they're useful for debugging anyway (haarg) 0.09 Tue May 4 16:24:09 PDT 2010 - Added new Parameters panel (franckcuny) 0.08 Sat May 1 04:56:08 PDT 2010 - Update Encode.pm dependency RT #57087 (jnareb) - Fixed packages - Moved git URL 0.07 Wed Feb 3 09:53:56 PST 2010 - No code change. Fixes the packaging issue due to the Module::Install::Share bug 0.06 Sat Jan 30 05:21:21 PST 2010 - Fixes UTF-8 issues when panels such as Env contains UTF-8 wide characters (Thanks to tomyhero) 0.05 Sat Jan 30 00:24:39 PST 2010 - Major refactoring of middleware panels: Now panels are also middleware - Support streaming interface as well (clkao) - Added Session middleware panel 0.04 Tue 2009.12.15 22:25:16 CET (Marcel Gruenauer <marcel@cpan.org>) - fixed 'uninitialized' warnings for undef values in vardump() (hanekomu) - fix POD typos (hanekomu) 0.03 Sun 2009.12.13 23:49:53 CET (Marcel Gruenauer <marcel@cpan.org>) - added CatalystLog panel (hanekomu, miyagawa) - Added ability to pass arguments and objects to panels (hanekomu) - circumvented a bug in Data::Dump(er) related typeglobs (miyagawa) - DBITrace panel takes an optional 'level' argument (trace level) (hanekomu) - nav_title() defaults to title() now, so need to set it in most panels (hanekomu) - added documentation (hanekomu) - fix a memory leak by declaring renderer only once (miyagawa) - added very basic tests (hanekomu) - Environment panel does its work in process_response() now - various small bug fixes and improvements (miyagawa, hanekomu) - refactoring (hanekomu) 0.02 Sun 2009.12.13 12:01:29 CET (Marcel Gruenauer <marcel@cpan.org>) - For debug information to be sent, the Content-Type should contain 'text/html'; it's not necessary that it's equal to it. So 'text/html; charset=utf-8' is ok as well (thanks tomyhero) 0.01 Sun 2009.12.13 01:12:58 CET (Marcel Gruenauer <marcel@cpan.org>) - original version
http://web-stage.metacpan.org/changes/distribution/Plack-Middleware-Debug
CC-MAIN-2021-10
refinedweb
521
58.38
I have extended Sale Order Line with parent / child hierarchy relationship because some lines (children) can be connected to others (parent) in the same Sale Order class SaleOrderLine(models.Model): _inherit = 'sale.order.line' _parent_name = 'my_parent_id' my_parent_id = fields.Many2one('sale.order.line', 'Operation for', index=True, domain='[("my_parent_id", "=", False)]', ondelete='cascade') my_children_ids = fields.One2many('sale.order.line', 'my_parent_id', 'Operations') I am presenting children records differently in the view (different row color, disabled re-sequennce, and so on) based on the `my_parent_id` field (and I am also dealing with re-sequencing of the children together with the parent and all the rest) which is working fine The problem I have is that I don't know how to properly add a new parent line with couple of children records on changing some field of an existing line (in the same Sale Order) Meaning that if I change the quantity of one line, based on some conditions of course, I need to add another parent line with couple of children lines. There are actually two problems, combined (examples of code below): Where exactly to put the code ? Most logical place would be in `sale_order_line.onchange('product_uom_qty')` But here I couldn't add even the single parent line using `self.new()` (it's just not showing up) although I'm on the same model, and using `self.create()` it's working but the new records do not show up until the user saves the Sale Order or just refresh / reloads it (as the records have been created into the DB using create() method) I did try also on `sale_order.onchange('order_line')` Here it's working to add the lines even with `new()` but the problem is that the parent / child relationship it's not held What method to use ? `sale_order_line.new()` - I would have preferred not to have the records saved into DB directly (in order to allow user to discard the change) but at least one method to work would be nice ... but this is not keeping the parent / child relationship Although if using debugger on the moment they're added, the connection between them seems fine using the NewIDs but as soon as the transaction finishes (I don't know which other code it's executing after my function) the relation drops (on next debug the relationship fields are empty) `sale_order_line.create()` - this seems to work, adding first the parent line and then connecting each child with the parent record ID, but the records do not show up in the view until user saves the Sale Order or simply refreshes / reloads the page `sale_order.update({'order_line': [(0, 0, {'product_id': parent, 'my_children_ids': [(0, 0, child products ...)]})` same issues as above Code examples: 1. using `sale_order_line.new()` inside `sale_order_line._onchange_product_uom_qty()` method not working at all, even for the single parent line, it doesn't show up ... # in my SaleOrderLine extension class @api.onchange('product_uom_qty') def _onchange_product_uom_qty(self): new_parent_line = self.new({ 'order_id': rec.order_id.id, 'product_id': 10, # I'm adding all the other required fields just to be sure ... 'name': 'Test parent', 'price_unit': 10, 'product_uom_qty': 1, }) 2. using `sale_order_line.create()` inside `sale_order_line._onchange_product_uom_qty()` method it's working, even adding child lines correctly, but: they are not visible to the user until Sale Order get's saved manually by the user (which does some kind of refresh afterwards) or entire page reloaded (as the records are already saved in the DB) Is there a method to save the Sale Order from code and automatically show the new records created ? it would have been nice to be able to use the discard functionality (like new()) - but anyway, at least one decent way to achieve what I need would be nice though (correct parent / child relationship and displayed to the user after the change ...) # in my SaleOrderLine extension class @api.onchange('product_uom_qty') def _onchange_product_uom_qty(self): new_parent_line = self.create({ # I need to use the _origin to take order integer ID instead of the NewID format in order to work correctly ... 'order_id': rec._origin.order_id.id, 'product_id': 10, # I'm adding all the other required fields just to be sure ... 'name': 'Test parent', 'price_unit': 10, 'product_uom_qty': 1, # this doesn't work to automatically create children records too ... # 'my_children_ids': [ # (0, 0, {child 1 values ...}), # (0, 0, {child 2 values ...}), # ], }) new_child_1_line = self.create({ 'my_parent_id': new_parent_line.id, # other child 1 values ... }) 3. using `sale_order.order_line.new()` from `sale_order._onchange_order_line()` The records show up, but the parent / child relation it's not kept Actually debugging the code during execution which adds them, the relationship seems fine (based on the NewIDs), but as soon as the code ends (and whatever the framework does afterwards) it seems that is broken I've debugged again and for those records the link fields (parent / child) are empty # in my SaleOrder extension class @api.onchange('order_line') def _onchange_order_line(self): new_parent_line = self.order_line.new({ 'order_id': self.id, 'product_id': 10, # I'm adding all the other required fields just to be sure ... 'name': 'Test parent', 'price_unit': 10, 'product_uom_qty': 1, 'my_children_ids': [ (0, 0, {child 1 values ...}), (0, 0, {child 2 values ...}), ] }) 4. using `sale_order.update({'order_line': [(0, 0, {parent values ...}]})` from `sale_order._omchange_order_line()` the same like point above, they appear but without parent / child relation # in my SaleOrder extension class @api.onchange('order_line') def _onchange_order_line(self): self.update({ 'order_line': [(0, 0, { 'order_id': self.id, 'product_id': 10, # I'm adding all the other required fields just to be sure ... 'name': 'Test parent', 'price_unit': 10, 'product_uom_qty': 1, 'my_children_ids': [ (0, 0, {child 1 values ...}), (0, 0, {child 2 values ...}), ] })] }) Are there any other ways to achieve what I need ? Thx,
https://www.odoo.com/th_TH/forum/chwyehluue-1/hierarchy-relationship-187438
CC-MAIN-2021-31
refinedweb
926
54.32
Understanding .NET Encryption These days, all you ever seem to see in the news are stories about websites getting hacked, and how many developers don't do enough to protect the applications they write from the bad guys. Although that may be true in some places, there's certainly no shortage of functionality built into the .NET framework to help you encrypt and secure your data. The 'System.Security.Cryptography' namespace has a treasure trove of functionality that allows you to perform hashes, two-way data encryption, and a good few utility scenarios related to both of those subjects. Technically, when it comes to encryption, there are actually two very different things you can do. The first scenario (usually known as hashing) is the process of taking some piece of input data and providing a one-way, cryptographic signature on it. MD5 is a very good example of this, whereby you can take any bit of input data and turn it into a 16-character signature that can never ever be used to obtain the original data. For a long time, standard hashes such as MD5 were the primary means by which passwords, user names, and other sensitive information were stored in many databases. These days however (especially with the rise in cheap, high-speed processing power), many ciphers like MD5 need extra data appending to them, such as a 'salt' value to protect them against massive checking databases known as 'Rainbow Tables'. This is not to say that things such as MD5 don't still have a use, however, as we'll see in just a moment. The second scenario typically addressed is the process of protecting data while it's in transit. For web server and http communication, this is typically handled automatically using the secure HTTPS protocol. There are, however, many other instances where you might want to encrypt a payload; one that springs to mind is Email. In this situation, the sender needs to be able to encrypt the contents of a message, then send that message over a public network, where the receiver can then un-encrypt that message, revealing the original contents for them to read. Among the functionality available in the .NET security namespace, this second case is handled by 'asymmetric public key encryption' amongst others. Some Practical Uses We'll take a look at a two-way example soon, but first let's take a quick look at one way MD5 can still help with a quite surprising task. As I mentioned in the previous section, MD5 is now relatively easy for those who have the means to reverse back to an original phrase. This is possible, because MD5 will always produce the same signature for the same input no matter how many times you ask it. The only way you can prevent this is by picking a random key, phrase, or some other extra bit of information known ONLY to the system this encryption is being performed on. This extra bit of information, known as a salt, then makes the data being encrypted different enough that the signature does not match what would be produced had the data just been encrypted on its own. However, forgetting about using this to encrypt something like passwords for a moment, there is actually one thing that MD5 is exceptionally good for, and that's detecting changes. Let's imagine, for a moment, that you have a library of corporate documents, and in a secure database somewhere, you've taken those documents, performed an MD5 hash of the contents of said documents, then saved that hash in a secure location. If one of those documents were then changed by an unauthorised person, it would be quite a simple process to loop through them all, reading out the contents, recalculating the hash and comparing it to the hash you have stored. Hashes are so good at detecting changes like this that many file protection programs and antivirus tools employ them in some way to help protect files on your system. A good hash can detect something as small as an individual bit being changed in a file, which also means there also very good at confirming a file you've downloaded has arrived without any encryption. The following code will take a simple string and produce an MD5 hash of that string for you: byte[] theHash; string simpleString = "Some Text The Hash"; using(MD5 md5 = MD5.Create()) { theHash = md5.ComputeHash (Encoding.ASCII.GetBytes(simpleString)); } This will produce a hash for the text in 'simpleString' as a byte array, which you then can use something like the following to turn into a hex number that you can easily use. StringBuilder strBuilder = new StringBuilder(); for (int index = 0; index < theHash.Length; index++) { strBuilder.Append(data[index].ToString("x2")); } string hexHash = strBuilder.ToString(); Putting this code into a console app and running it should give you something like the following Figure 1: Running a console app This was just using a simple constant string; however, using a file stream, or just grabbing all the bytes of a file into a byte array is just as simple. As way of a bit of food for thought, I actually have a utility I've written that uses this very method to look around on my hard drive for duplicate images and MP3 files. Moving on, however, let's get a bit more creative, and have a brief look at how to do the two-way encryption. Public key encryption works by having two security keys: one private, and one public. Each key can work only one way at a time; that is, either key can be used to Encrypt or Decrypt some data, but NEVER both. What this means in practice is that if you encrypt the data with one key, you need the other key to decrypt it. If you're sending data, then usually the intended recipient will make his/her public key available. You would then use this public key to encrypt the data, knowing that the recipient can then use their private key to decrypt the data and reveal the original payload. To use the public/private key encryption functions, you first need to generate a public & private key pair. Generating a suitable pair of files to use with RSA based encryption is relatively easy and can be achieved with the following code: private static CspParameters cspParameters; private static RSACryptoServiceProvider rsaProvider; private static string publicKey; private static string privateKey; // See // system.security.cryptography.cspparameters. // providertype(v=vs.110).aspx for other values = rsaProvider.ToXmlString(false); privateKey = rsaProvider.ToXmlString(true); File.WriteAllText(@"d:\publickey.xml", publicKey, Encoding.ASCII); File.WriteAllText(@"d:\privatekey.xml", privateKey, Encoding.ASCII); } This will save the public and private keys into the XML files specified, and then you can use those XML files when encrypting and decrypting text. Needless to say, the private key file needs to be stored away, far from prying eyes. Because the crypto provider produces standard strings, you can easily store the strings anywhere you please. I just popped them into XML files for convenience; it's up to you where you hide them. Once you've generated some keys, it's very easy to use them to encrypt some text, as the following code shows: = File.ReadAllText(@"d:\publickey.xml"); rsaProvider.FromXmlString(publicKey); unencryptedFile = Encoding.ASCII.GetBytes("This is some text for me to encrypt, it can't be too long."); encryptedFile = rsaProvider.Encrypt(unencryptedFile, true); File.WriteAllBytes(@"d:\encryptedtest.bin", encryptedFile); } One thing you have to be careful of, though, is that you can see the text I'm encrypting is not very long. RSA, because of the way it works, has a length restriction. This length restriction varies depending on how many bits you specify for the key, something I'm not doing here. I'm just going with the defaults. You might be thinking to yourself, what good is the API then, if I can't encrypt large payloads. Well, you can, and there are some (such as the Diffie Hellman algorithm) that allow you to do so. The main purpose with the two-way public/private key encryption routines is to allow secure transport of a smaller piece of information, such as a single symmetric password or key phrase, one that's to be kept secure only until the other party receives it. At that point, both parties would then keep this one key a secret between them both to work on larger volumes of data. For now, however, let's finish this post off by looking at the code that would be used to decrypt the string we previously encrypted.); privateKey = File.ReadAllText(@"d:\privatekey.xml"); rsaProvider.FromXmlString(privateKey); encryptedFile = File.ReadAllBytes(@"d:\encryptedtest.bin"); string unencryptedFileString = Encoding.ASCII.GetString(rsaProvider.Decrypt (encryptedFile, true)); } Dealing with full file streams and symmetric keys is a little too much for this article at the moment; we'll cover that in the future. For now, though, this will encrypt/decrypt small amounts of data. There's actually nothing stopping you from reading a file in small, known-size chunks and using this to encrypt an entire file. I definitely wouldn't recommend it, though. If there's a topic that interests you in .NET, or you've found a strange API you never knew was there and want to know how it works, please leave a comment below, I'll happily do what I can to write a post on it in this column. You also can generally find me hanging around in the Linked .NET users group (otherwise known as Lidnug) on the Linked-in platform, or you can find me on Twitter as @shawty_ds. DON'T USE MD5!!Posted by Andrew Fenster on 09/11/2017 02:02pm MD5 has now been cracked! There are free online websites where you can enter something hashed with MD5 and it will tell you the original un-hashed value. Just Google for "md5 online cracker." The same is true with SHA1. Before you pick a hash or encryption algorithm, you need to read up on the very latest security news to see if your chosen algorithm is still secure.Reply a typo in this articlePosted by Gjuro on 03/13/2017 11:58am I believe that line: " strBuilder.Append(data[index].ToString("x2"));" should actually say: " strBuilder.Append(theHash[index].ToString("x2"));" :-)Reply
https://www.codeguru.com/columns/dotnet/understanding-.net-encryption.html
CC-MAIN-2019-26
refinedweb
1,735
59.84
MALLOC(9) BSD Kernel Manual MALLOC(9) malloc - kernel memory allocator #include <sys/types.h> #include <sys/malloc.h> void * malloc(unsigned long size, int type, int flags); MALLOC(space, cast, unsigned long size, int type, int flags); void free(void *addr, int type); FREE(void *addr, int type); The malloc() function allocates uninitialized memory in kernel address space for an object whose size is specified by size. free() releases memory at address addr that was previously allocated by malloc() for re- use. The MALLOC() macro variant is functionally equivalent to (space) = (cast)malloc((u_long)(size), type, flags) and the FREE() macro variant is equivalent to free((caddr_t)(addr), type) These macros should only be used when the size argument is a constant. Unlike its standard C library counterpart (malloc(3)), the kernel version takes two more arguments. The flags argument further qualifies malloc()'s operational characteristics as follows: M_NOWAIT Causes malloc() to return NULL if the request cannot be im- mediately fulfilled due to resource shortage. Otherwise, mal- loc() may call sleep to wait for resources to be released by other processes. If this flag is not set, malloc() will never return NULL. Note that M_WAITOK is conveniently defined to be 0, and hence maybe or'ed into the flags argument to indicate that it's OK to wait for resources. Currently, only one flag is defined. The type argument broadly identifies the kernel subsystem for which the allocated memory was needed, and is commonly used to maintain statistics about kernel memory usage. The following types are currently defined: M_FREE Should be on free list. M_MBUF Mbuf memory. M_DEVBUF Device driver memory. M_DEBUG malloc debug structures. M_PCB Protocol control blocks. M_RTABLE Routing tables. M_FTABLE Fragment reassembly headers. M_IFADDR Interface addresses. M_SOOPTS Socket options. M_SYSCTL Sysctl persistent buffers. M_NAMEI Namei path name buffers. M_IOCTLOPS Ioctl data buffers. M_IOV Large IOVs. M_MOUNT VFS mount structs. M_NFSREQ NFS request headers. M_NFSMNT NFS mount structures. M_NFSNODE NFS vnode private part. M_VNODE Dynamically allocated vnodes. M_CACHE Dynamically allocated cache entries. M_DQUOT UFS quota entries. M_UFSMNT UFS mount structures. M_SHM SVID compatible shared memory segments. M_VMMAP VM map structures. M_VMPMAP VM pmap data. M_FILE Open file structures. M_FILEDESC Open file descriptor tables. M_PROC Proc structures. M_SUBPROC Proc sub-structures. M_VCLUSTER Cluster for VFS. M_MFSNODE MFS vnode private part. M_NETADDR Export host address structures. M_NFSSVC NFS server structures. M_NFSUID NFS uid mapping structures. M_NFSD NFS server daemon structures. M_IPMOPTS Internet multicast options. M_IPMADDR Internet multicast addresses. M_IFMADDR Link-level multicast addresses. M_MRTABLE Multicast routing tables. M_ISOFSMNT ISOFS mount structures. M_ISOFSNODE ISOFS vnode private part. M_MSDOSFSMNT MSDOS FS mount structures. M_MSDOSFSFAT MSDOS FS FAT tables. M_MSDOSFSNODE MSDOS FS vnode private part. M_TTYS Allocated tty structures. M_EXEC Argument lists & other mem used by exec. M_MISCFSMNT Misc. FS mount structures. M_ADOSFSMNT ADOSFS mount structures. M_ANODE ADOSFS anode structures and tables. M_ADOSFSBITMAP ADOSFS bitmap. M_EXT2FSNODE EXT2FS vnode private part. M_PFKEY Pfkey data. M_TDB Transforms database. M_XDATA IPsec data. M_VFS VFS file systems. M_PAGEDEP File page dependencies. M_INODEDEP Inode dependencies. M_NEWBLK New block allocation. M_VMSWAP VM swap structures. M_RAIDFRAME RAIDframe data. M_UVMAMAP UVM amap and related. M_UVMAOBJ UVM aobj and related. M_USB USB general. M_USBDEV USB device driver. M_USBHC USB host controller. M_MEMDESC Memory range. M_UFS_EXTATTR UFS Extended Attributes. M_CREDENTIALS ipsec(4) related credentials. M_PACKET_TAGS Packet-attached information tags. M1394CTL IEEE 1394 control structures. M1394DATA IEEE 1394 data buffers. M_EMULDATA Per process emulation data. M_IP6OPT IPv6 options. M_IP6NDP IPv6 neighbour discovery structures. M_IP6RR IPv6 router renumbering prefix. M_RR_ADDR IPv6 router renumbering interface identifiers. M_TEMP Miscellaneous temporary data buffers. M_NTFSMNT NTFS mount structures. M_NTFSNTNODE NTFS ntnode information. M_NTFSNODE NTFS fnode information. M_NTFSDIR NTFS directory buffers. M_NTFSHASH NTFS ntnode hash tables. M_NTFSVATTR NTFS file attribute information. M_NTFSRDATA NTFS resident data. M_NTFSDECOMP NTFS decompression temporary storage. M_NTFSRUN NTFS vrun storage. Statistics based on the type argument are maintained only if the kernel option KMEMSTATS is used when compiling the kernel (the default in current OpenBSD kernels) and can be examined by using 'vmstat -m'. malloc() returns a kernel virtual address that is suitably aligned for storage of any type of object. A kernel compiled with the DIAGNOSTIC configuration option attempts to detect memory corruption caused by such things as writing outside the al- located area and unbalanced calls to the malloc() and free() functions. Failing consistency checks will cause a panic or a system console mes- sage: • panic: "malloc - bogus type" • panic: "malloc: out of space in kmem_map" • panic: "malloc: allocation too large" • panic: "malloc: wrong bucket" • panic: "malloc: lost data" • panic: "free: unaligned addr" • panic: "free: duplicated free" • panic: "free: multiple frees" • panic: "kmeminit: minbucket too small/struct freelist too big" • "multiply freed item <addr>" • "Data modified on freelist: <data object description>" A kernel compiled with the MALLOC_DEBUG option allows for more extensive debugging of memory allocations. The debug_malloc_type, debug_malloc_size, debug_malloc_size_lo and debug_malloc_size_hi vari- ables choose which allocation to debug. debug_malloc_type should be set to the memory type and debug_malloc_size should be set to the memory size to debug. 0 can be used as a wildcard. debug_malloc_size_lo and debug_malloc_size_hi can be used to specify a range of sizes if the exact size to debug is not known. When those are used, debug_malloc_size needs to be set to the wildcard. M_DEBUG can also be specified as an allocation type to force allocation with debugging. Every call to malloc() with a memory type and size that matches the de- bugged type and size will allocate two virtual pages. The pointer re- turned will be aligned so that the requested area will end at the page boundary and the second virtual page will be left unmapped. This way we can catch reads and writes outside the allocated area. Every call to free() with memory that was returned by the debugging mal- loc will cause the memory area to become unmapped so that we can catch dangling reads and writes to freed memory. There are no special diagnostics if any errors are caught by the debug- ging malloc. The errors will look like normal access to unmapped memory. On a memory access error, the show malloc command in ddb(4) can be in- voked to see what memory areas are allocated and freed. If the faulting address is within two pages from an address on the allocated list, there was an access outside the allocated area. If the faulting address is within two pages from an address on the free list, there was an access to freed memory. Care needs to be taken when using the MALLOC_DEBUG option: the memory consumption can run away pretty quickly and there is a severe performance degradation when allocating and freeing debugged memory types. vmstat(8) MirOS BSD #10-current June 16,.
https://www.mirbsd.org/htman/sparc/man9/FREE.htm
CC-MAIN-2016-18
refinedweb
1,111
53.68
C# & ASP.NET Developer BLOG I have seen many versions of these and a lot of the time people are expecting that a bad word would be written complete, I.e. BADWORD. Sometimes they overlook the fact that others get hold of this rule and simply bypass by adding symbols in between, I.e. B*A*D*W*O*R*D. Of course this would not be recognized if simply searching the string for BADWORD. This technique I have used here relies on a base list in XML. I have created a class which is called BarWordFilter and with this I use the singleton pattern. I do this because the class has to first compile a list of Regexs from the words inside the base XML File, and as I do not want a re compilation of these at every bad word check, I have opted for the singleton pattern. for any word which is in the list the rendered pattern will follow a set trend. So if we look again at BADWORD, the regular expression I have come with would be as follows. ([b|B][\W]*[a|A][\W]*[d|D][\W]*[w|W][\W]*[o|O][\W]*[r|R][\W]*[d|D][\W]*) What I do is I create the pattern at runtime. I look for instances of lower or upper case, and ultimately anything which, if we ignore anything which is not a character, spells our bad word. I have create a simple test page here to have a go. Please note I have only got the real serious words in the list for the purposes of this demonstration. I have not published this list as I do not think it is necessary. I have used a simple XML structure so please feel free to copy the code here, and generate as many bad words as you like <s>. Example Page : using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; /// <summary> /// Summary description for BadWordFilter /// </summary> public class BadWordFilter { /// <summary> /// These are the options which I use in order to determine the way I handle any bad text /// </summary> public enum CleanUpOptions { ReplaceEachWord, BlankBadText, ReplaceWholeText } /// <summary> /// Private constructor and instantiate the list of regex /// </summary> private BadWordFilter() { // // TODO: Add constructor logic here // patterns = new List<Regex>(); } /// <summary> /// The patterns /// </summary> private List<Regex> patterns; public List<Regex> Patterns { get { return patterns; } set { patterns = value; } } private static BadWordFilter m_instance = null; public static BadWordFilter Instance { get { if (m_instance == null) m_instance = CreateBadWordFilter(HttpContext.Current.Server.MapPath("listofwords.xml")); return m_instance; } } /// <summary> /// Create all the patterns required and add them to the list /// </summary> /// <param name="badWordFile"></param> /// <returns></returns> protected static BadWordFilter CreateBadWordFilter(string badWordFile) { BadWordFilter filter = new BadWordFilter(); XmlDocument badWordDoc = new XmlDocument(); badWordDoc.Load(badWordFile); //Loop through the xml document for each bad word in the list for (int i = 0; i < badWordDoc.GetElementsByTagName("word").Count; i++) { //Split each word into a character array char[] characters = badWordDoc.GetElementsByTagName("word")[i].InnerText.ToCharArray(); //We need a fast way of appending to an exisiting string StringBuilder patternBuilder = new StringBuilder(); //The start of the patterm patternBuilder.Append("("); //We next go through each letter and append the part of the pattern. //It is this stage which generates the upper and lower case variations for (int j = 0; j < characters.Length; j++) { patternBuilder.AppendFormat("[{0}|{1}][\\W]*", characters[j].ToString().ToLower(), characters[j].ToString().ToUpper()); } //End the pattern patternBuilder.Append(")"); //Add the new pattern to our list. filter.Patterns.Add(new Regex(patternBuilder.ToString())); } return filter; } /// <summary> /// The function which returns the manipulated string /// </summary> /// <param name="input"></param> /// <param name="options"></param> /// <returns></returns> public string GetCleanString(string input, CleanUpOptions options) { if (options == CleanUpOptions.BlankBadText) { for (int i = 0; i < patterns.Count; i++) { //In this instance we want to return an empty string if we find any bad word if (patterns[i].Match(input).Success) return String.Empty; } } else if (options == CleanUpOptions.ReplaceWholeText) { for (int i = 0; i < patterns.Count; i++) { //In this instance we want to return a specified statement if we find any bad word if (patterns[i].Match(input).Success) return "The text contains unsuitable content"; } } else { for (int i = 0; i < patterns.Count; i++) { //In this instance we actually replace each instance of any bad word with a specified string. input = patterns[i].Replace(input, "**Unsuitable Word**"); } } //return the manipulated string return input; } } The XML file which I have used is below. Dead simple, but does the job. <?xml version="1.0" encoding="utf-8" ?> <words> <word>bad word</word> <word>ugly word</word> <word>bla bla bla</word> </words> Cheers, Andrew :-) Doesn't catch sh!t $hit or $h!t SarcasticBaldGuy Obviously it would be very difficult to interpret symbols for letters as you have pointed out, using dollar sign for S and exclamation mark for an i. Do you know of any current techniques which are used to counter act that. I would say that the bad word file should be used to a great degree, with obvious filters in place, and maybe a common mapping class for synbol to letter i.e. $ => S|s ! => \|| In fairness though, it is a judgement call, as what they have typed in that case would not be an offensive word, yet it could be interpretted as offensive. I would opt for the big difference there. I could write "I sh!t the door," so in this case I have attempted to spell shut and not the bad word expected from your example. My example is early doors and in need of refinement big time, but I feel the theory is sound and provides a good bounding block for other to build on. Thanks for the post, I appreciate the feedback!! what if user writes BADDWORD you should place a + after the letters bracket... ([b|B]+[\W]*[a|A]+[\W]*[d|D]+[\W]*[w|W]+[\W]*[o|O]+[\W]*[r|R]+[\W]*[d|D]+[\W]*) but again this sucks when user writes BAD-DWORD... or fuc-cker... i think it's really hard to clear them... ppl will find a way to surpass it.... Could you please post the code for the demo page, minus the XML file which is understandable. I converted your C# to VB but I'm having trouble using it. Hi Brian, sure. I have zipped the files for: here is the link. andrewrea.co.uk/.../BadWordFilter.rar Andrew Hi Enzo The problem with the current build is that it searches for the word as part or as a whole in any word. I think what you require is an enhancement to this where by you can differentiate the types of searches made i.e. part word searches or whole word searches. So in your case the word "for" would come under the latter so in effect the XML file would have to change to incorporate different methods of search or rather different conditions. I am thinking of staring this as a CodePlex Project so that I can continually update, I will do this either tomorrrow or the next day. If you would like access to make contributions to the small project, let me know and I will give you write access when it comes online at CodePlex. Any updates to the BadWordFilter.cs. I look for it in CodePlex and could not find it. Thanks, Dave To over come the issue with the words getting replaced that can possibly be added into the middle of a word for example brass will get cut if a** is in your xml. I added an attribute to the xml <word middleWord="true">filtered word</word> then in the code just check for the attibute being true. if its true my expression will have the /b added to the beginining and remove the astrix on the last char in the string. So using the badword example expression from above the new expression for only finding that word would be. \b([b|B][\W]*[a|A][\W]*[d|D][\W]*[w|W][\W]*[o|O][\W]*[r|R][\W]*[d|D][\W]) so if i typed abadword it would not find it. Basicly words can still be snuck through but should if careful give you some flexibility with what words you allow inside of words and what ones you dont Terrific application of dynamic creation of patterns and filtering offensive terms. Only noticeable drawback - all of the characters of the original word must be present, one workaround could be to make vowels optional - $h!t, cr@p - as well as making the $ interchangable with "S" by treating it like a consonant, or adding commonly used badword hacks to the definition list. Something like \b[a-zA-Z$$][/W]* ... [a-zA-Z$$]\b , keeping the character case insensitive, etc. Or, perish the thought, asking folks to be courteous and not use annoying text decoration$ in their on-line p!r@o#s$e. Honestly, how many words are spelled with symbols smack-dab in the middle? OK, smack-dab doesn't count. Gotta' start another list :o) Thanks for posting your solution - I plan on experimenting with this to provide some level of protection on my site's comments page. This seems to work fine for just changing the bad word in the textbox, but I can't seem to get it working with a custom validator for a Form View. I want to trigger an error to prevent the data from being inserted so that the author can rewrite stuff. A of now it just inserts things with "unwanted word" instead of what was originally there I tried the following to trigger an error: If text.Text = BadWordFilter.Instance.GetCleanString(text.Text, BadWordFilter.CleanUpOptions.ReplaceEachWord) Then args.IsValid = False End If Shouldn't this trigger an error preventing insertion of the data while also replacing the bad words? Here is an idea that would be fun, but not necessary. Can this be set up with each bad word in the XML file having a specific word to replace it. I am trying to stop people from bad mouthing my company on my own website without requiring human oversight. For example if someone says, "this is a bad company that should be sued" with the bad words being "bad" and "sued". Could "bad" be replaced with "great" and "sued" be replaced with "awarded for excellence" so that what ends up on the sites blog/forum reads "this is a great company that should be awarded for excellence"? I fixed my problem and need to stop coding at 4 AM with little sleep. To create an error message without inserting bad words into a database just add the following: VB.Net Dim mytext As TextBox = CType(myFormView.FindControl("myTextBox"), TextBox) Dim mytextcontent As String = mytext.Text mytextcontent = BadWordFilter.Instance.GetCleanString(mytextcontent,BadWordFilter.CleanUpOptions.ReplaceWholeText) Dim unsuitable As String = "The text contains unsuitable content" If mytextcontent = "The text contains unsuitable content" Then Else args.IsValid = True
http://weblogs.asp.net/andrewrea/archive/2008/05/03/bad-word-filter-with-regular-expressions.aspx
CC-MAIN-2014-15
refinedweb
1,832
62.98
The public static void main() method is the entry point of the Java program. Whenever you execute a program in Java, the JVM searches for the main method and starts executing from it. You can write the main method in your program with return type other than void, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this new method (with return type other than void) as the entry point of the program. It searches for the main method which is public, static, with return type void, and a String array as an argument. public static int main(String[] args){ } If such a method is not found, a run time error is generated. In the following Java program, we are trying to write the main method with the return type integer − import java.util.Scanner; public class Sample{ public static int main(String[] args){ Scanner sc = new Scanner(System.in); int num = sc.nextInt(); System.out.println("This is a sample program"); return num; } } On executing, this program generates the following error − Error: Main method must return a value of type void in class Sample, please define the main method as: public static void main(String[] args)
https://www.tutorialspoint.com/can-we-change-return-type-of-main-method-in-java
CC-MAIN-2021-43
refinedweb
205
60.24
in struts i want to validate my form fields but it couldn't work can you fix what mistakes i have done</p>... be added to your projects ApplicationResources.properties file or you can Hi - Struts Hi Hi Friends, I want to installed tomcat5.0 version please help me i already visit ur site then i can't understood that why i installed please give some idea for installed tomcat version 5 i have already tomcat 4 i have no any idea about struts.please tell me briefly about struts?** Hi Friend, You can learn struts from the given link: Struts Tutorials Thanks struts - Struts and do run on server. whole project i have run?or any particular...struts hi, i have formbean class,action class,java classes and i configured all in struts-config.xml then i dont know how to deploy and can anyone tell me how can i implement session tracking... one otherwise returns existing one.then u can put any object value in session.... you can do like this.... session.setAttribute("",); //finally u can remove Struts Projects the database Struts Projects explains here can be used as dummy project to learn... that can be used later in any big Struts Hibernate and Spring based... Error - Struts Error Hi, I downloaded the roseindia first struts example... these two files. Do I have to do any more changes in the project? Please.... If you can please send me a small Struts application developed using eclips. My i want to learn more examples on struts like menu creation... and client side validation in struts are not running which are present on rose india. plz do hurry to solve my problem I/O Java I/O Java import java.io.File; import java.io.FileNotFoundException... a RuntimeException if any problem occurs in // opening the inputFile // The copy... writer = new PrintWriter(outFile); for(int i=0;i<inputFiles.length;i Struts - Struts Struts Hi, I m getting Error when runing struts application. i... ActionServlet *.do but i m getting error-- : Struts Tutorials types of cleanup you can do to improve your Struts configurations. Prerequisites... module based configuration. That means we can have multiple Struts configuration... as popular as Struts. If you need to brush up your knowledge on JUnit I can recommend Code - Struts Struts Code Hi I executed "select * from example" query... using struts . I am placing two links Update and Delete beside each record . Now I... But it is not appending.. Can any one help me. Thanks in Advance struts titles - Struts Use Struts Titles in Web Applications hi i want to use titles in my web project please help me . in my project i have four titles such as banner, menu , content and footer . please provide any example code struts... name stored in database. how can i do this please suggest me.. I am using first example - Struts Struts first example Hi! I have field price. I want to check... the version of struts is used struts1/struts 2. Thanks Hi! I am using struts 2 for work. Thanks. Hi friend, Please visit Struts Interview Questions ; Question: Can I setup Apache Struts to use multiple configuration files? Answer: Yes Struts can use multiple configuration files. Here... it. For any small project less experience developers could spend more time Struts - Struts Struts Dear Sir , I am very new in Struts and want... validation and one of custom validation program, may be i can understand.Plz provide the that examples zip. Thanks and regards Sanjeev. Hi friend Hi what is struts flow of 1.2 version struts? i have struts applicatin then from jsp page how struts application flows Thanks Kalins Naik Please visit the following link: Struts Tutorial Java I/O - Java Beginners Creating Directory Java I/O Hi, I wanted to know how to create a directory in Java I/O? Hi, Creating directory with the help of Java.../java yeah i konw tht method but i want another program whr we shld nt use what it can and can't do. Of the Struts example applications I've seen...-Controller (MVC) design paradigm. Want to learn Struts and want get... for applying Struts to J2EE projects and generally accepted best practices as struts struts hi Before asking question, i would like to thank you... technologies like servlets, jsp,and struts. i am doing one struts application where i... into the database could you please give me one example on this where i i have How to build a Struts Project - Struts How to build a Struts Project Please Help me. i will be building a small Struts Projects, please give some Suggestion & tips example on struts - Struts example on struts i need an example on Struts, any example. Please help me out. Hi friend, For more information,Tutorials and Examples on Struts visit to : Thanks tabbedpanel - Struts struts 2 tabbedpanel Hi Friend do I change the background color of a tab? bye bye struts html tag - Struts struts html tag Hi, the company I work for use an "id" tag on their tag like this: How can I do this with struts? I tried and they don't work JSP - Struts another list of values of students names. 3.when we select any student i want to display a text box with his grade.....which am unable to do... please help...JSP am using struts frame work for my project, my requirement Based on struts Upload - Struts Based on struts Upload hi, i can upload the file in struts but i want the example how to delete uploaded file.Can you please give the code Struts - Struts Struts What is Struts Framework? Hi,Struts 1 tutorial with examples are available at Struts 2 Tutorials... are looking for Struts projects to learn struts in details then visit at http the checkbox.i want code in struts...struts I have no.of checkboxes in jsp.those checkboxes values came from the databases.we don't know howmany checkbox values are came My struts application runs differently in Firefox and IE... What's the problem? I initially viewed it in Firefox.It was OK... But in IE the o/p was different I want to create tiles programme using struts1.3.8 but i got jasper exception help <p>hi here is my code can you please help me to solve...; <h1></h1> <p>struts-config.xml</p> <p>...;<struts-config> <form-beans> <form-bean name struts validation struts validation I want to apply validation on my program.But i am failure to do that.I have followed all the rules for validation still I am unable to solve the problem. please kindly help me.. I describe my program below Ask Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/tutorialhelp/comment/3635
CC-MAIN-2013-20
refinedweb
1,158
76.11
If you are not familliar with OpenFaas, it's definitely time that you should have a look at it, plus, they are doing some pretty awesome." - openfaas.com Make sure to give them a visit at openfaas.com and while you are there, in the world of serverless, have a look at how Alex outlines architecture and patterns he applies in a real-world example, absolutely great read! What are we doing today? Today we will build a slack app using python which we will deploy as a function on OpenFaas! Our slash command will make a request to our slack-request function, which will respond with a json string, which will then be parsed in a slack attachment message, then based on your button decision, it will then invoke our slack-interaction function, which will then respond with another message that will allow you to follow the embedded link. The slack messages are really basic, but you can create a awesome workflow using slack apps. And the best of all, its running on OpenFaas! Deploying OpenFaas Docker Swarm and Kubernetes are supported, but since I am using Docker Swarm at the moment of writing, this tutorial will show how to deploy OpenFaas to your cluster. Have a look at OpenFaas Documentation for more detailed information. Installing OpenFaas CLI for Mac: $ brew install faas-cli Deploy the OpenFaas Stack: $ git clone $ cd faas $ ./deploy_stack.sh Credentials: The default configuration will create credentials for you and returns instructions on how to authorize faas-cli, for demonstration it will look more or less like the following: $ echo -n <some_hash_secret> | faas-cli login --username=admin --password-stdin The UI will be available at:. For this demonstration we will only use the cli. Create the Functions I will create 2 python functions: - The slack-requestfunction, which will be associated to the slash command - The slack-interactivefunction, which will be used for interactivity Create a home directory for your functions and create 2 functions: $ mkdir -p ~/functions && cd ~/functions $ faas-cli new --lang python slack-request $ faas-cli new --lang python slack-interactive Read the documentation if you'd like to learn more. Configure the first function: $ vim slack-request/handler.py And our function code: import json def handle(req): data = { "text": "Serverless Message", "attachments": [{ "title": "The Awesome world of Serverless introduces: OpenFaas!", "fields": [{ "title": "Amazing Level", "value": "10", "short": True }, { "title": "Github Stars", "value": "15k +", "short": True }], "author_name": "OpenFaas", "author_icon": "", "image_url": "" }, { "title": "About OpenFaas", "text": "OpenFaaS is a framework for packaging code, binaries or containers as Serverless functions on any platform." }, { "fallback": "Would you recommend OpenFaas to your friends?", "title": "Would you recommend OpenFaas to your friends?", "callback_id": "response123", "color": "#3AA3E3", "attachment_type": "default", "actions": [ { "name": "recommend", "text": "Ofcourse!", "type": "button", "value": "recommend" }, { "name": "definitely", "text": "Most Definitely!", "type": "button", "value": "definitely" } ] }] } return json.dumps(data) Since our response needs to be parsed as json, we need to set the content type for our environment in our yaml configuration. Read more on it here. Edit the slack-request.yml : provider: name: faas gateway: http://<your.gw.address>:8080 functions: slack-request: lang: python handler: ./slack-request image: <your-repo>/slack-request:latest environment: content_type: application/json Now we need to build our image, push it to our repository like dockerhub, then deploy to openfaas: $ faas-cli build -f ./slack-request.yml $ faas-cli push -f ./slack-request.yml $ faas-cli deploy -f ./slack-request.yml Deploying: slack-request. Deployed. 202 Accepted. URL: Configure the slack-interactive function: $ vim slack-interactive/handler.py Note that whenever your interact with the first message, a post request will be made against the interactivity request url, you will notice that I decoded the payload (but not doing anything with it), where you will find the callback_id, request_url etc. But for simplicity, I am just using a static json message to respond. Our function code: import json import urllib def handle(req): urlstring = urllib.unquote(req).decode('utf8').strip('payload=') response = json.loads(urlstring) data = { "attachments": [ { "replace_original": True, "response_type": "ephemeral", "fallback": "Required plain-text summary of the attachment.", "color": "#36a64f", "pretext": "Ahh yeah! Great choice, OpenFaas is absolutely brilliant!", "author_name": "", "author_link": "", "author_icon": "", "title": "OpenFaas", "title_link": "", "text": "Head over to OpenFaas", "image_url": "", "thumb_url": "", "footer": "Slack Apps built on OpenFaas", "footer_icon": "", "ts": 123456789 } ] } return json.dumps(data) We also need to set the content type to json: provider: name: faas gateway: http://<your.gw.address>:8080 functions: slack-interactive: lang: python handler: ./slack-interactive image: <repo>/slack-interactive:latest environment: content_type: application/json Build, deploy and ship: $ faas-cli build -f ./slack-interactive.yml $ faas-cli push -f ./slack-interactive.yml $ faas-cli deploy -f ./slack-interactive.yml Deploying: slack-interactive. Deployed. 202 Accepted. URL: http://<your.gw.address>:8080/function/slack-interactive When your functions are deployed, go ahead and create the slack app. Create the Slack App - Head over to and create a new app - Create a incoming webhook - Head over to slash commands and create a new command, in my case it was /supersam, set the request url to the public endpoint of your function: - Head over to interactive components, set the request url for the interactivity: - If you dont have a public routable address, have a look at ngrok Once you are set, you should be able to see the slash command integration in your slack workspace, head over to slacks documentation if you run into any trouble. Test your Slack App Now that everything is good to go, its time to test your slack app running on OpenFaas! Head over to slack and run your command /<your-slack-slash-command>. You should see this output: When you select one of the buttons, you will get a new message: This is a real basic example of slack apps, but slack apps are really powerful. You can for example create a slack app that deploys ephemeral environments on swarm, or create change management approval workflows etc. I hope this was informative, I am really enjoying OpenFaas at the moment and if your have not tested it, I encourage you to try it out, its really, really amazing! Thank You Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.
https://sysadmins.co.za/building-python-serverless-slack-apps-on-openfaas/
CC-MAIN-2019-22
refinedweb
1,054
53.41
HtmlTextWriter Class Writes markup characters and text to an ASP.NET server control output stream. This class provides formatting capabilities that ASP.NET server controls use when rendering markup to clients. Assembly: System.Web (in System.Web.dll) The HtmlTextWriter class is used to render HTML 4.0 to desktop browsers. The HtmlTextWriter is also the base class for all markup writers in the System.Web.UI namespace, including the ChtmlTextWriter, Html32TextWriter, and XhtmlTextWriter classes. These classes are used to write the elements, attributes, and style and layout information for different types of markup. In addition, these classes are used by the page and control adapter classes that are associated with each markup language. In most circumstances, ASP.NET automatically uses the appropriate writer for the requesting device. However, if you create a custom text writer or if you want to specify a particular writer to render a page for a specific device, you must map the writer to the page in the controlAdapters section of the application .browser file. The following code example shows how to override the Render method of a custom control that is derived from the Control class. The code example illustrates how to use various HtmlTextWriter methods, properties, and fields. Available since 1.1 Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
https://msdn.microsoft.com/en-us/library/system.web.ui.htmltextwriter(v=vs.108).aspx?cs-save-lang=1&cs-lang=fsharp
CC-MAIN-2017-22
refinedweb
233
59.6
A few weeks back, in "7 programming languages in 7 days," I intended to include Ceylon, but its creator Gavin King insisted it was too soon. Now Ceylon has released Milestone 5 with an HTTP package, making it possible for me to do the inevitable: Port Granny's Addressbook to Ceylon. My assessment? While Ceylon is still not ready to anchor a large project, it's worth an early look. There's a lot to like about Ceylon -- as well as a number of frustrating details. [. ] The Ceylon IDE The Ceylon IDE is essentially a set of plug-ins for Eclipse. While it works well for a milestone release, it is not entirely stable and at times freezes inexplicably. Nevertheless, those with a Java background will find it comfortably familiar. The debugger works, but imperfectly; sometimes the variables view isn't populated or you see more of Ceylon's underbelly than your actual variables. There is relatively good integration with the language and its features, but it lacks shine. For instance, I think the modules.ceylon file deserves its own icon or visual clue to let you know it's special. Modules Speaking of modules, Ceylon integrates the concept of modules and a module repository. This is probably my favorite part of Ceylon. If you're familiar with Java's Maven or Ivy, Perl's CPAN, or Ruby's gems, you're familiar with modules and repositories. But Ceylon improves substantially on its Java roots. Maven modules have no real relationship to Java; they're simply loaded into its class path. Ceylon makes modules a first-order member of the language and its environment independent of the build system. Unlike Java, where there are always weird bugs with how Maven views the world versus the IDE's view, this works seamlessly in Ceylon. Upgrading to a new module is simply a matter of updating your module.ceylon file. module com.osintegrators.example.ceylon.hello '1.0.0' { import ceylon.net '0.5'; import ceylon.dbc '0.5'; import java.jdbc '7'; import java.base '7'; } Modules must then be imported in your runnable source code with the import statement: import java.sql { DriverManager{ getConnection }, Connection{...}, ResultSet, Statement, PreparedStatement}
http://www.infoworld.com/d/application-development/first-look-gavin-kings-ceylon-217197?source=rss_
CC-MAIN-2013-48
refinedweb
368
58.28
john rob Total Post:108 Points:756 Posted by john rob December-27-2013 6:51 AM C# C# 1 Reply(s) 2634 View(s) Ratings: Rate this: I have three windows forms in my project, and I have an object class. How can I make a list of those objects that will be available for all three forms to use? Post:67Points:471 Re: How to make a global list in c# Hi John, You could create a class containing an instance of your object: public class MyClass { public static List<string> MyList {get; set} } Then you can access it from your form MyClass.MyList = new List<string>(); Obviously string will be replaced with the name of your object.
https://www.mindstick.com/forum/1847/how-to-make-a-global-list-in-c-sharp
CC-MAIN-2018-05
refinedweb
120
69.45
A Fast Track to Machine Learning with GPU, on Oracle Cloud How to easily provision an environment with GPU, H2O4GPU, TensorFlow, PyTorch, on Oracle Cloud. Introduction in Oracle Cloud, using Ubuntu 18 LTS. Now, there is an even easier way using an HPC VM template, available in Oracle Cloud Marketplace. In this article, I will show you how to set up such an environment and how to install a powerful GPU-enabled framework like H2O4GPU. Besides, I’ll illustrate some tests I have executed, exploring the reduction of training time due to GPU. The new GPU image in Oracle Cloud. You can create a Virtual Machine directly from the Cloud Marketplace. The icon is the one shown above. You only need to create a Virtual Cloud Network (VCN), where to host the VM. VM creation and startup will take around 10 minutes. I have tested it using a VM.GPU 2.1 shape. The shape provides you with one Tesla P100 GPU and 12 OCPU. If you need more power, you can use also BM.GPU 2.2, with 2 GPUs. After that, you can directly access, through ssh, to a VM fully equipped with: - Oracle Linux 7 - Cuda version 10.1 - NVidia drivers - Python Anaconda distribution - an Anaconda environment, named “sandbox”, where all the needed packages have been installed - TensorFlow 2.1, with GPU support - Pandas - Scikit-learn - Jupyter Notebook - many more useful packages for Data Science Besides, there is more: PyTorch 1.3 is there installed if you prefer it to TensorFlow. Start a Notebook with TLS support. Jupyter Notebook is already installed, equipped with a self-signed certificate to enable access using TLS. You need only to set up a password: [opc@ml05gpu ~]$ jupyter notebook passwordEnter password: and then start Jupyter: [opc@ml05gpu ~]$ jupyter notebook — certfile=jupyter-cert.pem — keyfile=jupyter-key.key The default port (8888) is already open in the firewall. You need only to define a security rule for network access, in the VCN, as specified in the provided documentation. After that, you can start developing your Deep Learning and Machine Learning models in the Jupyter Notebook environment. Some quick initial tests. You can check that the GPU is correctly set up at the OS level with this command: [opc@ml05gpu ~]$ nvidia-smi The output of the command shows the number and type of GPUs, the available memory (16 GB) and if processes are running on them. Good to see what’s happening when Python code is running. After that, you can easily check that TensorFlow can work using the GPU. Simply, run this block of code inside a Notebook cell: import tensorflow as tfif tf.test.gpu_device_name(): print('GPU Device: {}'.format(tf.test.gpu_device_name())) else: print("Any troubles with GPU?") Now, let’s go with H2O4GPU. First of all, H2O is a popular Open Source framework for Machine Learning (ML). It provides many different ML algorithms. But, the most important thing is that it provides a performant and scalable implementation, capable of running efficiently on many cores, on a cluster (distributed ML) and on Hadoop (Sparkling Water). H2O implementation for GPU is called H2O4GPU. Even if Scikit-learn is the most popular ML framework, H2O supports all the most innovative algorithms (Gradient Boosting, Distributed Random Forest, XGBoost, Stacked Ensamble, …) and can run efficiently on very large datasets. I have decided to install H2O4GPU on my VM, to verify how easy the installation is and to check the performances, compared to an environment where ML code is running on CPU. The installation steps are not so difficult. First of all, I have decided to create a separate “conda environment”, to avoid any conflicts with the existing (sandbox) environment. It is a best practice, especially if you’re trying something new and you don’t know how easy will be the voyage. conda create -n h2o4gpu -c h2oai -c conda-forge h2o4gpu-cuda10 The next part is crucial to set up an environment compatible with the CUDA version (10.1). First, activate the environment: conda activate h2o4gpu Next steps are needed to solve an incompatibility between H2O4GPU and tornado (used by Jupyter, see issue #680), as described in H2O documentation conda install tornado==4.5.3conda upgrade jupyter_client At this point, you can start Jupyter jupyter notebook — certfile=jupyter-cert.pem — keyfile=jupyter-key.key As a first test of the installation, as recommended by H2O4GPU documentation, run the following code in a Notebook cell: import h2o4gpu import numpy as npX = np.array([[1.,1.], [1.,4.], [1.,0.]]) model = h2o4gpu.KMeans(n_clusters=2,random_state=1234).fit(X) model.cluster_centers_ Test the performance using XGBoost. In the Machine Learning field, one area of active research is the area of “ensemble methods”. With ensemble methods, you train a (large) set of models, to get better performances. With Gradient Boosting, you train sequentially Decision Trees, each one trained on the residual errors of the preceding models. See, for example, XGBoost (eXtreme Gradient Boosting) is a variant of the Gradient Boosting algorithm, born to be extremely scalable and performant. Since these algorithms work training a large set of models (even thousands), they sometimes need a lot of computational power, especially if the training set is very large (let’s say, one million samples). For these reasons, XGBoost and GBM are ideal candidates for GPU implementation. For the test, I have decided to follow one of the examples provided on the H2O4GPU Github site: The test is using one of the Scikit-learn datasets: “Forest Covertypes”. Each sample in the dataset corresponds to a 30x30 patch of US forest. The task is to predict the patch’s dominant type of tree. Therefore, it is a multi-class (8) classification task. The dataset contains 581012 samples and each sample has 54 characteristics. I have reproduced here the first part of the code, taken from H2O4GPU GitHub, with very slight modifications. import xgboost as xgb import numpy as np from sklearn.datasets import fetch_covtype from sklearn.model_selection import train_test_split import time%%time # Fetch dataset using sklearn cov = fetch_covtype() X = cov.data y = cov.target%%time # Create 0.75/0.25 train/test split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, train_size=0.75, random_state=42)%%time # Convert input data from numpy to XGBoost format dtrain = xgb.DMatrix(X_train, label=y_train) dtest = xgb.DMatrix(X_test, label=y_test)num_round = 10 maxdepth = 6 # base parameters param = {'tree_method': 'gpu_hist', 'grow_policy': 'depthwise', 'max_depth': maxdepth, 'random_state': 1234, 'objective': 'multi:softmax', # Specify multiclass classification 'num_class': 8, # Number of possible output classes 'base_score': 0.5, 'booster': 'gbtree', 'colsample_bylevel': 1, 'colsample_bytree': 1, 'gamma': 0, 'learning_rate': 0.1, 'max_delta_step': 0, 'min_child_weight': 1, 'missing': None, 'n_estimators': 3, 'scale_pos_weight': 1, 'silent': True, 'subsample': 1, 'verbose': True, 'n_jobs': -1 }%%time # First setup: GPU HIST DEPTHWISE param['tree_method'] = 'gpu_hist' param['grow_policy'] = 'depthwise' param['max_depth'] = maxdepth param['max_leaves'] = 0 gpu_res = {} # Store accuracy result tmp = time.time() # Train model xgb.train(param, dtrain, num_round, evals=[(dtest, 'test')], evals_result=gpu_res) print("GPU Training Time: %s seconds" % (str(time.time() - tmp)))%%time # Second setup: GPU HIST LOSSGUIDE param['tree_method'] = 'gpu_hist' param['grow_policy'] = 'lossguide' param['max_depth'] = 0 param['max_leaves'] = np.power(2,maxdepth) gpu_res = {} # Store accuracy result tmp = time.time() # Train model xgb.train(param, dtrain, num_round, evals=[(dtest, 'test')], evals_result=gpu_res) print("GPU Training Time: %s seconds" % (str(time.time() - tmp)))%%time # Third setup: CPU HIST DEPTHWISE param['tree_method'] = 'hist' param['grow_policy'] = 'depthwise' param['max_depth'] = maxdepth param['max_leaves'] = 0 cpu_res = {} # Store accuracy result tmp = time.time() # Train model xgb.train(param, dtrain, num_round, evals=[(dtest, 'test')], evals_result=cpu_res) print("CPU Training Time: %s seconds" % (str(time.time() - tmp)))%time # Fourth setup: CPU HIST LOSSGUIDE param['tree_method'] = 'hist' param['grow_policy'] = 'lossguide' param['max_depth'] = 0 param['max_leaves'] = np.power(2,maxdepth) cpu_res = {} # Store accuracy result tmp = time.time() # Train model xgb.train(param, dtrain, num_round, evals=[(dtest, 'test')], evals_result=cpu_res) print("CPU Training Time: %s seconds" % (str(time.time() - tmp))) To clarify: - in the above example, we train XGBoost using four different setups, two for GPU (before) and two for CPU (after), to compare train time - The crucial setting to use GPU is param[‘tree_method’], that needs to be set to ‘gpu_hist’ - Suggestion: run each setup in a different Jupyter cell, to get the execution time Results from my runs are in the following table: It is easy to see that, with GPU, the training of the model is from 2 to 4 times faster. One final question: how much is it using the GPU? Here is the answer (see the Volatile GPU utilization in the right): Conclusion. It is nice to discover that you can set up an environment equipped with a GPU, on Oracle Cloud, in no more than ten minutes. With it, you can quickly start developing and testing your models, using frameworks like H2O4GPU, TensorFlow-Keras, PyTorch. You can concentrate on analyzing data and developing models, not wasting time to set up the environment. In the article, I have shown how to set up such an environment and how to install one powerful ML framework that provides support for GPU: H2O4GPU. Then, I have compared the performances, with and without GPU, using one of the most advanced algorithms for structured (tabular) data: XGBoost. Additionally, I have given insights into the fact that GPU can be a powerful enabler not only in Deep Learning (for example Image Recognition) but also working with structured data. The conclusion: if you have a lot of data, use a GPU and don’t waste your time. Enjoy.
https://luigi-saetta.medium.com/a-fast-track-to-machine-learning-and-gpu-on-oracle-cloud-efea2cf77287?source=post_internal_links---------0----------------------------
CC-MAIN-2021-25
refinedweb
1,578
55.74
Messages¶ Sometimes you don’t want to generate actions. sometimes you just want an individual isolated message, the way traditional logging systems work. Here’s how to do that. When you have an action¶ If you already have an action object, you can log a message in that action’s context: from eliot import start_action class YourClass(object): def run(self): with start_action(action_type="myaction") as ctx: ctx.log(message_type="mymessage", key="abc", key2=4) If you don’t have an action¶ If you don’t have a reference to an action, or you’re worried the function will sometimes be called outside the context of any action at all, you can use log_message: from eliot import log_message def run(x): log_message(message_type="in_run", xfield=x) The main downside to using this function is that it’s a little slower, since it needs to handle the case where there is no action in context.
https://eliot.readthedocs.io/en/1.14.0_a/generating/messages.html
CC-MAIN-2022-40
refinedweb
154
52.73
sub update { my ( $url, $dir ) = @_; my @possible_suffixes = qw( .gz .bz2 ); my $basename = extract_basename( $url, @possible_suffixes ); my $local_file = "$dir/$basename"; [download] return if -e $local_file and not is_newer( $url, $local_file ); [download] my $temp_file = download( $url, TEMP_DIR ) or die "download of $url +failed"; [download] if ( -e $local_file ) { my $new_name = rename_file( $local_file, suffix( time ) ); compress( $new_name ); } [download] move_file( $temp_file, $local_file ); maybe_uncompress( $local_file ); [download] return 1; } [download] curtain Erratum extirpated. Thanks to the gimlet-eyed Dr. Zaxo. Update 2: s/Dr. Perl/JAPH/ on one of the lines. Thanks to ambrus and castaway. the lowliest monk You need a new Perl Quack, you have an abcessed qw: my @possible_suffixes = qw( '.gz', '.bz2' ); Lets lance that and give you some antibiotics, my @possible_suffixes = qw( .gz .bz2 ); There, the swelling's down. Feel better now? After Compline,Zaxo Aarrgh! But ++ :-) It sounds like "It just works." Nothing wrong with that. There's code that keeps the lights on that hasn't been looked at in 30 years. If it works, then it ... well, works! And, if you don't need to, then DON'T CHANGE IT. Fiddling for the sake of fiddling is a good way to learn where all the food banks in your neighborhood are. Now, if you have a need to do so, then I would look at improving the name and maybe adding some logging or something of that nature. (Only after correct source control, test suites, and other refactoring infrastructure is in place, though.). :) The return value of Update::update is used by the calling code to decide whether there are newly updated primary data files that need reprocessing. This doesn't seem unreasonable to me, though I'm open to second opinions on how best to do this, too. You name two extremes though, you have a module, complete with own namespace etc, and are trying to decide between that and system()ing a script? The module/own namespace gives you the assurance that you can even use it in scripts that may already have some sort of "update" function that does something else. The other alternative would be to make it a simple .pl containing the sub, and using do "update.pl" in your scripts, which will give the calling script it the update sub in it's own namespace. C. -K.
http://www.perlmonks.org/?node_id=461946
CC-MAIN-2018-13
refinedweb
384
74.08
A ListView is a view (logic) that allows you to see numerous instances of the same table in the database. In List View – Function-based Views Django, one of the core fundamentals is the ListView. Views can be implemented as Python objects instead of functions using class-based views. They do not replace function-based views, but they do have several advantages and differences when compared to them: - Different methods, rather than conditional branching, can organize code relevant to various HTTP methods (GET, POST, etc.). - Mixins (multiple inheritances) and other object-oriented approaches can fold code into reusable components. - Views based on classes are easier to manage and maintain than views based on functions. You can transform a function-based view with many lines of code into a class-based view with only a few lines of code. - Object-Oriented Programming (OOP) comes into play here. Let’s create a view with the base view View, change it to TemplateView, then ListView. We hope to demonstrate that a ListView would save us several lines of code while also providing greater separation of concerns in the application. ListViews in Django — Function-Based Views Using an example, demonstrate how to construct and operate a List view. Consider a project called CodeunderscordListView, which has a CodeApp. In this case, let’s first establish a model from which we’ll create instances through our view after creating the project and an app. In the CodeApp/models.py file, # importing the standard Django Model from the built-in library from django.db import models # declaration of a new model with a name "CodeModel" class CodeModel(models.Model): # model's fields title = models.CharField(max_length = 200) description = models.TextField() # renaming model instances with their title name def __str__(self): return self.title After creating this model, we’ll need to run two commands to establish a database for it. Python manage.py makemigrations Python manage.py migrate Now let’s use the shell to build some instances of this model by running bash form as shown below. python manage.py shell Enter the commands below. from CodeApp.models import CodeModel CodeModel.objects.create(title="first title",description=" first description").save() CodeModel.objects.create(title="second title",description="second description").save() CodeModel.objects.create(title="second title",description="second description").save() Everything is now ready for the back end. You can confirm this by checking to ensure if instances have been created. Vanilla View We want to create a page that displays all of the items in the CodeModel in the database. The following is an example of a view: class CodeListView(View): def get(self, request, *args, **kwargs): codes = CodeModel.objects.all() context = {'codes': codes} return render(request, "codemodel_list.html", context=context) Subclassing the TemplateView class CodeListView(TemplateView): template_name = 'codemodel_list.html' def get_context_data(self, *args, **kwargs): context = super(CodeListView, self).get_context_data(*args, **kwargs) context['codes'] = CodeModel.objects.all() return context When utilizing TemplateView, we don’t have to give a get() implementation or worry about render(). TemplateView takes care of everything. To add context to the template, we merely needed a get_context_data() implementation. Subclassing the ListView from django.views.generic.list import ListView class CodeListView(ListView): template_name = 'codemodel_list.html' queryset = CodeModel.objects.all() context_object_name = 'codes' ListView reduces the amount of boilerplate in TemplateView. We didn’t have to worry about implementing get_context_data() with ListView. ListView establishes the ‘codes’ context variable and delivers it to the template. In addition, you can also add filtering to ListView.queryset as follows: class CodeListView(ListView): template_name = 'codemodel_list.html' queryset = CodeModel.objects.filter(name='Advanced Programming in Python') context_object_name = 'codes' We would have had to add numerous lines of code to TemplateView or the vanilla View implementation if we desired pagination. We don’t have to write a pagination code because ListView provides it free. ListView subclasses can have pagination enabled by setting the paginate_by variable below. class CodeListView(ListView): template_name = 'codemodel_list.html' queryset = CodeModel.objects.all() context_object_name = 'codes' paginate_by = 15 Following that, /codemodel-list/?page=1 returns the first 15 books. On the other hand, /codemodel-list/?page=2 returns the following 15 books, and so on. If your queryset on your list page doesn’t require any filtering and works with your model’s.all() method, you can use a model attribute on the CodeListView instead of queryset. # Adding to the ListView configuration class CodeListView(ListView): template_name = 'codemodel_list.html' model = CodeModel context_object_name = 'codes' paginate_by = 15 The ordering attribute on View can add an order to your queryset. Assume you want the codes on the page sorted in ascending order by their creation date. What you can do is: class CodeListView(ListView): template_name = 'codemodel_list.html' model = CodeModel context_object_name = 'codes' paginate_by = 15 ordering = ['-created'] You can order by several qualities because the order is a list. In addition, you can forgo adding model or queryset to the list view and instead supply a get_queryset() implementation if you want to filter the queryset differently for different web requests. class CodeListView(ListView): template_name = 'codemodel_list.html' context_object_name = 'CodeModel' paginate_by = 15 ordering = ['-created'] def get_queryset(self): return CodeModel.objects.filter(created_by=self.request.user) You can instead avoid using the template_name attribute. Because ListView’s default behavior is to utilize a template called / _list.html. As a result, you can modify the appearance of your CodeListView to something like this: class CodeListView(ListView): model = CodeModel context_object_name = 'codes' paginate_by = 15 Your template code, however, should be under CodeApp/codemodel_list.html. It implies your CodeModel model is a collection of app CodeApp. If the CodeModel model is used in an app, such as entitites, the template code is placed in entities/codemodel_list.html. You can also avoid using context_object_name. Since ListView’s default behavior is to fill the template with the context name object_list. Thus, you can modify the appearance of your CodeListView to something like this: class CodeListView(ListView): model = CodeModel paginate_by = 15 Essentially, a ListView saves you time by removing boilerplate code such as: - Provision of a GET() implementation - Creating an ordered queryset - It delivers pagination code that is encapsulated. In fact, it would have been easy to add another 10 lines of code if we had implemented pagination code in the vanilla view. - providing a reasonable context for the template - Creating and returning a HttpResponse() or HttpResponse() subclass object. A ListView must have a model, queryset, or get_queryset() implementation at a minimum. Every other component has a reasonable default value. ListView in Action Class-Based Views take care of everything from start to finish. Indicate the model to establish a ListView for, and Class-based ListView will automatically look for a template in app name/modelname_list.html. It’s CodeApp/templates/code/codemodel_list.html in our case. Let’s start by making our class-based view. In the CodeApp/views.py file, from django.views.generic.list import ListView from .models import CodeModel class CodeList(ListView): # specify the model for list view model = CodeModel Now create a URL path to map the view. In CodeApp/urls.py, from django.urls import path # importing views from views..py from .views import CodeList urlpatterns = [ path('', CodeList.as_view()), ] In templates/CodeApp/codemodel_list.html, make a template. <ul> <!-- Iterate over object_list --> {% for object in object_list %} <!-- Display Objects --> <li>{{ object.title }}</li> <li>{{ object.description }}</li> <hr/> <!-- If object_list is empty --> {% empty %} <li>No objects yet.</li> {% endfor %} </ul> When done, you can check what is there on The latter should be done after firing up your server and doing the prerequisites covered earlier to create database tables. Manipulating the Queryset In ListView By default, ListView displays all table instances in the order generated. The get_queryset method is overridden if the sequence or order of these instances is changed. In the CodeApp/views.py file, from django.views.generic.list import ListView from .models import CodeModel class CodeList(ListView): # specifying the list view's model model = CodeModel def get_queryset(self, *args, **kwargs): qs = super(CodeList, self).get_queryset(*args, **kwargs) qs = qs.order_by("-id") return qs Check to ascertain if the order of the instances has been changed. It allows you to change the entire queryset in whatever way you choose. Conclusion Django includes several generic views based on classes to help with everyday tasks. ListView is one of them. TemplateView is the most basic class-based generic view. However, when you wish to exhibit a list of objects on an HTML page, you should use the ListView. When your page has forms and creates or updates objects, you should not use a ListView. FormView, CreateView, and UpdateView are better for working with forms, object creation, and object updates. TemplateView can do everything the ListView can; however, the ListView has the advantage of not requiring as much boilerplate code as TemplateView would.
https://www.codeunderscored.com/listview-in-django/
CC-MAIN-2022-21
refinedweb
1,452
51.44
Table of Contents Here are some basic moves you need to play with TurboGears. If you take a look at the code that quickstart created, you’ll see that there isn’t much involved in getting up and running. In particular, you’ll want to check out the files directly involved in displaying this welcome page: start-tutorial.pyis an implicit starting script that you could add your starting operations here. dev.cfgand prod.cfgfor development and production configuration respectively. Note To change the port used by the built-in web server, edit dev.cfg to change the default server port: server.socket_port = 8080 Note To use the default ‘production’ configuration, you could specify which configuration file to use when starting the server: $ python start-tutorial.py prod.cfg tutorial/templates/welcome.htmlis the template you view on the welcome screen. It’s a standard XHTML file with some simple namespaced attributes. You can even preview it directly by open it in your browser! Very designer-friendly. tutorial/controllers.pyis responsible to generate the welcome page. Let’s say ‘Hello World’ to them respectively. To start adding and modifying template, open tutorial/templates/welcome.html. If we replace the HTML body in welcome.html with the code below, we’ll have the TurboGears equivalent of a ‘Hello, world’ application: .... <body> Hello, world! </body> .... Start the server again and browse to. You should see “Hello, world!” appeared in your web browser. Controllers are your way of specifying what code gets executed when an incoming request to your web service is received. To map request URLs and parameters to Python functions, TurboGears uses a module called CherryPy. You just write methods and expose them to the web with a @expose()`` decorator. (The decorator is a powerful element in TurboGears, you’ll learn more of them). To start adding and modifying controllers, open tutorial/controllers.py. If we replace the Root class in controllers.py with the code below, we have the TurboGears equivalent of a ‘Hello, world’ application: class Root(controllers.RootController): @turbogears.expose() def index(self): return "Hello, world!" Start the server again and browse to. You should see “Hello, world!” in plaintext. So far we’ve been returning plaintext for every incoming request. But you might have noticed how the default welcome page work. Let’s plug real templates into the controllers. TurboGears uses the Genshi templating system by deault for controlling dynamic content in your markup. For each page on your site, you could give each of them the corresponding template in your controllers. You could specifying the template argument with``@expose`` decorator: @expose(template="tutorial.templates.welcome") def index(self): ... Template arguments are used to pass variables and other dynamic content to the template. You can pass template arguments from your controllers by returning a dictionary whose keys are the names by which the variables will be accessible in the template: @expose(template="tutorial.templates.welcome") def index(self): records = ['iterable', 'items'] return dict(records = records) Not every template has dynamic content and therefore may not need arguments. In that case, just return an empty dictionary: @expose(template="tutorial.templates.welcome") def index(self): return dict() To create more skeletons for your templates, just copy the default welcome.html template that was generated when your project was created.
http://www.turbogears.org/1.1/docs/BasicMoves.html
CC-MAIN-2015-40
refinedweb
550
51.34
Control.Lens Description This package provides lens families, setters, getters, traversals, isomorphisms, and folds that can all be composed automatically with each other (and other lenses from other van Laarhoven lens libraries) using (.) from Prelude, while reducing the complexity of the API. For a longer description and motivation of why you should care about lens families, see. Note: If you merely want your library to provide lenses you may not have to actually import any lens library. For, say, a , just export a function with the signature: Simple Lens Bar Foo foo :: Functor f => (Foo -> f Foo) -> Bar -> f Bar and then you can compose it with other lenses with (.) without needing anything from this library at all. Usage: You can derive lenses automatically for many data types: import Control.Lens data Foo a = Foo { _fooArgs :: [String], _fooValue :: a } makeLenses ''Foo This defines the following lenses: fooArgs :: Simple Lens (Foo a) [String] fooValue :: Lens (Foo a) (Foo b) a b The combinators here have unusually specific type signatures, so for particularly tricky ones, I've tried to list the simpler type signatures you might want to pretend the combinators have. Documentation module Control.Lens.Type module Control.Lens.Traversal module Control.Lens.Getter module Control.Lens.Setter module Control.Lens.Fold module Control.Lens.Iso module Control.Lens.Indexed module Control.Lens.Representable module Control.Lens.TH
http://hackage.haskell.org/package/lens-1.5/docs/Control-Lens.html
CC-MAIN-2014-52
refinedweb
227
50.73
This python plugin reads names and addresses from a MySQL database and creates golden mailing labels (with optional return label). I created this script out of the desire to have golden text on my wedding invitation and save the date envelopes. I may have taken this too far :-) WARNING: Some understanding of SQL required. Screen shots & Examples added (03-18-08) The completed envelope(s) are either displayed or exported to a png or jpeg file. I found windows preview far more capable of printing than the GIMP (sorry everybody). Unfortunately, while this works for me, it may need some tweaks to work for you. What you will need: - A working gimp/python setup (I've tested this only under windows XP so far) - You will need the MySQLdb python module - a MySQL server with the data you need: name, street1, street2, city, state, zip (street1 is the first line of the address, street2 is the second line). - a golden environment map, see the tutorial at for instructions and an example. It's hard to say that my script makes golden labels. Without a good envmap, it doesn't make anything at all worthwhile. I was reluctant to code up the creation of a golden envmap as part of the script because having it in there would remove control of the final product. Once you have an envmap, you may need to rotate it to tweak the brightness and shading to make things look right. To make the return label I started up the python console (a wonderfully useful plugin) and imported the following script: import gimpfu gimpfu.debug_environment = True from gimpfu import * import sys sys.path.append("C:\\Documents and Settings\\Andy\\.gimp-2.4\\plug-ins") I then imported "golden_label" which was located in the path listed above. I then called the "golden" function with the appropriate arguments, thus bypassing the MySQL code entirely. Feel free to edit and redistribute as you see fit (GPLv2+). Any questions please feel free to send me an email (gmail) at: ajzobro Update (03-19-10) to work with Gimp 2.6. Untested, however, as the database connection and original envmap are no longer readily available (hard drive crash). Recent comments
http://registry.gimp.org/node/1955
CC-MAIN-2018-05
refinedweb
369
62.27
Hard mode: nothing that ends in "ville". Type: Posts; User: Babkockdood Hard mode: nothing that ends in "ville". Think about this. printf, sprintf, and fprintf all work on streams, right? Just like scanf, sscanf, and fscanf work on streams? When I use a function like rewind() or fseek() with SEEK_END, it... Like Jim said, %d is used with integers. Use %f in the final two printf statements, since cir and area are of the type float. Let's talk about pi now. First of all, 3.14 is not an integer. It is a... That worked, thanks. scanf("%[^\n]", s->name) does the same thing. Hey C Board. I created a typedef structure called Student, and I want to pass this structure to two functions, getStudent, to scanf all the members, and printStudent, to print all the members. ... #include <stdio.h> #include <stdlib.h> typedef struct node { int value; struct node *next; } block; int main(void) { block *root = NULL; The Windows equivalent of that command is find /V "(ROM_LOAD|ROM_REGION)" your_sourcefile.c Just a suggestion, even though your program technically works like it's supposed to. Make i an integer, use while (i != 8) for the while condition, and replace the two getchars with scanf("%d", &i);... if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password, opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL) Well there's your problem. You're not giving it a host... Some psuedocode: int main(int argc, char *argv[]) if argv[1] is null, printf usage message argv[1] will be file to be copied FILE *in = fopen argv[1], mode "r" Do you have to set up a web server like Apache on localhost first? If so, make sure it's set up properly. Thanks for all the explanations. I'm starting to understand it better. I'm an experienced C programmer, but I don't know that much about C++ and I'd like to know why it's better, worse, or just as good. I'm probably just ignorant, but to me, I don't see that many... The double data type is usually eight bytes. Try chdir, or opendir if chdir isn't available. chdir will return -1 if the specified directory doesn't exist. opendir will return NULL if the specified directory doesn't exist. Also, you can use... CommonTater is in the lead. Whoever writes the fanciest program gets a cookie. Post the code or quit asking for help. unsigned int iseed = (unsigned int)time(NULL); srand(iseed); You don't need a variable for time(NULL). Just replace that with srand(time(NULL));. That while loop is completely unnecessary.... The C Board is not a homework machine. Announcements - General Programming Boards Try writing the code yourself, and we'll tell you what's wrong with it. a. The odds of it being EOF are incredibly slim, and b. Why doesn't he just assign it to 0? Maybe this wouldn't work in this case, but I've always used fgets(str, sizeof(str), stdin) to get strings from stdin. And your main function should look like this: int main(void) { //... Just curious, why wouldn't your compiler include string.h? It's apart of the standard C library, and all of those headers should be installed by default. Take out the scanf statement, and assign data to getchar() inside the while conditional. #include <stdio.h> int main(void) { int data; while ((data = getchar()) != EOF) ...
https://cboard.cprogramming.com/search.php?s=07001192074783a05e27a44979447d0c&searchid=2963352
CC-MAIN-2020-10
refinedweb
571
77.74
Creating an Angular 7 App With ASP.NET Core: A Step-by-Step Guide Creating an Angular 7 App With ASP.NET Core: A Step-by-Step Guide Angular 7 has just arrived. In this post, a dev gives a step-by-step guide to creating an Angular 7 app using ASP.NET Core SPA templates in Visual Studio 2017. Join the DZone community and get the full member experience.Join For Free Finally, we have a new major version of Angular,: - We will see how to create Angular 7 applications with ASP.NET Core SPA template. - We will also see the features introduced with this major release. - I will demo some of the Angular Material features introduced with Angular 7. Angular 7 With SPA Template Let's first see how to create an Angular 7 application with ASP.NET Core SPA templates using Visual Studio 2017. There are more ways than one to create an Angular 7application the command prompt and run the command: npm i -g @angular/cli Once done, your CLI will be updated to version 7: Create the Angular Application Using .NET Core 2.1 Template in VS 2017 Once you have all these installed, open your Visual Studio 2017 -> Create New Project -> Select Core Web application: Click on "Ok," and, in the next window, select Angular as shown below: Visual Studio will create a well-structured application for you, which is currently in Angular 5. Angular: Angular 7 Major Features Let's examine some of the major features released with Angular 7. The CLI Is More Talkative From Angular 7 onwards, the CLI will prompt users when they run commands like ng new or ng add to help the user to choose features like routing, SCSS support, etc.: As you can see above, you can reply either Yes or No, or by selecting the option using the up/down arrow keys. Angular Material Improvements The Component Dev Kit (CDK) has been improved, and now we can use functionalities like virtual scrolling and drag and drop. Let's see how to do it using Angular 7. Install Angular Material. Drag and Drop Feature I remember some Stack Overflow questions about this, and, personally, I wished this would be part of Material. From Angular 7 onwards, we will be able to drag and drop using Material. We can now drag items horizontally, vertically, from one list to another list, reorder the list, open draggable items, etc. For this, we first need to add the DragDropModule into app.component.ts as below: import { DragDropModule } from '@angular/cdk/drag-drop'; @NgModule({ ... imports: [DragDropModule], ... }) Let's create a horizontal drag and drop. For this, add the below code in app.coponent.html: <div cdkDropList <div class="example-box" *ngFor="let timePeriod of timePeriods" cdkDrag>{{timePeriod}}</div> </div> Next, we will need the timePeriods. For this, add below code in app.component.ts: timePeriods = [ 'Bronze age', 'Iron age', 'Middle ages', 'Early modern period', 'Long nineteenth century' ]; drop(event: CdkDragDrop<string[]>) { moveItemInArray(this.timePeriods, event.previousIndex, event.currentIndex); } We're all set. Now, run the application using ng serve: You can find more details here. Virtual Scrolling: import { ScrollDispatchModule } from '@angular/cdk/scrolling'; @NgModule({ ... imports: [ScrollDispatchModule], ... }) Let's add virtual scrolling in our Angular 7 app. For this, add the below code in app.coponent.html: <cdk-virtual-scroll-viewport <div *{{item}}</div> </cdk-virtual-scroll-viewport> Next, we will need the items. For this, add below code in app.component.ts: items = Array.from({ length: 100000 }).map((_, i) => `Item #${i}`); That's it. Now, run the application using ng serve: More details can be found here. Ability to Use Native Select in Angular Material Performance Improvement for Production. Bundle Budget Feature With this, if your bundle is more than 2 MB -> you will be warned by the application, and if the bundle is more than 5 MB -> you will get an error from the application. But it is configurable, so you can change the settings from the angular.json file: "budgets": [{ "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }] This way, you will get used to creating applications with as low a of bundle size as possible. These are some of the major features of Angular 7. Let's quickly mention a few more features that shipped with Angular 7 which Stephen Fluin mentions in his! If you enjoyed this article and want to learn more about Angular, check out our compendium of tutorials and articles from JS to 8. Published at DZone with permission of Neel Bhatt , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/creating-an-angular-7-app-with-aspnet-core-a-step-1
CC-MAIN-2020-29
refinedweb
783
57.47
Learning Resources for Software Engineering Students » Author: Aadyaa Maddi Reviewers: Amrut Prabhu, Marvin Chin The official website describes React as follows: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called 'components'. Let us understand some key features of React with the help of an example. A web application that displays the name of a person is given below: The UI of a React application is defined using a mix of HTML code and HTML-like syntax, called JSX. The main view of the application above (defined in the App.render() method in index.js) is given as follows: <div className="App"> <h1>Person Data</h1> <PersonComponent name={this.state.name} changeHandler={this.handleChange} /> </div> In the above example, we declare what we want to display (i.e. name) and React renders the appropriate view based on the updated application data. This is known as the React encapsulates application views and relevant data and logic for updating the views using components. A combination of components that exchange information with one another is used to build the UI of a React application. For example, the application above is divided into two components: App The App component (defined in index.js) contains the main view of the application. It stores the application data (i.e. name) in an object called state and has a method to update the it every time the value in the textbox changes. It passes the application data and the method to the PersonComponent. class App extends Component { state = { name: "John Doe" }; handleChange = event => { this.setState({ name: event.target.value }); }; render() { return ( <div className="App"> <h1>Person Data</h1> <PersonComponent name={this.state.name} changeHandler={this.handleChange} /> </div> ); } } PersonComponent PersonComponent (defined in personComponent.js) renders the details of the person. It accepts input from the App component in the form of props. const PersonComponent = props => { return ( <div className="Person"> <h2>About Me</h2> <p>My name is {props.name}.</p> <label htmlFor="name">Name: </label> <input id="name" onChange={props.changeHandler} value={props.name} /> </div> ); }; As you can see, React components are just JavaScript functions that accept arbitrary input and return a declarative view describing what should appear in the application's UI. Data binding refers to the exchange of information between the application data and the UI. React provides one-way data binding. In applications that use one-way data binding, changes to the application data are automatically reflected in the UI. However, changes to the UI need to be manually propagated to the application data. In the above application, you can see that the UI is updated whenever a different name is entered in the textbox. These updates do not happen in a single step - the application data is first updated using the handleChange() method, and then the UI is updated to reflect these changes. Now that we know what React is, let us take a look at some of its benefits. Web applications can have a lot of user interaction and data updates, which results in changes being made to the React minimizes this update time by using a virtual DOM. The virtual DOM is a JavaScript object that is kept in the memory of your application. Figure 1. How React's actual DOM gets updated. As shown in Figure 1 above, updates to the UI will first be made to the virtual DOM. Then, React will compare the virtual DOM with the actual DOM using a diffing algorithm. Finally, React updates the actual DOM only in places it differs with the virtual DOM. It batches multiple changes together and updates the actual DOM in one go, minimizing update time. The traditional Most web applications usually have to interact with a lot of DOM elements and events. Also, different browsers have variations in their implementations of the React's declarative approach simplifies this process because it abstracts the complexity of interacting with the actual DOM elements and events. For example, the virtual DOM helps React abstract browser-specific operations on DOM elements. Additionally, React provides its own events system so that events can work in the same way across different browsers. A React application is made up of a combination of components. Components are independent from each other, and like functions, they map the same input to the same output. This makes it easy to write unit tests for your application. Additionally, React only allows data to flow downwards (one-way data binding) using state and props, which makes your application easier to debug as you can be sure that the data updates the UI, and never the other way around. Besides the three main benefits explained above, React has the following advantages: Some of React's disadvantages are given below: There are a lot of JavaScript frameworks and libraries that you can use to build your next web application. Some popular alternatives to React are Angular and Vue. How do you decide which one to use? Here are some resources to help you choose between them: Every framework has its pros and cons, but hopefully you have managed to see that React removes some of the complexity that comes with building user interfaces. The official React website is a great place to get started. It includes: If you want to add React to an existing project, you can take a look at React's official guide for doing so. Alternatively, if you are creating a new React application, you can use one of the recommended toolchains to get the best user and developer experience. Create React App is a convenient environment for learning React, and it is the recommended way to create The official website also has advanced guides if you want to understand how React works behind the scenes. As React is a fairly popular library, you can find a lot of comprehensive resources online. Here are some resources that can be useful: If you need help with React, you can get support from React's community of millions of developers that are active on Stack Overflow and discussion forums like Dev and Hashnode. Lastly, if you want to know what to learn after getting familiar with React, here is a comprehensive roadmap that you can follow to become a full-fledged React developer.
https://se-education.org/learningresources/contents/javascript/Javascript-framework-React.html
CC-MAIN-2019-26
refinedweb
1,058
53.81
PHP benchmarking While. <?php<br ?> //Initial memory $memory1 = xdebug_memory_usage( ); $data = array(); for ($i=0; $i\<100; $i++) { for ($j =0; $j\<=1000; $j++) { $data[$i][md5($j)] = microtime(); } } $array = xdebug_memory_usage() -$memory1; $time1 = microtime(TRUE); for ($i=0; $i\<100; $i++) { for ($j =0; $j\<=1000; $j++) { $var = md5(rand(0,1000)); $var = $data[$i][$var]; } } $time2 = microtime(TRUE) - $time1; echo $array.PHP_EOL; echo $time2.PHP_EOL; ?\> And for objects it's very similar: <?php<br ?> $data= array(); $memory2 = xdebug_memory_usage(); for ($i=0; $i\<100; $i++) { $data[$i] = new stdClass; for ($j =0; $j\<=1000; $j++) { $prop = md5($j); $data[$i]-\>$prop = microtime(); } } $object = xdebug_memory_usage() - $memory2; $time3 = microtime(TRUE); for ($i=0; $i\<100; $i++) { for ($j =0; $j\<=1000; $j++) { $var = md5(rand(0,1000)); $var = $data[$i]-\>$var; } } $time4 = microtime(TRUE) - $time3; echo $object.PHP_EOL; echo $time4.PHP_EOL; ?\> In this tests I create 10 arrays (then objects) and give them 1000 values that are the current time (in string format) and 16 byte key (an MD5 hash). I measured the memory before and after, and the amount of memory used by the array or object is the difference. Then I do another loop, and copy a value from the array each time. This is to test the read performance of arrays and objects. The two values are printed on two different lines. However, one value is useless by itself. Maybe my computer had an extra load for the duration of a test (running a background AV check), maybe the test hit a rare bottleneck in the memory allocation etc. So to do a proper benchmark, you have to run each test multiple times and then take the average and calculate the standard deviation. To run the tests multiple times I decided to use cURL to remotely load the URL's and parse the results into an array. <?php if (!isset($_GET['q'])) { echo 'You must give a URL to test'; die(); } $url = $_GET['q']; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = array(); $nr = isset($_GET['nr'])?$_GET['nr']:10; for ($i=0; $i\<10; $i++) { $val = curl_exec($ch); $val = explode(PHP_EOL,trim($val)); foreach ($val as $key=\>$el) { $data[$key][] = $el; } } // close cURL resource, and free up system resources curl_close($ch); foreach ($data as $key=\>$values) { $key++; echo "Param {$key}: "; echo 'Maximum is: '.max($values).' '; echo 'Minimum is: '.min($values).' '; echo 'Arithmetic mean is: '.arithmetic_mean($values).' '; echo 'Median is: '.median($values).' '; echo 'Population standard deviation is: '.standard_deviation($values).' '; echo 'Sample standard deviation is: '.sd($values).' '; echo ' '; } function arithmetic_mean($a) { return array_sum($a)/count($a); } function median($a) { sort($a,SORT_NUMERIC); return (count($a) % 2) ? $a[floor(count($a)/2)] : ($a[floor(count($a)/2)] + $a[floor(count($a)/2) - 1]) / 2; } function standard_deviation($aValues, $bSample = false) { $fMean = array_sum($aValues) / count($aValues); $fVariance = 0.0; foreach ($aValues as $i) { $fVariance += pow($i - $fMean, 2); } $fVariance /= ( $bSample ? count($aValues) - 1 : count($aValues) ); return (float) sqrt($fVariance); } function sd_square($x, $mean) { return pow($x - $mean,2); } function sd($array) { return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)-1) ); } ?\> Don't ask me about the two functions two calculate the standard deviation. I found them in the PHP manual (because the Stats extension has no Windows binaries X( ). This script loads the URL passed in the q GET parameter and loads it several times (10 times by default, or the value of nr GET parameter if it exists). Then, for each value outputed on a new line, it calculates the average, the maximum value, the minimum value and two types of standard deviations. The results I got for 30 runs is: - Arrays: - Memory usage: Maximum is: 14838656 Minimum is: 14838656 Arithmetic mean is: 14838656 Median is: 14838656 Population standard deviation is: 0 Sample standard deviation is: 0 - Time spent reading: Maximum is: 0.56820487976074 Minimum is: 0.3705358505249 Arithmetic mean is: 0.46606066226959 Median is: 0.46564090251923 Population standard deviation is: 0.094189880474856 Sample standard deviation is: 0.099284851613188 - Objects: - Memory usage: Maximum is: 14841032 Minimum is: 14841032 Arithmetic mean is: 14841032 Median is: 14841032 Population standard deviation is: 0 Sample standard deviation is: 0 - Time spent looping: Maximum is: 0.59881019592285 Minimum is: 0.38148784637451 Arithmetic mean is: 0.48865029811859 Median is: 0.50128650665284 Population standard deviation is: 0.095435870065359 Sample standard deviation is: 0.10059823996214 As you can see, there is virtually no difference between the memory usage (0.01601% difference). Reading from the array seems to be slightly faster (4.623% difference). After this I ran another series of tests, to see which method is faster for looping through associative arrays: foreach, while, or a simple for loop. And I was quite shocked. I created a single array, similarly to above: $data = array(); for ($i=0; $i\<100000; $i++) { $data[md5($i)] = microtime(); } And then I did the following three tests: Foreach: foreach ($data as $key\>$value) { $data[$key].='a'; } While: while (list($key) = each ($data)) { $data[$key].='a'; } For: $key = array_keys($data); $size = sizeOf($key); for ($i=0; $i\<$size; $i++) { $data[$key[$i]] .= "a"; } (I left the timing bits out. They're the same as above) The results are interesting: - Foreach Maximum is: 0.14385986328125 Minimum is: 0.097252130508423 Arithmetic mean is: 0.12040016651153 Median is: 0.12920439243317 Population standard deviation is: 0.019063768371205 Sample standard deviation is: 0.020094976279628 - While Maximum is: 0.33422708511353 Minimum is: 0.22083210945129 Arithmetic mean is: 0.25493462085724 Median is: 0.22828495502472 Population standard deviation is: 0.041753633338567 Sample standard deviation is: 0.044012193979137 - For Maximum is: 0.11151194572449 Minimum is: 0.070990085601807 Arithmetic mean is: 0.086783051490784 Median is: 0.080439567565918 Population standard deviation is: 0.015436115114854 Sample standard deviation is: 0.01627109399583 While is the slowest, by faaaar, and for is the fastest than foreach with 38%. Quite a difference. I will continue to do some benchmarks so that the rolisz framework can be one of the fastest ones around :D
https://rolisz.ro/2011/04/23/php-benchmarking/
CC-MAIN-2019-13
refinedweb
989
59.6
As .NET is penetrating the development environment day by day, we are having unmanaged and managed code running parallel. These days, managed to unmanaged calls have become very popular. But unmanaged to managed calls are still tedious. So my aim was to make such calls as simple as possible. Unmanaged to managed calls using Regasm are very common. I have tried a straightforward call from unmanaged C++ code to a managed C# code. The main funda which I worked on are: Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run. In my project, I have made an attempt to create a CLRHost to call methods of a managed DLL or EXE. I have done the steps described in the following section. Suppose we have a .NET DLL with a method declaration like this: using System; namespace ManagedDll { public class ManagedClass { public ManagedClass() { } public int Add(int i, int j) { return(i+j); } } } Now, the C++ code which directly calls this DLL without using Regasm would be: We need to be careful about some settings like: MSCOREE.H contains the definition of the interfaces used in this program. So it is done. Unmanaged to managed call becomes very simple, we just need to pass the namespace, class name and the method name with the arguments to be passed. If you want more fundas, click here. This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here varArgs[0].vt = VT_BSTR; varArgs[0].bstrVal = ::SysAllocString( L"d:\\PROJECT\\SPP\\SmartISO\\PRODUCT\\INDEX\\SPP.xls" ); Now I need to Call these C# functions from Delphi6 code. CAN YOU HELP ME......!!!!!!!!! General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/12662/Unmanaged-to-Managed-calls-C-to-C-without-Regasm?msg=2876955
CC-MAIN-2017-26
refinedweb
368
65.32
How to obtain elements from the matrix above the main diagonal? Assuming I have a matrix: m = np.arange(16).reshape((4, 4)) m array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) And I need to get a list of elements which are above the main diagonal (I don't care about the order as long as it is determined and will not change from call to call), I wrote: def get_elements_above_diagonal(m): for i in range(len(m)): for j in range(i + 1, len(m)): yield m[i, j] list(get_elements_above_diagonal(m)) [1, 2, 3, 6, 7, 11] But then I wondered, may be I am reinventing the wheel here. Is there a simpler way to obtain these elements as a flat list?
https://ask.sagemath.org/question/25949/how-to-obtain-elements-from-the-matrix-above-the-main-diagonal/
CC-MAIN-2018-30
refinedweb
134
66.1
Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources. When a program is started, the resulting process consists of a single thread, called the initial or main thread. In this section, we look at how to create additional threads. The pthread_create() function creates a new thread. #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start)(void *), void *arg); Returns 0 on success, or a positive error number on error The new thread commences execution by calling the function identified by start with the argument arg (i.e., start(arg)). The thread that calls pthread_create() continues execution with the next statement that follows the call. (This behavior is the same as the glibc wrapper function for the clone() system call described in Section 28.2.)
http://my.safaribooksonline.com/book/programming/linux/9781593272203/threads-introduction/thread_creation
CC-MAIN-2014-15
refinedweb
135
52.9
- Training Library - Microsoft Azure - Courses - Designing an Azure Network Implementation Connectivity for Hybrid Applications In an earlier lesson, you learned how to make external connections from Azure, especially using ExpressRoute or a VPN. Those solutions are great, but if you only need external connectivity for a single application, then they’re probably overkill, because you need to modify your network to use them. Fortunately, there are much simpler, more focused solutions that you can use instead. Azure provides many services to help you build hybrid applications that combine Azure and on-premises resources. Which one you use depends on what you’re trying to do. Azure WCF Relay lets you expose Windows Communication Foundation services in on-premises applications to Azure. Azure Relay Hybrid Connections is a newer service that does the same thing for WebSockets and HTTP rather than WCF. You can also use Hybrid Connections from within Azure App Service. The Azure Data Management Gateway, now known as the Self-hosted Integration Runtime, lets you copy data between Azure and on-premises data stores. Finally, the Azure On-Premises Data Gateway connects on-premises data sources with Azure Analysis Services. I have to admit that I get the Data Management Gateway and the On-Premises Data Gateway confused sometimes, because their names sound very similar, even though they’re totally different. Maybe that’s why Microsoft renamed Data Management Gateway to Self-hosted Integration Runtime. Of course, the new name doesn’t really help you remember what it does either. Oh well, after you’ve worked with them for a while, you’ll remember which one is which. Azure Relay service allows you to expose on-premises applications to Azure without having to open a port on your firewall. The way this works is the server and the client communicate through an Azure Service Bus namespace. The on-premises application communicates with Service Bus over HTTP or HTTPS. Since these ports are already open on most firewalls, no changes are needed. Of course, both the server and the client need to include code that connects to Azure Relay. Originally, Azure Relay was called Service Bus Relay and it only worked with Windows Communication Foundation services. Microsoft renamed it WCF Relay, because they created an alternative feature that doesn’t use WCF. It’s called Hybrid Connections and it works with WebSockets and HTTP. WCF Relay and Hybrid Connections exist as side-by-side alternatives in the Azure Relay service. Microsoft considers WCF Relay to be a legacy service, though. If you have existing WCF-based applications, then WCF Relay is the way to go, but if you’re developing new applications, you should write them with WebSockets or HTTP instead and use Hybrid Connections. The biggest advantage of using WebSockets or HTTP is that they’re open standards, so you can use them in any language on any platform that supports them. Azure App Service has a Hybrid Connections feature as well, but it works slightly differently. Suppose you have an Azure app that needs to access an on-premises database. You’d have to install a Hybrid Connection Manager (or HCM) in the network where the database resides. It runs on Windows Server 2012 and higher. Both sides would still connect to Service Bus, but the on-premises side would connect through the HCM to get to Service Bus. This would set up a TCP tunnel between the app and the database. The connection would be over HTTPS. Authentication and authorization would be done using a shared access signature. By the way, if you already have a VPN connection between an Azure virtual network and an on-premises location, then App Service can use it through its VNet Integration feature. OK, on to the Self-hosted Integration Runtime (formerly known as the Data Management Gateway). This is an on-premises client that works with Azure Data Factory, so let’s go over how Data Factory works before diving into the Integration Runtime client. Data Factory is used to move and transform data. For example, suppose that every night you want to copy records from SQL Database to Data Lake Store, then run a Spark job on an HDInsight cluster to process that data, and finally, store the processed data in SQL Data Warehouse. You could automate this process by creating a Data Factory pipeline that consists of three activities, one for each step. Before creating the pipeline and activities, you’d need to define the data sources and sinks. First, you’d create a linked service for each data source. A linked service contains the connection information Data Factory will use to access the data. For example, the linked service for the input data would give the connection string for the SQL Database instance. Then you’d create a dataset that tells Data Factory which data to access. In this case, it would be the name of the table. You’d also need to create linked services and datasets for Data Lake Store and SQL Data Warehouse. Now you could create a pipeline with 3 activities in it, one to copy the data from SQL Database to Data Lake Store, one to spin up an HDInsight cluster and run a Spark job, and one to copy the output data to SQL Data Warehouse. Once the pipeline is ready, you could run it manually, but it would be much easier to schedule it to run every night automatically, which you could do by setting a schedule trigger. OK, so that’s how Data Factory normally works, but how do you get it to work with external data? That’s where the Self-hosted Integration Runtime comes in. You install it in your on-premises environment, register it with Azure, and connect it to your SQL Server instance. Then, when you create the linked service for the data source, you give it the connection details for the SQL Server instance, but you tell it to connect using the integration runtime. Data Factory supports two other integration runtimes as well. The Azure Integration Runtime is the default, so you don’t normally need to explicitly create it. The Azure-SSIS Integration Runtime lets you run SQL Server Integration Services packages on Azure. An SSIS package is actually kind of like a Data Factory pipeline. It contains a series of tasks to transform data. If you already have SSIS packages that you’ve been running locally, then this is a great way to lift and shift them to Azure. When you create an SSIS Integration Runtime, you are provisioning a cluster that can run SSIS packages. Once it’s provisioned, you can even use SQL Server Data Tools or SQL Server Management Studio to deploy packages to it. However, the SSIS integration runtime incurs charges while it’s running, so to save money, you can use Data Factory to start it, execute an SSIS package, and stop it. This is similar to how Data Factory spins up an HDInsight cluster to process data. If your SSIS packages need to access on-premises data, then you have to connect the integration runtime to a virtual network that’s connected to your on-premises environment. Alright, now we’ll move on to the Azure On-Premises Data Gateway. This is something you install onsite that will let Azure Analysis Services retrieve on-premises data. First, you install it as a Windows service. Then you register it with the Gateway Cloud Service. Next, you create a gateway resource in Azure. Finally, you connect your Azure Analysis Services servers to your gateway resource. Once you have it set up, your data models can access your on-premises data sources through the gateway resource, which goes through Azure Service Bus to reach the On-Premises Data Gateway, which connects to your data sources. As you’ve seen, there are usually better ways to connect specific on-premises resources to Azure than using a VPN or ExpressRoute. Another example of this is with domain services. Most Azure customers already have a locally-installed Active Directory Domain, so if you have a direct connection to Azure, then it might seem like a good idea to just connect your Azure VMs to your on-premises domain servers. Although that would work, it could potentially be unreliable or slow, especially over a VPN. A better solution is to use Azure Active Directory Domain Services. I won’t go into the details of synchronizing it with your on-premises domain, because that’s covered in our Active Directory course. I do want to point out a couple of things to watch out for when you’re joining an Azure VM to a domain, though. First, the VM needs to be in a virtual network that’s connected to the one where your managed domain resides. Otherwise, it won’t be able to join. Second, the user whose credentials you specify for joining the VM to the domain has to be a member of the Azure AD domain controller administrators group or it won’t work. And that’s it for hybrid application).
https://cloudacademy.com/course/designing-an-azure-network-implementation/hybrid-applications/?context_resource=lp&context_id=220
CC-MAIN-2022-40
refinedweb
1,521
61.87
Recently my website was hacked, due to my stupidity. I thought I was using a secure password, but clearly I wasn't. This incident made me rethink my password management strategies and I came up with a really simple Arduino based password manager. It's not a complete commercial full proof solution for various reasons. It's more like a proof of concept. The core of the hardware is an Arduino Leonardo. The Leonardo is built around the ATMega U32 microcontroller, that has hardware USB capabilities. Optionally an Arduino Due or Yún could be used, because the controllers used on that boards also has USB capabilities. Other Arduino models are not suitable. Although every Arduino is programmed with USB, only the above mentioned models support USB natively. On boards, like the Uno a special USB-Serial translator chip is used, so it can't emulate USB devices like a keyboard or a mouse. The key point here is keyboard emulation. The device stores login passwords for various sites in the microcontroller's FLASH memory, and with a single key press it enters the key into the selected password box. The device acts like a keyboard, and it will type the passwords letters into the selected password box very fast. Because the device acts like a keyboard the solution is really platform free. It could be used under Windows, Linux, OS-X, or even Phones, and Tablets regardless of the operating system. For the user interface I used an LCD keypad shield. It can be ordered from various sites. I got mine from a Chinese reseller on e-bay. For example you can buy it here. Each reseller has it's own version, so the look of the shield may vary, but they all work the same way. The Shield features a Hitachi HD44780U compatible 16x2 Character LCD and 5 buttons. The LCD can be used with the built in LiquidCrystal library, which is good, because no additional libraries are required. The other good thing about this shield is the buttons. They only use only one analog input, because they are wired like a voltage divider. The software is relay simple. At start-up the device will ask you for an unlock key. The unlock key is a sequence of key presses on the shield. It can be configured in the sketch, you can use any combination with any length. However there are only four keys used, so if you really want to use this as a full proof key vault then I recommend using 8 key presses or more. For a precaution to make brute force attacks more harder it features a lock down timer. The Lock down timer is started when you enter 3 invalid unlock codes. It makes you wait 30 seconds, before you can try inputing the code agin. You can exit from this, by resetting the board, but it will take at least 5 seconds, because of the Arduino bootloader. Theoretically, if your unlock code uses 10 key presses then the total number of combinations is 410, which is 1 048 576. Now, let's assume that your lock down code is very strong, so to crack it we have to try out every combination. Also let's assume that the attacker is very fast and can try a combination under 1 second, but on every 3rd combination he gets a lock down, so every 3rd combination takes at least 5 seconds, which means he can try 3 combinations under 7 seconds in theory. This means that the attacker needs at least 2 446 677 seconds to test all combinations, which is 28 days without sleep or stop. In conclusion this means that if your device gets stolen, you will have plenty of time replacing your critical passwords. If you successfully unlocked the device, then you can choose the account with the up and down buttons. Pressing the select key will send the stored password to the computer. #include <LiquidCrystal.h> //Unlock key. U - Up, D - Down, L - Left, R - Right char unlock[] = "UUDDLR"; //password descriptions //static storage means it's stored in flash instead of ram static char *desc[] = { "Facebook", "Gmail", "CodeProject" }; //passwords static char *keys[] = { "Password1", "Password2", "Password3" }; //number of passwords and descriptions #define COUNT 3 //----------------------------------------------------------------- int index = 0; #define UP 0 #define DOWN 1 #define SELECT 2 #define RIGHT 3 #define LEFT 4 //Initialize LiquidCrystal lib. LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //waits for a key press and returns it's identifier int ReadKey() { int x = 1023; do { x = analogRead (0); if (x < 60) return RIGHT; else if (x < 200) return UP; else if (x < 400) return DOWN; else if (x < 600) return LEFT; else if (x < 800) return SELECT; } while (x > 800); } //initialize controller void setup() { Keyboard.begin(); lcd.begin(16, 2); //16 chars in 2 rows lcd.setCursor(0, 0); lcd.print("Arduino Keylock"); lcd.setCursor(0, 1); lcd.print("by Webmaster442"); delay(2000); Unlock(); } //Wait for lock code //Blocks further execution void Unlock() { int len = strlen(unlock); char c; int good, bad, i, count, repeat; count = 0; while (1) { c = '-'; good = 0; bad = 0; lcd.clear(); lcd.setCursor(0, 0); lcd.print("Enter unlock key:"); lcd.setCursor(0, 1); i = 0; repeat = 1; while (repeat) { int key = ReadKey(); delay(200); switch (key) { case UP: c = 'U'; break; case DOWN: c = 'D'; break; case LEFT: c = 'L'; break; case RIGHT: c = 'R'; break; case SELECT: repeat = 0; break; } if (unlock[i] == c) ++good; else if (repeat != 0) ++bad; lcd.print(c); ++i; if (i > len) break; } if ((good == len) && (bad == 0)) return; else { ++count; if (count > 2) { //lockdown mode for (int i = 30; i >= 0; i--) { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Stop guessing!"); lcd.setCursor(0, 1); lcd.print("Wait "); lcd.print(i); lcd.print(" Seconds"); delay(1000); } count = 0; } } } } void loop() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Key: "); lcd.setCursor(0, 1); lcd.print(desc[index]); int key = ReadKey(); delay(200); switch (key) { case UP: --index; if (index < 0) index = COUNT - 1; break; case DOWN: ++index; if (index > (COUNT - 1)) index = 0; break; case SELECT: Keyboard.print(keys[index]); lcd.print(" - OK"); delay(1000); break; } } The project can be expanded in various ways. The most important improvement is to make it anti tampering safe. A good start at this is to find an enclosure that fits the components and once it's placed fill the electronics and it with a two component epoxy. Optionally hot glue can be used, but I don't recommend it, because it becomes a liquid if you heat it up. Another improvement possibility is to add a serial SRAM memory for password storage. I recommend a SRAM because you can implement additional anti tampering mechanisms. For example a switch, which is activated when someone tries to take apart your device. The switch then disconnects the SRAM from backup battery, so the passwords contained in the are RAM are destroyed. For this function to work really well a computer program could be made, which would make managing the passwords and accounts simple. This solution has a problem. It's vulnerable against software key-loggers, because it acts like a keyboard. This problem can be solved with a different password transfer solution, but it would require a special software on the computer. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
https://www.codeproject.com/Articles/896923/A-Password-safe-built-with-Arduino-Leonardo
CC-MAIN-2018-51
refinedweb
1,241
63.7
, which includes Web caching and bandwidth management, an optimized firewall filtering engine, and comprehensive access controls. Safeguard your information technology environment to reduce security risks and costs, and help eliminate the effects that malicious software and attackers have on your business, by using comprehensive tools for scanning and blocking harmful content, files, and Web sites. In this document, the following new or enhanced features are discussed: Scenario Solution Network Topology Secure Application Publishing Walk-Throughs Appendix A: Additional Publishing Features Appendix B: LDAP Configuration Appendix C: Alternate Access Mapping Appendix D: Security Tips Appendix E: Administrative Tips Contoso, Ltd wants to provide employees, when they are not in the office, simple and secure access to the following business applications: Contoso also wants to enhance the working relationship with partners and vendors by providing access to these applications. Currently, access to these applications is available only to users through a client access VPN connection. For security reasons, Contoso does not want to allow direct access from the Internet to these applications, because attacks may be hidden within Secure Sockets Layer (SSL) connections. Contoso does not want internal servers to be accessible directly from the Internet. Client access VPN connections can be slow, and proper configuration of the VPN connection on the client computer is required. Also, when employees are at an off-site location, they may be behind a firewall, which blocks client access VPN connections. These limitations reduce the effectiveness of accessing important information when not in the office. ISA Server 2006 publishing provides secure and quick access to applications. The prescribed solution is to publish applications with ISA Server 2006. Communication from external clients to the ISA Server computer and from the ISA Server computer to the published server is encrypted using SSL. ISA Server is not joined to the domain and performs authentication via a Lightweight Directory Access Protocol (LDAP) connection to the domain. ISA Server 2006 Standard Edition or ISA Server 2006 Enterprise Edition can be used in this solution. ISA Server 2006 addresses the Contoso issues by making their applications available over the Internet in a secure way. When you publish an application through ISA Server 2006, you are protecting the server from direct external access because the name and IP address of the server are not accessible to the user. The user accesses the ISA Server computer, which then forwards the request to the server according to the conditions of the server publishing rule. SSL bridging protects against attacks that are hidden in SSL-encrypted connections. For SSL-enabled Web applications, after receiving the client's request, ISA Server 2006 decrypts it, inspects it, and terminates the SSL connection with the client computer. The Web publishing rules determine how ISA Server communicates the request for the object to the publishing Web server. If the secure Web publishing rule is configured to forward the request using Secure HTTP (HTTPS), ISA Server initiates a new SSL connection with the published server. Because the ISA Server computer is now an SSL client, it requires that the publishing Web server responds with a server-side certificate. ISA Server 2006 enables you to configure forms-based authentication for supported applications. Forms-based authentication enables you to enforce required authentication methods, enable two-factor authentication, control e-mail attachment availability, and provide centralized logging. ISA Server 2006 supports LDAP authentication, enabling you to place the ISA Server computer in the perimeter network (also known as DMZ, demilitarized zone, and screened subnet). The ISA Server computer does not join the domain, so you no longer need to open all of the required ports for Active Directory® directory service communications. You still need to open LDAP or global catalog ports between the ISA Server computer and the configured Active Directory domain controller. Keeping your ISA Server computers in a workgroup configuration reduces the attack surface and simplifies the deployment of ISA Server. For more information about authentication, see "Authentication in ISA Server 2006" at the Microsoft TechNet Web site. ISA Server 2006 overcomes the difficulties of using client access VPN connections in the following ways: The scenarios assume that you will deploy this solution in a laboratory environment that includes the following two networks: The following figure illustrates the computers used in the feature walk-through. The following table provides information about the computers used in the feature walk-through. dc01 Microsoft Windows Server® 2003 with Service Pack 1 (SP1) Domain controller, Domain Name System (DNS), Internet Information Services (IIS), certification authority (CA) Domain controller and internal CA exchange01 Windows Server 2003 SP1 Microsoft Exchange Server 2003 SP1, IIS Back-end Exchange server owa01 Windows Server 2003 SP1 Exchange Server 2003 SP1, IIS Front-end Exchange server sps01 Microsoft Office SharePoint Portal Server 2003 with Service Pack 2, IIS None isa01 ISA Server 2006 Standard Edition or Enterprise Edition client01 Windows® XP Professional with Service Pack 2 (SP2) Microsoft Office Word 2003, Office Excel 2003, and Office Outlook 2003 storage01 ISA Server 2006 Enterprise Edition Configuration Storage server required only for Enterprise Edition router01 IIS, DNS, CA Simulated Internet routing, DNS, and CA services The following applies: For more information about installing ISA Server 2006, see the Quick Start Guides and the Installation Guides on the product CD. The following table shows three users who have been created in the domain and have mailboxes on exchange01. Matt Berg mberg Mberg Passw0rd Yes Jeff Hay Jhay Lisa Miller lmiller Lmiller A computer referred to as router01 is providing DNS and CA services to the Test_Internet network. This computer is not a member of the domain. This section discusses the following topics: Configure ISA Server 2006 for LDAP Authentication Publish Outlook Web Access and RPC over HTTP Publish SharePoint Sites Secure Single Sign On Between Web and Outlook Web Access Publishing LDAP authentication is similar to Active Directory authentication, except that the ISA Server computer does not have to be a member of the domain. ISA Server 2006 more information about LDAP, see Appendix B: LDAP Configuration. To configure LDAP authentication, you need to: Create an LDAP Server Set Create an LDAP User Set Perform the following procedure to create an LDAP Server set. For Standard Edition, perform the following procedure on computer isa01. For Enterprise Edition, perform the following procedure on computer storage01. In the console tree of ISA Server Management, click General: In the details pane, click Specify RADIUS and LDAP Servers. On the LDAP Servers Sets tab, click Add to open the Add LDAP Server Set dialog box. In LDAP server set name, type CorpLDAP. Click Add, to add each LDAP server name or IP address. In Server name, type dc01 and click OK. Click OK to close the Add LDAP Server Set dialog box. Click New to open the New LDAP Server Mapping dialog box. In Login expression, type corp\*. In LDAP server set, select CorpLDAP, and click OK. Click Close to close the Authentication Servers window. For more information about LDAP server settings, see Appendix B: LDAP Configuration To authenticate users through LDAP, you need to determine which users to authenticate and who authenticates the users. To do this, you need to create an LDAP user set. Perform the following procedure to create an LDAP user set. For Standard Edition, perform the following procedure on computer isa01. For Enterprise Edition, perform the following procedure on computer storage01. In the console tree of ISA Server Management, click Firewall Policy: User set name Type LDAPUsers. Users Select the users to include in this user set Click Add, and select LDAP. Add LDAP User LDAP server set User name Select CorpLDAP, the LDAP server set from the drop-down list. Select All Users in this namespace. Note You can also specify user groups or specific user accounts if you do not want all users to be part of this LDAP user set. Completing the New User Set Wizard Review settings. Click Back to make changes and Finish to complete the wizard. Outlook Web Access provides Web browser access to e-mail, scheduling (including group scheduling), contacts, tasks, and collaborative information stored in Exchange Storage System folders. Outlook Web Access is used by remote, home, and roving users. RPC over HTTP enables users to access e-mail with Office Outlook 2003 over the Internet. Exchange Server 2003, together with Outlook 2003 and Windows Server 2003, support the use of RPC over HTTP to access servers that are running Exchange Server. By using RPC over HTTP, users no longer have to use a VPN connection to connect to Exchange mailboxes. Users who are running Outlook 2003 on client computers can connect to an Exchange server in a corporate environment from the Internet. When you publish Outlook Web Access servers and RPC over HTTP through ISA Server, you are protecting the Outlook Web Access server and the RPC over HTTP proxy server from direct external access because the name and IP address are not accessible to the user. The user accesses the ISA Server computer, which then forwards the request to the Outlook Web Access server or RPC over HTTP proxy server according to the conditions of your mail server publishing rule. Further, when you publish Outlook Web Access, ISA Server enables you to configure forms-based authentication, enforce required authentication methods, enable two-factor authentication, control e-mail attachment availability, and provide centralized logging. The New Exchange Server Publishing Wizard®-based devices, such as Pocket PC, Pocket PC Phone Edition, and Smartphones. In this section, the assumptions for the scenario are reviewed. Information worksheets are provided to assist in gathering the necessary information required when using the New Web Listener Wizard and the New Exchange Publishing Rule Wizard. The following assumptions apply to the scenario: Update the following table with information that will be used when you use the New Web Listener Wizard. Web listener name Name: ________________________ Client connection security Note the following: HTTPS or HTTP (circle one) Web listener IP address Network: ___________________ Optional Specific IP address: ___.___.___.___ Authentication settings Web listener SSL certificate Note This is only required if HTTPS has been selected for client connectivity security. ___Use a single certificate for this Web listener. Certificate issued to: _______________________ ___Assign a certificate for each IP address. (This option will only be available if a specific IP address has been assigned to the Web listener.) Single sign on settings ___Enable single sign on. Single sign on domain name: ___________________________: _________________ __________________ The following computers are required for this walk-through: The following procedures are used to publish Outlook Web Access and RPC over HTTP: Create a server farm (optional) Create a Web listener Create an Exchange Web client access publishing rule When you have more than one Web server providing access to the same content, you can use ISA Server 2006 2006 will detect that the server is not available and will direct users to servers that are working. ISA Server 2006 verifies on regular intervals that the servers that are members of the server farm are functioning. The server farm properties determine the following: Server farm considerations: Perform the following procedure to create a server farm. On the Toolbox tab, click Network Objects, click New, and select Server Farm. Use the wizard to create the server farm as outlined in the following table. Server farm name Type Exchange OWA. Servers Select Add and enter either the IP addresses or names of your servers: owa01.corp.contoso.com owa02.corp.contoso.com Connectivity Monitoring Apply this method Select Send an HTTP/HTTPS "GET" request to the following URL. Completing the New Server Farm Wizard Reviews settings. For more information about connectivity verifiers, see the product Help. When you create a Web publishing rule, you must specify a Web listener to be used when creating the rule. The Web listener properties determine the following: FBA. Client Connection Security Connection type, either SSL or not SSL. Select Require SSL secured connections with clients. Web Listener IP Addresses Listen for incoming Web requests on these networks ISA Server will compress content Select IP Addresses Select the External network. Check box should be selected (default). See External Network Listener IP Selection page. External Network Listener IP Selection Listen for requests on Available IP Addresses Select Specified IP addresses on the ISA Server computer in the selected network. Select 172.16.0.104 and click Add. Listener SSL Certificates A Web listener can use a single certificate for all of its IP addresses, or a different certificate for each IP address. Select Assign a certificate for each IP address. Select IP address 172.16.0.104 and click Select Certificate. Select Certificate Select a certificate Select the certificate issued to mail.contoso.com and click Select. The certificate must be installed before running the wizard. Authentication Settings Specify how clients will provide credentials to ISA Server Select how ISA Server will validate client credentials Select HTML Form Authentication. Select LDAP (Active Directory). Single Sign On Settings Enable SSO for Web sites published with this Web listener SSO domain name Clear this check box. SSO will be enabled later in the solution. Leave this field blank. Completing the New Web Listener Wizard Click Back to make changes or Finish to complete the wizard. When you publish an internal Web server through ISA Server 2006, you are protecting the Web server from direct external access because the name and IP address of the server are not accessible to the user. The user accesses the ISA Server 2006 computer, which then forwards the request to the internal Web server according to the conditions of your Web server publishing rule. An Exchange Web client access publishing rule is a Web publishing rule that contains default settings appropriate to Exchange Web client access.. Exchange Publishing rule name Type Exchange OWA Publishing. Select Services Exchange version Web client mail services Select Exchange Server 2003. Select Outlook Web Access and Outlook RPC/HTTP(s). Publishing Type Select the type of publishing. Select Publish a single Web site or load balancer. Server Connectivity Security Choose the type of connections ISA Server will establish with the published Web server or server farm. Select Use SSL to connect to the published Web server or server farm. Internal Publishing Details Internal site name Type owa01.corp.contoso.com. Public Name Details Accept requests for Public name This domain name (type below) Type mail.contoso.com. Select Web Listener Web listener Select FBA. Authentication Delegation Select the method used by ISA Server to authenticate to the published Web server Select Basic authentication. User Sets This rule applies to requests from the following user sets Select All Authenticated Users and click Remove. Click Add, select LDAPUsers, click Add, and then click Close. Completing the New Exchange Publishing Rule Wizard Go to SSL Bridging. Select Publish a server farm of load balanced Web servers. Choose the type of connections ISA Server will establish with the published Web server or server farm. Type owa. Specify Server Farm Select the Web mail farm you want to publish Select Exchange OWA. SSL bridging is used when ISA Server ends a port—by default, port 443. After receiving the client's request, ISA Server decrypts it, terminating the SSL connection. The Web publishing rules determine how ISA Server communicates the request for the object to the publishing Web server (FTP, HTTP, or SSL). If the secure Web publishing rule is configured to forward the request using HTTPS, ISA Server initiates a new SSL connection with the publishing server, sending a request to port 443. Because the ISA Server computer is now an SSL client, it requires that the publishing Web server responds with a server-side certificate. In this section, you will test the new Exchange publishing rule that you just created. Test Outlook Web Access From the router01 or client01 computer, use the following procedure to test the new Exchange Web client access publishing rule. Note Make sure that you have the root CA of the issuing CA of the mail.contoso.com certificate installed. Open Microsoft Internet Explorer. Browse to the following URL: and use the following details to log on: Test RPC over HTTP This procedure must be done from client01. Change the following account setting in Outlook 2003: ISA Server 2006 works with Windows SharePoint Services and SharePoint Portal Server 2003, to enhance security. Using the combined collaboration features of Windows SharePoint Services and SharePoint Portal Server 2003, users in your organization can easily create, manage, and build their own collaborative Web sites and make them available throughout the organization. When you publish SharePoint portal sites to the Internet, you provide employees, who are not in the office, access to the information that they need to complete their jobs, no matter where they are located, without compromising security. When you publish a SharePoint site through ISA Server, you protect the SharePoint site from direct external access because the name and IP address of the SharePoint site are not accessible to the user. The user accesses the ISA Server computer, which then forwards the request to the published SharePoint site according to the conditions of your SharePoint publishing rule. When you publish a SharePoint site, ISA Server enables you to configure forms-based authentication, enforce a required authentication method, enable two-factor authentication, control attachment availability, and control centralized logging. In this section, the assumptions for the scenario are reviewed. Information worksheets are provided to assist in gathering the necessary information required when using the SharePoint Publishing Rule Wizard. The following assumptions apply for this walk-through: You should have the following information available before running the SharePoint Publishing Rule Wizard. SharePoint publishing rule name How ISA Server connects to the published Web server If HTTPS is selected, a server certificate needs to be installed on the Web server. If the FQDN is not resolvable by ISA Server: Alternate access mapping For more information about configuring alternate access mapping, see Appendix C: Alternate Access Mapping. Confirm whether alternate access mapping has been configured on the SharePoint Portal Server computer. Yes or no (circle one) List users sets that will have access to this rule: The following sections describe how to configure the solution: Edit the Web listener Publish SharePoint site Test SharePoint publishing You need to modify the Web listener, created in Create a Web listener, so that the ISA Server computer listens for requests on the IP address 172.16.0.103, and uses the portal.contoso.com server certificate only on this IP address. The Web listener will then listen for Exchange Web client requests on 172.16.0.104, using the certificate that matches the public name used for Exchange Web client access, and will listen on 172.16.0.103 for SharePoint client requests, using the certificate that matches the public name used for SharePoint client access. On the Toolbox tab, click Network Objects, expand Web Listeners, right-click FBA, and then select Properties. Select the Networks tab. Select External and click Address. Select 172.16.0.103 from the Available IP Addresses column, click Add, and click OK. Click the Certificates tab, and then: Click OK to close the properties of the FBA Web listener. Use the information on the worksheet that you filled in previously, and perform the following procedure to publish a SharePoint site. On the Tasks tab, click Publish SharePoint Sites. Use the wizard to create a rule as outlined in the following table. SharePoint publishing rule name Type Publishing SharePoint. Publishing type options Server Connection Security Choose the type of connections ISA Server will establish with the published server or server farm Select Use SSL to connect to the published Web server or server farm. Type sps01. Type portal.contoso.com. Select NTLM authentication. Alternate Access Mapping Configuration For complete integration and functionality, you need to configure alternate access mapping on the published SharePoint site. Select SharePoint AAM is already configured on the SharePoint server. Completing the New SharePoint Publishing Rule Wizard On the router01 or client01 computer, perform the following procedure to test the new SharePoint publishing rule. Open Internet Explorer. Browse to the following url:. Use the following details to log on: You should be in the portal now. This is not ideal, because users must log on multiple times with the same credentials. This might be confusing, generating unnecessary support calls. This also increases the time it takes to complete a task. When users are rushed, such as trying to depart on an airplane flight, they might not be able to complete the task. For this reason, you should configure SSO, as described in the next topic. When users access two different Web sites, such as an Outlook Web Access site and a SharePoint site, users should not have to provide the same credentials again when they click a link to open another site. The ISA Server 2006 SSO feature reuses user credentials for another published server, eliminating the need to reenter credentials a second or third time. This will enhance the user experience, because users will click a link that will open another Web application without having to provide their credentials. The following assumptions apply: The following computers are required: Modify a Web Listener to Enable Single Sign On Test Single Sign On Between SharePoint Portal Server and Outlook Web Access Click the SSO tab. Select Enable Single Sign On. (Typically, this is enabled by default. You disabled SSO when you created the Web listener in Create a Web Listener.) Click Add to specify the SSO domains for the Web listener. Enter .contoso.com and click OK. Click OK to close the FBA Properties dialog box. Click the Apply button in the details pane to save the changes and update the configuration. Browse to the following URL:. Use the following details to log on: In this section, these additional features, which you can configure to ease your deployments, are discussed: When publishing a Web site, we recommend that users open an HTTPS connection between them and the ISA Server computer to protect the sensitive information that is being transferred over the Internet. This requires that users enter a URL such as. If the user just enters portal.contoso.com, your users to change their passwords so they do not expire. Users will also be able to change an expired password. To configure the Change Password option when using LDAP authentication, LDAP needs to be configured with the following. ISA Server 2006 features the ability to authenticate users via LDAP on computers that are running Windows Server 2003 or Windows 2000 Server. ISA Server currently does not support other LDAP servers. LDAP authentication enables the ISA Server computer to remain in a workgroup. ISA Server authenticates users in Active Directory, using an authentication method that is similar to the method used when the ISA Server computer is a domain member. Users can authenticate via LDAP using the following, which are shown as login expressions in ISA Server Management: ISA Server can connect to an LDAP server in any of the ways described in the following table. LDAP 389 No LDAPS 636 LDAP using global catalog 3268 LDAPS using global catalog 3269 To properly configure LDAP authentication, you need to configure an LDAP server set and at least one login expression. An LDAP server set is a grouping of LDAP servers, which ISA Server uses to perform user authentication. All the servers in an LDAP server set share the same LDAP connection settings. The following table lists the properties of an LDAP server set. LDAP server set Listing of LDAP servers available for LDAP user authentication. All servers listed will share the same LDAP connection settings. Required. LDAP servers Listing of LDAP servers available for LDAP user authentication. Minimum of one server is required. Active Directory domain Enter the domain name of the domain where the user accounts are defined. The name of the domain can be in one of the following formats: Optional if Use Global Catalog (GC) has not been selected. Use global catalog If your LDAP servers are also configured to be global catalog servers, select the Use Global Catalog (GC) option and you do not need to specify an Active Directory domain name. To use the Change Password option, this option must not be selected. Optional. Note The Password Management feature does not work when an LDAP server set is configured with this property. Connect LDAP servers over secure connection Select the Connect LDAP servers over secure connection option, if you want the connection between the ISA Server computer and the LDAP server to be encrypted via SSL. For more information about enabling LDAP over SSL, see "How to Enable LDAP over SSL with a third party certification authority" at the Microsoft Support Web site. Optional. User name and password This option is only required if you want to use the Password Management option with forms-based authentication. Because the ISA Server computer will not be a member of the domain, you need to specify a user name and password that will be used for verifying user account status. This account can be any domain account, even a restrictive user account. This account is used by the ISA Server to bind to the LDAP server and query the properties of the user who is logging on. This account is not involved when changing the user's password. A login expression matches the user entered credentials with the correct LDAP server set. You need at least one login expression for each LDAP server set for authentication to occur. An LDAP server set can have more than one login expression assigned to it. However, a login expression can only be assigned to one LDAP server set. Examples of login expressions: corp\* *@corp.contoso.com If a user entered credentials in the format mberg@contoso.com, and the login expression *@contoso.com has not been entered, the logon attempt will fail. Update the following table with information about the LDAP server set and login expressions. Name: _________________ Server name Name: ___________________ or IP address: ___.___.___.___ Active Directory domain name FQDN or distinguished name: _____________________________ Note If you have selected to connect over a secure connection, confirm that the proper certificates have been installed. User name and password User name: ______________ Login expression For example: corp\* To create an LDAP server set, see Create an LDAP Server Set. Alternate access mappings provide a mechanism for SharePoint administrators to identify the different ways in which users access portal sites, ensuring that URLs (links) are displayed appropriately for the manner in which the user accesses the portal site. Note the following: The Microsoft. Every alternate access setting entry must have a default URL. Each entry can have additional alternate access methods or zones,. Windows SharePoint Services allows teams to create Web sites for information sharing and document collaboration, benefits that help increase individual and team productivity. Windows SharePoint Services is a component of the Windows Server 2003 information worker infrastructure and provides team services and sites to the Microsoft Office System and other desktop programs. It also serves as a platform for application development. Including such information technology (IT) resources as portals, team workspaces, e-mail, presence awareness, and Web-based conferencing, Windows SharePoint Services enables users to locate distributed information quickly and efficiently, as well as connect to and work with others more productively. For more information about Windows SharePoint Services, see the Windows SharePoint Services home page. SharePoint Portal Server 2003 enables enterprises to develop an intelligent portal that seamlessly connects users, teams, and knowledge so that people can take advantage of relevant information across business processes to help them work more efficiently. SharePoint Portal Server 2003 defined. SharePoint Portal Server 2003 uses Windows SharePoint Services sites to create portal pages for people, information, and organizations. The portal also extends the capabilities of Windows SharePoint Services sites with organization and management tools, and enables teams to publish information in their sites to the entire organization. For more information about SharePoint Portal Server, see the SharePoint Portal Server home page. To properly configure alternate access mapping settings, you need the software versions discussed in the following table. Windows SharePoint Services Windows SharePoint Services with Service Pack 2 SharePoint Portal Server SharePoint Portal Server 2003 with Service Pack 2 Consider the following: You have published a SharePoint site through ISA Server 2006 using the SharePoint Publishing Wizard. Users will access the site by entering the following URL:. ISA Server will connect to the internal Web server using the following URL:. Based on the following information, you will configure alternate access mapping for Windows SharePoint Services and SharePoint Portal Server. When configuring alternate access mapping settings, you configure the extranet zone. A zone is another method of accessing the SharePoint site that is different than the default zone. For example, a SharePoint site named sps01 is accessed from the Internal network as. However, when accessed by a user on the Internet via ISA Server, the user accesses. Run the Stsadm.exe commands. For Stsadm.exe, you need to define both an incoming and outgoing setting for each alternate access mapping method (zone). To configure the outgoing zone, run the following command at a command prompt: stsadm.exe -o addzoneurl -urlzone extranet -zonemappedurl -url To configure the incoming zone, run the following command at a command prompt: stsadm.exe -o addalternatedomain -urlzone extranet -incomingurl -url To confirm the Stsadm setting, run the following command at a command prompt: stsadm.exe -o enumalternatedomains -url For SharePoint Portal Server, you need to configure the alternate access mapping method (zone), which automatically configures both the incoming and outgoing setting. Click Start, point to Programs, point to SharePoint Portal Server, and then click SharePoint Central Administration to open the SharePoint Central Administration application. On the SharePoint Portal Server Central Administration for SPS01 page, in the Portal Site and Virtual Server Configuration section, click Configure alternate portal site URLs for intranet, extranet, and custom access. On the Configure Alternate Portal Access Settings page, point to Default Web Site, and then click the arrow that appears. On the menu that appears, click Edit. On the Change Alternate Access Setting page, in the Extranet URL box, type the extranet URL. Click OK. The following sections highlight some security items that should be considered when publishing Web servers. We do not recommend publishing two sites with the same host name. If you had two internal Web sites, and, do not publish them using the same host name, and. The more secure publishing method is to publish each site with a unique host name, and. Users should be educated to properly log off from kiosk workstations. This is especially important when using published applications that do not have a log off button and when single sign on is configured. If a user is accessing a published application, a cookie is stored on the local computer. If the application does not have a log off button, and the user browses to another Web page and then leaves the kiosk without logging off, the cookie is still on the computer and still valid. Another user could use this cookie to access any other published application that has been configured as a single sign on published application. The following best practices should be used when using public computers to access the Internet: You should ensure that your Web application is designed to resist session riding attacks (also known as cross-site-posting, cross-site-request-forgery, or luring attacks) before publishing it using ISA Server. This section provides administrative tips for RPC over HTTP logging and for non-English forms-based authentication. When you publish RPC over HTTP, the ISA Server log may contain Failed Connection entries including Error 64: "The specified network name is no longer available" (ERROR_NETNAME_DELETED). You can safely ignore these entries, which are a response to how Exchange handles the RPC over HTTP connection. The language settings of the user’s browser determine the language of the forms that ISA Server uses. This is automatic and there are no configuration changes required..
http://technet.microsoft.com/en-us/library/bb794854.aspx
crawl-002
refinedweb
5,354
53
Back to project page compCellScope. The source code is released under: MIT License If you think the Android project compCellScope listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks. package com.wallerlab.compcellscope; //from w ww . ja v a 2s . co m /** * This class does all the work for setting up and managing Bluetooth * connections with other devices. It has a thread that listens for * incoming connections, a thread for connecting with a device, and a * thread for performing data transmissions when connected. */ public class BluetoothActivity { }
http://www.java2s.com/Open-Source/Android_Free_Code/App/project/com_wallerlab_compcellscopeBluetoothActivity_java.htm
CC-MAIN-2022-27
refinedweb
101
57.27
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 macherius wrote: | I've produced 2 intrinsic versions of the inner loop from listing 1, | one using GCC syntax (listing 4 (C) and 5 (ASM output)) and one using | icc syntax (listing 6 (C) and 7 (ASM output)). Do to time and bug | constraints, I was not able to run the gcc version, it may well be | incorrect. I've made a vectorized version of the last loop in Evaluate() that works. I've used GCC intrinsics. The last loop does only 128 * 5 mulitplications so I didn't expcet much of a speed improvement, and I didn't get much either. I've attached a patch. It works as expected, but it assumes that the nueral net has 128 hidden nodes, so make sure you don't use any of the pruning neural nets. It's compiled with GCC 3.4.2. With GCC 4.1 I get some errors with the typedef of v4sf. Can you look at the patch and see if it can be improved further? If not I will start working on the main looks with 250 * 128 multiplications. I guess that will be a real killer. | So what is worth knowing if we decided to code intrinsics for gcc? | 1) All commands needed for "float" as compared to "double" arithmetic | are in SSE already. The only addition useful for gnubg code in SSE2 | would be data type conversion (i.e. int to float). The other commands | deal with double precision arithmetic, which gnubg does not use. So | we should produce SSE code rather than SSE2 code, which will run on a | much wider base of CPUs (e.g. including AMD) too. Sure! I've only used SSE intrisics, no SSE2! | 2) In the early stages of development, gcc used Intel syntax for it's | intrinsics but later gcc switched to an own naming scheme. The | intrinsics are still 1:1 beside naming and the fact that Intel offers | a few more, which are macros (i.e. combination of several SSE | instructions). So if intrinsics are coded for gnubg, it seems | appropriate to use an own syntax to be able to #define compile time | appearance for both Intel and gcc. Since I only have GCC, I will use the GCC naming scheme. Let's worry about other compilers later. I guess it won't be that many changes. [snipp 3 and 4 about alignment] Alignment? I'm not even sure I know what it is.... - -Øystein -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (MingW32) Comment: Using GnuPG with Thunderbird - iD8DBQFCX/or6kDTFPhwyqYRArZ0AJ9rhplX3lNfGYWIxoUMxgIgTbWvJQCfYtaW te6b4QH/Lgc3dIAMal1wf5Y= =S8M7 -----END PGP SIGNATURE----- Index: neuralnet.c =================================================================== RCS file: /cvsroot/gnubg/gnubg/lib/neuralnet.c,v retrieving revision 1.23 diff -u -r1.23 neuralnet.c --- neuralnet.c 25 Feb 2005 11:34:24 -0000 1.23 +++ neuralnet.c 15 Apr 2005 17:10:25 -0000 @@ -444,6 +444,21 @@ return 0; } +typedef int v4sf __attribute__ ((mode(V4SF))); + +typedef union _vec4f { + v4sf v; + float f[4]; +} vec4f; + +#if DEBUG +void +printvec( v4sf vec ){ + float *pFloat = ( float *) &vec; + printf("%f, %f, %f, %f\n", pFloat[0], pFloat[1], pFloat[2], pFloat[3]); +} +#endif + static int Evaluate( neuralnet *pnn, float arInput[], float ar[], float arOutput[], float *saveAr ) { @@ -452,6 +467,8 @@ #else int i, j; float *prWeight; + + assert(pnn->cHidden == 128); /* Calculate activity at hidden nodes */ for( i = 0; i < pnn->cHidden; i++ ) @@ -484,14 +501,22 @@ /* Calculate activity at output nodes */ prWeight = pnn->arOutputWeight; - + for( i = 0; i < pnn->cOutput; i++ ) { - float r = pnn->arOutputThreshold[ i ]; - - for( j = 0; j < pnn->cHidden; j++ ) - r += ar[ j ] * *prWeight++; - - arOutput[ i ] = sigmoid( -pnn->rBetaOutput * r ); + float r = pnn->arOutputThreshold[ i ]; + float *pr = ar; + vec4f sum; + v4sf vec0, vec1, vec3; + sum.v = __builtin_ia32_xorps(sum.v, sum.v); + for( j = 32; j ; j--, prWeight += 4, pr += 4 ){ + vec0 = __builtin_ia32_loadups(pr); /* Four floats into vec0 */ + vec1 = __builtin_ia32_loadups(prWeight); /* Four weights into vect1 */ + vec3 = __builtin_ia32_mulps(vec0, vec1); /* Multiply */ + sum.v = __builtin_ia32_addps(sum.v, vec3); /* Add */ + } + + r += sum.f[0] + sum.f[1] + sum.f[2] + sum.f[3]; + arOutput[ i ] = sigmoid( -pnn->rBetaOutput * r ); } return 0;
http://lists.gnu.org/archive/html/bug-gnubg/2005-04/msg00018.html
CC-MAIN-2014-41
refinedweb
684
73.17
Wrong installer Flex Builder 2.0.1 Errors With all the blog posts about the arrival of the Flex 2.0.1 update there can be some confusion about where the correct installer is. The main crux of it is that if you have Flex 2 products installed (Flex Builder, Flex Data Services, etc…) you want to get a updater download, and if you are new to Flex the main installers will be Flex 2.0.1 from here on out. Well, for the heck of it I installed a new full Flex Builder 2.0.1 over my Flex Builder 2 to see what would happen. Needless to say I am not sure what it did, but when I tried to compile my projects I would get the following errors: 1172: Definition mx.core:IFlexModule could not be found. 1144: Interface method create in namespace mx.core:IFlexModuleFactory is implemented with an incompatible signature in class _HelloWorldTest_mx_managers_SystemManager. 1023: Incompatible override. 1120: Access of undefined property IFlexModule. 1180: Call to a possibly undefined method IFlexModule. I tried new projects, new workspaces and new applications, nothing got rid of the errors. Then I went back and downloaded the proper Flex 2.0.1 updater for Flex Builder 2 and everything work fine. Here is a good link with both the Flex 2 updater and try downloads to the current full installs.
http://renaun.com/blog/2007/01/wrong-installer-flex-builder-201-errors/
CC-MAIN-2018-43
refinedweb
230
76.22
Singleton Design patterns is the most simple of all the design patterns in Java. It is also the most frequently asked interview question. So lets go ahead and understand what this design pattern is all about. Understanding Singleton Design pattern Singleton as the name suggests there can be only one instance of the class.There are various cases in which we strictly need only one instance of the class. Like for example we Window manager or Print spoolers or filesystems. There are only two main points in the definition of Singleton Design pattern - - There must be only instance allowed for the class. - This single instance of the class must be allowed global point of access. Singleton instance creation Lets see the code first and then we will try to understand it. package designPatterns; public class SingletonPatternDemo { private static volatile SingletonPatternDemo singleInstance; private SingletonPatternDemo() { } // Constructor public static SingletonPatternDemo getSingleInstance() { if (singleInstance == null) { synchronized (SingletonPatternDemo.class) { if (singleInstance == null) { singleInstance = new SingletonPatternDemo(); } } } return singleInstance; } } Lets understand the code written above. First of all we have the package and the class declaration. Carefully analyze the next line private static SingletonPatternDemo singleInstance; we have a reference to the object of class SingletonPatternDemo. Note that it is just the reference and we have not created any associated object yet. Another view point can be that we have not yet used any space on heap for any object. This reference is defined as private and static. It is private which mean we cannot directly access it using class objects For Ex. objectName.singleInstance is not allowed. See Access modifiers for more details. Next it is also defined to be static which means the variable belongs to the class and not individual objects. We will get to static keyword in subsequent tutorials but for now you understand it this way - we can access the variable using SingletonPatternDemo.singleInstance i.e className.instanceVariableName. Next we have defined our constructor to be private which means we cannot create any objects by using the new keyword. Only way to create a object is the getSingleInstance() function which is public and static and returns an object of SingletonPatternDemo class. Again static means we can access it using the class Ex. SingletonPatternDemo.getSingleInstance(). Inside the getSingleInstance() method we first check whether instance of the class is already created. If it is already created we return the same instance of the class(as we are allowed to have only one instance of the class) but if there is no instance of the class that is already created we create one and return it.What we have inside the getSingleInstance() method is what we call a Double locking mechanism which i will explain explicitly.But before that lets understand what synchronized is. Note :Also note that the singleton instance is defined to be volatile. This keyword is used for consistency of data across threads. You know that each thread has it's cache where the data reference by the thread is cached and when a thread modifies the data it is still in it's local cache and may not be visible to other threads. To avoid this problem variables can be declared volatile. By declaring a variable as volatile we essentially instruct JVM not to cache the variable in threads cache. Instead all the reads and writes must directly happen in the main memory. Understanding synchronized keyword This keyword is used when we are dealing with multi-threading. Note that only member functions can be defined as synchronized not the member variables or class itself. When we declare a function to be synchronized it means only one thread can access it at a given point of time. Other than synchronized functions we can have synchronized blocks like the one we have used in the above code. It also means the same - only one thread can access the block at a given point of time. We will cover this in depth when we go through what do we mean by a class being thread-safe and related advanced topics but till then given information should suffice.Next lets understand what is the Double locking mechanism we talked about. Understanding Double locking mechanism Lets see the above code again if (singleInstance == null) { synchronized (SingletonPatternDemo.class) { if (singleInstance == null) { singleInstance = new SingletonPatternDemo(); } } This is double locking mechanism. Lets see how this works. Now our aim was to allow only single instance of the class. In multi-threading scenario lets say one thread checks singleInstance finds it to be null and enters the synchronized block. Lets say now there is s context switch or time quantum of the process is over. Next thread takes over, checks if singleInstance is null which is true so even this thread will enter the first if block. Now if we did not have the second check in the synchronized block both thread would go ahead and create an instance of the class. Final result would be we having two instances of our class which is against our Singleton goal. Hence we do a double check once again in the synchronized block. Now since it is in synchronized block only one thread will execute it at a given time and create a instance. When second thread enters this block it will find singleInstance is not null and will not create a new instance. This method is what we call double locking mechanism. Early and lazy instantiation in singleton pattern What we did in above code example is lazy instantiation which means we create instance of the class only when it is needed. On the other hand we have Early instantiation which means we create the instance once as soon as the class is loaded and return the same when user need it. Code for Early instantiation is as follows - package designPatterns; public class SingletonPatternDemo { private static SingletonPatternDemo singleInstance = new SingletonPatternDemo() ; private SingletonPatternDemo() { } // Constructor public static SingletonPatternDemo getSingleInstance() { return singleInstance; } } So we create instance of the class as soon as class is loaded and just return it when getSingleInstance() is called. This demonstrates Early instantiation. You must have notice there is no synchronization involved in early initialization. Since Singleton instance is static variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe. Note : You must have notice there is no synchronization involved in early initialization. Since Singleton instance is static variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe. Note : In Java you must have used Runtime class quite some time. For example to execute processes from Java - Runtime.getRuntime().exec(). This Runtime class is a Singleton class. There is only one instance of this class per JVM. yes as you must have notice it, they have use Early initialization ( not lazy init). Is Singleton instance garbage collected? Simple plain answer is No! This was an issue prior to Java 1.2 in which if singleton instance did not have a global reference it would be garbage collected. This defeated the very purpose of singleton as next reference created a new instance of it. But this was fixed in Java 1.2. New garbage collection model forbids any of the classes that it has loaded from being garbage collected unless all the classes are unreferenced (in which case the class loaded is itself eligible for GC). So unless the class loader is garbage collected the singleton class having static reference to singleton instance is never eligible for garbage collection. So you can be sure that the singleton instance will never be GCed. When Singleton does not remain Singleton? There are various ways Singleton property can be violated - Use reflection to create new instance - Deserialize and Serialize it again - Clone it if it implements Cloneable interface. - Use different class loaders etc. - Create constructor and throw exception from it - Implement Serializable and return same instance in readResolve() method - throw exception from clone method Related Links - When is a Singleton not a Singleton(oracle)? - When is a singleton not a singleton(Java World)? - Race Condition, Synchronization, atomic operations and Volatile keyword. - Double-checked locking wiki. - 10 Singleton Pattern Interview Questions in Java(JavaRevisited) - Why Enum Singleton are better in Java(JavaRevisited)
http://opensourceforgeeks.blogspot.com/2013/03/singleton-design-pattern.html
CC-MAIN-2018-09
refinedweb
1,372
55.24
public static C RotateLeft<C, T>(C list, int count) where C : IEnumerable<T> { return list.Skip (count).Concat(list.Take(count)); } I want to achive something like this, where T is a type paramter to IEnumerable, and C implements IEnumerable. This is the syntax I came up with but it does not pass the compiler. Any way to get what I want? Thanks! Why don´t you leave out the C-param at all? public static IEnumerable<T> RotateLeft<T>(IEnumerable<T> list, int count) { return list.Skip (count).Concat(list.Take(count)); } EDIT: As Suresh Kumar Veluswamy already mentioned you may also simply cast your result to an instance of C: public static C RotateLeft<C, T>(C list, int count) where C : IEnumerable<T> { return (C) list.Skip(count).Concat(list.Take(count)); } However whilst this will solve your compiler-issue it won´t let you get what you want as it returns an InvalidCastException when trying to cast the result of Concat to an instance of C.
http://databasefaq.com/index.php/answer/29506/c-generics-ienumerable-c-pass-generic-type-as-a-generic-type-parameter
CC-MAIN-2018-39
refinedweb
171
62.07
Many. In this tutorial we will take a deep dive into geospatial analysis in Python, using tools like geopandas, shapely, and pysal to analyze a dataset, provided by Kaggle (and originally from Inside AirBnB), of sample AirBnB locations in Boston, Massachusetts. This tutorial is targeted at folks who know a thing or two about data but haven't used Python's geospatial data tools just yet. As such, it assumes a high level of familiarity with pandas. Some familiarity with scikit-learn, statsmodels, matplotlib, and seaborn is also helpful. import pandas as pd import matplotlib.pyplot as plt %matplotlib inline pd.set_option("max_columns", None) First, let's boot up and examine our data. Since our data comes in a simple CSV file, we load it into a pandas DataFrame. listings = pd.read_csv("../input/listings.csv") listings.head() len(listings) 3585 At the moment our listings have several geospatial variables, the most important of which are longitude and latitude, which give the exact coordinates of the BnB in question. This means that it's easy for us to, say, plot every BnB location on a map: plt.scatter(listings['longitude'], listings['latitude']) <matplotlib.collections.PathCollection at 0x34240470> Chances are you've already done this before, and it's a perfectly adequate way to get started working with locations. In this plot we see...not much, really. If you're very intimately familiar with the layout of the city of Boston, you will probably be able to make sense of some of these clusters which are, to me, not being from the city, totally mysterious. In other words, this plot is missing something important: geospatial context. Additionally, this display is unprojected—it's displayed in terms of raw coordinates. The amount of distance contained in a coordinate degree varies greatly depending on where you are, so this naive plot potentially pretty badly distorts distances. We'll come back to the projection issue later; for now, there's an easy fix for both these problems. Enter mplleaflet. mplleaflet is a tool that automatically takes a coordinate matplotlib plot of any kind and places it on top of a leaflet slippy map. The best part is that it's just one additional line of code. Just throw mplleaflet.display() after generating your plot to drop it inline in your Jupyter notebook: import mplleaflet sample = listings.sample(1000) plt.scatter(sample['longitude'], sample['latitude']) mplleaflet.display()
https://nbviewer.jupyter.org/github/ResidentMario/boston-airbnb-geo/blob/master/notebooks/boston-airbnb-geo.ipynb
CC-MAIN-2019-13
refinedweb
401
56.05
From: Zach Laine (whatwasthataddress_at_[hidden]) Date: 2007-03-23 10:46:26 On 3/22/07, Robert Ramey <ramey_at_[hidden]> wrote: > How about sending me the whole file. I don't have 1.33 on my machine > and export.hpp is ALOT different in the HEAD branch where any changes > would be made. > > Robert Ramey > > Zach Laine wrote: > > On 3/15/07, Zach Laine <whatwasthataddress_at_[hidden]> wrote: > >> I did something stupid with my serialization code. I blithely > >> changed the names of several polymorphic classes everywhere they > >> appeared in the code, since they had moved out of a class into that > >> class's namespace (e.g. SomeNS::View::Primitive became > >> SomeNS::Primitive). Several months later, I discovered that I could > >> no longer read old binary archives, because I was using > >> Boost.Serialization's BOOST_CLASS_EXPORT() macro, and this macro was > >> now registering the Primtive type with the name-string "Primitive", > >> instead of "View::Primitive", which is how it was saved in the > >> oldest archives. > >> > >> Since there is a 1-1 mapping between name-strings and types, and > >> since most of the Serialization code uses static/global data, I > >> cannot currently support both the archives saved with and the > >> archives saved without the "View::" in the same program. > >> > >> Since I suspect this is not the first time someone has done this, nor > >> the last time someone will do so, is there a way to fix this using > >> the current library? If not, would it be technically possible to > >> add a BOOST_CLASS_EXPORT_ALIAS() macro, or some such? If it is > >> possible, I'm willing to supply the implementation. > >> > >> Zach Laine > >> > > > > Robert, is there any kind of verdict on the alias patch? I'd like to > > finish this topic before the thread gets too stale. > > > > Zach Laine > > _______________________________________________ > > Unsubscribe & other changes: > > > > > > _______________________________________________ > Unsubscribe & other changes: > The patch is actually against 5 files, so I'm leaving it as a patch. This time the patch is against HEAD. Find the patch and test program attached. Zach Laine Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2007/03/118596.php
CC-MAIN-2020-16
refinedweb
352
73.78
In today’s Programming Praxis exercise our task is to write two functions to convert numbers to and from Excel’s letter-based column names. Let’s get started, shall we? A quick import: import Data.Char The easiest way to covert numbers to Excel notation is recursively. I also wrote a version that uses an unfold to mirror the single fold below, but this version is more concise. toExcel :: Int -> String toExcel 0 = "" toExcel n = toExcel d ++ [chr $ m + 65] where (d,m) = divMod (n - 1) 26 Converting back to numbers is even easier and can be done in a single fold. fromExcel :: String -> Int fromExcel = foldl (\a x -> 26 * a + ord x - 64) 0 Some test cases: main :: IO () main = do print $ toExcel 1 == "A" print $ toExcel 26 == "Z" print $ toExcel 27 == "AA" print $ toExcel 256 == "IV" print $ fromExcel "A" == 1 print $ fromExcel "Z" == 26 print $ fromExcel "AA" == 27 print $ fromExcel "IV" == 256 print $ all (\n -> n == (fromExcel . toExcel) n) [1..2^16] Everything seems to be working correctly. Advertisements Tags: bonsai, code, column, columns, excel, Haskell, kata, praxis, programming
https://bonsaicode.wordpress.com/2011/02/04/programming-praxis-excel-columns/
CC-MAIN-2017-30
refinedweb
182
70.73