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
This action might not be possible to undo. Are you sure you want to continue? University of Waterloo Faculty of Mathematics A Comparison of Java to C# and Microsoft.NET NET .NET Documentation Java C# and .NET Other Considerations Java C# and .NET Porting Issues Conclusions Recommendations References 3 4 4 4 5 5 7 7 7 9 9 10 10 11 12 13 14 15 16 Graydon Armstrong A Comparison of Java to C# and Microsoft.Table of Contents Executive Summary Introduction Analysis Language Java C# APIs Java . until it is determined whether . due mainly to a poor design of the . flexibility and ease of use.NET really catches on in industry.NET. The report recommends considering scaling back . The basis of evaluation is a combination of factors.NET APIs and Microsoft’s relative lack of compatibility with other software.NET development to a core set of features.Executive Summary This report examines and compares Sun Microsystems’ Java programming language and associated APIs with Microsoft’s C# programming language and . This report concludes that Java is preferable to C# and .NET APIs. primarily including power. Cost is not an issue.NET . Graydon Armstrong 3 A Comparison of Java to C# and Microsoft. as all three packages are available freely. with a set of APIs and a virtual machine. logical design balancing power and simplicity is of great importance. flexibility and simplicity. Developers may abandon a crippled language lacking in power. and may become frustrated with a language that is unnecessarily complex.NET framework combines a new language. portability. C#. and also discusses issues encountered porting code from Java to C#. flexibility and ease of development. but Microsoft may charge for . Analysis Comparative analysis of the two platforms is based primarily on criteria of power. on the surface it sounds very much like Java. Sun Microsystems’ Java platform. which debuted in 1995. Language A strong programming language can be the foundation of a strong development platform.Introduction Microsoft in late 2000 made available a public beta release of their latest development initiative. A clean.NET tools in the future. Cost is not an issue at this time. This report compares the Java platform to the C# language and .NET APIs. has become quite popular in industry due to its type-safe object-oriented design.NET . The . Graydon Armstrong 4 A Comparison of Java to C# and Microsoft. While the keyword is convenient. does not contain features such as pointers. The result is a very powerful language.NET . This results in cleaner and more readable code. They take the place of Java’s getter and setter methods. but one which is also quite complex (possibly excessively so). structs. C++ developers may bemoan such omissions. if somewhat less efficient. the foreach keyword masks what is really a for loop using an enumeration. Other features introduced in the C# language are very welcome.NET framework in late 2000. but for simplicity. Indexers allow access to elements of a collection in a style similar to array access. C# Microsoft released the first public beta of their new C# language and . Properties in C# have advantages and disadvantages. enums. In many cases. Although very similar to – and clearly designed to compete with – Java.Java Sun Microsystems’ Java language made its debut in 1995 when it was evolved and renamed from Oak. C# supports many of the features of C++ that were dropped from Java and adds new ones as well. The language itself is similar to C++. and is employed with particular frequency by the collections and data access frameworks. C# has almost 20 more keywords than Java. such functionality probably does not belong in the language specification. this functionality would be used to check data validity before 5 Graydon Armstrong A Comparison of Java to C# and Microsoft. but there is elegance in this simplicity. Many of these keywords are used to mask simple functionality. allowing a property value to be stored or retrieved as if it were just a variable. For example. multiple inheritance or templates. code for a Java solution is generally relatively clean. by specifying the index in square brackets. operator overloading. it is entirely possible to encounter the disturbing situation in which an exception is thrown during access of what appears in code to be a regular variable. Therefore. but the stability issues are much more severe. this ends up cluttering the code. Also. In summary. Apparently this design decision was made because Microsoft felt the trivial try and catch blocks that often appear in Java were clutter. it is impossible to tell whether an exception can be thrown. but like much of the rest of . When calling a method in C#. in order to ensure stability. Graydon Armstrong 6 A Comparison of Java to C# and Microsoft. and the property body code is a regular method. These are valid concerns. to propagate an exception down the stack in Java. C# is a powerful language. However. each method along the way must declare the exception to be thrown. C# does not support checked exceptions. some aspects could have been better thought-out. Also. which may or may not be correct or current.storing the value or to perform simple processing on the value. methods are not required to declare exceptions they throw.NET. In most production systems. the danger of which is only exacerbated by C#’s lack of checked exceptions. This is not good programming form.NET . it is not desirable to have an exception propagate down the stack to a level where it may crash the program. developers may be forced to put bits of code within try blocks and catching any exception. This is unsafe operation. except by referring to the API documentation. This was a very dangerous design decision. since the act of accessing a property is really a method call. catches should be specific. a few poor (and quite illogical) design decisions seriously cripple what would otherwise be a reasonably good set of APIs.NET API used by C# is. . a well-thought-out group of collection interfaces and a variety of implementations of sets. they are a product of years of evolution. and they fumbled the opportunity badly.APIs APIs are libraries of classes implementing core functionality and concepts required by applications. unjustifiably poor. Although the problem is widespread throughout the .NET The design of the . nowhere is the problem more apparent than in the collections framework. The core Java APIs will grow significantly in size with the upcoming release of Merlin (Java 1. lists. The developers at Microsoft had a clean start. The API design can make or break an otherwise good language. logging and non-blocking IO. and maps. Of particular strength is the Java collections framework. in short. among other things. The future of the Java APIs looks bright.4). Java The core Java APIs are very well designed in most cases. Graydon Armstrong 7 A Comparison of Java to C# and Microsoft.NET APIs (suggesting it was a definite design decision). Of particular disgust are the poor implementations (or lack thereof) of the Equals and ToString methods. Support will be added for.NET . a chance to do everything right. if two collections contain all the same elements. Fixing but a few small but glaring problems would have resulted in a good API. for example. then C# should have included support for templates. delegates and such that should have been written as nested classes because of their applicability only in the context of the would-be outer class. there is the equality operator. but apparently this was not to Graydon Armstrong 8 A Comparison of Java to C# and Microsoft.NET . one can only label this as another poor design decision by Microsoft. Instead. must write their own comparator method. Overall. classes. displaying a text representation of a collection can be invaluable during the development process. any program wishing to check. many of these classes seem to be crying out for templates. yet so little to be desired. Less severe but a definite annoyance nonetheless is the ToString method. although this is more of a style issue than a real problem. Thus. Finally. Considering the uselessness of the default functionality. Worse.Microsoft decided that the Equals method should check for referential equality. and the trivial amount of code required to override it to provide a useful function. The issue becomes even more complex if collections are nested. the APIs are not wonderfully organized. they clutter the main namespaces. This was a ridiculous design decision on Microsoft’s part. the . In normal operation. There are hundreds of enums.NET API leaves so much. not equivalency of content. in particular while debugging. for the few occasions when a program does need to check referential equality. the default operation of which is to return the type name of the object. If Microsoft considers extending classes in such a way to be an acceptable practice. most programs will not have cause to call ToString on a collection. in many cases the only difference in functionality to the superclass is the return or parameter type of some methods. However. It is not unreasonable to suggest that Javadoc has been one of the main factors driving widespread adoption of the Java platform.NET C# appears to have a documentation standard. Unfortunately. By defining a standard format for documenting code and providing the Javadoc compiler. Visual Studio sets it up with XML tags in what one can only Graydon Armstrong 9 A Comparison of Java to C# and Microsoft. but based on XML. This facilitates – and thereby encourages – third-party development. a search of the MSDN Library turns up no documentation about the documentation format.NET . Ironically. Documentation Documentation is a key resource in development on any platform. similar to Javadoc. Java The Javadoc documentation system. The only suggestion that such a format exists comes from the auto-format and auto-complete features in Microsoft Visual Studio. when a developer begins a comment in an appropriate context. at the time of writing.NET. C# and . C# provides similar functionality. Likewise.be. Java defined a standard format for code documentation and provided tools to compile it to HTML. in-house productivity is improved by virtue of having available quick reference for libraries used by the code under development. Good documentation can be a significant factor in encouraging adoption of a technology. meta-documentation for C# is difficult-to-impossible to find. certainly deserves mention. it is likely too late to remedy these problems. Sun has made it easy to produce excellent HTML documentation of APIs. as doing so at this point would break countless pieces of software already developed for . while not technically part of Java. The documentation can be compiled into XML with a command-line tool.NET . which is heavyweight and unnecessarily convoluted.NET API documentation in the MSDN Library. but no apparent tool is yet provided to transform the XML to a readable HTML format. One can hope that when such a tool is eventually provided. Graydon Armstrong 10 A Comparison of Java to C# and Microsoft. and not like the . that the generated HTML will be of a simple format similar to Javadoc.presume is the C# documentation format. the Java virtual machine has been ported to literally scores of operating environments. testing APIs. and as such. it runs Java. Chances are. if an API feature is not adequately documented. including Windows. A variety of compilers are available. one cannot yet expect it to have the wide platform support enjoyed by Java. many for free. BSD.NET . as it promotes greater understanding of what is occurring behind the scenes. Source code for the APIs is included in the Java Development Kit. C# and . It is certainly beneficial to developers to be able to see API source code. Microsoft has so far only released the 11 Graydon Armstrong A Comparison of Java to C# and Microsoft. debuggers. if someone runs it. a developer can peek at the source to determine what the feature does and how it works. Issues such as costs and levels of industry adoption must also be addressed. not to mention high-end server platforms such as IBM OS/390 mainframes and handheld devices such as the Palm platform.Other Considerations Quality is not the only factor in a comparison between two technologies such as Java and .NET . Solaris.NET. subject to licensing terms. and in some cases allows optimization for these processes. and other tools. MacOS and virtually every flavour of Unix. Additionally. Java Java already has a large developer and user base. It is very platform independent. Linux.NET is a relative newcomer to the marketplace. Java development tools are also prolific. as are profilers. Java is open-source. although a subset of the framework has been approved as an ECMA standard and so a reference implementation of this subset may be provided. though.NET API is closed-source.NET. Graydon Armstrong 12 A Comparison of Java to C# and Microsoft.NET APIs appear to be quite Microsoft-centric. however. and this is a dangerous trap.. the . although a port to FreeBSD is apparently in the works. . documentation of some classes suggests their functions are clearly only applicable to a Windows machine. Currently. and the data access classes are designed to use Microsoft SQL Server. This may change with the final release of .NET framework for their Windows platform. Microsoft seems intent on locking consumers into their technology in this way.NET . it is reasonable to expect Microsoft software to work efficiently together.NET. On the plus side. and should be considered in a decision to develop for .NET development tools such as the C# compiler are available for free download from Microsoft. This may be simply a “token” port to allow . The .NET to claim cross-platform compatibility. Porting Issues Because both Java and C# have their roots in C++. Methods must be explicitly declared virtual if they are to be able to be overridden. In general. which become apparent when normally-overridden methods such as Equals seem to be misbehaving. the default implementation (referential equality check) is being used.NET . This issue can frequently cause runtime problems. fields and constants to be named using the InitialCaps (e. types. the only difference between the names of Java methods and their .NET counterparts is the capitalization. myString) style is used for 13 Graydon Armstrong A Comparison of Java to C# and Microsoft. Often. this is trivial to convert. The .g. this is not the case. all but minor aspects of the grammar are identical. properties.NET naming standard is for all namespaces. methods are virtual by default. C# uses a namespace block and using statements instead of Java’s package declaration and import statements. the superclass is accessed with the base keyword (super in Java). subclasses may override their implementations to provide isomorphism. A final language issue that often escapes preliminary detection is C#’s virtual and override methods. The initialCaps (e. really. there are no major language issues that arise during porting. In C#. In Java. Many of the .g. startIndex.NET classes are isomorphs of their Java counterparts. A C# type declaration is in the C++ style. and its constructor is called in the C++ style. methods. In C#. As such. ArrayList. The overriding method must also declare with the override keyword that it overrides a method. with the class name followed by a colon and a comma-delimited list of the type it extends and/or the interfaces it implements (as opposed to Java’s extends and implements keywords). it is a fairly trivial task in many cases to port Java code to C#. CompareTo) style. the main method is called Main. The tool would automate the conversion of Java code to C#. there exists Visual J#. Since the main issue in porting is in dealing with the API differences. if it is. it will likely be in no small part due to Microsoft’s marketing clout and their lock-in strategy.NET will be a real contender.NET had a fresh start. In the meantime. there is no reason not to port it all the way to C#.NET” (Java User Migration Path to . but they may be rendered irrelevant anyway if Microsoft releases the “JUMP to . A full discussion of porting issues is beyond the scope of this report. and Java already has a large developer and user base. unconstrained by requirements of backward compatibility.NET to be done in the Java language.NET APIs. Java will likely remain a powerful force in the industry for years to come.NET . Considering that . Its APIs are much better designed than the . Note that in an executable class in C#. Conclusions Java is a much simpler language than C#. its offering could have been much better.local variables only. which allows coding for .NET) tool it announced long ago. Graydon Armstrong 14 A Comparison of Java to C# and Microsoft. yet it lacks little of the power of C#. though. It remains to be seen whether . but viable. If porting becomes a significant time sink without much payoff. Clients should be encouraged to use Java solutions wherever possible. This issue may need to be reopened at a later date.NET API is poorly designed. difficulties in porting may increase in number and severity. customer requirements may demand support for . and it remains to be seen whether it will be truly accepted by the industry. The recommended course of action is to focus primarily on development for Java. Conversely. Abandoning a minimal set of ported code is not a big deal. the proposed solution allows for quick development around a minimal existing ported code base should the need arise while at the same time insulating the company from danger should the . However. Currently. since time is of great importance in software development. and neither is adding functionality to that code.NET. Either course of action can be undertaken with minimal costs. as the code increases in complexity. it may be worthwhile to abandon . However. It may not seem wise to wait “sitting on the fence” about this issue. it may make sense to provide full support for . The . if the API is improved or gains wide acceptance in industry. the task of porting Java code to C# is awkward. However.NET. Graydon Armstrong 15 A Comparison of Java to C# and Microsoft. development in only Java would be sufficient.NET initiative be a flop.Recommendations Ideally.NET . Porting to C# should be done only in cases where the work required to port is trivial or where key functionality is implemented by the code in question.NET. 3/techdocs/api/ The Java Language Specification (Second Edition) Java 2 Platform Enterprise Edition v1.com/CsharpVsJava.geocities.References Java 2 Platform Standard Edition v1.NET Framework Class Library C# From A Java Developer’s Perspective Java Resources Overview API Specification Graydon Armstrong 16 A Comparison of Java to C# and Microsoft.html .25hoursaday.com/library/en-us/csspec/html/CSharpSpecStart.sun.sun.asp C# Language Specification API Specification .
https://www.scribd.com/document/128837767/A-Comparison-of-Java
CC-MAIN-2017-26
refinedweb
3,186
52.97
>> validate the response time of a request in Rest Assured? We can validate the response time of a request in Rest Assured. The time elapsed after a request is sent to the server and then receiving the response is known as the response time. The response time is obtained in milliseconds by default. To validate the response time with Matchers, we need to use the below-overloaded methods of the ValidatableResponseOptions − - time(matcher) - it verifies the response time in milliseconds with the matcher passed as a parameter to the method. - time(matcher, time unit) - it verifies the response time with the matcher and time unit is passed as parameters to the method. We shall perform the assertion with the help of the Hamcrest framework which uses the Matcher class for assertion. To work with Hamcrest we have to add the Hamcrest Core dependency in the pom.xml in our Maven project. The link to this dependency is available in the below link − Example Code Implementation import org.hamcrest.Matchers; import org.testng.annotations.Test; import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; public class NewTest { @Test public void verifyResTime() { //base URI with Rest Assured class RestAssured.baseURI =""; //input details RequestSpecification r = RestAssured.given(); // GET request Response res = r.get(); //obtain Response as string String j = res.asString(); // obtain ValidatableResponse type ValidatableResponse v = res.then(); //verify response time lesser than 1000 milliseconds v.time(Matchers.lessThan(1000L)); } } Output - Related Questions & Answers - How to get the response time of a request in Rest Assured? - How to validate XML response in Rest Assured? - Explain DELETE request in Rest Assured. - Explain PUT request in Rest Assured. - Validate JSON Schema in Rest Assured. - How to use Assertion in response in Rest Assured? - How to verify JSON response headers in Rest Assured? - How to update the value of a field in a request using Rest Assured? - How to transform the response to the Java list in Rest Assured? - Explain how to get the size of a JSON array response in Rest Assured. - How to parse a JSON response and get a particular field from the response in Rest Assured? - How to extract the whole JSON response as a string in Rest Assured? - How to verify a JSON response body using Assertions in Rest Assured? - How to incorporate TestNG assertions in validating Response in Rest Assured? - How to pass more than one header in a request in Rest Assured? Advertisements
https://www.tutorialspoint.com/how-to-validate-the-response-time-of-a-request-in-rest-assured
CC-MAIN-2022-33
refinedweb
414
60.61
I've come abit further parsing FOAF-files. The result is available for download at, but it's still a bit buggy, for instance it crashes when I tried to load Mark Pilgrims FOAF-profile. Still, it can generate rather easily a structured FOAF-document and load data from a xml-file or an url. It has some special properties not part of the FOAF-standard, but they're in a seperate namespace in the xml-file and should not be hard to remove or not use for people who want to use it for ordinary FOAF-stuff. If anybody has time to test it that would be nice. Problems remaining are : 1. cannot get the encoding set correctly in the generated document. This means norwegian characters and other non-english characters will cause the document to be seen as invalid xml. THIS IS A MAJOR PROBLEM. Any help here would be appreciated. 2. The code is very verbose. I'm not good at creating xml in code other than doing the old hard way. Hints on how to do it more object-like are welcome, allthough the way I do it now works ok too. 3. The parser uses DOM, ie. everything is read into memory. Other solutions, like using minidom or SAX/Expat are welcome. I cannot use anymore time on this at the moment, due to other deadlines. It has not been tested on huge documents so I know nothing about speed etc. 4. Better support for all the goodies available in RDF, like Dublin Core and Syndication elements. Eh ... support for some of them, any support at all, would be an improvement. Best regards, Thomas Weholt "Thomas Weholt" <2002 at weholt.org> wrote in message news:M6XIa.8186$Hb.144201 at news4.e.nsc.no... > Hi, > > I need a FOAF[1]-parser that can handle deep-hierarchy of nodes ( ie. > Friends knowing friends knowing friends etc. ) So far I've looked at >. > > Any help would be highly appreciated. > > [1] : > [2] : > > Best regards, > Thomas Weholt > >
https://mail.python.org/pipermail/python-list/2003-June/220763.html
CC-MAIN-2016-50
refinedweb
338
77.13
I'm trying to determine whether it is a bug that Python's urllib.urlopen() function omits an HTTP Accept header when making simple REST API requests. The Facebook Graph API seems to notice whether the header is present or not: GET /zuck HTTP/1.0 Host: graph.facebook.com Accept: */* application/json; charset=UTF-8 text/javascript; charset=UTF-8 Accept: */* $ curl -v > GET /zuck HTTP/1.1 > User-Agent: curl/7.30.0 > Host: graph.facebook.com > Accept: */* Accept: */* def default_headers(): return CaseInsensitiveDict({ 'User-Agent': default_user_agent(), 'Accept-Encoding': ', '.join(('gzip', 'deflate')), 'Accept': '*/*', 'Connection': 'keep-alive', }) */* indicates all media types if no Accept header field is present, then it is assumed that the client accepts all media types Accept: */* Accept: */* >>> import httplib >>> httplib.HTTPConnection.debuglevel = 1 >>> import urllib >>> u = urllib.urlopen('') send: 'GET /zuck HTTP/1.0\r\nHost: graph.facebook.com\r\nUser-Agent: Python-urllib/1.17\r\n\r\n' */* */* Reading-up about proxy servers (like NGinx and Varnish) helped me figure out what is going on. While the presence of an Accept: */* header shouldn't make a difference to a server, it can and likely will make a difference to a proxy server when the response includes a Vary: Accept header. In particular, the proxy server is allowed to cache different results for different or omitted Accept headers. Facebook has updated (and closed-off) its API since this question was asked, but at the time, here is the scenario that caused the observed effects. For backwards compatibility reasons, Facebook was using content negotiation and responding with text/javascript; charset=UTF-8 when getting the request that either omitted the Accept header or had a browser-like Accept: text/html;text/*;*/*. However, when it received Accept: */*, it returned the more modern application/json; charset=UTF-8. When a proxy server receives a request without an accept header, it can give either one of the cached responses; however, when it gets Accept: */*, it always gives the last response. So here is why you should include the Accept: */* header: If you do, then a caching proxy will alway return the same content type. If omit the header, the response can vary depending on the results of the last user's content negotiation. REST API clients tend to rely on always getting the same content type back every time.
https://codedump.io/share/bHTpa0KA2D77/1/is-it-a-bug-to-omit-an-accept--header-in-an-http10-request-for-a-rest-api
CC-MAIN-2017-47
refinedweb
390
55.34
I, though, am "one of those condescending Unix computer users". I've used Windows on and off since 1993, but I've only used Windows out of some kind of necessity. It always seemed to me to be badly designed and obscure and cluttered with legacy crap, and I might try to use that as an excuse for not liking Windows, if it weren't for the fact that you could say the same things about Unix. It may be that the real difference is just that I'm much better versed in the bad design and obscurity and clutter of Unix. I don't actually believe that, but doesn't matter anyway: the fact is, Windows exists, and Windows is huge. One reason I've never been convinced by the argument that "Linux will win the desktop because it costs nothing, and people love not paying for stuff" is that you don't have to strike up too many conversations with strangers to find that the man on the street considers Windows (and MS Office and the like) to cost nothing either. Software either comes with the computer (and they get a new version when they get a new computer), or, if they're really keen, it comes from work or a friend. People proudly tell me they copy Windows, which I've always found strange on many levels. But that in itself tells you something about Windows' ubiquity and how it's perceived. Ignoring Windows is like ignoring religion. You may personally think it's a load of shite, but you can't deny its influence, and that influence alone makes it worthy of study. Although I sometimes read posts on Chen's blog when they're linked to from places I read, and I was aware of the book's existence, I hadn't been curious enough to go out and buy "The Old New Thing", but I saw a copy on a shelf at work, borrowed it, and read it over this past weekend. I loved it. It's full of random stuff from a perspective quite different from my own, but with an obvious shared heritage of double-frees and memory leaks and performance problems and so forth. There were whole chapters I basically skipped over (chapter 15, "How Window Messages Are Delivered and Retrieved", for example), but the range of the book is sufficiently diverse, and Windows' influence so far-reaching, that there's bound to be something of interest. Topics range from memory allocation (and problems all the way from 16- through 32- to 64-bit), concurrency primitives, text rendering, debugging, reverse engineering, to why various Windows features/APIs are the way they are. I liked the debugging tips slipped in here and there; the kinds of things you learn on the job rather than in class. "The poor man's way of identifying memory leaks", for example, talks about just letting a program leak away, and seeing what the heap's full of. And the fact that the caller whose allocation attempt causes your system's out of memory failure is probably responsible (despite your temptation to assume innocence unless proven guilty). And that the former can help you confirm or deny the latter. These are the kinds of things that aren't usually considered academic enough to be written down, but are still bloody useful. Sure, you and I know that one, and probably most of the other debugging tips in the book (though there were also common Windows API mistakes, and thus fairly meaningless to me), but we also know people who still don't know this stuff, and we can probably still remember the time when we didn't know it either. If, on the other hand, you're thinking "dude, get better tools", just wait: one of these days you'll be looking at a customer's production system, or looking at a postmortem, or a system too large or new or small to be able to afford better tools. The Windows-specific stuff is sometimes a bit annoying, but it's only to be expected in a book like this, and it's not too hard to work out what's going on. For example, it seems like Windows uses the terms "brush" and "pen" for something like (but not exactly the same as) Java2D's Paint and Stroke respectively. It's easy enough to work out, and the (surprisingly few) sections that are obviously of no relevance outside Windows itself are easily skimmed over. The book opens with a chapter of anecdotal examples of the kinds of lessons the Linux desktop still needs to learn. It's interesting at many points in the book, in fact, to contrast the three camps. Chen usually only talks about the Windows camp, for obvious reasons, and their position can seemingly be summarized as "we started this a long time ago, on really crappy hardware, and we know better now, and try to do new stuff in a way that shows we've learned some of these lessons, but our business is selling OS upgrades, and every incompatible change we make costs us a sale, so we go to ridiculous lengths to avoid ever breaking anything, even stuff that only ever worked by coincidence, or that deliberately went out of its way to fiddle with undocumented internals". Mac OS is pretty much at the opposite end of the scale, with "we know that you can't make an omelet without breaking eggs, so eggs will be broken if we consider it to be in our greater good, and you get about one year of deprecation and the year after that, your code breaks; we're a hardware company, so we know people will buy the new release anyway, even if only because it comes 'free' with your next machine, but actually, they'll probably buy it anyway, because our main customers are individuals, not corporations, and they like shiny new stuff and don't have any DOS applications written in assembler in 1982 that they've long since lost the source to". Linux? "Nothing really works very well yet, but it's free and Free, and you can fix it yourself, and it doesn't matter anyway because next week we're going to rip out all this half-working stuff and replace it with stuff that fixes a few things that currently don't work while at the same time breaking things that did work; it doesn't matter because we don't have customers, and our non-customers don't have any software they don't have the source to anyway". Of course, you never hear these philosophies stated explicitly like that. Apple's too secretive, no-one can seriously claim to speak for "Linux", and I've no idea whether Chen is really representative of Microsoft, assuming it's any more possible to be representative (in the non-legal sense) of a company that large than it is to represent "the Linux community". But Chen has a clear voice, and it's an interesting perspective to me, especially presented through the course of a book, rather than in bits and pieces as I read occasional linked-to blog posts. If you want just one contrast, try this, from "Why does DS_SHELLFONT = DS_FIXEDSYS | DS_SETFONT" (someone spank the editor who changed == to = there!): ... This allowed people to write a single program that got the Windows 2000 look when running on Windows 2000 and got the classic look when running on older systems. (If you make people have to write two versions of their program, one that runs on all systems and one that runs only on the newer system and looks slightly cooler, they will usually not bother writing the second one.) This, to me, was a revelation. By "people", he means, of course, "Windows programmers". But how interesting that, from my position outside the Windows camp, I actually did a double-take when reading his parenthetical comment. Surely, I thought, he means they won't bother writing the backwards-compatible version? Let the dead bury the dead, and all that? Isn't "looks slightly cooler" an important selling feature, even for Windows (the OS)? Try to find a Mac application (that's still maintained) that still runs on 10.2, say, and you'll not have much luck. Try to run the latest version of a Linux app on Ubuntu 8.04 (the "long-term" release that some people will be stuck with until 2010-04) without resorting to building it yourself from source... and even then, you'll probably need to build the latest versions of umpteen different libraries it depends on. I was well aware that Microsoft bend over backwards to keep stuff working (and I was disappointed that Chen doesn't actually go into much detail on the techniques they use, which was something I would have been particularly interested to read about), but I didn't realize the backwards-compatibility-above-all mindset extended to third-party developers too, or is at least perceived to do so. Going back to some of the other topics, I was interested to hear both that Windows gets the old "pointer change without mouse movement" problem right, and how, and that it causes complaints (presumably from people who haven't suffered systems that get it wrong), and that no-one appreciates the effort much because the related "pointer change when a component scrolls under the mouse" problem needs to be solved per-application, and often isn't. I've always hated programming for systems that won't even let me get those details right, and it's interesting to hear a Windows programmer ("of all people!") saying how much he hates it when apps don't get those details right. The weird part is that in the final chapter of the book he mentions several "funny stories" that are actually just annoying bugs in Microsoft software, but which he seems to see as cases of user error. It's almost like the last chapter is written by a different person, that depressing guy you always imagine works at Microsoft, cranking out shit code with a shit UI and with no interest in rising to the challenge of writing something that works well under all the awful constraints imposed on it, but who's just interested in getting all the relevant forms filled and boxes checked so he can move on to the next task he also doesn't care about. Maybe Chen is that guy, at times, and his editor asked for an extra 20 pages Chen didn't want to write? Maybe we're all that guy at times, though most programmers I've known tend to be good at losing tasks in their to-do lists, because there's always more stuff to do than there is time to do it. What else did I like? I liked the repeated mentions of the need for a holistic view of performance: that making one thing better at the expense of some other thing isn't necessarily a good idea. There are repeated reminders that it's bad to assume that your application is the most important application in the user's day, every day. (You'd hope this wouldn't even need mentioning, but everyone who's ever used software knows it does.) Speaking of things that shouldn't need mentioning, I was amused to see an analog of something I first came across in a Studs Terkel interview with a Republican ex-governor of a state like Montana. This old Republican was criticizing modern politicians on both sides, complaining that they'd lost the insight of looking at any new legislation as if it had been brought up by the opposition for the opposition's own use. His point being that at some point, anything can and will be used against you. And if you don't like the look of it from the unfriendly end of the barrel, maybe you ought not be handing it out in the first place. Chen's version is more like "what could a virus writer do with this API?" or "if I was a user, how could a developer make a really annoying application with this API?". One of Chen's code snippets had me mystified. I'll ignore the use of SIZE_T instead of size_t and assume I don't want to know, but there was a bit of C++ that contained this: // Since this is just a quick test, we're going to be sloppy using namespace std; // sloppy The code contains three lines that would need an explicit "std::", none of which, with the "std::" added, would be as long as the "sloppy" comment. Bizarre. And a missed opportunity to show a handy trick I learned from Martin Dorey. Don't want to keep repeating std::cout (which were two of the three uses of "std::" in Chen's code)? Do this: std::ostream& os(std::cout); os << blah; This is nice even in code that's "just a quick test", but it's better still when that "quick test" turns into production code, and you need to refactor so you can pass in an arbitrary stream. Your code is already referring to just "os" (the usual name for an ostream), so all you need to do is turn the local "os" into an extra argument. Job done. Returning one last time to things I liked, there was an explanation of why NTFS keeps a Unicode case mapping table on disk, which is something I'd wondered about, but obviously never enough to ask. And the weird code I just mentioned was actually in a section titled after the only thing I knowingly quote from a Microsoft developer, Rico Mariani: "a cache with a bad policy is another name for a memory leak". Would I buy this book? No. It's not a classic, or a reference work I can imagine I'd keep coming back to. But it was an enjoyable read, and an interesting insight into a parallel universe. Borrow.
http://elliotth.blogspot.com/2008/11/review-old-new-thing.html
CC-MAIN-2017-13
refinedweb
2,366
58.86
[ ] Dean Pullen commented on WW-2987: --------------------------------- Ok, as requested via the mailing lists, I'm reopening this issue. As a summary - a JSP forward as the input will work, but ONLY if you use a non-root namespace for the relevent actions. A redirectAction will not work, with or without using messageStoreInterceptor. You can get a redirectAction to work if you 'fudge' the process, using a messageStoreInterceptor, by including an input result on the action used by redirectAction - which is slightly odd. I'm attaching a test class, a test struts-test.xml (uses namespace 'test' to get the JSP forward to work), and an appropriate JSP. If you wished this to be packed in someway different, let me know. >.
https://mail-archives.us.apache.org/mod_mbox/struts-issues/200902.mbox/%3C48979547.1234265986467.JavaMail.jira@brutus%3E
CC-MAIN-2021-31
refinedweb
120
63.39
Controlling Banshee Media player with Python using multiprocessing and threading banshee-control gist Whenever I have tried to control Banshee Media Player using terminal, I always had to use two terminals! One for the main process and other for sub process such as ‘banshee –pause’,etc. So, I always wanted to make something which would control banshee with one terminal. I thought I could use threading, but sometimes it’s difficult to end a thread and also my last experience with multithreading was not that good as I tried to implement it in my gmail-GUI, and it did not work well. So, I moved on to multiprocess. Python docs for multithreading and multiprocessing are not as neat as some of the other lib docs. I looked it up on google and found this IBM webpage about multiprocessing using Python. It was not the first time I had gone to this webpage. I stumbled upon this page when I was making my gmail-GUI and needless to say multiprocessing didn’t work well either. I tried multithreading and it was working fine, but there was just one problem. I could not terminate the main thread and had to kill it using ctrl^d. I browsed many pages, many stackoverflow questions but none of them showed any significant results. I could not end the main banshee process. I tried to terminate the thread with os.system('kill '+thread._Thread__ident) but since it was thread and not a process, _Thread__ident gave me some id which was not process id! ob! I also tried thread.exit(), ._Thread__stop . But nothing worked. I looked for multiprocessing using Python and somehow found that I could terminate a process using Process.terminate(). I thought this is it and tried it out on banshee! It worked! sigh! import os import time import threading import sys from multiprocessing import Process def banshee(): os.system('banshee --play') return class do(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): try: command_str = str(raw_input('Command: ')) if command_str == 'quit': os.system('banshee --stop') return os.system('banshee --'+command_str) print command_str self.run() except EOFError: print 'Got keyboard interrupt' print 'quitting' os.system('banshee --stop') return def main(): p = Process(target = banshee) p.start() command = do() command.start() command.join() print 'Quitting' p.terminate() print 'terminate' if __name__ == '__main__': main() So, first create a process which will initialize/start banshee! There is a bug in banshee media player, due to which it doesn’t start playing on its own when command $ banshee –play is given for the first time, i.e., banshee player is not running. create a Process p in the background, which will start banshee. We have initialized banshee. Now, we need to give commands. So, create a new thread to give commands. So, I created a thread command. It takes the input from the user, and feeds it to the banshee. Since banshee has already been initialized by Process p, the thread will end. To keep it continue, I have used recursion. Unless and ‘quit’ is not given as input, the thread will continue. ‘quit’ will end the command thread. In the main(), I’m waiting for command thread to end by using command.join(). As soon as it ends, it prints ‘Quitting’. Now, I have stopped banshee but my Process p is still running since there is no command for banshee to exit. So, I terminate Process p. Even after terminating the Process p, though, python script has ended, banshee window will still be there. The reason behind is the new policy of Ubuntu.. I am looking for same thing for vlc! since every command like ‘vlc –play’, ‘vlc –pause’, will initialize a new vlc window! P.S. It’s always fun doing multiprocessing and multithreading with Python! Playing around with Android UI Articles focusing on Android UI - playing around with ViewPagers, CoordinatorLayout, meaningful motions and animations, implementing difficult customized views, etc.
https://jayrambhia.com/blog/controlling-banshee-media-player-with-python-using-multiprocessing-and-threading
CC-MAIN-2022-05
refinedweb
656
67.96
Redirect on Login Our secured pages redirect to the login page when the user is not logged in, with a referral to the originating page. To redirect back after they login, we need to do a couple of more things. Currently, our Login component does the redirecting after the user logs in. We are going to move this to the newly created UnauthenticatedRoute component. Let’s start by adding a method to read the redirect URL from the querystring. Add the following method to your src/components/UnauthenticatedRoute.js below the imports. function querystring(name, url = window.location.href) { name = name.replace(/[[]]/g, "\\$&"); const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)", "i"); const results = regex.exec(url); if (!results) { return null; } if (!results[2]) { return ""; } return decodeURIComponent(results[2].replace(/\+/g, " ")); } This method takes the querystring param we want to read and returns it. Now let’s update our Redirect component to use this when it redirects. Replace our current export default ({ component: C, props: cProps, ...rest }) => { method with the following. export default ({ component: C, props: cProps, ...rest }) => { const redirect = querystring("redirect"); return ( <Route {...rest} render={props => !cProps.isAuthenticated ? <C {...props} {...cProps} /> : <Redirect to={redirect === "" || redirect === null ? "/" : redirect} />} /> ); }; And remove the following from the handleSubmit method in src/containers/Login.js. this.props.history.push("/"); Now our login page should redirect after we login. And that’s it! Our app is ready to go live. Let’s look at how we are going to deploy it using our serverless setup. If you liked this post, please subscribe to our newsletter, give us a star on GitHub, and check out our sponsors. For help and discussionComments on this chapter For reference, here is the code so farFrontend Source :redirect-on-login
https://branchv21--serverless-stack.netlify.app/chapters/redirect-on-login.html
CC-MAIN-2022-33
refinedweb
287
53.37
Hide Forgot Description of problem: After choosing this kernel in the fedora start menu i get a kernelloop and my system freeze. This happens in the begining of the boot process before udev. There was no trace or anything other logged. So i had to write it down from the screen. My root-filesystem is btrfs on /dev/sda1. If you want to know more info let me know. Version-Release number of selected component (if applicable): kernel-2.6.33.5-112.fc13.x86_64 How reproducible: Starting kernel Steps to Reproduce: 1. 2. 3. Actual results: Expected results: Additional info: -with kernel-2.6.33.5-112.fc13.x86_64.debug: Kernel-panic - not syncing:VFS: Unable to mount root fs on unknown-block (0,0) Pid:1 comm:swapper Not tainted 2.6.33.5-112.fc13.x86_64.debug #1 Call trace: [<ffffffff8147939b>] panic x0x7a/0x142 [<ffffffff81d7931b>] mount_block_root x0x266/0x291 [<ffffffff81d7939b>] mount_root x0x56/0x5d [<ffffffff81d79510>] prepare_namespace x0x170/0x26a [<ffffffff81d787a8>] kernel_init x0x256/0x26a [<ffffffff8100aae4>] kernel_threat_helper x0x4/0x10 [<ffffffff8147b410>] restore args x0x0/0x26a [<ffffffff81d78552>] kernel_init x0x0/0x26a [<ffffffff8100aae0>] kernel_threat_helper x0x0/0x10 grub.conf: title Fedora (2.6.33.5-112.fc13.x86_64.debug) root (hd0,1) kernel /vmlinuz-2.6.33.5-112.fc13.x86_64.debug ro root=UUID=5654627e-a81f-4456-965a-8ed3469c4126 rd_NO_LUKS rd_NO_LVM rd_NO_MD rd_NO_DM rd_NO_PLYMOUTH LANG=de_DE.UTF-8 SYSFONT=latarcyrheb-sun16 KEYTABLE=de-latin1-nodeadkeys nofirewire fastboot raid=noautodetect selinux=0 nomodeset vga=789 The patch btrfs-check-for-read-permission-on-src-file-in-clone-ioctl.patch is ugly for my system. I delete the patch lines in patch-2.6.33.5 from this patch and rebuild the kernel. With this rebuild-kernel my system boot and work with no problems. I hope you delete this patch from the kernel mainline or make a rework of it. I have exactly the same issue with an ext4 filesystem. I run on a fresh installation of fedora (about 30min when the bug appends), so all my configs are about the default ones. Try use kernel-2.6.33.5-122.fc13.x86_64 from koji. With this kernel include the btrfs-patch my system starts well. Same issue on same I686 kernel-2.6.33.5-112.fc13.i686 on ext4, only other thing i have noticed is that the Caps Lock flashes on my thinkpad display, doubt relevant but thought odd so Bug-Developmenters, But it's to late, i do not use fc13 since 1 years ago. ;)
https://bugzilla.redhat.com/show_bug.cgi?id=597710
CC-MAIN-2019-22
refinedweb
412
60.01
Recall that PCA maximizes information retained when we project our data to lower dimensions. Even when projecting our dataset down to 1 dimension, PCA will capture as much information as possible from the original dataset. What's unique about 1 dimension data? Well it's an array, and it can be sorted! So if we have objects that can be represented as a high-dimnesional vector, we have an oppurtunity to endow an "order" to them somehow (now you can't see it, but I am air-quoting "order"). This order has nothing to do with one object being "better", or "larger" (again air quotes) than another object, but instead has to do with an ordering that minimizes information lost. What does that mean? Let's try this with colors! Colors can exist in 3 dimensions, and the dimensions are R (red), G (green) and B (blue). This example actually came from a problem I had. I wanted to sort my books my color, like: I took a photo of a subset of my book collection, sampled what color they were using Gimp, and recorded the colour in rgb. Sorting them was going to be inpractical: it would take time - plus it's actually really hard to decide on an order for colors. Example: %pylab inline from mpl_toolkits.mplot3d import Axes3D figsize(12,8) colours = np.array([[111, 28, 21], [ 27, 17, 20], [ 79, 23, 17], [185, 125, 50], [155, 76, 32], [ 82, 24, 17], [127, 63, 33], [193, 91, 63], [176, 97, 36], [ 79, 15, 19], [176, 140, 47], [203, 65, 46], [174, 139, 87], [138, 44, 34], [144, 91, 36], [ 86, 21, 16], [123, 44, 32], [109, 44, 30], [ 84, 29, 27], [121, 42, 65], [ 70, 15, 11], [107, 24, 17]])/255.0 # I've normalized the colours between 0 and 1 This a the color list of a subset of library that I pulled from a photo. There are 22 book colours here, and I've normalized the dimensions to be between 0 and 1. def display_colours(colours): figsize(13,2) N = colours.shape[0] for i,c in enumerate(colours): ax = subplot(1,N,(i+1)%N, axisbg=c) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() This is a little helper function that will display a list of colours passed in. display_colours(colours) Populating the interactive namespace from numpy and matplotlib (22, 3) You can probably do a pretty good job of sorting these, though there are some odd ones: But it is pretty time consuming even for only 22 colours here, and the process is very subjective. Likely your friend will have a very different ordering. We'd like something objective, and that scales to potentially hundreds or thousands of colors. Let's next visualize these colours in 3-space: figsize(12,8) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(colours[:,0], colours[:,1], colours[:,2], c =colours, s=50 ) plt.xlim(0,1) plt.ylim(0,1) plt.show() What we'd like to do This is exactly what PCA does. So let's do that: from sklearn.decomposition import PCA pca = PCA(n_components=1) # I'm setting n_components to 1 as we are projecting down to only 1 dimension one_d_colours = pca.fit_transform(colours)[:,0] print one_d_colours.shape print one_d_colours (22,) [-0.1251 -0.3963 -0.2339 0.356 0.1311 -0.2228 0.019 0.3082 0.2474 -0.2516 0.3639 0.2567 0.3946 0.0051 0.14 -0.2195 -0.0403 -0.0827 -0.1949 -0.0188 -0.2855 -0.1504] ix = np.argsort(one_d_colours) #what I want is the sorted order of elements in 1-dimension, and I'll use that in # ordering the colours. display_colours(colours[ix]) N = 60 colours = np.random.uniform([0.15,0.1,0.5], [.9,0.5,0.7], size=(N,3)) #here are the colours, unsorted display_colours(colours) figsize(12,8) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(colours[:,0], colours[:,1], colours[:,2], c =colours, s=50 ) plt.show() one_d_colours = pca.fit_transform(colours)[:,0] ix = np.argsort(one_d_colours) display_colours(colours[ix]) This looks pretty good to me, I'd grade it an 80%. There are some oddities, but considering what is means to "sort colors", I'd say it did a pretty decent job. Recall that this method of sorting is completely unsupervised: there is no "better" or "larger" colour. PCA is finding the line in 3-space that maximizes the data variance in 1-space. This line also happens to be what we wanted: we wanted different colors in 3-space to be maximally different in 1-space too. I chose rgb space. Though this way arbitrary. You could also use other color schemes: HSV, HSL, or CMYK. HSV might even produce better results, as it was designed to be more intuitive and perceptually relevant than RGB. Interestingly, CMYK colors would live in 4 dimensions originally, not 3 like RGB. On sorting colors: There is acutally a better way to sort colours using the travelling salesman problem, but I'll explain that in another lecture.
https://nbviewer.jupyter.org/gist/CamDavidsonPilon/abe3f0e4f589f53c4128
CC-MAIN-2020-40
refinedweb
856
65.93
Coding Assistance in F# This topic describes JetBrains Rider's coding assistance features available in F#. You can find the detailed information on these features in the corresponding topics of the Coding Assistance section. Syntax highlighting F# syntax highlighting uses the default font and color scheme that is applied to all languages and currently cannot be customized specifically for F#. Default syntax highlighting: To configure default color and font settings: - Press Ctrl+Alt+S, or alternatively chooseon Windows and Linux or on macOS, then choose on the left. Change the settings under the General and Language Defaults nodes. Code completion Code Completion features help you write code faster by providing a set of items to complete based on surrounding context. For more information, see Code Completion (IntelliSense). Currently, only Basic code completion is supported in F#. It suggests namespaces, types, methods, fields, properties, etc. as you type. You can see the entire list of suggestions by placing the caret at the position where you're going to type your code (or on an existing member) and press Ctrl+Space. Code formatting JetBrains Rider can reformat existing code in a selected F# file, fixing the following spacing violations: - space after comma - space after semicolon - space around delimiter - space before argument - space before colon - inconsistent indents Open the file you want to reformat, then go toor just press Ctrl+Alt+Enter. Here is an example of a code fragment reformatted with JetBrains Rider. Before: After:
https://www.jetbrains.com/help/rider/2018.1/Coding_Assistance_in_F_Sharp.html
CC-MAIN-2020-40
refinedweb
243
53
There are situations when you may need to remove HTML tags from your character string data. As an example, consider having to submit a product data feed to a search engine like Google. The detailed product description is mandatory in this case. It is recommended that you remove all special characters and HTML formatting. This task can be handled in TSQL code, however in this case I have the opportunity to use .NET and the power of the regular expressions to manage the string. In this tip, I'll build a CLR function which cleans up a string of HTML tags and special characters. I'll use Visual Studio 2010 with C# as the programming language. Check out this tip for my solution. In one of my previous tips I've detailed the steps you need to build and deploy a CLR user defined function from Visual Studio 2010. Below are the steps that need to be followed. First, make sure that the CLR integration is enabled. This can be accomplished by using the server facets in SQL Server 2008, the Surface Area Configuration tool in SQL Server 2005 or run the following code: sp_configure 'clr enabled', 1 GO RECONFIGURE GO Next, follow these steps: As you can see, before applying the regex pattern, which finds the HTML tags, I strip out the control characters from the final result. Afterwards, I find the HTML tags using the regex pattern and I replace them with an empty string. Here is the code of the user defined function: using System; using System.Data.Sql; using System.Data.SqlTypes; using System.Collections.Generic; using Microsoft.SqlServer.Server; using System.Text; using System.Text.RegularExpressions; public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction] public static SqlString CleanHTML(SqlString s){ if (s.IsNull) return String.Empty; string s1 = s.ToString().Trim(); if (s1.Length == 0) return String.Empty; StringBuilder tmpS = new StringBuilder(s1.Length); //striping out the "control characters" if (!Char.IsControl(s1[0])) tmpS.Append(s1[0]); for (int i = 1; i <= s1.Length - 1; i++) { if (Char.IsControl(s1[i])) { if (s1[i - 1] != ' ') tmpS.Append(' '); } else { tmpS.Append(s1[i]); } } string result = tmpS.ToString(); //finding the HTML tags and replacing them with an empty string string pattern = @"<[^>]*?>|<[^>]*>"; Regex rgx = new Regex(pattern); return rgx.Replace(result, String.Empty); } } This task can be carried out using TSQL - for example I could use this piece of simple and elegant code provided by Pinal Dave. It uses the STUFF TSQL string function to replace the HTML tags with empty strings. Should I use CLR or TSQL? Which is the right choice in this case? To answer this question, I've done a little bit of testing. I used a ~61,000 records ProductDescription table, consisting of an integer ProductID column (clustered primary key) and a Description varchar(max) column which contains HTML markup. I used a slightly different .NET code, which deals only with the HTML replacement as shown below: using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.Text; using System.Text.RegularExpressions; public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction] public static SqlString CleanHTMLOnlyString(SqlString s) { if (s.IsNull) return String.Empty; string s1 = s.ToString().Trim(); if (s1.Length == 0) return String.Empty; string pattern = @"<[^>]*?>|<[^>]*>"; Regex rgx = new Regex(pattern); return rgx.Replace(s1, String.Empty); } } In my test cases, I worked on a virtual machine with Windows Server Standard 2003 SP2, 2GB of RAM on SQL Server 2008 Developer Edition with SP2. This is a development machine with no other code running on this machine during the test. I ran two pieces of code in separate SSMS windows, one using Pinal's function and the other using the CLR function as shown below: --window 1 - CLR function SET STATISTICS IO ON SET STATISTICS TIME ON GO SELECT ProductDescriptionID, dbo.CleanHTMLOnlyString([Description]) FROM ProductDescription --window 2 - Pinal's TSQL function SET STATISTICS IO ON SET STATISTICS TIME ON GO SELECT ProductDescriptionID, dbo.udf_StripHTML([Description]) FROM ProductDescription Based on the testing environment listed above, using the T-SQL code the CPU time and the elapsed time are greater. There is an average CPU time of ~9 seconds with the T-SQL code vs. ~4 seconds with the CLR code. In addition, there is an average elapsed time of ~10 seconds with the T-SQL code vs. ~5 seconds with the CLR Code. When I ran this same code in a similar hardware environment, but with SQL Server 2005 SP4 Developer Edition, differences are greater. The results for CPU time were ~31 seconds for T-SQL code vs. ~4 seconds for CLR code as well as elapsed time of ~33 seconds for T-SQL code vs. ~5 seconds for CLR code. But what is the price for this? A little bit of research led me to this article about the SQL CLR memory usage. Checking out the sys.dm_os_memory_clerks DMV I could see that the MEMORYCLERK_SQLCLR reserves and commits memory. I've run the query recommended by Steven Hemingray on my SQL Server 2008 development virtual machine and I obtained 8548 KB. Depending on the operating system, how busy the environment is and how the CLR code is written, you may experience memory pressure. Searching more, I've found 2 extreme situations here and here. So these are something to consider as well.
https://www.mssqltips.com/sqlservertip/2418/remove-html-tags-from-strings-using-the-sql-server-clr/
CC-MAIN-2015-32
refinedweb
899
60.82
I like flight simulators, but I’m not very good at them. What I need is a panic button that puts me at a safe altitude for recovery. Fortunately the flight simulator I’m playing right now, FlightGear, has a way to get and set internal properties over a socket interface. There are some super big problems I ran into that aren’t well documented (or documented at all) in FlightGear’s wiki pages on the subject, and I go over those at the end. Here is how I used my Arduino Uno to create a panic button that immediately sets my altitude to 9000 feet (there’s a video of it in action at the bottom of this post). For a quick crash course in FlightGear’s property tree, start FlightGear with the “–httpd=5480” option and point a web browser (on the same machine) to. You can click through all the properties, and also set them right in the browser. Navigate to /position/altitude-ft and enter in 9000 (and click “submit”). This is pretty much what we’re going to do with the button, but instead of using the httpd interface we’ll be doing it over a network socket. First thing is to create an XML file defining what properties we want exposed for manipulation. There’s a “generic” protocol that FlightGear uses for this. You can see an example near the bottom of. Here’s what mine looks like for the panic button: <?xml version="1.0"?> <PropertyList> <generic> <input> <line_separator>newline</line_separator> <var_separator>tab</var_separator> <chunk> <node>/position/altitude-ft</node> <name>altitude</name> <type>int</type> <format>%i</format> </chunk> </input> </generic> </PropertyList> Call it “setaltitude.xml” and put it in the FlightGear\Data\Protocol directory. Here’s the Arduino code for handling the button press. It’s not all that interesting – it just detects the button press and sends a serial message. The delay is to prevent button bounce from generating a ton of serial messages. const int buttonPin = 2; int buttonState = 0; void setup() { pinMode(buttonPin, INPUT); Serial.begin(9600); } void loop() { buttonState = digitalRead(buttonPin); if (buttonState == LOW) { Serial.print("Pressed\n"); delay(500); } } Here is a small Python program that acts as the middle-man between the Arduino and FlightGear. It intercepts the serial message and then sends the desired altitude to FlightGear over a socket. from serial import Serial from socket import * ser = Serial('/dev/cu.usbmodemfd121', 9600) s = socket(AF_INET, SOCK_STREAM) s.connect(('192.168.1.5', 5500)) while(1): if (ser.inWaiting() > 0): serialRead = ser.readline() print "Read: " + serialRead s.sendall('9000\n') Before I go over tying it all together I want to lay out two problems I had. 1) The XML file lets you define the properties you want to set, and the type of data (integer, float, string) that it is. I thought that this meant you needed to deliver the data in that way, too. I spent a lot of time getting erratic behavior from FlightGear because I was packing the altitude as binary data before sending it across. Regardless of the data type described in the XML file you need to send the data as a simple string terminated by the line_ separator defined. 2) I had assumed that FlightGear always acted like the server when the socket interface was enabled. This is incorrect (and again… not documented as far as I can tell). If you’ve set FlightGear’s socket interface as input you need to write the program delivering the data as the client. If you’ve set FlightGear’s socket interface as the output, you need to write your data receiving program as the server. Since I’m setting the socket interface as an input I have written my Python program as the client and it MUST be run after starting FlightGear, or you’ll get an error. I have no idea what the behavior is if you set the socket to be bi-directional. To tie it all together, start FlightGear with the socket interface enabled and set to use the XML file as a generic description of what we want to send to FlightGear. Then start the Python program. It will sit and wait for a serial command from the Arduino and then send FlightGear the altitude. I set the rate at 5 Hz since I’m not really sending a lot of data rapidly. This is what my settings (in Windows) looks like for FlightGear. Here’s the button in action. I’ve already gone the next step and interfaced a potentiometer for controlling the rudder. I’ll go over that in a future post, but I want to mention it now because I ran into bit of a problem. It was my intention to add this rudder control to the button program, but I discovered that if you have two property inputs defined in the XML file (in this case the altitude and the rudder position) you MUST send two values over the socket every time you update one or both values. The implication here is that every time I send rudder values I have to send an altitude. This is obviously impractical since I don’t want to alter the altitude all the time. I had hoped there was a value I could pass (such as an empty string) that would indicate “don’t update this value”, but no such luck. The only solution I can think of is to not mix control surface manipulation with flight model manipulation. The other solution would be to implement a bi-directional protocol and be constantly reading the altitude so that I know what the current altitude is and can send it along with the rudder values. This might cause very bad behavior if I can’t get and send the altitude value faster than the flight model changes it. I like FlightGear, but the nearly nonexistent documentation is preventing me from loving it. It’s open source and the source is very well organized and clean, which is the only reason I figured out the solutions/workarounds to the problems I described above. Visually it’s behind the times, but that’s forgivable. It takes 58 seconds to start on both of my machines which have wildly different specs. I know it’s got a lot of terrain and stuff to parse through, but still.
http://chrisheydrick.com/2013/01/17/flightgear-panic-button-with-an-arduino/
CC-MAIN-2015-35
refinedweb
1,069
62.58
Index Links to LINQ The previous posts in this series have focused on using LINQ to Objects. It is now time to turn our attention to querying a database. In this post I will show connectivity to Microsoft SQL Server 2005 or SQL Server Express from C# using LINQ. You can use the May 2006 CTP to run the code shown in this post. The May CTP installs on top of Visual Studio 2005. At the time of this writing, the February 2007 Orcas CTP is not yet out, but once it is out, then you should use it, or later versions of Orcas, as the preferred means to run LINQ queries. The screen shots shown in this post are taken from both the May CTP and pre-release versions of Orcas. Except for a few minor details, LINQ will look much the same whether you use the May CTP or an early build of Orcas. This post covers three primary topics. The queries are run against the Northwind database and the text assumes basic familiarity with accessing databases from Visual Studio. If you are not familiar with the Visual Studio Database/Server Explorer, or if you need help getting Northwind installed, then view the Connecting to Northwind post. NOTES: Since all of the examples shown in this post are run against pre-release software, we can assume that at least some minor changes will occur between now and the time when Orcas ships. You can double click the screen shots in this post to see full size images. All the hotkeys used in this post are part of the Visual C# 2005 Key Binding or its Orcas equivalent. To choose this binding, select Tools | Options from the menu, then select Environment | Keyboard, and apply the appropriate keyboard mapping scheme. The example program shown in this post is based on a simple Console application. The technique for creating a LINQ console application differs slightly in Orcas and in the May CTP. The LINQ to SQL Designer is an invaluable tool for developers who want to connect to a database using LINQ. The process for doing this is essentially identical in the May CTP and in Orcas, but the terminology differs in each instance. You now need to select the tables from the Northwind database that you want to query. This can be done using the LINQ to SQL Designer. Press Ctrl + Shift + A to bring up the Add Item dialog. Press Ctrl + W, L to bring up the Database/Server Explorer and drag the Customer table onto the Designer, as shown in Figure 3. Figure 03: Viewing the Customer table in the LINQ to SQL Designer. Drag the Customer table from Server Explorer on the left to the Designer, which is shown in the middle of this screen shot. The purpose of this designer is to help you create a mapping between the tables in your database and the code in your program. With the help of the code generated by the designer, you get both type checking and IntelliSense support for your LINQ queries. In particular, the designer creates a class which represents a single row from the Customer table in the database. It specifies all of the fields in the Customer table and includes numerous methods for helping you to access the row from your code. To view this class declaration, press Ctrl+W,S to bring up the Solution Explorer. The first few lines of the class are shown in Listing 1. Listing 1: The first few lines of the declaration for the Customer table. 1: [global::System.Data.Linq.Table(Name="dbo.Customers")] 2: public partial class Customer : global::System.Data.Linq.INotifyPropertyChanging, global::System.ComponentModel.INotifyPropertyChanged 3: { 4: private string _CustomerID; 5: private string _CompanyName; 6: private string _ContactName; 7: private string _ContactTitle; 8: private string _Address; 9: private string _City; 10: private string _Region; 11: private string _PostalCode; 12: private string _Country; 13: private string _Phone; 14: private string _Fax; The attribute at the top of Listing 1 tells the compiler that this is a mapping to an object in a database. The class itself is declared as partial so that you can optionally extend it in your own source files. You should not try to change the code in the generated source as you may need to regenerate it if the objects in your database change or if you decide to add or remove objects in the designer. The code generated by the designer allows the compiler and Visual Studio to provide type checking and IntelliSense when you are writing LINQ queries. It makes the structure of the tables and rows in the database visible to you. It is like a clear window allowing C# developers to see and work with the objects in the database. You are not yet seeing the values in the tables, but you can see the structure of the tables. The LINQ to SQL Designer provides a mapping between the objects in your database and classes in your code. However the designer also creates a handy class derived from DataContext which helps you automatically connect to the database, and also gives you a simple means of accessing the Customer class. Listing 2: The DataContext descendant generated by the Linq to SQL Designer. 1: public partial class DataClasses1DataContext : global::System.Data.Linq.DataContext { 2: 3: [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 4: public DataClasses1DataContext(string connection) : 5: base(connection) { 6: } 7: 8: [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 9: public DataClasses1DataContext(global::System.Data.IDbConnection connection) : 10: base(connection) { 11: } 12: 13: [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 14: public DataClasses1DataContext() : 15: base(global::ConsoleApplication4.Properties.Settings.Default.NorthwindConnectionString) { 16: } 17: 18: public global::System.Data.Linq.Table<Customer> Customers { 19: get { 20: return this.GetTable<Customer>(); 21: } 22: } 23: } The first three methods in DataClasses1DataContext help you connect to the database. Each of these methods are marked with the DebuggerNonUserCodeAttribute, which tells the debugger to ignore the methods. The compiler knows they are there, of course, but the debugger essentially ignores them so as not to clutter up your debugging experience with methods that you don't really need to see. If for some reason you want to step through these constructors while debugging, you can remove that attribute and rerun the program. The Customers property at the end of the class gives you easy access to the to the Customers table from the database. It exposes this table as a collection of objects. Each object is an individual row encapsulated by the Customer class shown in Listing 1. By returning an instance of the Table class, the Customers property also provides the following services: Listing 3 shows the declaration for the Table class. Note that it supports IQueryable<T> and IEnumerable<T>. (Remember that you can read these class as "IQueryable of T" and "IEnumerable of T.") These two interfaces are needed if you want to query an object with LINQ. Note also that there are methods called Add and Remove. These methods make it possible for LINQ to update the database behind the scenes. Listing 3: The Table class is built into LINQ. It is a helper class that converts a simple class like that shown in Listing 1 and makes it part of a collection of objects representing a table. The table is fully LINQ enabled and supports the ability to modify the rows in the database. 1: public sealed class Table<T> : IQueryable<T>, IEnumerable<T>, ITable, IQueryable, IEnumerable, IListSource 2: { 3: public Table(DataContext context, MetaTable metaTable); 4: public DataContext Context { get; } 5: public bool IsReadOnly { get; } 6: public string Name { get; } 7: public Type RowType { get; } 8: public void Add(T item); 9: public void Attach(T item); 10: public IEnumerator<T> GetEnumerator(); 11: public void Remove(T item); 12: public void RemoveAll(IEnumerable<T> items); 13: public override string ToString(); 14: } We have finally covered all the background tasks and information needed to support a LINQ query. If you have been following this series as it develops, you will now find the code for the actual query needed to access the database almost anti-climatic in appearance. This is a good thing, since we want LINQ to be simple and easy to use, and indeed you will find that it easily achieves those goals. The code is shown in Listing 4. The key lines are found on lines 12, 14 and 15. Listing 4: The code for running a simple LINQ query. 1: using System; 2: using System.Linq; 3: using System.Collections.Generic; 4: using System.Text; 5: 6: namespace ConsoleApplication4 7: { 8: class Program 9: { 10: static void Main(string[] args) 11: { 12: DataClasses1DataContext dataContext = new DataClasses1DataContext(); 13: 14: var query = from c in dataContext.Customers 15: select c; 16: 17: foreach (var q in query) 18: { 19: Console.WriteLine(String.Format("{0}, {1}, {2}", q.CompanyName, q.ContactName, q.City)); 20: } Line 12 shows the code for creating an instance of the DataContext from Listing 2. Needless to say we are using the third constructor shown on lines 13-15 of Listing 2. The actual connection string used to access the database is stored in the Settings.Designer.cs file found under the Properties node in the Solution Explorer. The DataContext is used again in line 14, when we access the Customers property discussed at length at the end of the previous section of this post. Translated into standard SQL, lines 13 and 14 read something like "Select * from Customers." The exact line of SQL is accessible from the dataContext.Log property. To view it, add the following code on Line 16 of your program: dataContext.Log = Console.Out; If you then re-run your program, the following SQL will be printed in the first few lines of text printed to the console: SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax] FROM [dbo].[Customers] AS [t0] You will probably have to scroll the contents of the console window up to view this query. Remember that you can get a handy view of the console output if you run your program from the IDE by pressing Ctrl + F5. The code on line 19 prints out a few fields from the results of the query. There are actually tricks and helper classes which make it easy to print out the results of a database query. For now, however, I want to work with this simple means of displaying the results so that what is happening is as obvious and transparent as possible. If you are using Orcas you get both an IntelliSense window and automatic code completion to help you discover the fields of the table exposed in the query. I have chosen to expose just three of the fields, but you can access all eleven fields from the Customers table if you wish. This post explains how to write a simple LINQ query expression to pull data from a table stored in Microsoft SQL Server. The majority of the text focused on how to use the LINQ to SQL Designer, and in particular how to understand the code generated by the designer. The most important section of that discussion focused on the Customers property which exposes the Customers table as a collection of Customer objects, where each Customer object represents a single row in the database. The actual code for querying the database turned out to be extremely simple. If you find the query expression shown in lines 14 and 15 mysterious, you might want to reread some of the earlier posts in this series on LINQ. If you would like to receive an email when updates are made to this post, please register here RSS What kind of extensibility will there be in the LINQ to SQL implementation? So far, nothing I've seen shows that you can use CTE's or Full-Text functions directly from LINQ code. It would be very useful if there was a mechanism where additional functions could be added to expression tree that could add additional SQL calls. Is there any way to do this? Pingback: Hi Charlie, In your post you refer to the "March 2007 Orcas CTP" - does this mean there isn't going to be a Orcas CTP in February now? Kind regards, tom Tom, The date for the next CTP is a bit of a moving target. At this time it has moved back into February, which means it should be out quite soon. The team is working to get it out as soon as possible, and right now it looks like we will get it out very soon. - Charlie You've been kicked (a good thing) - Trackback from DotNetKicks.com This short video contains the basic information that you need to use LINQ to SQL to connect to a relational Welcome to the twenty-second Community Convergence, the March CTP issue. I'm Charlie Calvert, the C# I can connect to and query a database much faster using the SqlClient. It really seems to me that it is a choice of learning LINQ or learning SQL. And I don't think you would be able to get a job knowing LINQ and not knowing SQL. Of course, with all the shops that swarm to every new "simplification" Microsoft does, I suppose knowing LINQ will be a job prerequisite for many shops. Lexapro and alcohol. Lexapro withdrawal. Valium during pregnancy. What is valium used for. Valium. How in the world do you contact in Database Explorer to a SQLExpress Instance.... When I view the advanced properties it is attempting to use .SQLExpress.. I need INSTANCE\DBSERVER.. Everyone uses Northwid so examples are of no help.
http://blogs.msdn.com/charlie/archive/2007/02/16/linq-farm-connecting-to-a-database-with-linq-to-sql.aspx
crawl-002
refinedweb
2,296
61.77
Are you sure? This action might not be possible to undo. Are you sure you want to continue? 1120-W Estimated Tax for Corporations For calendar year 2007, or tax year beginning , 2007, and ending , 20 OMB No. 1545-0975 (WORKSHEET) Department of the Treasury Internal Revenue Service (Keep for the corporation’s records—Do not send to the Internal Revenue Service.) 2007 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 Taxable income expected for the tax year Qualified personal service corporations (defined in the instructions), skip lines 2 through 13 and go to line 14. Members of a controlled group, see instructions. 2 Enter the smaller of line 1 or $50,000 Multiply line 2 by 15% 4 Subtract line 2 from line 1 5 Enter the smaller of line 4 or $25,000 Multiply line 5 by 25% 7 Subtract line 5 from line 4 8 Enter the smaller of line 7 or $9,925,000 Multiply line 8 by 34% 10 Subtract line 8 from line 7 Multiply line 10 by 35% If line 1 is greater than $100,000, enter the smaller of (a) 5% of the excess over $100,000 or (b) $11,750. Otherwise, enter -0If line 1 is greater than $15 million, enter the smaller of (a) 3% of the excess over $15 million or (b) $100,000. Otherwise, enter -0Add lines 3, 6, 9, and 11 through 13. (Qualified personal service corporations, multiply line 1 by 35%.) Alternative minimum tax (see instructions) Total. Add lines 14 and 15 Tax credits (see instructions) Subtract line 17 from line 16 Other taxes (see instructions) Total tax. Add lines 18 and 19 Credit for Federal tax paid on fuels (see instructions) Subtract line 21 from line 20. Note: If the result is less than $500, the corporation is not required to make estimated tax payments 3 6 9 11 12 13 14 15 16 17 18 19 20 21 22 15 16 17 18 19 20 21 22 23a Enter the tax shown on the corporation’s 2006 tax return (see instructions). Caution: If the tax is (b) (c) (a) 24 25 Installment due dates (see instructions) Required installments. Enter 25% of line 23b in columns (a) through (d) unless the corporation uses the annualized income installment method or adjusted seasonal installment method or is a “large corporation” (see instructions) 24 23a 23b (d) 25 Cat. No. 11525G Form For Paperwork Reduction Act Notice, see instructions. 1120-W (2007) Form 1120-W (WORKSHEET) 2007 Page 2 Schedule A Adjusted Seasonal Installment Method and Annualized Income Installment Method (see instructions) Part I Adjusted Seasonal Installment Method (a) (b) (c) (Use this method only if the base period percentage for any 6 consecutive months is at least 70%.) First 3 months First 5 months First 8 months (d) First 11 months 1 Enter taxable income for the following periods: a Tax year beginning in 2004. b Tax year beginning in 2005. c Tax year beginning in 2006. 1a 1b 1c 2 First 4 months First 6 months First 9 months Entire year 2 Enter taxable income for each period for the tax year beginning in 2007. Enter taxable income for the following periods: a Tax year beginning in 2004. b Tax year beginning in 2005. c Tax year beginning in 2006. 3 3a 3b 3c 4 5 6 7 8 9 10 11a 11b 11c 12 13 4 5 6 Divide the amount in each column on line 1a by the amount in column (d) on line 3a. Divide the amount in each column on line 1b by the amount in column (d) on line 3b. Divide the amount in each column on line 1c by the amount in column (d) on line 3c. Add lines 4 through 6. Divide line 7 by 3. Divide line 2 by line 8. Figure the tax on the amount on line 9 by following the same steps used to figure the tax for line 14, page 1, of Form 1120-W. 7 8 9 10 11a Divide the amount in columns (a) through (c) on line 3a by the amount in column (d) on line 3a. b Divide the amount in columns (a) through (c) on line 3b by the amount in column (d) on line 3b. c Divide the amount in columns (a) through (c) on line 3c by the amount in column (d) on line 3c. 12 13 14 Add lines 11a through 11c. Divide line 12 by 3. Multiply the amount in columns (a) through (c) of line 10 by the amount in the corresponding column of line 13. In column (d), enter the amount from line 10, column (d). Enter any alternative minimum tax for each payment period (see instructions). Enter any other taxes for each payment period (see instructions). Add lines 14 through 16. For each period, enter the same type of credits as allowed on lines 17 and 21, page 1, of Form 1120-W (see instructions). Subtract line 18 from line 17. If zero or less, enter -0-. 14 15 16 17 18 19 Form 15 16 17 18 19 1120-W (2007) Form 1120-W (WORKSHEET) 2007 Page 3 Part II Annualized Income Installment Method (a) (b) First ______ months (c) First ______ months (d) First ______ months 20 21 Annualization periods (see instructions). Enter taxable income for each annualization period (see instructions). Annualization amounts (see instructions). Annualized taxable income. Multiply line 21 by line 22. Figure the tax on the amount in each column on line 23 by following the same steps used to figure the tax for line 14, page 1, of Form 1120-W. Enter any alternative minimum tax for each annualization period (see instructions). Enter any other taxes for each annualization period (see instructions). Total tax. Add lines 24 through 26. For each annualization period, enter the same type of credits as allowed on lines 17 and 21, page 1, of Form 1120-W (see instructions). Total tax after credits. Subtract line 28 from line 27. If zero or less, enter -0-. Applicable percentage. Multiply line 29 by line 30. 20 21 22 23 First ______ months 22 23 24 24 25 26 27 25 26 27 28 28 29 30 31 25% 50% 75% 100% 29 30 31 Part III Required Installments 1st installment 2nd installment 3rd installment 4th installment Note: Complete lines 32 through 38 of one column before completing the next column. 32 If only Part I or Part II is completed, enter the amount in each column from line 19 or line 31. If both parts are completed, enter the smaller of the amounts in each column from line 19 or line 31. Add the amounts in all preceding columns of line 38 (see instructions). Adjusted seasonal or annualized income installments. Subtract line 33 from line 32. If zero or less, enter -0-. Enter 25% of line 23b, page 1, in each column. (Note: “Large corporations,” see the instructions for line 25 for the amount to enter.) Subtract line 38 of the preceding column from line 37 of the preceding column. Add lines 35 and 36. Required installments. Enter the smaller of line 34 or line 37 here and on line 25, page 1 (see instructions). 32 33 34 33 34 35 35 36 37 38 Form 36 37 38 1120-W (2007) Form 1120-W (WORKSHEET) 2007 Page 4 IRS E-Services Make Taxes Easier Now, more than ever before, businesses can enjoy the benefits of filing and paying their federal taxes electronically. Whether you rely on a tax professional or handle your own taxes, the IRS offers you convenient programs to make filing and paying taxes easier. ● You can e-file your Form 1120 tax return and certain other business income tax returns; Form 940 and 941 employment tax returns; Form 1099 and certain other information returns. Visit for more information. ● You can pay taxes online or by phone using the free Electronic Federal Tax Payment System (EFTPS). Visit or call 1-800-555-4477 for more information. EFTPS is required for certain corporations; see Depository Methods of Tax Payment below.. corporation may have to pay a penalty. Mail or deliver the completed Form 8109 with the payment to an authorized depositary (that. General Instructions Section references are to the Internal Revenue Code unless otherwise noted. Who Must Make Estimated Tax Payments ● Corporations generally must make estimated tax payments if they expect their estimated tax (income tax less credits) to be $500 or more. ● S corporations must also make estimated tax payments for certain taxes. S corporations should see the instructions for Form 1120S, U.S. Income Tax Return for an S Corporation, to figure their estimated tax payments.. ●. Form 4466 may not be filed later than the 15th day of the 3rd month after the end of the tax year. Depository Methods of Tax Payment Some corporations (described below) are required to electronically deposit all depository taxes, including estimated tax payments. Electronic deposit requirement. The corporation must make electronic deposits of all depository taxes (such as employment tax, excise tax, and corporate income tax) using the Electronic Federal Tax Payment System (EFTPS) in 2007 if: ● The total deposits of such taxes in 2005 were more than $200,000 or ● The corporation was required to use EFTPS in 2006. If the corporation is required to use EFTPS and fails to do so, it may be subject to a 10% penalty. If the corporation is not required to use EFTPS, it may participate voluntarily. See IRS E-Services Make Taxes Easier above. Lines 2, 5, and 8. Members of a Controlled Group Members of a controlled group enter on line 2 the smaller of (a) the amount on line 1 or (b) their share of the $50,000 amount. On line 5, enter the smaller of (a) the amount on line 4 or (b) their share of the $25,000 amount. On line 8, enter the smaller of (a) the amount on line 7 or (b) their share of the $9,925,000 amount. Form 1120-W (WORKSHEET) 2007 Page 5 5, and ● $4,962,500 (one-half of $9,925,000) on line 8. Unequal apportionment plan. Members of a controlled group can. Installment Due Dates Calendar-year taxpayers: Enter 4-16-2007, 6-15-2007, 9-17-2007, and 12-17-2007,. Line 25. Required Installments Payments of estimated tax should reflect any 2006 overpayment that the corporation chose to credit against its 2007 on pages 2 and 3. If Schedule A is used for any payment date, it must be used for all payment due dates. To arrive at 2007 tax year. For this purpose, taxable income is modified to exclude net operating loss and capital loss carrybacks or carryovers. Members of a controlled group, as defined in section 1563, must divide the $1 million amount among themselves according to rules similar to those in section 1561. If Schedule A is not used, follow the instructions below to figure the amounts to enter on line 25. If Schedule A is used, follow the instructions below to figure the amounts to enter on line 35 of Schedule A. ● If line 22 is smaller than line 23a: Enter 25% of line 22 in columns (a) through (d) of line 25. ● If line 23a is smaller than line 22: Enter 25% of line 23a in column (a) of line 25. In column (b), determine the amount to enter as follows: 1. Subtract line 23a from line 22, 2. Add the result to the amount on line 22, and 3. Multiply the result in 2 above by 25% and enter the result in column (b). Enter 25% of line (a) 5% of the taxable income in excess of $100,000 or (b) $11,750. Line 13. Additional 3% Tax If the additional 3% tax applies, each member of the controlled group must enter on line 13 its share of the smaller of (a) 3% of the taxable income in excess of $15 million or (b) $100,000. See the instructions for line 12 above. Line 15. Alternative Minimum Tax (AMT) Note. Skip this line if the corporation is treated as a “small corporation” exempt from the AMT under section 55(e). AMT is generally the excess of tentative minimum tax (TMT) for the tax year over the regular tax for the tax year. See section 55 for definitions of TMT and regular tax. A limited amount of the foreign tax credit, as refigured for the AMT, is allowed in computing the TMT. Line 17. Tax Credits For information on tax credits the corporation can take, see the instructions for Form 1120, Schedule J, lines 5a through 5e, (Form 1120-A, Part I, line 2), or the instructions for the applicable lines and schedule of other income tax returns. Line 19. Other Taxes For information on other taxes the corporation may owe, see the instructions for Form 1120, Schedule J, line 9, (Form 1120-A, Part I, line 4), or the instructions for the applicable line and schedule of other income tax returns. line 25, page 1, the amounts from the corresponding column of line 38. If Schedule A is used for any payment date, it must be used for all payment dates. Do not figure any required installment until after the end of the month preceding the due date for that installment. CAUTION Line 21. Credit for Federal Tax Paid on Fuels See Form 4136, Credit for Federal Tax Paid on Fuels, to find out if the corporation qualifies to take this credit. Also include on line 21 any credit the corporation is claiming under section 4682(g)(2) for tax on ozone-depleting chemicals. Line 23a. 2006 Tax Figure the corporation’s 2006 tax in the same way that line 22 of this worksheet was figured, using the taxes and credits from the 2006 income tax return. Large corporations, see the instructions for line 25 below. If a return was not filed for the 2006 tax year showing a liability for at least some amount of tax or the 2006 tax year was for less than 12 months, do not complete line 23a. Instead, skip line 23a and enter the amount from line 22 on line 23b. Part I. Adjusted Seasonal Installment Method Complete this part only if the corporation’s base period percentage for any 6 consecutive months of the tax year equals or exceeds 70% (. Form 1120-W (WORKSHEET) 2007 Page 6 Example. An amusement park with a calendar year as its tax year receives the largest part of its taxable income during the 6-month period from May through October. To compute its base period percentage for this 6-month period in 2007, the amusement park figures its taxable income for each May–October period in 2004, 2005, and 2006. It then divides the taxable income for each May–October period by the total taxable income for that particular tax year. The resulting percentages are 69% (.69) for May–October 2004, 74% (.74) for May–October 2005, and 67% (.67) for May–October 2006. Because the average of 69%, 74%, and 67% is 70%, the base period percentage for May through October 2007 is 70%. Therefore, the amusement park qualifies for the adjusted seasonal installment method. Line 22. Annualization Amounts Enter the annualization amounts for the option used on line 20. For example, if the corporation elects Option 1, enter on line 22 the annualization amounts 6, 3, 1.71429, and 1.2, in columns (a) through (d), respectively. 1st 2nd 3rd 4th Installment Installment Installment Installment Standard option Option 1 Option 2 4 6 4 4 3 2.4 2 1.71429 1.5 1.33333 1.2 1.09091 Line 15. Alternative Minimum Tax The corporation may owe AMT unless it will be a “small corporation” exempt from the AMT under section 55(e) for its 2007 tax year. To figure the AMT, use the 2006 Form 4626 and its instructions as a guide. Figure. Line 25. Alternative Minimum Tax The corporation may owe AMT unless it will be a “small corporation” exempt from the AMT under section 55(e) for its 2007 tax year. To figure the AMT, use the 2006 Form 4626 and its instructions as a guide. Figure. Line 26. Other Taxes For the same taxes used to figure line 19 of Form 1120-W, figure the amounts for the months shown on line 20. Line 16. Other Taxes For the same taxes used to figure line 19 of Form 1120-W, figure the amounts for the months shown in the column headings above line 1. Line 28. Credits Enter the credits to which the corporation is entitled for the months shown in each column on line 20. Do not annualize any credit. However, when figuring the credits, annualize any item of income or deduction used to figure the credit. For more details, see Rev. Rul. 79-179, 1979-1 C.B. 436. Line 18. Credits Enter the credits to which the corporation is entitled. Use Option 1 or Option 2 only if the corporation elected to use one of these options by filing Form 8842, Election To Use Different Annualization Periods for Corporate CAUTION Estimated Tax, on or before the due date of the first required installment payment. Once made, the election is irrevocable for the particular tax year. 1st 2nd 3rd 4th Installment Installment Installment Installment Part III. Required Installments Line 33 Before completing line 33 in columns (b) through (d), complete lines 34 through 38 in each of the preceding columns. For example, complete lines 34 through 38 in column (a) before completing line 33 in column (b). Line 38. Required Installments For each installment, enter the smaller of line 34 or line 37 on line 38. Also enter the result on line 25, page 8 hr., 7 min. 1120-W, Sch. A (Pt. I) 22 hr., 43 min. 1120-W, Sch. A (Pt. II) 10 hr., 31 min. 1120-W, Sch. A (Pt. III) 6 hr., 13 min. Learning about the law or the form 1 hr., 0 min. 6 min. 35 min. Preparing the form 1 hr., 10 min. 28 min. 48 min. 6 min. Standard option Option 1 Option 2 3 2 3 3 4 5 6 7 8 9 10 11 section 951(a) office. Instead, keep the form for your records.
https://www.scribd.com/document/373117/f1120w
CC-MAIN-2018-34
refinedweb
3,081
71.34
import sublime_plugin class AlwaysCenterCommand(sublime_plugin.EventListener): def on_modified(self, view): sel = view.sel() pt = sel[0].begin() if len(sel) == 1 else None if pt != None: view.show_at_center(pt) Center if not multi selection and modifying. That is it. Or alternatively you could just use the region. import sublime_plugin class AlwaysCenterCommand(sublime_plugin.EventListener): def on_modified(self, view): sel = view.sel() region = sel[0] if len(sel) == 1 else None if region != None: view.show_at_center(region) Thank you for the quick response! It works exactly as expected and it's even more robust than what I asked for. I was actually planning to break multi-selection. (So why it hadn't occured to me that sel is an array?) I've tinkered with it to make it center the cursor when selection is modified: import sublime_plugin class AlwaysCenterCommand(sublime_plugin.EventListener): def on_selection_modified(self, view): self.center_cursor(view) def center_cursor(self, view): sel = view.sel() region = sel[0] if len(sel) == 1 else None if region != None: view.show_at_center(region) This may be a bit overkill. It's nice that now the cursor is always centered, but it's very difficult to select text with the mouse. (I think I won't mind if I am writing prose, but I have yet to try it out at length.) I've had a couple ideas about this (but I haven't looked into them, yet): ]Differentiate between mouseclicks and keypresses. I know FocusWriter uses this strategy, but I don't quite like it. (I found myself having scrolled with the mouse to a location and then, when I started typing, the view reverted to where the cursor was.)/]]Differentiate between regular and distraction-free mode, centering on_modified in the former case and on_selection_modified in the latter./] If anyone has used WriteRoom or iA's Writer or any other software which centers the cursor, could you please share strategies for keeping the cursor centered while not breaking (too much) the editor's functionality? (And thanks again to facelessuser.) Alex Pardon my ignorance, but what is a typical use case for a centered cursor? And by "centered", do you mean always centered on the current line, ie, in the center of the text input area? I know this may sound dumb, but I don't understand how this would be helpful. Not trying to suggest it should/could not be, just that I'm drawing a blank. Thanks. He meant centered vertically in the view-able screen, not centered horizontally on the line. So when he says he modified it to center during the on_selection_modified, so when moving the cursors, the lines would move up and down instead of the cursor. Thanks for the explanation. Interesting. I don't think I've ever considered that as a possibility. Do many people use/desire such functionality? I'd like to hear some user stories about how this has made a difference in their day to day use. Or you could just try it out for yourself... Everyone is different and likes different things. I personally don't care for the functionality, but quodlibet does; that is good enough for me. But give it a try if your curious as COD312 says . Short Answer I use ST2 for two different tasks. Writing HTML, CSS & the occasional Javascript and writing prose. I would neither use nor recommend this for the former task or coding in general; I find it very useful for the latter. Long Answer Centering the cursor is a feature of several "distraction free environments". Although the whole idea of such software is a little gimmicky, keeping the cursor centered is actually a useful feature. When writing prose, especially on first drafts, you treat the screen like a page: you start on the top left and work your way down and to the right. But screens, unlike pages, do not turn, so most of the time you end up looking at the bottom of your screen. The solution (or a solution) is to treat the screen like a typewriter, by centering the cursor. This keeps your sight focused on a single line so that you can focus on typing and let the editor worry about scrolling. The current implementation, as posted above, is a little glitchy and makes mouse-use very difficult. But I have used editors dedicated to writing prose, and I spent too much time missing ST2 features. As I use this in my writing projects, I hope I will be able to improve the problems which will inevitably arise. (I wrote this comment in ST2 with cursor-centering enabled, and I got a "slow plugin" as I was editing this paragraph, so there's surely work to be done.) If you happen to write prose (or blog or whatever), you can try it and see if it works for you. I should repeat that I think it would be a bad idea to write code in this mode. Cheers,Alex Edit: a theme that takes cursor-centering into account is important. (I.e., centering text, 67 character wrap, 16px+ font-size, etc.) I will shape up what I am using and share it soon-ish. You might get a cheap improvement by using the on_modified event instead. if view.match_selector(0, 'text.plain'): ... can restrict to only text files. if view.match_selector(0, 'text.plain'): ... Check out the Idle Watcher example at sublimetext.com/docs/plugin-examples, though you'll need to translate the example from ST1 to ST2. Idle Watcher Thanks. Thanks for the input. Using the on_modified event is what I originally was planning to use and the code that facelessuser provided. I switched to on_selection_modified because that was closer to the behavior I wanted. I knew that mouse-selection would be a disaster, but it doesn't bother me; I love scrolling with the keys with on_selection_modified. I have thought that it might be possible to put together a function (or series of functions) that centers the cursor on_modified, as well as every command that potentially moves the cursor up or down. But maybe that would be rewriting the on_selection_modified function Restricting it to text files or related syntaxes (markdown, textile etc.) is in the TODO, but it's a little more complicated than that. For this plugin to "work" properly, it needs a specific theme as well. And, as far as I can, tell plugins can't override a user's theme settings. (I derive this information from the fact that the "org mode" plugin doesn't do this, either.) I'll take a look at 'Idle Watcher', but I think a second is maybe half-a-second too slow for this purpose. Writing code with this plugin drives me bonkers. But writing prose is a whole different beast. To put it another way: what I call a line when I write code, I call a paragraph when I write prose. The semantic units are utterly different. I'm a just a writer, not a coder at all. This functionality is very useful. However, I have been wondering ... I recently added BufferScroll to my install of ST2 so I can have a single file cloned over multiple pane which will all scroll with me. One of the points of this behavior for my work is so I could, for example, set up with 3 columns and focus on the middle one while I work which would give me a column worth of text front and back of the point I'm working at. Very useful for me most of the time as I'm trying to make things flow into each other, agree with each other, etc. Now the typewriter scrolling you have with this code works only to center the cursor in the first panel. If you try typing in any other panel, things get all wonkey, similarly to how things go when you try to make mouse selections (which, incidentally, is no problem for me, just thought I'd try it out to see for myself since reading of it in this thread). The most ideal situation would be for it to work in any panel you chose to place you're cursor, for a couple of reasons. First, I think the optimal default mode here is to be able to input text in the second panel and have 3 or 4 columns of sync scrolled material presenting a good panorama of the surrounding text. Second, I know there will be times when you'll see something in one of the panes you aren't currently inputting to that needs to be changed or expanded, and it will often be a great deal more useful to simply be able to click over to a spot and just start typing without things going crazy. Regardless, this is useful as is, thank you. Just not optimal yet. Kensai
https://forum.sublimetext.com/t/always-centered-cursor/4005/9
CC-MAIN-2016-36
refinedweb
1,479
64.61
> From: rbb@covalent.net [mailto:rbb@covalent.net] > Sent: Thursday, November 09, 2000 11:47 AM > > On Thu, 9 Nov 2000, William A. Rowe, Jr. wrote: > > > Ryan, > > > > is there a reason we choose to include "plat/foo.h" rather than > > set the include path to include/arch/myplat, include/arch/unix, include > > (in that order)? > > The only reason is that this ties all code re-use to the unix > platform. That may be OK, or it may not. I personally think it makes > sense for the C file to specify which header file it requires, because > that allows one C file to refer to different platforms for different > headers. However, it also restricts that the C file knows which > platform it wants. This is a trade-off. I may have made the wrong > choice. I really don't have a good answer, because I think it is > 6-one-half-dozen of the other here. My patch to apr includes: ./include ./include/arch ./include/arch/win32 ./include/arch/unix so all is well, at least for today. > One way the C file decides which header to use. The other > the Makefiles (or .dsps) decide. I haven't got a clue which > is easier to maintain. :-) Really, I'd rather see namespace protection (include "aprarch/foo.h" and include "apr/apr_foo.h") rather than these platform names. I'll grant that they are nearly equal tradeoffs, but the way we do it now means that a simple patch and creation of a special case .h file is a source change to half a dozen (plus) c files. That isn't good. As we chatted about ... I agree that the hybrid as400+mainframe or the win32+os2 cases are a pain in this structure. That's why I propose we create arch/bigiron/ or arc/msibm for the hybrids, choosing decent names that tag them as a common ancestor.
http://mail-archives.apache.org/mod_mbox/httpd-dev/200011.mbox/%3C001201c04a83$7452d290$92c0b0d0@roweclan.net%3E
CC-MAIN-2015-32
refinedweb
317
76.52
EuroPython 2010: Registration, Call for Papers and Call for Volunteers Planning for EuroPython 2010 is well underway. Both registration (Early Bird) and the talk submission system are open, and we need your help! As well as the core conference itself there are tutorials before the conference, development sprints afterwards and Python Language Summit and a Python Software Foundation meeting (first one in Europe) during the conference. Confirmed speakers include Brett Cannon and Raymond Hettinger. We also have some exciting keynote speakers that have yet to be announced. There is lots to do and we need your help! Ways you can help: - Come to the conference! Seriously, register now. - Join the EuroPython Improve Mailing List and introduce yourself - Submit your talk, tutorial and sprint proposals - If your company uses Python then they need to sponsor EuroPython. Hassle your boss today - Publicise EuroPython in your community EuroPython 2010 - 17th to 24th July 2010: Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2010-03-16 20:17:58 | | Categories: Python, Fun Tags: europython, conference AMD unittest2 0.2.0 Released and News on nose I've pushed out a new release of unittest2, version 0.2.0. unittest2 is a backport of all the fancy new features added to the unittest testing framework in Python 2.7. It is tested to run on Python 2.4 - 2.6. The biggest new feature in the 0.2.0 release is the addition of shared fixtures; setUpClass, setUpModule, tearDownClass and tearDownModule. Before I explain these new features there is some interesting news about the next version of nose. Jason Pellerin, creator and maintainer of nose, sent an email to the Testing in Python mailing list. unittest2 and the future of nose: nose has always been intended to be an extension of unittest -- one that opens unittest up, makes it easier to use, and easier to adapt to the needs of your crazy package or environment. Fact: unittest2 is coming: ... indeed, it's already here (just not yet in stdlib). It does test discovery (though not by default), can support test functions (though not by default), will eventually support a better form of parameterized tests than nose does, and also will eventually support at least class and module-level fixtures. Second fact: I have very little time to work on nose anymore, and with offspring #2 due any day now, that's not going to change much for at least a few years. Third fact: setuptools is dying, distribute is going with it, and something called distutils2 is going to rise to take its place. This matters because a LOT of nose's internal complexity is there to support one thing: 'python setup.py test'. If that command goes away or changes substantially, nose will have to change with it. Fourth fact: many high-level nose users want it to be released under a more liberal license than LGPL and won't become contributors until/unless that happens. I think this all adds up to starting a new project. Call it nose2. Call it @testinggoat. Whatever it's called, it should be based on extending unittest2, and designed to work with distutils2's test command. It should support as much of the current nose plugin api as is reasonable given the changes in unittest2. And it should be BSD or MIT licensed (or some reasonable equivalent) so more people feel comfortable contributing. Actually Jason is mistaken about a couple of the details, unittest2 is just a backport of what is already in the Python standard library and test discovery is supported right out of the box (not quite sure what he means by 'default'). That aside, nose has inspired a lot of the improvements that are in unittest2, and hose still has plenty of features that have not yet made it across. There are some features from nose that will never make it into core unittest, but the foundation of unittest2 and distutils2 will make a new version of nose substantially simpler. Various people have volunteered to work on the shiny new nose (bite my shiny metal nose?), but the first step is for unittest to gain a decent extension API. After Python 2.7 hits beta this is my highest priority for unittest. Follow the rest of the nose2 email thread for an idea of how it all fits together. Class and Module Level Fixtures unittest2 now allows you to create class and module level fixtures; these are versions of setUp and tearDown that are run once per class or module. in the suite have run the final tearDownClass and tearDownModule are run. Caution! Note that shared fixtures do not play well with features like test parallelization and they also break test isolation. They should be used with care. setUpClass and tearDownClass These must be implemented as class methods. import unittest2 class Test(unittest2.. There are a few important details about these functions, particularly how they behave when test suites are randomized. More information in the docs. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2010-03-16 00:09:45 | | Categories: Python, Projects Tags: testing, unittest2, nose, release Archives This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License. Counter...
http://www.voidspace.org.uk/python/weblog/arch_d7_2010_03_13.shtml
CC-MAIN-2015-48
refinedweb
882
72.16
Upgrading to SilverStripe 4 SilverStripe applications should be kept up to date with the latest security releases. Usually an update or upgrade to your SilverStripe installation means overwriting files, flushing the cache and updating your database schema. See our upgrade notes and changelogs for 4.0.0 specific information, bugfixes and API changes. Composer For projects managed through Composer, update the version number of framework and cms to ^4.0 in your composer.json file and run composer update. "require": { "silverstripe/framework": "^4.0", "silverstripe/cms": "^4.0" } Please note that until SilverStripe 4 is stable you will need to also add "minimum-stability": "dev" and "prefer-stable": true to your composer.json to be able to pull these modules. This will also add extra dependencies, the reports and siteconfig modules. SilverStripe CMS is becoming more modular, and composer is becoming the preferred way to manage your code. Asset-admin SilverStripe 4 comes with a new asset administration module. While it is installed by default for new projects, if you are upgrading you will need to install it manually: composer require silverstripe/asset-admin ^1.0 This will also install the graphql module for GraphQL API access to your SilverStripe system, which powers the asset-admin module. Migrate to dotenv SilverStripe 4 requires the use of .env and "real" environment variables instead of _ss_environment.php for your environment configuration. You'll need to move your constants to a new .env file before SilverStripe will build successfully. If you are not able to move your webserver away from using _ss_environment.php files, you can use this example file and include it at the top of your mysite/_config.php file. This will export your constants as environment variables. Manual - Check if any modules (e.g. blogand any additional modules). - Delete existing system folders (or move them outside of your webroot). - Rename your Page_Controllerclass to PageController. - Add a private static $table_name = 'MyDataObject'for any custom DataObjects in your code that are namespaced. This ensures that your database table name will be MyDataObjectinstead of Me\MyPackage\Model\MyDataObject(your namespace for the class). - Ensure you add namespaces to any custom classes in your mysitefolder. Your namespaces should follow the pattern of Vendor\Packagewith anything additional defined at your discretion. Note: The Pageand PageControllerclasses must be defined in the global namespace (or; without a namespace). - Install the updated framework, CMS and any other modules you require by updating your composer.jsonconfiguration and running composer update. As of SilverStripe 4.0.0 you should also include the asset-adminmodule to power your asset management in the CMS. - Check if you need to adapt your code to changed PHP APIs. For more information please refer to the changelog. There is an upgrader tool available to help you with most of the changes required (see below). - Visit to rebuild the website database. - Check if you have overwritten any core templates or styles which might need an update. Never update a website on the live server without trying it on a development copy first! Using the upgrader tool We've developed an upgrader tool which you can use to help you with the upgrade process to SilverStripe 4. See the upgrading notes in the changelog for more detailed instructions on how to use it. Quick tips If you've already had a look over the changelog, you will see that there are some fundamental changes that need to be implemented to upgrade from 3.x. Here's a couple of the most important ones to consider: - PHP 5.5 is now the minimum required version (and PHP 7.x is supported!). - All SilverStripe classes are now namespaced, and some have been renamed. Most of your modules will also have been namespaced, and you will need to consider this when updating class references (including YAML configuration) in your own code. - CMS CSS has been re-developed using Bootstrap 4 as a base. - SilverStripe code should now be PSR-2 compliant. While this is not a requirement, we strongly suggest you switch over now. You can use tools such as phpcbfto do most of it automatically. We've also introduced some best practices for module development. See the Modules article for more information.izations of a well defined type - such as custom page types or custom blog widgets - are going to be easier to upgrade than customisations that modify deep system internals like rewriting SQL queries.
https://docs.silverstripe.org/en/4/upgrading/
CC-MAIN-2017-47
refinedweb
736
59.3
PyX — Example: bargraphs/stacked.py Stack bars on top of each other from pyx import * g = graph.graphxy(width=14, height=6, x=graph.axis.bar()) g.plot(graph.data.file("minimal.dat", xname=0, y=2, stack=3), [graph.style.bar(), graph.style.text("y"), graph.style.stackedbarpos("stack"), graph.style.bar([color.rgb.green]), graph.style.text("stack")]) g.writeEPSfile("stacked") g.writePDFfile("stacked") Description To stack bars on top of each other, you can add stackedbarpos styles and further bars to the list of styles. The stackbarpos need to get different column names each time to access the new stack data. This example also adds text styles to the bars, which just repeat the value column data here, but they could refer to other columns as well.
http://pyx.sourceforge.net/examples/bargraphs/stacked.html
CC-MAIN-2014-15
refinedweb
130
58.18
[ ] Dian Fu commented on HADOOP-11335: ---------------------------------- Major changes in this patch: Remove class KeyProviderAuthorizationExtension and move all its functionality to KeyProviderCryptoExtension. Thanks [~asuresh] for the suggestions about the re-design. I found some of the ideas you proposed are difficult to implement, could you help to see if the issues described below make sense? * Metadata You suggest to use a extension of {{Metadata}} to support ACL, such as use {{MetadataWithAcl}} and use templatized {{KeyProvider}} such as {{pubic class KeyProvider<M extends Metadata>}}. I really like this idea but I encountered some difficulties in implementation. The difficulties are: Let’s image such implementation: {{public class JavaKeyStoreProvider extends KeyProvider<Metadata>}} and {{public class KeyProviderCryptoExtension extends KeyProvider<MetadataWithAcl>}}. If user create a ACL via the methods of {{KeyProviderCryptoExtension}}, an instance of {{MetadataWithACL}} will be serialized and stored into backend storage. Then user roll a new version of the key via the methods of {{JavaKeyStoreProvider}}, the metadata of the key will be firstly deserialized to instance of {{Metadata}} and is then serialized to the backend storage. This will cause problems. As the instance of {{MetadataWithACL}} is changed to {{Metadata}}. In my opinion, generic is unsuitable for this use case. Any thoughts? * KeyACLs You suggest to use the {{KeyAuthorizationKeyProvider.KeyACLs}} interface to implement the different ACL providers. It’s a good idea, while I found the following two reasons which prevent me to do so, I’m not sure if these reasons make sense to you: *# This interface not only considers key acl, but also other acls such as default key acl, white list key acl, etc. But in our design, we only consider supporting different key ACL. For default key acl and whitelist key acl, we still use configuration. *# This interface is used by KMS, which means that user can only access ACL through KMS. But we also want to make ACL can be accessible without KMS, although this is not a requirement in product environment. This is a code level requirement. As we know that in KeyShell, it use {{keyProvider}} to communicate the backend keystore. {{KeyProvider}} can be any implementations such as {{JavaKeyStoreKeyProvider}}, {{KMSClientProvider}} or others implementations. If we use {{KeyAuthorizationKeyProvider.KeyACLs}} interface to implement different ACL providers, then how to deal with the case when a {{JavaKeyStoreKeyProvider}} is used? > KMS ACL in meta data or database > -------------------------------- > > Key: HADOOP-11335 > URL: > Project: Hadoop Common > Issue Type: Improvement > Components: kms > Affects Versions: 2.6.0 > Reporter: Jerry Chen > Assignee: Dian Fu > Labels: Security > Attachments: HADOOP-11335.001.patch, HADOOP-11335.002.patch, HADOOP-11335.003.patch, HADOOP-11335.004.patch, KMS ACL in metadata or database.pdf > > Original Estimate: 504h > Remaining Estimate: 504h > > Currently Hadoop KMS has implemented ACL for keys and the per key ACL are stored in the configuration file kms-acls.xml. > The management of ACL in configuration file would not be easy in enterprise usage and it is put difficulties for backup and recovery. > It is ideal to store the ACL for keys in the key meta data similar to what file system ACL does. In this way, the backup and recovery that works on keys should work for ACL for keys too. > On the other hand, with the ACL in meta data, the ACL of each key can be easily manipulate with API or command line tool and take effect instantly. This is very important for enterprise level access control management. This feature can be addressed by separate JIRA. While with the configuration file, these would be hard to provide. -- This message was sent by Atlassian JIRA (v6.3.4#6332)
http://mail-archives.apache.org/mod_mbox/hadoop-common-issues/201501.mbox/%3CJIRA.12757855.1416962075000.181867.1422343955365@Atlassian.JIRA%3E
CC-MAIN-2017-51
refinedweb
592
55.24
Merge remote-tracking branch 'aosp/upstream-master' into HEAD am: a78a14d02f Change-Id: Ib2f7c516889a8ac444a1f620e69451d38e2cc9cd The Guideline Support Library (GSL) contains functions and types that are suggested for use by the C++ Core Guidelines maintained by the Standard C++ Foundation. This repo contains Microsoft's implementation of GSL. The library includes types like span<T>, string_span, owner<> and others. The entire implementation is provided inline in the headers under the gsl directory. The implementation generally assumes a platform that implements C++14 support. There are specific workarounds to support MSVC 2015. While some types have been broken out into their own headers (e.g. gsl/span), it is simplest to just include gsl/gsl and gain access to the entire library. NOTE: We encourage contributions that improve or refine any of the types in this library as well as ports to other platforms. Please see CONTRIBUTING.md for more information about contributing. This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. This project makes use of the Catch testing library. Please see the ThirdPartyNotices.txt file for details regarding the licensing of Catch. The test suite that exercises GSL has been built and passes successfully on the following platforms:1) If you successfully port GSL to another platform, we would love to hear from you. Please submit an issue to let us know. Also please consider contributing any changes that were necessary back to this project to benefit the wider community. 1) For gsl::byte to work correctly with Clang and GCC you might have to use the -fno-strict-aliasing compiler option. To build the tests, you will require the following: These steps assume the source code of this repository has been cloned into a directory named c:\GSL. Create a directory to contain the build outputs for a particular architecture (we name it c:\GSL\build-x86 in this example). cd GSL md build-x86 cd build-x86 Configure CMake to use the compiler of your choice (you can see a list by running cmake --help). cmake -G "Visual Studio 14 2015" c:\GSL Build the test suite (in this case, in the Debug configuration, Release is another good choice). cmake --build . --config Debug Run the test suite. ctest -C Debug All tests should pass - indicating your platform is fully supported and you are ready to use the GSL types! As the types are entirely implemented inline in headers, there are no linking requirements. You can copy the gsl directory into your source tree so it is available to your compiler, then include the appropriate headers in your program. Alternatively set your compiler's include path flag to point to the GSL development folder ( c:\GSL\include in the example above) or installation folder (after running the install). Eg. MSVC++ /I c:\GSL\include GCC/clang -I$HOME/dev/GSL/include Include the library using: #include <gsl/gsl> For Visual Studio users, the file GSL.natvis in the root directory of the repository can be added to your project if you would like more helpful visualization of GSL types in the Visual Studio debugger than would be offered by default.
https://android.googlesource.com/platform/external/Microsoft-GSL/+/c1b94b10a13f22e951c429e056b151d340238e27
CC-MAIN-2017-39
refinedweb
543
55.44
failed to create jaxb contextGary Pinkham Dec 22, 2010 4:31 PM I created a web service client using wsconsume. wrote a unit test and it worked fine.. could see the call going out and the data coming back.. I then created a custom Action for JBoss ESB to perform the call to the Web Service and this fails with "failed to create jaxb context" Any ideas what might be causing the hangup when calling from an ESB action as opposed to the command line unit test client? (I copied the code over so I know it's the same client code).. Thanks! Gary 1. Re: failed to create jaxb contextGary Pinkham Dec 23, 2010 10:25 AM (in response to Gary Pinkham) ok so i discovered a couple of facts... 1. when the unit test worked I had the Service locator using a local version of the WSDL (c:\foo\bar\myservice.wsdl)... I had changed this to the wsdl from the live running instance when I waned to deploy the client as a library jar in the ESB Action.. This WSDL produced on the fly by JBossWS came out different than the original that the Service and Clients we based on (top down service and client generation).. Needless to say the client didn't match this (I kept getting a service not found as the namespace and service names didn't match).. I tried to change the Service's annotation to include a WSDL location for the original WSDL file.. The service then failed to start (giving the same error about the namespace and service names not matching).. So at this point I'm not sure what exactly I did wrong.. I used JBossWS to generate the Service from the WSDL file.. I then used JBossWS to produce the client from the same exact WSDL file.. Having the client point to the file on disk seemed to work ok.. But this only worked with absolute path.. not sure how to get it to work with relative paths within the JAR file.. Suggestions? thanks! Gary 2. Re: failed to create jaxb contextGary Pinkham Dec 23, 2010 11:39 AM (in response to Gary Pinkham) OK.. So I solved this (not sure this is the correct solution but it works).. Basically I added the wsdl to the src folder of the client and just grabbed it from there.. So in the end the original posted issue was because the auto generated WSDL didn't conform to the original WSDL (not sure why). Having the client use the original static WSDL solved it.. Thanks Gary
https://developer.jboss.org/thread/160329
CC-MAIN-2018-39
refinedweb
434
78.28
I am trying to understand some code that I have found on github. Essentially there is a class called "HistoricCSVDataHandler" that has been imported from another module. In the main method this class is passed as a parameter to another class "backtest". How can a class name that does not represent a instantiated variable be called without raising a NameError. Or simply put : Why/How is the class being called as: Backtest(HistoricCSVDataHandler) CSV_Handler = HistoricCSVDataHandler(foo,bar,etc) Backtest(CSV_Handler) This is a technique called dependency injection. A class is an object just like any other, so there's nothing wrong with passing it as an argument to a function and then calling it inside the function. Suppose I want to read a string and get either an int or a float back. I could write a function that takes the desired class as an argument: def convert(s, typ): return typ(s) Calling this gives several possibilities: >>> convert(3, str) '3' >>> convert('3', int) 3 >>> convert('3', float) 3.0 So the Backtest function in your code is most likely creating an instance of whichever class you pass - i.e. it is calling HistoricCVSHandler internally to create an instance of that class. We normally think of Python objects as instances of some class. Classes are similarly objects, and in fact are instances of their so-called metaclass, which by default will be type for classes inheriting from object. >>> class MyClass(object): pass ... >>> type(MyClass) <type 'type'>
https://codedump.io/share/27MwvB52CLL0/1/python-class-instantiation-what-does-it-mean-when-a-class-is-called-without-accompanying-arguments
CC-MAIN-2017-04
refinedweb
247
63.29
Dimensions Remember that a parabola is defined by a second-order equation like this: y = ax2 In Figure 4, the Y axis is labeled “Depth” and the X axis is labeled “Height.” The focus of a parabola is given by: 1 f= 4a The focus is where the center of the ultrasonic transducer sits. A nice size for a half-paraboloidal antenna on a small robot might be one that is, say, four inches wide and 2. 5 or so inches high. If we make a = 0.333 and the maximum x = G02 (CW) and G03 (CCW) commands with increasingly-larger radii until all the material at this first layer is removed. 2. 5 inches, we will find from the above two equations the focus will be located at f = 0.75 inches (refer again to Listing 1: Gcode creating program. Figure 4) and the depth will be 2.08 inches (slightly larger than two inches). Now, if we take the Figure 4 curve and rotate it through 180°, we arrive at the half paraboloid of Figure 2. We now have the specifications for how to make the antenna mold. So, how do we turn that into a piece of wood with the correct CNC carving? In other words, we know what the shape of the wood mold should look like, but how do we get a machine to do that for us? Usually, when someone wants to create something with a CNC machine, they use CAD/CAM programs (the February 2018 issue of SERVO has a good introduction to using CNC). The final result of the CAD/CAM process is called G-code, which is just a long series of text commands that instruct the CNC machine to move in straight lines (G00 or G01 commands) or in clockwise (CW) or counterclockwise (CCW) arcs (G02 or G03 commands, respectively). We’re going to skip the CAD/CAM step for this project and use the mathematical equations for a parabola and the fact that we just want to rotate through 180° to write a program in a high-level programming language to create the G-code statements that will drive the CNC machine. The programming language we’ve chosen is Python, although C or some other language would work just as well. The Python program is shown in Listing 1. The program works like this: It first writes a G02 (CW arc) command to the G-code file. This first G02 command creates a semicircle arc that will remove the material at a 0.032 inch depth with a radius of 0.31 inches. The program then writes a G03 (CCW) arc command with a slightly larger (by 0.04 inches) radius than the previous G02 command. It continues to send alternating SERVO 07/08.2018 53 Figure 4. Parabola profile turned 90° on its side. import math fileID = open(‘gcodeSmallParaboloid.txt’,’w’) fileID.write(‘For now, negative Z is up \r\n’) fileID.write(‘G20 \r\n’) fileID.write(‘F25 \r\n’) fileID.write(‘G54 G90 M03 (Select coordinate system, absolute mode \r\n’) fileID.write(‘G00 Z-0.1 \r\n’) for i in range (1, 64): depth = i*0.032 radius = math.sqrt(depth/0.333) clockwise = 1 Xend = -radius y = 0 if radius > 1.25: Xend = -1.25 temp = math.acos(1.25/radius) y = radius*math.sin(temp) absXend = abs(Xend) fileID.write(‘G00 X’’+ str(“{:,.3f}”.format(Xend)) + ‘‘Y’’+ str(‘{:,.3f}’.format(y)) + ‘\r\n’) fileID.write(‘G02 X’’+ str(‘{:,.3f}’.format(-Xend)) + ‘‘Y’’+ str(‘{:,.3f}’.format(y)) + ‘‘R’’+ str(‘{:,.3f}’.format(absXend)) + ‘\r\n’) fileID.write(‘G03 X’’+ str(‘{:,.3f}’.format(Xend)) + ‘‘Y’’+ str(‘{:,.3f}’.format(y)) + ‘‘R’’+ str(‘{:,.3f}’.format(absXend)) + ‘\r\n’) fileID.write(‘G00 Z’’+ str(‘{:,.3f}’.format(depth)) + ‘\r\n’) for j in range (i, 64): if radius < 2.45: Click to subscribe to this magazine
http://servo.texterity.com/servo/201807?pg=53
CC-MAIN-2018-30
refinedweb
647
69.38
This sounds simple but i'm new to Unity. i have a gameObject with an image component that displays different images. i want to be able to display the file's name without an extension in a text field. for example... The file's name: (Blue Car.png). Output: Blue Car (in a text field). How can i achieve that through code? you can use something like this using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class a : MonoBehaviour { public Text t1; public GameObject image; // Update is called once per frame void Update () { t1.text = image.name.ToString (); } } Answer by look001 · Sep 09, 2017 at 12:22 PM This should do the job: Image image; public Text text; public void Start() { image = GetComponent<Image> (); text.text = image.sprite.name; } Don't forget to add using UnityEngine.UI to the top using UnityEngine.UI Now apply this code to the gameobject with the image, add a Text to your canvas and drag it in the text field of the script. Good Luck ;) Another simple thing that i couldn't figure out. Thank you, it worked perfectly. 398 People are following this question. Multiple Cars not working 1 Answer UI fade with CanvasGroup vs of Image.color.alpha or Text.color.alpha performance 1 Answer Load a GameObject that is outside of script and set it active at the same time 1 Answer Distribute terrain in zones 3 Answers Local Euler Angles not Rotating GameObjects 1 Answer
https://answers.unity.com/questions/1404580/how-to-display-a-file-name-on-a-text-field-c.html
CC-MAIN-2020-05
refinedweb
250
68.47
First, I've read through the forums, and checked out similar problems. I suspect this is an occasion where I don't understand the process well enough to use the features. Background We have three IP networks (two public class C addresses and one private class A subnetted). Scanning shows authentication errors on all workstations. We use the same username and password for local login (Built-in Administrator for the username). Q1. I've added various forms of the login name to the authentication list and tested with complete failure. What I am guessing it that because there is only a local administrator (they're are not part of a MS domain as we are a Netware shop) does each workstation's login need to be machine_name/Administrator? If so this is unusable in our situation (I'd need 300 possible logins manually added). Which, if so, would lead to a feature request - could the system be given the workgroup name(s) and then use the workgroup broadcast to find the machine names and append the machine name to the user name to do authentication? Q2. As noted we have 3 address ranges - is there a way to set the scanning priority by range? While I want to see the whole system, I'd like to be able to scan and work with the servers first. Looking at the log it appears to be scanning the class B sized range first, which is the workstations. Q3. Any provision for gathering info from Netware servers (non-Linux based)? Thanks. 6 Replies Oct 17, 2006 at 10:46 UTC The answer to Q1 is no, the format does not have to include the computer name. I use local admin on several machines not in our domain and it works fine. The answer to Q2 is that I believe the scan runs from last entered up to first entered into the devices to be scanned list. At least that's how it goes about scanning on my network. Can anyone else confirm that? Q3 I'll leave for someone else hehe. (No clue) Oct 17, 2006 at 12:33 UTC Q1 - Using a local account name should work fine. Here's a simple test you can do to make sure it's not a WMI error and that the account works correctly. Copy the script below into a text file and save it. Edit the account name and password to be your local account. Then, from the command line, run "cscript <scriptname>". You should be some machine information as the output. If not, there is an issue with WMI either on the machine your running from, or the machine your talking to. [ -- BEGIN CODE -] On Error Resume Next strUser = "account" strPass = "password" Const wbemFlagReturnImmediately = &h10 Const wbemFlagForwardOnly = &h20 For Each strComputer in Wscript.Arguments WScript.Echo WScript.Echo "==========================================" WScript.Echo "Computer: " & strComputer & " User: " & strUser WScript.Echo "==========================================" Set objLocator = CreateObject( "WbemScripting.SWbemLocator" ) Set objWMIService = objLocator.ConnectServer [ --- END CODE --] Q2 - Charlie is correct, it starts from the bottom up of your list of device ranges to scan. Q3 - We don't have any current plans to support Netware, but that doesn't mean we won't, just folks haven't asked for it. Go into the Feature Requests forum and suggest Netware. Be sure to bump up the SPICINESS of the vote. We use that to decide what new features to add. Oct 17, 2006 at 12:34 UTC Charlie is correct. on Q1 and Q2. For Q1, if the account name already has a domain name, it is used as is, and otherwise, the local machine name is automatically prepended. As for Q3, we don't current support gathering information from Netware. Does anyone know of a remote scripting way to get information from a netware machine? Oct 24, 2006 at 10:28 UTC 1st Post Can you expand on the method of running the code. I get an error saying "there is no file extention in spice" Nov 23, 2009 at 4:12 UTC 1st Post Here's what worked for me. Save the file with a .vbs extension. Remove the line break from the end of this line: Set objWMIService = objLocator.ConnectServer(strComputer, "root\CIMV2") and this one: wbemFlagReturnImmediately + wbemFlagForwardOnly) The line breaks mess up the script engine. When you run the script, pass in a machine name as a parameter. In the example below, my script is named "script.vbs" and the machine name is "machine-01" c:\>cscript script.vbs machine-01 Hope this helps. kc Mar 31, 2010 at 3:12 UTC Niagara Technology Group (NTG) is an IT service provider. Looks like this has been resolved.
https://community.spiceworks.com/topic/410-authentication-errors
CC-MAIN-2016-44
refinedweb
778
73.78
having to copy its code each time. In this article, we will see how to create Python modules and how to use them in Python code. Writing Modules A module is simply a Python file with the .py extension. The name of the file becomes the module name. Inside the file, we can have definitions and implementations of classes, variables, or functions. These can then be used in other Python programs. Let us begin by creating a function that simply prints "Hello World". To do this, create a new Python file and save it as hello.py. Add the following code to the file: def my_function(): print("Hello World") If you run the above code, it will return nothing. This is because we have not told the program to do anything. It is true that we have created a function named my_function() within the code, but we have not called or invoked the function. When invoked, this function should print the text "Hello World". Now, move to the same directory where you have saved the above file and create a new file named main.py. Add the following code to the file: import hello hello.my_function() Output Hello World The function was invoked successfully. We began by importing the module. The name of the file was hello.py, hence the name of the imported module is hello. Also, note the syntax that we have used to invoke the function. This is called the "dot notation", which allows us to call the function by first specifying the module name, and then the name of the function. However, that is just one way of importing the module and invoking the function. We could have done it as follows: from hello import my_function my_function() Output Hello World In the above example, the first line commands the Python interpreter to import a function named my_function from a module named hello. In such a case, you don't have to use the dot notation to access the function, you can just call it directly. However, in the case where our hello module has multiple functions, the statement from hello import my_function will not import all hello's functions into our program, only my_function. If you attempt to access any other function, an error will be generated. You have to import the whole module or import each individual functions in order to use them. We can define a variable within a module, which can then be used by other modules. To demonstrate this, open the file hello.py and add the following code to it: def my_function(): print("Hello World") # The variable that'll be used in other modules name = "Nicholas" Now, open the main.py file and modify it as follows: import hello hello.my_function() print(hello.name) Output Hello World Nicholas We have successfully invoked both the function and the variable defined in the module since we imported the whole module instead of just the my_function() function. We stated earlier that we can define a class within a module. Let's see how to do this in the next example. Open the hello.py file and modify it as follows: def my_function(): print("Hello World") # Defining our variable name = "Nicholas" # Defining a class class Student: def __init__(self, name, course): self.course = course self.name = name def get_student_details(self): print("Your name is " + self.name + ".") print("You are studying " + self.course) Here we have defined a class named Student. Two variables have been defined in this class, name and course. The method get_student_details() has also been defined within this, which prints the student details to the console. Now, open the file main.py and modify it as follows: import hello hello.my_function() print(hello.name) nicholas = hello.Student("Nicholas", "Computer Science") nicholas.get_student_details() Output Hello World Nicholas Your name is Nicholas. You are studying Computer Science In the script above, we again used the dot notation to create an object of the student class from the hello module. We then used the get_student_details() function to get the student details. Although modules mostly consist of class definitions (in most cases), it is possible for them to actually run their own code as well when imported. To demonstrate this, let us modify the hello.py file, where we have a definition of the function my_function(), along with the call to the function: def my_function(): print("Hello World") my_function() Now, open the file main.py and delete all the lines except the following: import hello Output Hello World The above output shows that we defined and called the function within the module. When the module is imported, it directly returns the result from the function without having to invoke the function. This behavior isn't always desired, but it's helpful for certain use-cases, like pre-loading data from cache when the module is imported. Importing all Module Objects To import all objects (functions, variables, classes, etc.) from a module, we can use the import * statement. For example, to import all objects contained in the hello module, we can use the following statement: from hello import * After adding the above statement to a program, we will be able to use any function, variable, or class contained in the hello module without having to prefix it with hello. Accessing a Module from Another Path In Python, modules are used in more than one project. Hence, it makes no sense if you keep your modules in the directory of one of the projects, since other projects wouldn't be able to use it as easily. You have a couple of options whenever you need to access a module that is not stored in the same directory as your program. Let us discuss these in the next few sections: Appending Paths To import a module from another path, you first need to import the sys module as well as any other Python modules that you would like to use in your program. The sys module is provided by the Python Standard Library and it provides functions and parameters that are system-specific. The path.append() function from the sys module can be used to add the path of the module to the current project. To demonstrate this, cut the hello.py file from the directory where you have the file main.py. Paste it in another directory. In my case, I have pasted it in the directory "F:\Python." Now, open the file main.py, import the sys module and specify the path in which the Python interpreter will look for files. This is demonstrated below: import sys sys.path.append('F:/Python/') import hello Output Hello World In the above script, the line sys.path.append('F:/Python/') tells the Python interpreter to include this path in the list of paths that will be searched while importing the modules. Adding a Module to Python Path The above method works only if you import the sys module. If you don't import the sys module and specify the path to the module, an error will be generated. To make the module available to the entire system, you can add it to the path where Python normally checks for modules and packages. This way, you will not have to import the sys module and specify the path to the module as we have done in the previous section. Before doing anything else, you should first identify the path that Python searches for modules and packages. Just open the command line of your operating system and run the python command. This will take you to the Python terminal. Import the sys module as follows: import sys You can then run the following command to print out the path: print(sys.path) The output will contain at least one system path. If you do it from a programming environment, you will get several paths. In my case, I got the following: $ python Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print(sys.path) ['', '/Library/Python/2.7/site-packages/six-1.10.0-py2.7.egg', '/Library/Python/2.7/site-packages/cffi-1.2.1-py2.7-macosx-10.9-intel.egg', '/Library/Python/2.7/site-packages/pycparser-2.14-py2.7.egg', '/Library/Python/2.7/site-packages/virtualenv-13.1.2'] >>> Your goal should be to find the one in the environment that you are currently using. You should look for something like the following: /Library/Python/2.7/site-packages Move your hello.py file to the path. After that, you will be able to import the hello module from any directory in the usual way, as shown below: import hello Output Hello World Conclusion This marks the end of this article. A module is simply a Python file with a set of variables and function definitions. A module facilitates code reusability since you can define a function in a module and invoke it from different programs instead of having to define the function in every program. Although a module is mostly used for function and class definitions, it may also export variables and class instances.
https://stackabuse.com/creating-and-importing-modules-in-python/
CC-MAIN-2019-43
refinedweb
1,550
64.71
Image by Mohamed Hassan from Pixabay It is the 21st century and we are literally obsessed with data. Data seems to be everywhere and companies currently hold huge amounts of it regardless of the industry they belong to. This brings us to the problem of storing data in a way that it can be accessed, processed, and used efficiently. Before cloud solutions, companies would have to spend a lot of money on physical storage and infrastructure to support all the data the company had. boto3 library). So let’s first see how AWS S3 works. As we have mentioned before AWS S3 is a cloud storage service and its name S3 actually stands for Simple Storage Service. Additionally, AWS S3 is unstructured object storage. What does that mean? This means that data is stored as objects without any explicit structure such as files or subdirectories. The object is stored directly in the bucket with its metadata. This approach has a lot of advantages. The flat structure allows fast data retrieval and offers high scalability (if more data needs to be added it is easy to add new nodes). The metadata information helps with searchability and allows faster analysis. These characteristics make object storage an attractive solution for bigger and smaller companies. Additionally, it may be the most cost-effective option of storing data nowadays. So, now that you have a bit of background on AWS S3 and object storage solutions, you can get started and create an AWS account. In order to create an account, head to AWS and click on create an AWS account. You will be prompted to fill in a form similar to the one below.. Once you are in the AWS Management Console you will be able to access S3 from there.. Once the bucket is created you should be able to see it from S3. Now you can add and delete files by accessing the bucket via the AWS S3 console. The next step is to learn how to interact with the bucket via Python and the boto3 library. The first step is to use pip to install boto3. In order to do this you can run the following command: pip3 install boto3 The next step is to set up a file with AWS credentials that boto will use to connect to your S3 storage. In order to do it, create a file called ~/.aws/credentials and set up its contents with your own access keys. [default] aws_access_key_id=AKIAIOSFODNN7EXAMPLE aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY In order to create keys, you will need to head to the AWS Management Console again and select IAM under Security, Identity & Compliance. Once in IAM, select the users option as shown in the screenshot below: This will lead you to the user management platform where you will be able to add a new user. Make sure you grant a new user programmatic access. Also, make sure that the user has AmazonS3FullAccess permission. Once the user creation process is successful you will see the access keys for the user you have created. You can now use your credentials to fill in ~/.aws/credentials file. Once the credentials file is set up you can get access to S3 via this Python code: import boto3 s3_resource = boto3.resource('s3') If you want to see all the buckets in your S3 you can use the following snippet: for bucket in s3_resource.buckets.all(): print(bucket.name) It’s time to learn how to upload a file to S3 with boto3. In order to send a file to S3, you need to create an object where you need to specify the S3 bucket, object name (e.g. my_file.txt) and a path from your local machine from which the file will be uploaded: s3_resource.Object('<bucket_name>', '<my_file.txt>').upload_file(Filename='<local_path_file>') Yes, it’s that simple! If you now look at the S3 Management Console the bucket should have a new file there. Like uploading a file, you can download one once it actually exists in your S3 bucket. In order to do it, you can use the download_file function and specify the bucket name, file name and your local path destination. s3_resource.Object('<bucket_name>', '<my_file.txt>').download_file('<local_path_file>') You have just learned how to upload and download files to S3 with Python. As you can see the process is very straightforward and easy to set up. In this article, you have learned about AWS S3 and how to get started with the service. You also learned how to interact with your storage via Python using the boto3 library. By now you should be able to upload and download files with Python code. There is still much more to learn but you just got started with AWS S3! Views: 403 Comment You need to be a member of Data Science Central to add comments! Join Data Science Central
https://www.datasciencecentral.com/profiles/blogs/using-amazon-s3-for-object-storage-1
CC-MAIN-2021-31
refinedweb
812
63.7
File.GetLastWriteTime Method Returns the date and time the specified file or directory was last written to.. If the file. For a list of common I/O tasks, see Common I/O Tasks. The following example demonstrates GetLastWriteTime. using System; using System.IO; class Test { public static void Main() { try { string path = @"c:\Temp\MyTest.txt"; if (!File.Exists(path)) { File.Create(path); } else { // Take an action that will affect the write time. File.SetLastWriteTime(path, new DateTime(1985,4,3)); } // Get the creation time of a well-known directory. DateTime dt = File.GetLastWriteTime(path); Console.WriteLine("The last write time for this file was {0}.", dt); // Update the last write time. File.SetLastWriteTime(path, DateTime.Now); dt = File.GetLastWriteTime(path); Console.WriteLine("The last write time for this file was {0}.", dt); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } } - FileIOPermission for reading from the specified file. Associated enumeration: FileIOPermissionAccess.
https://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.100).aspx
CC-MAIN-2016-40
refinedweb
154
55.71
Hi all, First time poster and relatively new to Dynamo and could use some help. I’ve been taking a stab at creating a graph that allows the user to select a titleblock, multiple panel schedules, and a panel schedule graphic that’s been placed on a sheet, so as to get it’s position relative to titleblock, and then create new sheets with panel schedule graphic instances placed using the position data acquired. Basically, the code is @SeanP’s Schedule.dyn from Place Legends on Multiple Sheets with Template Legend tweaked just a bit. (see attached) My problem is in the node “Create Panel Schedule Graphics 2”, where I get the error “list can not be called”. I was hoping someone might be able to point out what’s causing my error and if it can be remediated. When ran the node is actually receiving a list of Panel Schedule Views for IN[0] and a list of Sheets for IN[1]. Can provide more detail as necessary. pschedules = IN[0] templateSheets = IN[1] try: pschedGraphics = for i in range (0, 24): pschedGraphics.append(PanelScheduleSheetInstance.Create(doc, pschedules(i), templateSheets(i))) except: import traceback errorReport = traceback. format_exc () if errorReport is None: OUT = pschedGraphics else: OUT = errorReport
https://forum.dynamobim.com/t/create-panel-schedule-sheet-instances-on-sheets/30007
CC-MAIN-2020-45
refinedweb
207
62.27
--- Stefan Bodewig <bodewig@apache.org> > > </unzip> > > right? Yes; additionally, and more usefully perhaps: <echo output="file?foo">foo</echo> as a replacement for <echo file="foo">foo</echo> In general I suppose I have always seen this concept as being most useful for specifying output either with tasks' attributes/properties or with mappers. Then again, anyplace the resource could be specified in this inline fashion suggests higher ease-of-use; overriding a property from the command line could use an entirely different resource as source, destination, etc. for a given operation. > > Sounds > > I guess we'd need something dynamic, i.e. there has > to be a way to > register a ressource prefix with RU so that I can > have string > representations for my own ressource types. > I had assumed we could specify things in such a way as to specify the resource type simply by its typedef, but I suppose a shortcoming of doing it this way is that for types from antlibs they must be explicitly typedef'd or have their ns mapped. Well, I suppose e.g. antlib:org.foo/customResource?bar wouldn't be the end of the world, and of course xmlns:foo="antlib:org.foo" + foo:customResource?bar would be the preferred way of doing this; also having the long form available would mean one could add an antlib with -lib, set a property with the long form, and now custom resources from a given antlib can be injected into a build that has no knowledge of/dependency on that antlib. Weird. :) > > (for BC, FileResource would be the default). > > For BC we'd have to keep the File-argument setters > anyway. IH could > be changed to use setSrc(Ressource) in favor of > setSrc(File) and use > the later if no ressource mapping was found. No > real need to have a > default in RU. OTOH it might be convenient for > users when they can > simply omit the "file?" prefix for files. > That'd be quite a bit of IH modification to make it preserve > 1 type for a given property. I can't decide what would be the best all-around solution, but it does seem that if we overloaded the same property setters with File and Resource, it might be easiest overall to add explicit code that setSrc(File) won't override setSrc(Resource) in IH (maybe no type can override a Resource), then default to FileResources as planned. Otherwise IH will have to have its internals changed quite a bit to maintain knowledge of multiple potential property types. > >. This goes back to my idea of simply using the registered type name to denote the resource desired, hence the conflict with xmlns if a user were to use a custom resource in a namespaced antlib. :) > > > However I'm not sure what the RIGHT "trigger > character" is and IMO > > this is the only outstanding question stopping us > from adding this > > feature to Ant. > > bikeshedding? 8-) I get those little allegories mixed up. Is that the one where we can blab back and forth forever, but ultimately whoever is doing the work can make the choice? > > "?" isn't pretty but works for me. "@" would > probably work nicely > (file@/usr/local/bin/xemacs) but may get unwieldy if > you use constant > ressource specifications inside of macrodefs (you'd > have to double the > "@"). No obvious choice IMHO, I'd take whatever you > pick. > Agreed wrt @. > > Aside from allowing IH to transform a String into > a given Resource, > > you'll see that tasks using mappers can choose to > pass the mapped > > names to this same factory code and work with > resources, or they can > > behave as normal and they will break if a user > tries to map to an > > arbitrary resource type > > Sounds good. > > > (assuming its string representation can't be > misinterpreted as a > > file, a situation I hope we'll be able to prevent > esp. by choosing > > the right "trigger character"). > > There won't be any such character. AFAIK the only > forbidden character > in Unix filenames is a / and this obviously is a > very bad choice for > the "trigger". "?" and "*" are unlikely in > filenames, but both are > used as wildcards in patterns - now that you mention > using the string > representation in mappers: > > <globmapper from="file?*.xml" > > > Here the "?" might look ambiguos. Actually, globmapper doesn't seem to support ?. ;) Also, remember that mapping would ordinarily be undertaken by passing in getName(), e.g. the part of a filename beyond the basedir. So ordinarily the full resource representation wouldn't include the resource type and all. Really mappers are kind of kludgy as they require a lot of implicit knowledge on how to use them--I'm pretty sure there are places in Ant that use mappers slightly differently anyway. :| > > OK, what is left? "#", "="? Or > "url()"? I kind of liked the parentheses thing when I saw it... I wonder if it looks too much like a method call. -Matt > > Stefan > > --------------------------------------------------------------------- > To unsubscribe, e-mail: > dev-unsubscribe@ant.apache.org > For additional commands, e-mail: > dev-help@ant.apache.org > > ____________________________________________________________________________________ The fish are biting. Get more visitors on your site using Yahoo! Search Marketing. --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org For additional commands, e-mail: dev-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-dev/200703.mbox/%3C23991.20127.qm@web55105.mail.re4.yahoo.com%3E
CC-MAIN-2016-30
refinedweb
872
63.8
Here is a listing of C test questions on “Arithmetic Operators” along with answers, explanations and/or solutions: 1. What will be the output of the following C code? #include <stdio.h> void main() { int a = 3; int b = ++a + a++ + --a; printf("Value of b is %d", b); } a) Value of x is 12 b) Value of x is 13 c) Value of x is 10 d) Undefined behaviour View Answer Explanation: None. 2. What is the precedence of arithmetic operators (from highest to lowest)? a) %, *, /, +, – b) %, +, /, *, – c) +, -, %, *, / d) %, +, -, *, / View Answer Explanation: None. 3. Which of the following is not an arithmetic operation? a) a *= 10; b) a /= 10; c) a != 10; d) a %= 10; View Answer Explanation: None. 4. Which of the following data type will throw an error on modulus operation(%)? a) char b) short c) int d) float View Answer Explanation: None. 5. Which among the following are the fundamental arithmetic operators, i.e, performing the desired operation can be done using that operator only? a) +, – b) +, -, % c) +, -, *, / d) +, -, *, /, % View Answer Explanation: None. 6. What will be the output of the following C code? #include <stdio.h> int main() { int a = 10; double b = 5.6; int c; c = a + b; printf("%d", c); } a) 15 b) 16 c) 15.6 d) 10 View Answer Explanation: None. 7. What will be the output of the following C code? #include <stdio.h> int main() { int a = 10, b = 5, c = 5; int d; d = a == (b + c); printf("%d", d); } a) Syntax error b) 1 c) 10 d) 5 View Answer Explanation: None. Sanfoundry Global Education & Learning Series – C Programming Language.
https://www.sanfoundry.com/c-test-arithmetic-operators/
CC-MAIN-2018-47
refinedweb
274
75
Wiring select signal giving you a GPIO capability of an additional 128 pins per SPI select signal when using these devices. (or double that if you use 8 more on the 2nd SPI select) Include #include <wiringPi.h> #include <mcp23s17.h> or #include <mcp23s08.h> Initialise mcp23s17Setup (int pinBase, int spiPort, int devId) ; or mcp23s08Setup (int pinBase, int spiPort, int devId) ; pinBase is any number above 64 that doesn’t clash with any other wiringPi expansion module, spiPort is 0 or 1 for one of the two SPI ports on the Pi and devId is the ID of that MCP23x08 or MCP23s17 on the SPI port. You don’t need to specify the number of pins here as the MCP23s08 has 8 pins and the MCP23s17 has 16 pins. The following photo shows it in-use with an MCP23S17 on a breadboard connected to a Pi. The green wires are the SPI connections, then it’s just power and ground (white, black) The test board is connected to pins 0 through 11 and the button to pin 15 in the same way as the MCP23017 I2C example. Note the 3 black wires to the bottom-left. These are connecting the A0, A1 and A2 pins to 0v, giving a chip-id (devId) of 0. The test program is virtually identical to the MCP23017 I2C example: /* * 23s17.c: * WiringPi test with an MCP23S17 SPI GPIO expander chip * * Copyright (c) 2012-2013 Gordon Henderson. <projects@drogon.net> *********************************************************************** */ #include <stdio.h> #include <wiringPi.h> #include <mcp23s17.h> #define BASE 123 int main (void) { int i, bit ; wiringPiSetup () ; mcp23s17Setup (BASE, 0, 0) ; printf ("Raspberry Pi - MCP23S17 Test\n") ; for (i = 0 ; i < 10 ; ++i) pinMode (BASE + i, OUTPUT) ; pinMode (BASE + 15, INPUT) ; pullUpDnControl (BASE + 15, PUD_UP) ; for (;;) { for (i = 0 ; i < 1024 ; ++i) { for (bit = 0 ; bit < 10 ; ++bit) digitalWrite (BASE + bit, i & (1 << bit)) ; delay (5) ; while (digitalRead (BASE + 15) == 0) delay (1) ; } } return 0 ; } Notes - You need to load the SPI kernel modules before you can use SPI devices. Use the gpio command: gpio load spi - The MCP23s08 and MCP23s17 only have internal pull-up resistors, not pull-down. - The maximum current sourced of sunk on any pin is 25mA, however the chip can only source a maxmum on 125mA or sink a maximum of 150mA. If you are using more than one chip, then you must make sure that each one has a unique devId (set by the A0, A1 and A2 pins on the chip), and initialise each one in-turn. Failure to do this will result in multiple chips working at the same time which is probably not what you want!
http://wiringpi.com/extensions/spi-mcp23s08-mcp23s17/
CC-MAIN-2018-17
refinedweb
442
75.44
05 December 2011 19:15 [Source: ICIS news] SAO PAULO (ICIS)--?xml:namespace> Products with less demand included thermoplastic resins, detergents and basic petrochemicals, the association added. Compared with September, In the first 10 months of the year, domestic sales fell by 3.49% year on year as chemical imports continued to increase, Abiquim said. Domestic production of industrial chemicals in October dropped by 5.83% year on year and by 0.16% month on month, according to Abiquim. In the January-October period, output fell by 3.99% year on year. In the first 10 months of 2011, domestic prices of chemicals increased by 15.27% year on year. In October from September, prices increased by 3.50%, Abiqu
http://www.icis.com/Articles/2011/12/05/9514136/brazil-october-chemical-sales-fall-6.79-year-on-year.html
CC-MAIN-2015-14
refinedweb
120
62.14
From Elixir Mix configuration to release configuration - Alchemy 101 Part 2 by Thomas Hutchinson This is Part 2 in our Alchemy 101 series. Catch up on Part 1: Elixir Module Attributes and Part 3: Fault Tolerance Doesn’t Come Out Of The Box. Today we will be looking at what happens to your Mix configuration when you perform a release. Take a look at the Set up section and then proceed to Application Configuration. Set up You can follow along with the examples. You will require elixir and to perform the following steps. First create a new mix project. mix new my_app --module Twitter cd my_app Next add distillery (for creating releases) to mix.exs as a dependency. defp deps do [{:distillery, "~> 0.10.1"}] end Then download distillery and create the release configuration. mix deps.get mix release.init The rest of the blog assumes that you are in the my_app directory. Application Configuration When creating an Elixir OTP Application you will most probably need some configuration. There are 4 ways to supply application configuration on startup. 1. In your mix.exs file. Here you can specify default application environment variables. This file is used to generate the .app file which is used to start your application. Run ‘mix help compile.app’ for more information 2. In your config/config.exs file, this compiles down to sys.config. Alternatively with distillery you can supply your own sys.config file. 3. With an additional .config file. From what I can see distillery and exrm don’t seem to support this out the box. You can find out more here on how to use it. 4. You can supply it to the Erlang VM when it starts up. Distillery supports this via erl_opts in rel/config.exs. Simply add “-Application Key Value” to it for each application configuration variable e.g. set erl_opts: “-my_app magic_number 42”. From what I have seen most people tend to go with the option 2, supplying configuration via config/config.exs. As configuration is an Elixir script it gives us the potential to be very creative. When creating a release (with exrm or distillery) config.exs (by default) is evaluated and the result is written to rel/$app/releases/$version/sys.config which is picked up by your application on startup. Not knowing this can lead to confusion. Here comes another example where this can happen. Open lib/twitter_client.ex and add the following to it. defmodule Twitter do require Logger def log_twitter_url do url = Application.get_env(:my_app, :twitter_url) Logger.info("Using #{url}") end end Now add the following to config/config.exs. config :my_app, twitter_url: System.get_env("TWITTER_URL") Pretty nice eh? It appears like we can get TWITTER_URL at runtime. Lets create the release and inspect it. Run the following. export TWITTER_URL="" MIX_ENV=prod mix release ./rel/my_app/bin/my_app console iex(my_app@127.0.0.1)1> Twitter.log_twitter_url() 17:26:05.270 [info] Using Perfect! Everything looks good, the url to the mock is being used. Just what I want during development. Now I want to test the integration with the real twitter API, time to change TWITTER_URL. export TWITTER_URL="" Start your release in the console and invoke Twitter.log_twitter_url/0. ./rel/my_app/bin/my_app console iex(my_app@127.0.0.1)1> Twitter.log_twitter_url() 17:26:05.270 [info] Using Strange! It is still using the mock url, but why? As mentioned before when creating a release the configuration is evaluated and written to sys.config. Lets take a look. cat rel/my_app/releases/0.1.0/sys.config [{sasl,[{errlog_type,error}]}, {my_app,[{twitter_url,<<"">>}]}]. As you can see twitter_url is “”. When the release is being created config.exs is evaluated and the results are placed in sys.config. Part of this involved executing System.get_env(“TWITTER_URL”) and having “” returned. This doesn’t have to be a problem though as you can set Application configuration at runtime via Application.put_env/3. Using this you could create a function that reads the OS environmental variable and adds it to the application’s configuration. def os_env_config_to_app_env_config do twitter_url = System.get_env("TWITTER_URL") Application.put_env(:my_app, :twitter_url, twitter_url) :ok end Note that this function would have to be called before any initialisation in your application takes place. I’m sure there are other ways to handle this scenario, if so feel free to mention them in the comments section. Hope you enjoyed reading, tune in next time where I’ll be talking about what it means to be fault tolerant. This is Part 2 in our Alchemy 101 series. Catch up on Part 1: Elixir Module Attributes and Part 3: Fault Tolerance Doesn’t Come Out Of The Box.Go back to the blog
https://www.erlang-solutions.com/blog/from-elixir-mix-configuration-to-release-configuration-alchemy-101-part-2.html
CC-MAIN-2018-17
refinedweb
787
61.93
/* * Style guide for the OpenBSD KNF (Kernel Normal Form). */ /* * VERY important single-line comments look like this. */ /* Most single-line comments look like this. */ /* * Multi-line comments look like this. Make them real sentences. * Fill them so they look like real paragraphs. */ #include <sys/types.h> /* Non-local includes in brackets. */ #include <net/if.h> #include <net/if_dl.h> #include <net/route.h> #include <netinet/in.h> #include <paths.h> #include "pathnames.h" /* Local includes in double quotes. */ static’.); void function(int a); static char *function(int, const char *); static void usage(void); __deadfrom <sys/cdefs.h> for functions that don't return, i.e., __dead void abort(void); __BEGIN_DECLS / __END_DECLSmatching) enum enumtype { ONE, TWO } et; int^Ix;’ and ‘ struct^Ifoo ; }; struct foo *foohead; /* Head of global foo list */ ) { extern char *__progname; /* from crt0.o */ "usage: f [-12aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\n" "usage: f [-a | -b] [-c [-de] [-n number]]\n" __prognamestring may be used instead of hard-coding the program name. (void)fprintf(stderr, "usage: %s [-ab]\n", __progname); exit(7).
http://man.openbsd.org/OpenBSD-current/man9/style.9
CC-MAIN-2017-22
refinedweb
177
63.46
Hey everyone, been working hard to get past the newbie stage ! However I have yet one more totally newbie question. when I use cin.get(); at the end of a program or the end of a function to keep the prompt window open..... IT DOESN'T EVER WORK ~!! I see it in everyone elses code used the same way...... I think. here's an example. when I run even the ol' simple " hello world " program with cin.get(); at the end, it won't stay open. The program runs, and the window closes in about 0.343 seconds. here's a quick example code: Code: #include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; cin.get(); } Am I using it correctly ? if so why doesn't this work for any of my programs ? thanks #include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; cin.get(); } ok ok ok,,,, I get it... it's the return 0; right ? can someone steer me to an article or tutorial about the use of " return " because I'm not clear on it's use. Won't a C++ program automatically return 0 if it was successful ? why use it ? thanks. Originally Posted by Jeff++ it's the return 0; right ? Yes, you probably want to swap the order of the cin.get() call and the return statement. Alternatively, ditch the cin.get() call and run your program from the command prompt, or from an IDE that automatically pauses the program at the end, or by setting a break point with your debugger. Originally Posted by Jeff++ Won't a C++ program automatically return 0 if it was successful ? Yes, the global main function returns 0 if control reaches its end without encountering a return statement. Originally Posted by Jeff++ why use it ? Some people just want to be consistent with other functions since the global main function is special in this regard. C + C++ Compiler: MinGW port of GCC Build + Version Control System: SCons + Bazaar Look up a C/C++ Reference and learn How To Ask Questions The Smart Way Kindly rate my posts if you found them useful so.... a function WON'T return true or false unless that line is at the end of that function ? can you use more than 0 and 1 ? like..... number each function with a return number higher than the last one... so if there's an error you know what function it was ? thanks. Originally Posted by Jeff++ can you use more than 0 and 1 ? Since the return type is int, you can return any int value. However, in the case of the global main function you should only return 0, EXIT_SUCCESS or EXIT_FAILURE. The latter two are macros defined in <cstdlib>. cool. thanks laserlight. how does one know what functions or macros are defined in what header files ? and why do some need the .h on the end like <windows.h> and some don't like <iostream> ?? Books and learns View Tag Cloud Forum Rules
http://forums.codeguru.com/showthread.php?470885-cin.get()-Doesn-t-Work-for-me...-Anyone&p=1812767
CC-MAIN-2013-48
refinedweb
509
77.23
Improve this doc Edit videos using native device APIs Repo: $ ionic cordova plugin add cordova-plugin-video-editor $ npm install --save @ionic-native/video-editor import { VideoEditor } from '@ionic-native/video-editor'; constructor(private videoEditor: VideoEditor) { } ... this.videoEditor.transcodeVideo({ fileUri: '/path/to/input.mov', outputFileName: 'output.mp4', outputFileType: VideoEditor.OutputFileType.MPEG4 }) .then((fileUri: string) => console.log('video transcode success', fileUri)) .catch((error: any) => console.log('video transcode error', error)); OptimizeForNetworkUse OutputFileType transcodeVideo(options) Transcode a video TranscodeOptions Options Returns: Promise<string> Returns a promise that resolves to the path of the transcoded video Promise<string> trim(options) Platforms:iOS Trim a video TrimOptions Returns: Promise<string> Returns a promise that resolves to the path of the trimmed video createThumbnail(options) Create a JPEG thumbnail from a video CreateThumbnailOptions Returns: Promise<string> Returns a promise that resolves to the path to the jpeg image on the device getVideoInfo(options) Get info on a video (width, height, orientation, duration, size, & bitrate) GetVideoInfoOptions Returns: Promise<VideoInfo> Returns a promise that resolves to an object containing info on the video Promise<VideoInfo> string The path to the video on the device. The file name for the transcoded video number Instructions on how to encode the video. Android is always mp4 Should the video be processed with quailty or speed in mind. iOS only boolean Save the new video the library. Not supported in windows. Defaults to true Delete the original video. Android only. Defaults to false iOS only. Defaults to true Width of the result Height of the result Bitrate in bits. Defaults to 1 megabit (1000000). Frames per second of the result. Android only. Defaults to 24. Number of audio channels. iOS only. Defaults to 2. Sample rate for the audio. iOS only. Defaults to 44100 Sample rate for the audio. iOS only. Defaults to 128 kilobits (128000). (info: number) => void Not supported in windows, progress on the transcode. info will be a number from 0 to 100 Path to input video. Time to start trimming in seconds Time to end trimming in seconds Output file name (info: any) => void Progress on transcode. info will be a number from 0 to 100 The path to the video on the device The file name for the JPEG image Location in the video to create the thumbnail (in seconds) Width of the thumbnail. Height of the thumbnail. Quality of the thumbnail (between 1 and 100). Width of the video in pixels. Height of the video in pixels. 'portrait' | 'landscape' Orientation of the video. Will be either portrait or landscape. Duration of the video in seconds. Size of the video in bytes. Bitrate of the video in bits per second.
https://ionicframework.com/docs/native/video-editor/
CC-MAIN-2018-26
refinedweb
444
59.9
Type: Posts; User: newkid help ! this print program print nothing . all source code included. i am using jdk1.2.2 on win 95 pc. if i use a smaller jtable. it will print the jframe. why ? how can i print a big jframe ? ... tfStartDate.setText("30/05/1998"); tfEndDate.setText("30/03/1999"); String stryear1 = tfStartDate.getText().substring(6,10) ; String strmonth1 =... how do i validate a jtextfield which only allow dd/mm/yyyy in it. the length must be 10 and any other format will cause an error to pop out. any help is much appreciated. thanks ... how can i stop a jtextfield from being resized ? when the form is maximized, the jtextfield becomes so blotted and ugly... yukk... how can i prevent that while allowing the jframe to be... PLEASE HELP =========== i am really lost on how to do this. how do i update the table contents when the user select another date and click the button. i need to update the table (default... i have no idea how to start doing that. can you give me some code sampels ? thanks a lot. how do i clear all the rows in a jtable so that i can put in new rows as a result of clicking on a button ? how can i print a jpanel with many components on it ? components such as jlabel, jbutton and jtables ? the various examples i found only shows how to print the contents of a jtable or a... String cols[][][] = new String[7][2][]; int colcount[] = new int[7]; int i=0; while (rs.next()) { cols[0][0][i] = rs.getString(1); cols[0][1][i] = rs.getString(2); colcount[0] +=... can you give me a short example ? how do i put html in my jlabel. i thought jlabel only displays a single line of code ? thanks can i make a jlabel that span multiple lines ? it displays lines on top of other lines. that's all. thanks in advance. how to align the cell inside a jtable to left or right ? is there an easy way where we do not need to extend the cellrenderer ? this is just an easy question : how do i create a table with only columns and no rows and the table's height is its column height. can i specify the table's column width ? thanks ... how do i add the rows to the jtables. using my method, it is not a good way to add it. as i need to check j==0 , j==1 ...etc. //import java.util.Vector; import java.sql.*; import OraDB;... import javax.swing.*; import java.util.*; public class TableEx{ public static void main( String[] str ){ JFrame frame = new JFrame(); Vector columnNames = new Vector(); ... Yes. It works. I did not know that i have to download all the files you specified. Previously, i only downloaded 1 file and tried to compile. Now, it works. Thanks a lot. ... tableLabels.addElement("Emp Code"); tableData.addElement("0181"); JTable table = new JTable (tableData, tableLabels ); C:\JavaClass>java demotable Exception in thread "main"... below is my code. how do i implement adding rows dynamically to the jtable using vector. ( i know it is vector.addElement something... But what is the actual code ? ) Thanks import... the example is this, as below. it could not compile :- /* (swing1.1beta3) * *... cannot compile the source code at because it imports user defined classes. so, how now ? how does the whole file look like . well, i really need to get it fast and could not afford to read up on the java books. really appreciated some java code. hopefully a working demo. thanks a... how do i create a jtable header that takes up 2 lines ? such as below ? | Sex | | M | F | Thanks again yes. thanks for the code. but, i thought some of you really could come up with some code that can add and delete rows. Help. I am stuck. I want to implement a JTable which can addrows to it. From only contain... i got one from for oracle called 816classes12.zip jdbc driver category 4 - thin client . you can download from
http://forums.codeguru.com/search.php?s=20b6261aa663153a41b9dbfb9e51abb6&searchid=9127015
CC-MAIN-2016-30
refinedweb
683
79.56
The Python Pandas library The Pandas library is a Python library which aims to make your life easier in terms of data manipulation. It is therefore an essential element that must be mastered as a data scientist. The data structures managed by Pandas can contain all types of elements, namely (in Pandas jargon) Series and DataFrame and Panel. As part of our experiments, we will rather use the Dataframe because they offer a two-dimensional view of the data (like an Excel table), and this is exactly what we will try to use for our models. For information : - A Series Pandas is a labeled vector capable of containing any type of object (1-dimensional array) - A DataFrame is a two-dimensional matrix where the columns can be of different types (2-dimensional array) - A Panel is a three-dimensional data structure. If you have opted for a Python distribution (Anaconda for example) good news, you have nothing to do, this library is already present in said distribution … if this is not the case the pip command will allow you to install: $ pip install pandas The other good news is that this library is designed to work with two other famous and essential libraries: NumPy and matplotlib! As part of this little tutorial, I recommend that you use Jupyter notebook (the sources are available below) in order to go faster. Do not hesitate to consult the official documentation either: Data types Let’s first create a simple dataset (DataFrame) import pandas as pd pd.DataFrame({'Colonne 1': [1], 'Colonne 2': [2]}) The first command tells Python that we are going to work with the Pandas library. The second line tells Pandas to create a two-dimensional array. Here is the result : The columns have beautiful labels but if you also want to label your rows you will have to specify it with the index property as follows: pd.DataFrame({'Colonne 1': [35, 41], 'Colonne 2': [1, 2]}, index=['Ligne 1', 'Ligne 2']) Here is the result : It’s not necessarily the most useful but it can still be useful, here’s how to create a series (vector): pd.Series(["Valeur1", "Valeur2", "Valeur3", "Valeur4"], index=["Index1", "Index2", "Index3", "Index4"], name='Ma série') The result : On the other hand, to recover data from a csv file, it is more useful, for that use the read_csv command: csv = pd.read_csv("./datasets/housing/housing.csv") Note: If you want to read an excel file instead, refer to the read_excel command . Once read the file, several commands are very useful: - head () : used to display the first lines of the DataFrame - tail () : same but for the last lines - describe () : Very useful, gives indications on the data (count, standard deviation, median value, quantile, min, max, etc.). Warning ! some statistical indicators are only valid for numerical variables (eg mean, min, max, etc.), and conversely for non-numeric ones (eg top, freq, etc.), hence “NaN” in certain situations. To retrieve all the statistics, perform a df["colonne 1"].describe(include='all') - shape () : object dimensions - value_Counts () allows to obtain a very useful array of values + distribution frequency: df["colonne 1"].value_counts () - etc. Access the data (DataFrame) Get a vector We can recover a column vector (a column of the DataFrame) very simply via: csv.longitude ou csv["longitude"] NB: csv is a DataFrame which has a column labeled longitude. Recover a cell csv.longitude[0] Or csv["longitude"][0] Handling DataFrame data In the same spirit, we can retrieve pieces from the DataFrame via the iloc () and loc () commands: Get the first 4 columns and the first 3 lines: csv.iloc[:3, :4] Filtering on columns (via labels): csv.loc[:, ('longitude', 'latitude')] Handling character data It is often useful to break up strings. for this Pandas offers several very practical functions. The split () function for example allows you to split the character string according to a separator. Example: monDataframe["index1"].str.split("-", expand=True) In the example above, we cut out the character string corresponding to the “index1” column of the DataFrame mondataframe with the character – separator . Note two things here. the str attribute is used in the first place to handle the data of the DataFrame as a character. Second, the expand = True option allows you to return a new DataFrame instead of a series (it is much more practical later). See the official Python documentation for other character handling functions. Jupyter notebooks in this tutorial Find the examples and results above in the two jupyter notebooks on my Github Continuation of the tutorial (Part N ° 2) here
http://aishelf.org/pandas-1/
CC-MAIN-2021-31
refinedweb
758
58.62
viewtopic.php?t=6477 I'm figuring out how to do this on my board. I don't understand how to set the pulse width and timer values on ESP32. This is what I have. There is movement when I exectute this command, but beeping from the stepper for the frequency. But no further movement. Code: Select all import time import machine from machine import Pin, PWM en = machine.Pin(14, machine.Pin.OUT) IN1 = machine.Pin(2, machine.Pin.OUT) IN2 = machine.Pin(0, machine.Pin.OUT) #forward IN1.on() IN2.off() en.on() pwm2 = PWM(en, freq=1000, duty=512) I'm using this board. ... be&lang=nl
https://forum.micropython.org/viewtopic.php?t=8016&p=45616
CC-MAIN-2020-16
refinedweb
110
71.41
Diagnosing DFHPI0602 messages and PlisaxaRC SOAP Fault messages Technote (troubleshooting) Problem(Abstract) You send a SOAP message to CICS. As a result, CICS issues a SOAP Fault message with a PlisaxaRC and message DFHPI0602 to report a problem parsing the XML. But, you have difficulty knowing how to fix the problem. Cause The CICS SOAP handler program uses the Enterprise PL/I XML parser in order to process the contents of the SOAP message. If something goes wrong during this process then DFHPI0602 is issued: DFHPI0602 The CICS SOAP handler failed to parse a message. The parser error code is error_code. The DFHPIEP return code is return_code. The error was found at offset offset into the message. CICS also builds a SOAP Fault message to report the problem. If CICS is the Web service provider then this Fault message is returned to the requester. If CICS is the Web service requester then this Fault message replaces the invalid message returned from the remote Web service provider. The Fault message will look something like the following: <SOAP-ENV:Fault <faultcode>SOAP-ENV:Client</faultcode> <faultstring>Malformed SOAP message</faultstring> <detail> <cics:FaultDetail xmlns:</detail> <cics:SoapParsing></cics:FaultDetail> <cics:PlisaxaRC> error_code</cics:PlisaxaRC></cics:SoapParsing> <cics:Offset> offset</cics:Offset> <cics:PiepRC> return_code</cics:PiepRC> </SOAP-ENV:Fault> DFHPIEP error codes are formatted out properly in the CICS Transaction Server for z/OS (CICS TS) V4.1 and V4.2 DFHPI0602 message. Also, most scenarios that used to result in message DFHPI0602 now result in a different message so this document is less necessary. However, DFHPI0602 is still used in some places. Resolving the problem As documented in the user response for message DFHPI0602, you can look up the parser error code in the Enterprise PL/I Programming Guide. This is available at: This book contains sections that list Continuable exception codes and Terminating exception codes. Between these two sections all of the relevant codes that the XML parser can return are listed. For example, if you see message: DFHPI0602 The CICS SOAP handler failed to parse a message. The parser error code is 317. The DFHPIEP return code is 10. The error was found at offset 0 into the message. Code 317 can be resolved to mean: The parser cannot determine the document encoding. The document may be damaged. If the error code is '0' then the XML Parser has not reported a problem. DFHPIEP has encountered a problem whilst processing the output from the XML Parser. This usually implies that the SOAP message does not conform to the SOAP protocol, even though it is valid XML. Following are the possible return codes issued by DFHPIEP: a GETMAIN failure occurred whilst processing the SOAP message 2 fc_null_pointer a logic error in DFHPIEP 3 fc_invalid_child a tag other than a SOAP Body or Header tag was found within the SOAP envelope 4 fc_dtd_found an in-line DTD was found within the SOAP message 5 fc_no_envelope currently unused 6 fc_versionmismatch the namespace for the SOAP envelope tag is not recognized 7 fc_process_instr an XML processing instruction was found within the SOAP message 8 fc_invalid_msg there is a problem with the structure of the SOAP envelope 9 fc_unqualified_attr an unqualified attribute was found on a SOAP tag 10 fc_fatal_parse the XML parser returned a fatal error code 11 fc_filler currently unused 12 fc_tag_null_pointer a logic error in DFHPIEP 13 fc_attr_null_pointer a logic error in DFHPIEP The offset in the DFHPI0602 message indicates the position within the SOAP message at which the problem was found. You can view the XML in either the DFHREQUEST or the DFHRESPONSE containers, though there are some scenarios where this offset can be misleading. For example, the SOAP message is parsed by CICS in UTF-8 encoding, but the data may be converted to EBCDIC before it is logged. This code page conversion could cause the offset of the problem to move. Another problem is that the contents of the container may change before they are logged. A problem to be aware of is that in requester mode, if there is a problem with the SOAP message returned to CICS by a remote Web service provider application, CICS might issue the DFHPI0602 message and then replace the contents of the DFHRESPONSE container with a new Fault message. In which case, it will be necessary for you to take a trace of the problem in order to see the contents of the DFHRESPONSE container as it was when CICS issued the DFHPI0602 message. Product Alias/Synonym CICS/TS CICS TS CICS Transaction Server Document information More support for: CICS Transaction Server Web Services Software version: 3.1, 3.2, 4.1, 4.2 Operating system(s): z/OS Reference #: 1264885 Modified date: 21 May 2012 Translate this page:
http://www-01.ibm.com/support/docview.wss?uid=swg21264885&myns=swgother&mynp=OCSSGMGV&mync=R
CC-MAIN-2018-22
refinedweb
798
50.77
Firstly, I, like many of you, am glad to see that Dare Obasanjo’s indefinite hiatus from the blogosphere was short lived. Secondly, while I most certainly agree with the premise of his recent “In Defense of XML” post — which was written in response to Jeff Atwood’s most recent attempt to get everyone in the XML communities of the world to hate him ;-) — the fact of the matter is: Jeff Atwood is right! Now before any of the members of the XML communities (of which I am a proud member of several!) pull out their pitchforks, and before any of the XML haters of the world declare some sort of moral victory, let me be perfectly clear: So is Dare! “WTF?” you say? Well, let’s first take a look at a portion of Dare’s argument: My problem with Jeff’s articles is that they take a very narrow view of how to evaluate a technology. No one should argue that XML is the simplest or most efficient technology to satisfy the uses it has been put to today. It isn’t. The value of XML isn’t in its simplicity or its efficiency. It is in the fact that there is a massive ecosystem of knowledge and tools around working with XML. Absolutely spot on! Then again, from Jeff Atwood’s recent “Revisiting the XML Angle Bracket Tax”:. Absolutely spot on! XML isn’t the right fit for everyone and everything. In particular, when the most common use-case for a given configuration file is one that includes a *developer* directly editing this file for an application that runs on a platform that doesn’t natively speak XML, then chances are pretty good XML is the wrong choice. But before I dig down further into my argument, let me first provide follow-up to a comment left by “markus” in response to Dare’s post referenced and linked to above: But there is the BIGGEST problem of XML, which it can never do away - It was never meant for humans. HUH???!!! Is that really a common belief by many of you out there? What’s funny is that for those of us in the various XML communities who have been around long enough to have listened to, argued for/against, and in other forms have battled our way into making XML the defacto serialization format for things related to documents, data, and interop between them both, the argument will often times center around the very fact that XML was designed around the notion of being *human readable*, not the other way around. There’s an entire legion of folks who have been making attempt at building a binary XML format (something I wholeheartedly support), and the biggest wall they tend to run up against is the argument that: If it’s not text, it’s not human readable, and therefore it’s not XML. Of course, this would be a fair argument if one of the following two points were true: * A binary format means it’s locked down and can not be “reverse engineered” back into its text “equivalent.” * Binary XML == proprietary format that requires a custom parser and processor. The fact of the matter, however, is that neither of the above are true. The argument for or against angle brackets is a red herring: What XML provides — whether that be text XML or binary XML — is a standard in which the industry can build upon in such a way that allows us to communicate with one another even though we may not natively speak the same dialect. That said, editing binary XML directly would be impossible for a human. But the reality is that “human readable text” is only an illusion. Our editors our purposely built to hide all of the noise that would otherwise look like gobbledygook to us humans. So its not that binary XML can’t be edited by a human. It’s just that we haven’t built a massive tooling infrastructure that easily allows us to open up a binary XML file and edit it directly like we have for text-based file formats. Could we? Of course! And maybe we will. But if we do, the conversion won’t be lacking angle brackets unless, of course, these same tools have built in features that allow the ability to edit an XML file in a grid control, a tree control, or simply a text editor that uses a WYSIWIG formatter to hide the angle brackets *and other* characters that can be conveyed to us in more human meaningful ways (e.g. a visible hard break in the white space instead of \n\r or \n or or etc.) and therefore are otherwise not required for us to understand. Of course, we have those tools today. For example, Visual Studio, oXygen, XML Spy, Stylus Studio, and 100’s of others that facilitate the ability to hide the complexities of XML, allowing us to focus on getting our work done instead of being “jabbed in the eyes” — as Jeff puts it — by angle brackets. But that’s only part of the story. The real success story of XML is all of the non-developer tools out there that have adopted an XML format that ensures our document infrastructure is founded upon a non-proprietary format that can easily be opened, edited, saved, parsed, and rendered on any platform and with any tool that understands how to parse the XML serialization format, which, as it turns out, just so happens to be *ALL OF THEM*. Do Mom, Grandma Joe, and Uncle Bill know or even care that the document editor they are using stores their documents in an XML format? Of course not! But that doesn’t take away from the importance of XML. What they gain is document portability, and therefore the option of using any tool they might choose in the future to open, edit, and save this same document. What we gain (meaning we developers) is a basic foundation in which — no matter what platform and toolset we might prefer to use — can build upon and extend from using off the shelf parts while at the same time ensuring the end result of our creation will be fully interoperable with the end result of the creation of someone else. With all of this said, however, I do have empathy towards those folks who get XML crammed down their throats in places where XML isn’t necessarily the best fit. While one could argue that using XML as the serialization format for a config file — for example, the *.config files used in the .NET framework — allows the ability quickly and easily gain access to its properties and values without having to think about or even look at the file itself, there are certainly other options. And there’s certainly nothing wrong with using another format — like YAML, for example — that’s a bit more eyeball friendly. There is a trade off, of course. With XML you don’t have to worry about things like indenting given the fact that XML uses an open/close bracket format to encapsulate its data structure and hierarchy. So if someone inadvertently adds a space or a tab where they shouldn’t have, the original intent of the configuration file is unaffected. On the other hand, it’s slightly more difficult for a human to interpret and/or edit an XML file by hand than it is to interpret and/or edit a YAML file. And this is important for applications that require a lot of direct developer interaction with its configuration file, especially when dealing with frameworks that don’t have XML support built into their core (e.g. Ruby, which has instead adopted YAML as its core configuration format of choice) which brings us back to my argument specified above: Developers who don’t regularly work with XML really despise the fact that they are often times faced with opening, reading, and editing an XML configuration file by hand. Fair enough. It’s easy to understand why, *especially* when you consider that most of these developers are writing server-side web applications that — as a direct side-effect — don’t ever leave the machine they were created on, and if they do, it’s usually related to checking the file in and out of a VCS of one type or another or in other ways distributed in a “safe” container (e.g. Ruby gems, Python eggs, etc.) that ensures the implied structure — in this case YAML — remains intact. So the benefits of “interop” are irrelevant. What’s there to interop with? It’s a configuration file, and that same configuration file — unlike, for example, an ODF, OOXML, XHTML, and other document types that gain the derived benefits of using XML as their base format — will never have to be read and/or interpreted and/or edited and saved by an application it was never intended to provide configuration settings for. But does that mean XML truly sucks, or does it simply mean that when writing applications that: 1) Are built on platforms that don’t natively speak XML. 2) Primarily reside in a server-side environment. 3) Utilize configuration files that contain application specific settings as opposed to user specific settings and therefore have no need to be deemed “portable”. 4) Have a high probability of being hacked on, re-configured, and in other forms customized by developers for their specific needs. … that we, as developers, need to be a bit more mindful to the needs and desires of our “target audience” and, for the reasons specified above, utilize configuration file formats that are free from the “clutter” that is often times associated with the combination of angle brackets, namespaces, and namespace extensions? Yeah, I think we probably should. On the other hand, I believe that it’s important to point out that we are moving further and further into a world pwned by XML — Document formats, Web Services, declarative UI languages, etc. — so while it might make better sense to *standardize* on YAML for server-side application configuration, that doesn’t mean you, as a developer, shouldn’t learn all you possibly can about XML. It simply means that you don’t have to directly muck with it inside of your text editor of choice, which, if not mistaken, is the biggest beef the XML haters of the world have with the XML format: They don’t mind working with it in code, they just don’t want it gouging out their eyeballs and/or would prefer to keep the Carpal Tunnel Syndrome at bay for an additional 10 years or so. Seems fair enough to me. What about you? I've got to disagree with your enthusiasm for binary XML - the biggest advantage of text based XML is the fact that I don't need any special tools to use it. I regularly use less to display local XML, curl to make SOAP/XML-RPC calls and I often write XML by hand in gEdit - 3 things I could not do with a binary format. As soon as you have the need for special tools you weaken a file format. Sure, some schemas are easier to read or write than others, but at least it 's always possible. As for XML configuration, an app that's difficult to configure is going to be difficult to configure no matter what format the config file is in. It would make me mad if httpd.conf or php.ini became httpd.xml or php.xml. 1. Readability: yes, a goal since the SGML days. Easy to read, YMMV. It depends on the language designers. .... is informative but not very. 2. Interpretable? Again, YMMV. It doesn't have to be easy to read; just possible for some n of training or prior knowledge. It's a very old perrenial thread topic and I'm pretty sure each generation of markup newbs has to go through it once of twice. For the rest, someone wake me up when a decision is made. XML is often the best of the worst or just terrible. VRML was a lot cleaner without it. X3D is a lot more successful with it. Yawn. downloadable oem cd Adobe Creative Suite 3 Web Premium software buying oem cd Macromedia Flash 8 Pro software purchase Macromedia Dreamweaver MX 2004 software
http://www.oreillynet.com/xml/blog/2008/07/why_jeff_atwood_is_right.html
crawl-002
refinedweb
2,076
56.59
master status Quilt provides versioned, reusable building blocks for analysis in the form of data packages. A data package may contain data of any type or any size. Quilt does for data what package managers do for code: provide a centralized store of record. Reproducibility - Imagine source code without versions. Ouch. Why live with un-versioned data? Versioned data makes analysis reproducible by creating unambiguous references to potentially complex data dependencies. Collaboration and transparency - Data likes to be shared. Quilt offers a unified catalog for finding and sharing data. Auditing - the registry tracks all reads and writes so that admins know when data are accessed or changed. Less data prep - the registry abstracts away network, storage, and file format so that users can focus on what they wish to do with the data. De-duplication - Data are identified by their SHA-256 hash. Duplicate data are written to disk once, for each. A Quilt data package is a tree of data wrapped in a Python form a package instance. Package instances are immutable. Leaf nodes in the package tree are called fragments or objects. Installed fragments are de-duplicated and kept in a local object store. build hashes and serializes data. All data and metadata are tracked in a hash-tree that specifies the structure of the package. By default: Unstructured and semi-structured data are copied "as is" (e.g. JSON, TXT) You may override the above defaults, for example if you wish data to remain in its original format, with the transform: id setting in build.yml. Packages are registered against a Flask/MySQL endpoint that controls permissions and keeps track of where data lives in blob storage (S3 for the Free tier). After a permissions check the client receives a signed URL to download the package from blob storage. Installed packages are stored in a local quilt_modules folder. Type $ quilt ls to see where quilt_modules is located. Quilt data packages are wrapped in a Python module so that users can import data like code: from quilt.data.USER_NAME import PACKAGE_NAME. Data import is lazy to minimize I/O. Data are only loaded from disk if and when the user references the data (usually by adding parenthesis to a package path, pkg.foo.bar()). Quilt is offered as a managed service at quiltdata.com. Alternatively, users can run their own registries (refer to the registry documentation). Quilt consists of three components. See the contributing docs for further details.
https://docs.quiltdata.com/v/quilt-2-master/
CC-MAIN-2020-05
refinedweb
410
67.45
<list> (C# Programming Guide) Visual Studio 2015 - term A term to define, which will be defined in description. - description Either an item in a bullet or numbered list or the definition of a term. The <listheader> block is used to define the heading row of either a table or definition list.. Compile with /doc to process documentation comments to a file. // compile with: /doc:DocFileName.xml /// text for class TestClass public class TestClass { /// <summary>Here is an example of a bulleted list: /// <list type="bullet"> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// </summary> static void Main() { } } Show:
https://msdn.microsoft.com/en-us/library/y3ww3c7e(d=printer).aspx
CC-MAIN-2015-40
refinedweb
103
59.4
#include <hallo.h> * Joey Hess [Fri, Sep 12 2003, 11:27:23AM]: > It doesn't require this. It is a recommendation and svn-inject adds it with the -i switch. Feel free to remove tarballs directory from the repository but keep it localy. svn-uupdate will take care of it (IIRC) and no longer add tarballs to the repository. > What really suprised me is that you don't use svn_load_dirs. For all its I didn't like it - IMHO overkill for my purpose. Afterwards, I think I should have used it. > warts, it is very useful, especially when upstream moves files around. I > also suspect that it is far more efficient than is your method. You run It is. I will look on how it exactly works and decide wheter I keep my code or use svn_load_dirs though. > one svn add or remove for every new or deleted file in the new upstream > source. Some of us have our subversion server on the other side of a > modem, and opening possibly hundreds of ssh connections is a pain. This argument is pointless, rewritting this to work with one call is a job of few seconds/minutes. > technique also won't properly handle files that were in the old upstream > version, are in the new one, but were deleted from the debian > repository. I belive it will re-add those files, whereas svn_load_dirs > will not. Nope, svn does not re-add them. However, I will consider switching to svn_load_dirs since it seems to be more mature. > Sounds useful; AFAICS you are used to have a directory layout different to the one in the repository why my scripts rely on the same structure. Btw, your script files in my layout. >.) Okay, I will consider this when making changes in svn-uupdate. Working on local directories is, in fact, asking for trouble and forces to keep the same directory structure in the repository, not flexible enough. I will change this soon to act the way you wished above. >. Sure. > # You may need to change these expressions to match your repo. > tagurl=`svnpath tags`/upstream_version_$upstream_version > oldupstreamurl=`svnpath tags`/upstream_version_$oldupstream_version > upstream_branch=`svnpath branches`/upstream And this also may become an option. I can imagine a config file in $HOME where such schemes are defined for local directories, and svn-uupdate/svn-buildpackage take the right one depending on the start directory. > As said, I fail to see the reason to be glad about it. The local-path/svn-path independence can be easily achieved with a simple sub routine. On the contrary, I dislike having a random mixture of perl-over-shell-over-perl-with-shell-calls. MfG, Eduard. Attachment: pgpmkiFoDHTzX.pgp Description: PGP signature
https://lists.debian.org/debian-devel/2003/09/msg00743.html
CC-MAIN-2020-40
refinedweb
452
65.83
DES7GNMGZ 1 28 contents share 7 We Welcome Fall 8 Travel Corner Postcards in the Fall 10 Fall Fashion 2016 The Fall Color Palette 22 Mommy Corner Back to School Time Management Basics 8 23 Emotional Health Fear and Authenticity 26 The Tree and the Business An Organizational Life Cycle 34 Kenya M. Griffin & God’s Amazing Grace 45 Healthy Dining with CLS! classy news 16 Linens and Sandals An Evening of Appreciation 18 CLS Biz Zone Yaminah Childress 24 CLS in the City Dine & Discuss 28 Yellow Blouses and Brunch CLS Goes to Cali 36 Community Outreach 40 Member Spotlight Agnes Jamison 46 Fedoras and Friends Canned Food Drive 2 DES7GNMGZ CLASSY CHRONICLES 46 24 FROM Janine’s DESK The Editor-at-Large shares her thoughts “You Can’t Go Home Again” is a novel by Thomas Wolfe about an author who wrote a book which contained tidbits about his hometown -- and maybe the tidbits were a mite too truthful because when he returned home after writing it, the townspeople weren’t very happy with him and things just weren’t the same. I began to think about the title of this book, which has become a catchphrase unto itself. It is a phrase that conjures melancholy in most hopelessly nostalgic people like myself...but actually, just like almost everything else, the phrase and the acceptance of it holds a bright side. It” replica leather jacket from 1982...but just those simple acts will not transform who we are now to who we were then. No, you can’t go home again...if you go back, it will never be like the first time. Remember the bright side I talked about earlier? Well, the fact that it isn’t the same means that we’ve lived and enjoyed a life full of wonderful new experiences since then. We’ve grown and lived, loved and laughed. We’ve said hello and we’ve said goodbye. Through it all, we’ve progressed and came to know that home is where our hearts are right now. All we’ve got is here and now - and that’s home. It’s fall of the year...and many of my peers are saying goodbye to their children as they leave them behind in apartments and college dorm rooms across America. When these new college students leave their “Where you come from is gone, Happy Fall! Enjoy our fall issue, as where you thought you were usual chock full of splendoriferious childhood homes, some of them going to was never there, (yes, I make up words) photos and leave their childhood rooms intact, and where you are is no good articles. Helpful hints -- what colors filled with stuffed animals, school unless you can get away from do I wear this fall that is all the rage? and sports memorabilia and their it. Where is there a place for Traveling abroad in the fall -- and twin bed with their favorite blanket. As they turn to look back at their you to be? No place... Nothing how do you get the children out of outside you can give you any the house on time now that school rooms before leaving, they somehow believe when they come back to this place... In yourself right now is has started? Business, health and all the place you’ve got.” inspirational tips are here at your room, they’ll metamorphose into the ~ Flannery O’Connor, Wise Blood fingertips and, of course, you will child or teenager they were when learn what Classy Living Society has they inhabited the room. Yet, truth been doing! be told, they won’t. Because once they begin to live the college life, and that of a young adult out on their own, I’d also be remiss if I didn’t acknowledge the newest the room may look the same when they return (that is, addition to the Classy Chronicles team - our new if the parents haven’t turned it into a guest bedroom or Assistant Editor Shiwana L. Rucker. Ms. Rucker is fulltv room), but they themselves will be forever different time student (and soon to be graduating!), majoring -- their experiences have reshaped them and their very in English at the University of Phoenix. Her writing lives into something altogether different and brand new. has been featured on the award-winning blog site, No, you can’t go home again. “The Sophisticated Life,” “Free to be Unpluckable” and in ministry newsletters. She is also the author of a When thinking of all the great experiences that warm published collection of poetry, “I’m Finished.” Visit her our hearts about our past (and hopefully we all have website at! I am tickled been blessed with many of those), we realize that the journey life has taken us on has changed us forever. We to have her as my partner in crime! Welcome Shiwana! can go back to old homes and places, former haunts, our 1970’s hairstyle, or don our Michael Jackson “Beat Janine Lattimore DES7GNMGZ 3 CONTRIBUTORS Issue 14 September - October 2016 EDITOR-IN-CHIEF LaShanda Pitts EDITOR-AT-LARGE Janine Lattimore ASSISTANT EDITOR Shiwana L. Rucker CONTRIBUTING WRITERS Janine Lattimore Craig Henry DeAna Danzy Simone Darlington Shiwana L. Rucker Vanessa Parker Crystal Hardy Yaminah Childress, J.D. Tarrah Gales Rebecca Hyde Walls Avis Pitts 4 DES7GNMGZ CLASSY CHRONICLES CREATIVE DIRECTOR LaShanda Pitts PHOTOGRAPHY Jason Byrdsell DESIGN DIRECTOR Simone Darlington BE A PART OF THE NEXT CLASSY CHRONICLES For advertising or editorial contribution, please contact us at marketing@cls-volunteer.org, advertising@cls-volunteer.org, or chronicles@cls-volunteer.org. DES7GNMGZ 5 6 DES7GNMGZ CLASSY CHRONICLES We Welcome the Fall Oh, fall - that time of year when people start to reflect on life and the remaining time they have to make those New Year’s promises a reality before the stroke of midnight at the end of the year. Our priorities start to shift as we begin to notice the greens around us transforming into bright, beautiful hues slowly dying. This time of year marks not only the start of fall but a time when these changes set the stage for the dark coldness of winter. It marks the beginning of the cycle. There are lessons that can be attributed to the coming of Fall. Here are three to ponder: 1. Balance Darkness with Our Light. I bet you didn’t know that on the autumn equinox, day and night are the same lengths. We have the same number of light and dark hours. This signifies the need for us to balance our light with our darkness. Time and again, we fear darkness and bask in the light. Fall is a good time to consider our darkness (whatever it may be), and embrace it. Acknowledgement of darkness releases light and brings balance. There are times when there is no key for embracing our darkness. It can be a daunting and difficult task especially if we are starting from a point of absolute darkness. Try quieting the noise around you. In our darkness, we are always alone, so get by yourself. Gather some “you time,” and use it to extinguish the busyness in your life and become one with who are in and out of the light. 2. Let Go and Relish. As we watch the leaves float gently to the ground in the fall, we are reminded that the cycles of nature are reflected in our lives. Autumn is a time for letting go and releasing those things that have been a burden to us. It is the perfect time to practice getting out of our own way and allowing our souls to recharge. Again, another challenging task, but remember this. In the art of acting, in order for the actor to achieve her goal, she must “get out of the way,” remove herself, so that the character she is to be can come to life. Similarly, the writer and the painter have to get out of the way to allow their work to flow from ink to pad and from brush to canvas. The key is to get out of your own way. Being able to let go, to give up, to surrender those things we hold onto to no avail, comes from inside of us. It gives us an overpowering sense of freedom. When we give into that freedom, we open ourselves to others. So fall is also the perfect time to give our time and our talents. Let go of you, and rechannel to recharge. 3. Accept the Temporary. Fall reminds us of the temporariness of everything. We experience the promise of life in the spring and the blossoms of summer. Now, the leaves fall to the ground and the naked branches on the trees are reminiscent of the passing of all things. When we consider the changes of fall, we become appreciative of the beauty around us. A quote I read once says, “Death is the mother of beauty.” Simply put, if we treasure the beauty of a sunrise, of an upstate autumn along a winding road, of a budding new relationship, of a child’s hug or a forehead kiss because those things are temporary as is life, we should take the time to enjoy them. Fall also reminds us of death and the challenges we face to live each day to the fullest. When we remember that life is a journey, and when we open ourselves to the light of the sun, the magic of the moon, and to the human experience, we become as the leaf giving permission to the wind to carry us from experience to experience until we rest solemnly amongst the blades of grass. n Shiwana L. Rucker CLASSY DES7GNMGZ CHRONICLES 7 the travel corner Postcards in the Fall Arguably, one of best times for travel would be during the summer months...the sun is always out, beaches are usually packed with people, there plenty of things to do. Not to mention there is plenty of HEAT almost everywhere you go. Yes, summer is definitely the most optimal time or best time to travel. So much so that travel companies put a premium on prices for summer travel -- and rightfully so based on all of the above listed reasons. Summer travel is KING!!!! Paris, Franc i a p S , a i v o Seg For the savvy traveler, or travelers that love to be low key and take in more sights than sun, summer is not as friendly as expected. When planning to see certain sites, the crowds may be too large and you may find yourself waiting in a long line at the Eiffel Tower in Paris. Or the heat may be a factor -- such as the extremely high temperatures in Athens, Greece, which could make your sojourn to climb to the top of the ancient Acropolis a pretty miserable venture. As some may know firsthand, if you don’t trek up to the top before midday, the sun and heat bouncing off of the old marble stone can be quite unbearable for some. Yes, summer may be KING, but it is king at a cost - to your pocket AND your person. There is another time of year I have found to be excellent when it comes to travel. A time when there’s not as many people in certain places, or in areas of a specific exhibition or attraction. A time when the sun is not constantly beating down on you. What’s more, you can pretty much relax wherever you may be in the world. What time of year is this you ask…? I introduce you to: THE FALL! 8 DES7GNMGZ CLASSY CHRONICLES Zhang Jia Jie,China ce n i a p S , a i Segov in On a recent trip to Spain, I encountered some of the best weather imaginable. I didn’t have to wear a big bulky coat, nor did I have to deal with excessive heat. There were no lines at the popular attractions and I was even able to squeeze in multiple locations on that one visit to Spain. I began to think about past trips to Europe, Asia and South America during the fall and around that time of year. These trips were all by far the most enjoyable and pleasurable. Now, surely it wasn’t just because it was cool outside -- it was also because the fall made each location look extremely picturesque. The morning dew on the old cobblestone in cities in France, or the weeping willows found in many of the parks and greenspace in China, and the leaves on the trees and streets in various cities in Spain were spectacular. Because of the fall weather, it made each of these locations into absolutely fabulous backdrops for photographs. On a recent fall trip to a quaint city in Spain called Segovia, I was snapping pictures, and showed some of my shots to a fellow traveler and she said, “Wow, that looks like a postcard!” At that very moment, I had an idea -- instead of posting and sending pictures to people who would probably never look at them again, I decided to create my very own Postcards from the Fall. I immediately printed the photos, had them labeled and began sending them to friends and family around the world. Now every trip I take during the fall, I’m always searching for the perfect shot I can use as new Postcards in the Fall entries. Yes, summer IS a great time of year for travel and you will produce some of your fondest memories in the sunshine. But do not overlook the magnificent postcards you can create by traveling during the fall. Craig Henry The Travel Junkees Instagram: @thetravelhjunkees CLASSY DES7GNMGZ CHRONICLES 9 Fall Fashion 2016 The Fall Color Palette Are you ready for the fall and winter color palette? The colors of the season are warm and vibrant, rich, deep and sophisticated. Looking forward to seeing Airy Blue with the look of light blue ice, giving a feel of serenity. 10 DES7GNMGZ CLASSY CHRONICLES Riverside cool and calm deep blue, signifying strength and depth. Sharkskin can be paired with any of the fall colors, with its soft gray contemporary look. CLASSY DES7GNMGZ CHRONICLES 11 Aurora Red is the punch color of the season. It is a warm, rich bold red that catches the eye. Who dares to wear Aurora Red? Dusty Cedar – think rose quartz with a dusty warm rich pink tone. This color is very soft and feminine. 12 DES7GNMGZ CLASSY CHRONICLES Warm Taupe is translated as a timeless, stable and grounded hue. Spicy Mustard – now there’s an unusual color for the fall! It offers an uplifting zesty yellow quality. CLASSY DES7GNMGZ CHRONICLES 13 Lush Meadow is like looking into the deep wilderness of green botanical jewel tones. Potter’s Clay is a win-win – this russet color speaks of the season with its orange undertones. Potter’s Clay can be used as a strong foundation with its earthy richness. How many of these shades are already in your wardrobe? You’d be surprised to find a few pieces that already fit the bill! We are in LOVE with the new fall color palette! n DeAna Danzy 14 DES7GNMGZ CLASSY CHRONICLES YOUR AD HERE DES7GNMGZ 15 LINEN AND SANDALS An Evening of Appreciation - Table for 10 Our wildly passionate leader and founder of Classy Living Society, Mrs. LaShanda Pitts decided that she wanted to show her appreciation to the CLS women of leadership who play an important role in the success of the organization. We had no idea what events would unfold on the evening of Saturday, August 6 -- all we knew were our instructions to meet at Sole Spa in Buckhead, wear linen pants and sandals and arrange to park our cars for approximately seven hours. Pleasantly surprised by the invitation, we could not imagine what was in store for us that evening. Much like the passengers arriving at Fantasy Island (without Tattoo and Mr. Roarke, of course), we arrived at Sole Spa with excited anticipation. We, the proud sisters of leadership and volunteers of CLS were gifted with an appreciation evening so grand we will never forget it! We laughed, we cried, we ate, we drank, we were pampered, we were chauffeured. We talked, we were inspired, we felt valued, we received gifts and we loved on each other. LaShanda, you started this amazing journey and allowed us to be part of something much bigger than ourselves. Nothing we do at CLS is done for reward or praise. As like-minded women, we simply possess similar humble spirits -- to give our time and efforts in the hope that we can impact our community in positive ways. To have our efforts recognized in such a generous and thoughtful way really touched our hearts. Being part of this volunteer community has given us another purpose. We have bonded as sisters with one common goal. Speaking for myself and on behalf of my leadership sisters, we are extremely humbled and honored that you have entrusted your vision -- your baby -- to us. Thank you so very much for always letting us know how much you value our service. It was another fabulous night to remember... an experience that only you could put together. n Simone Darlington 16 DES7GNMGZ CLASSY CHRONICLES CLASSY DES7GNMGZ CHRONICLES 17 cls biz zone Wonder Woman has a Name, it is Wonder: noun, won·der \’wen-der\: something or someone that is very surprising, beautiful, amazing, etc. 18 Yaminah DES7GNMGZ CLASSY CHRONICLES DES7GNMGZ CLASSY CHRONICLES 19 Y even with my businesses, my nonprofit is what I love the most because I get to help others.” Her mission is to “empower and support women and entrepreneurs in personal and professional development through legal support, taxation, and business consulting & management.” She accomplishes this through her plethora of businesses and her non-profit: The Childress Group, LLC is a company Yaminah started that combines her J.D. and love of contract law, her business degree, IRS background, and mediator certificate. She is a business consultant who “helps people realize their dreams and helps them get started. InteleTravel travel business where she serves as an Independent Travel Agent. As a kid, I remember watching the Wonder Woman television series thinking, “I want to be like her.” Every little girl, at some point, desired to be Wonder Woman. In fact, she was created, according to William Moulton Marston, Ph.D. the creator of the female superhero, “to set a standard of strong, free, courageous women; to combat the idea that women are inferior to men, and to inspire girls to self-confidence and achievement in athletics, occupations and professions monopolized by men” because “the only hope for civilization is the greater freedom, development, and equality of women in all fields of human activity.” He says, “Wonder Woman is a psychological propaganda for the new type of woman who should, I believe, rule the world.” Shouldn’t we all strive to, at least, change some part of our world? Yaminah Childress does. The mother of three girls (ages 16, 10 and 6) and a little prince on the way, entrepreneur, consultant, philanthropist, artist, writer, mentor, scholar with three degrees (an Associate’s Degree in Education, a Bachelor’s Degree in Business and a Juris Doctorate (J.D.) in Law), and a superhero with a huge heart, is living up to the qualities of a Wonder Woman. “I call myself a social entrepreneur, but I am more of a philanthropist than anything because 20 DES7GNMGZ CLASSY CHRONICLES YANY Cosmetics line is operated alongside her 16year old daughter, Shania. The company is designed to “help build confidence in girls of color.” The Dream It Forward Foundation is where her heart is. The mentoring foundation was created with the idea behind the term “Pay it Forward.” She explains, “When you are blessed to come out of situations and are able to move forward in your life, you owe it to others to pay it forward. As a single mom, Yaminah started as a non-profit for single moms and has grown into a mentoring program for all youth 18 and younger that also services single moms. They offer: • Mentoring at Hampton High School by adult mentors who shape and train mentees into leaders and mentors for the kids at Hampton Elementary • Mentoring at Hampton Elementary School • Food Program that started in 2015 in partnership with the FDA • Dream Angel Project that fills the Christmas wish lists of children of five single moms through an application process that has grown to hundreds of applicants. ‘‘ I’m not saying I’m Wonder Woman, but you’ve never seen Wonder Woman and I in the same room.” ~ Yaminah Childress, J.D. The I AM Empowerment Women’s Conference was started in 2013 to encourage and motivate women of all ages. The annual conference is open to women “from all walks of life who have a story to share” and women opened to listening and who are looking to become unstuck in different stages in their lives. The conference is held in Atlanta, Indiana, and Chicago with hopes of adding a different city every year. I AM Empowered Class (E-Class) is an extension of the Childress Group but helps others by offering a costeffective approach to receiving business consulting. WHEW!! With all that she does, when does she have time to sleep? I had to ask. “Believe it or not, I do sleep.” She says, “I have always been like this, always on the go.” Yaminah is an inspiration in her own right, but credits her children and her friend, Lori, for providing inspiration. “It has been all God. I hate to say this because it sounds so vain, but it is the truth, but I had to learn to do everything on my own, but now, I have my children and they inspire me more than they will ever know.” Yaminah’s final words to anyone who reads this: “The things that I do, I do because I was called to do them. We are blessed with talents and gifts that you cannot put a price tag on. So I say to others, know your value, believe in yourself, do what you are called to do. If you try, you cannot fail. Never be afraid to walk in your purpose.” In her spare time, (What spare time, right?) Yaminah paints to liberate the starving artist that lives within her. Beautiful, surprising and amazing! Yaminah is a WONDERful woman looking to change the world and the lives of the people who inhabit it. n Shiwana L. Rucker Editor’s Note: Read her informative business article “The Tree & The Business – An Organizational Life Cycle” on page 26! DES7GNMGZ CLASSY CHRONICLES 21 Time Management Basics the Mommy corner E arly mornings, homework, football practice and bedtime - Oh MY! It’s fall -- and school is back in session. The hustle and bustle of the daily grind can be exhausting! I have found myself angry and upset because my kids were “accidently” leaving their homework at home, or forgetting to take their lunch box to school. On top of all the other daily items, figuring how to juggle it all was becoming overwhelming. After talking with a few other moms, I discovered the only way to get my sanity back was to get organized. Here are few things that I have done in the Parker Household to get my sanity back and enjoy the school year. Remember that tomorrow starts the night before. I realized that if my morning starts off crazy that my day will be downhill from there. I have made it a point to make sure the kids pick out their clothes, and I make their lunches the night before. This allows me to take these two things off of my list in the morning. Get up before everyone else. I work from home -- but that doesn’t mean I just sit around all day! By the time the kids get on the bus and I finish my morning coffee, it is meeting after meeting and I never have time to shower. I make it a point to wake up before everyone to spend a few moments with myself. I take this time to meditate and get myself ready. This allows me the opportunity to get ready for the day without everyone asking me 100 questions. Meditation. I know you have heard it over and over again -- but it works. I use an app called Calm ( a suggestion from another mom) that helps me get in the right headspace before everyone gets up. I am no expert, but it has helped me stay calm in the midst of the daily chaos. Chore charts and List. I invested in a chore chart for the kids and a checklist of things they need to do each day. This allows me to be nice in the morning instead of yelling...I mean reminding (lol) them about everything they need to do each day. Now I just tell them to look at their checklist. Get everyone involved. I began having family meetings to get everyone involved. In these meetings, we discuss what is coming up for the week and what chores are needed to be done. It is not formal, but it is a great way to get everyone’s help in getting things done. This is also a time to discuss things that might be bothering anyone. It is important for everyone to feel as if they are a part of the process of this business called family. This is equally as important whether you are a single parent or if you are married. You will lose your mind trying to do everything yourself. We are not superwomen...we are moms and we wear a lot of hats each day. Our families need us and we need them. So...get organized! Enjoy these years because they fly by! Vanessa Parker, PinkBoss, Inc. pinkboss.com | 888-326-5550 22 DES7GNMGZ CLASSY CHRONICLES Emotional Health Fear and Authenticity Your emotions are a powerful tool; used either to negatively drive your behaviors or, if harnessed, help you to create your own positive experiences. As you take this opportunity to learn more about emotional health, picture your feet being anchored to a moving sidewalk. As the sidewalk moves forward, you are willfully bound to the sidewalk -- you are moving, yet you do not have control of your movement. Similarly, if your emotions become your foothold, even though you are moving along in your life, you do not have control of your movement -- your emotions do. Take this colorful example. Nikki is conversing with her significant other. Nikki: “I had such a long week. I’ve been looking forward to this weekend. We can cook a nice dinner and cuddle.” S.O.: “Yeah, it’s definitely been a long week. It may be nice for you to spend time with your girls. We can spend Sunday together.” Nikki: “What?! I’ve been looking forward to this all week. I wanted to spend it with you! S.O.: “I’ll make it up to you. I just need some rest this Saturday, since the last several weekends have been busy.” Nikki: “WHAT?! I make time for YOU when I’m exhausted!” Nikki is angry and explains why she feels this way, and her significant other tries to assuage her concerns, to no avail. Nikki goes to bed that night feeling sad, but notices the more she thinks about it, her heart starts racing and thoughts jump to “What if he doesn’t think that I am… “. Instead of going further, she jumps to anger again and stays there. How familiar are you with fear? The physiological sensations of tightened muscles, shortness of breath, increased blood pressure, racing heartbeat, dizziness, and, most commonly, the inability to focus on anything, except the feared future event. Fear. Do you recognize fear? If so, what do you recognize first - the physiological sensations, thoughts, or your automatic response of avoidance? Nikki’s anger was her secondary emotion. Anger is the emotion she experienced because she felt sad. This gives us an idea of how she processed the conversation, but it does not give us the why. Let’s take a step back: her primary emotion was sadness. As she sat with the sadness, her heartbeat and thoughts raced. She even began a thought: “what if…”. This sounds like the start of feeling anxious, doesn’t it? Instead of sitting with the sadness and observing her thoughts, she cuts it off and avoids it. She jumps to anger, a comfortable emotion for her. Honestly, who welcomes fear?! However, fear holds the key to something more. Continued: Nikki’s thoughts to herself “I’m angry because he hurt me. What did his words mean to me? They meant that I wasn’t worthy of the sacrifice of his time this weekend. Why is this so bad? Because it means that he views me as worthless or, at least, unworthy to some degree…. So, do I believe that I’m unworthy of something to some degree? No,... BUT, well, I treat myself like it from time to time... Is that why I responded like this? This makes feel me sad.” Fear robs you of the key to authenticity; authenticity with yourself and others. To find the key, you must be willing to be mindful - present in your surroundings and yourself. This is how you find the key, and are able to begin learning how to unlock the door to assessing your needs and finding happiness. All of your emotions serve a purpose. Say “yes” and regain your foothold! n Crystal Hardy CLASSY DES7GNMGZ CHRONICLES 23 D CLS in the City & ine iscuss The lovely and courageous creator of such hit television shows as Scandal, How to Get Away with Murder and Grey’s Anatomy, Shonda Rhimes chronicled her journey to learning “how to dance it out, stand in the sun and be your own person” in her highly acclaimed book “Year of Yes.” In her book, Ms. Rhimes tells how she was able to overcome and face her fears by committing herself to saying “YES” to doing and being all of the things she was afraid of. The ladies of The Classy Woman Reads converged upon Soho Restaurant in the trendy section of Vinings near Atlanta. The goal of the evening was to enjoy sisterhood bonding over dinner and wine, and partake of great discussions with the group about Ms. Rhimes musings about her year of learning how to say yes. The evening’s discussions were facilitated by CLS sister Karen Seward, and as discussion questions were asked, the ladies offered their viewpoints on the many subjects discussed in the book. Many of the ladies shared personal anecdotes that mirrored the content of the book. The atmosphere of sisterhood and love granted each woman an air of vulnerability to express, just as Ms. Rhimes did in her book, the many ways in which they said yes, faced fears and difficulties, and how each found the ability to dance it out, stand in the sun and be their own person. Through CLS in the City, an innovative partnership of Classy Living Society designed to promote local establishments, the book club women discovered a wonderful restaurant in Soho Atlanta. Dining amid lovely flowers, candlelight and a charming tablescape designed by Laik Experiences, the ladies were seated SOHO for private dining in the Sun Room, where they enjoyed various American dishes and great wines. Soho is known as a local favorite of Vinings and the bar is a popular gathering place. The restaurant boasts an extensive beer and wine list and a highlight is Wednesday night’s “Flight Night,” a time when wine lovers can enjoy various wines from around the world. Soho has a dish for every palate - from seafood to steak to vegetarian choices and of course, delish desserts. As Classy Living Society continues to highlight restaurants throughout the Metro Atlanta area, they will continue to meet and discuss the book selections of The Classy Woman Reads at various venues. In doing so, the sisters of this wonderful book club will have the opportunity to try new venues throughout the city on a quarterly basis, dine with girlfriends, and participate in lively conversations about the book of the quarter. Stay tuned for more news and reports on upcoming Dine and Discuss events! n Janine Lattimore FOOD. WINE. PEOPLE. Located in historic Vinings, SOHO has been a neighborhood favorite since 1997 and offers a seasonal New-American menu, inspired wine list, wine & tapas paired weekly and creative cocktails. Attentive service, an award-winning wine bar and open kitchen all contribute to the high-energy buzz. Guests can dine al fresco on the charming patio, casually at the vibrant bar, or on the quaint enclosed Sun Porch overlooking the Vinings Jubilee Courtyard. Private dining areas are available for business functions and special events. 24 DES7GNMGZ CLASSY DES7GNMGZ CHRONICLES 25 the tree and the business An Organizational Life Cycle Like a newly planted tree changing during the four seasons, a small business goes through a life cycle very similar. The key to running a successful business is to know which phase of the cycle you are in, and to make adjustments accordingly. Take a look at each phase below to determine which one your business is currently in. Seed Phase: The seed phase is when you are first starting your business. You have an idea and are ready to launch, or may have already launched. Like a tree, you plant the seed into rich soil, birthing your ideas, and look forward to the growth. But, are you ensuring that the seeds you plant have the best chances of survival? Ask yourself these questions to maximize your likelihood of success. • Have I created a SWOT analysis? A SWOT analysis will help you identify your company’s strengths, weaknesses, opportunities and threats. • Have I created a business plan? A business plan is a written statement of your business goals, attainability of those goals and a plan to reach them. • Have I done my market research? Researching the market will ensure that your product or service is needed in your targeted area, identifies your target audience, and helps you keep in pace with market demands. Keep in mind that your business plan and market analysis are two of the most important aspects of successfully running a business, but not the only necessities. Always ensure your business is legally sound with the right licensing, entity, and insurance as required by your state business authority, or you may 26 DES7GNMGZ CLASSY CHRONICLES find yourself closing shop, before you even begin. Growth Phase: The growth phase is what we all look forward to, usually happening two to three years after startup (the Seed Phase). Profits are increasing, customer base is growing, and opportunities become more available. However, during this phase, the risks also increase. Think back to the tree. While leaves are blossoming, and the stump and branches are getting taller and longer, the tree is susceptible to adverse conditions: climate change, lack of rain, and poor sunlight - all of which can counteract its growth. So is the same in business: you may be confronted with new competition, lack of resources to move forward, lack of time (especially as a sole owner), or you may simply lose momentum. In order to continue past the growth phase, ask yourself: • Do I need to revisit my business and/or marketing plans? • Do I need to hire a management team, or rehire an effective team? • Do I have enough funding? If not, what avenues are available to attain additional finances? • Do I need to hire additional staff? • Am I being innovative and flexible in my approach to new products and services? Asking yourself these questions will guide you into strategic thinking on how to move forward. During the growth phase you should work with experts in your field of necessity, work with your management team and staff, and never attempt to do everything alone. Aging Phase: This phase of business includes an established business that is maturing. During this phase, businesses may have consistent year-over-year profits and expansion opportunities, but competition is still intense. Some businesses at this stage have consistent revenues, but are not actively increasing their profit margins. Like the tree that is tall and strong, with luscious foliage, it is still getting old and remains affected by outside stimuli. At this stage of the business game, you must decide whether or not you will continue to expand, roll out new products or services to keep customers coming and engaged, or if you have reached the point where you want to close up shop. To decide where you are in life and business, ask yourself: • Are there more products I want to “roll-out” or services I can offer? • Am I ready to retire? • Am I still mentally or emotionally invested in the business? • Do I have other life plans that may conflict with the day-to-day operations of my business? During this phase, questions become more personal to where you are in your personal life. Most businesses do not reach this phase until years and years into operations. Many of us are mentally and emotionally invested in our “babies” so we don’t want to let go. But, be very real with yourself to determine what’s next. Death: The final phase of the business cycle, like the end of the tree’s life cycle is death. While death may sound scary, it’s not as bad as you may imagine. When a tree dies, it becomes nourishment through decomposition, helping to feed and fuel other life sources. The same can be said about your business. When you have reached this phase, you have options. ‘‘ It is not the strongest or the most intelligent who will survive but those who can best manage change.” ~ Charles Darwin Consider the following: • Selling your business to the highest bidder, possibly to an entrepreneur, venture capitalist, or competitor. • Passing the business along to your heirs, friends or family members to keep your legacy alive, without the burden of investing more time and energy. • Dissolve the business, and liquidate all of your assets. Dissolution is a legal process that will require you to inform the State business authorities and pay off debts, before banking the remaining profits. Whichever route you choose, find comfort in knowing that you have had a great run, have successfully operated a business through all the phases, and can now sit back, relax, and enjoy the fruits of your labor. Remember, everything has life cycles or seasons. Equipped with the knowledge of which you are in makes dealing with the changes a lot easier. n Yaminah Childress, J.D CLASSY DES7GNMGZ CHRONICLES 27 LENA WRIGHT epiphanymakeup@gmail.com 404.933.9474 28 DES7GNMGZ Yellow Blouses & Brunch Classy Living Society Goes to Cali! DES7GNMGZ 29 n On Saturday, September 17, 2016, Classy Living Society officially launched in Los Angeles, California, on what could not have been a more perfect day! It would only be fitting for CLS to host our first West Coast event in downtown Manhattan Beach’s first hotel, Shade! Zinc restaurant, located inside the hotel, offered an unforgettable, chic venue situated in the heart of Manhattan Beach only two blocks from the ocean -- offering a taste of coastal living and California cool. As ladies arrived in all shades of yellow, greeting one another warmly, the excitement grew. It was almost as if we knew how special and monumental this day would be! For our founder, LaShanda Pitts, the Los Angeles launch solidified her unwavering faithfulness and dogged determination that not only would CLS go beyond amazing community-focused work in Atlanta; it would expand into neighboring cities -- and the world! The day had come for her to return home and present the bountiful gift of Classy Living Society -- and the 30 women in attendance were eager to accept! The private dining room of the terrace was abuzz with introductions, familiar reconnections, reminiscent reunions with old friends and new friendships being born. As always, we celebrated the cause by giving back. CLS partnered with the Dream Center to donate love kits to women housed in the residential recovery home for adult female survivors of domestic human trafficking. Founded in 1994, The Dream Center is a volunteer-driven organization that finds and fills the needs of over 80,000 individuals and families each month. We were honored to have Ra’Chelle from the Dream Center speak about their programs and outreaches, which are aimed to fill the needs of Los Angeles residents. They provide such efforts as mobile hunger relief and medical programs, residential rehabilitation programs, a shelter for victims of human trafficking, transitional housing for homeless families, foster care intervention programs, 30 DES7GNMGZ CLASSY CHRONICLES job skills training, life skills, counseling, basic education, Bible studies and more. One of our first California members, Brenda Gonzalez, shared her story of being a survivor of domestic violence and encouraged ladies who are passionate for a cause to consider joining CLS as a way to marry their passions with action! It was awesome to watch ladies chatting among themselves, asking pointed questions to our speakers and demonstrating all around how eager they were to get involved and give back! CLS has at the center of our mission, a focus on transforming the lives we touch within our membership and throughout the communities we serve. We do so through socialization, innovation and volunteerism with a firm commitment to provide a positive sisterhood bonding environment for women to give back, mentor our youth, and care for those who might otherwise be overlooked and neglected. The Yellow Blouses & Brunch was indeed a buffet for each of our five senses as we dined on small plates boasting decadent delights. Pairing our yellow blouses with bubbly mimosas, we raised our glasses to toast our amazing sisterhood journey, each of our past efforts and most of all, looking forward to sharing CLS’ bright future with lovely ladies from the Sunshine State! n Tarrah Gales CLASSY DES7GNMGZ CHRONICLES 31 32 DES7GNMGZ CLASSY CHRONICLES KAREN SEWARD 678-234-3026 DES7GNMGZ 33 Kenya M. Griffin & God’s Amazing Grace Most people know the first stanza of “Amazing Grace,” the gospel hymn. Amazing Grace, how sweet the sound, That saved a wretch like me. I once was lost but now I’m found, Was blind, but now I see. 34 DES7GNMGZ T he words Amazing Grace are not just lyrics, but words that define Kenya M. Griffin’s life’s purpose. It also happens to be the name of the dance company she founded in 2006, the Amazing Grace Dance Company, an Atlanta-based liturgical dance company. If you have ever seen a performance by the troupe, it is clear why the name is so fitting. As Founder and Artistic Director, Kenya is a 2016 nominee of the coveted R.I.C.E. – Rising In Community Excellence Award in the category of Music and Arts. The R.I.C.E. Awards, founded by C. Chandon Carter in 2010 and derived from The Gospel Choice Awards, is given to individuals who display awareness about the needs of the community. Nominees are “innovative and charitable visionaries who recognize the importance of their presence and contribution to the greater Atlanta community and beyond.” This happens to be why Kenya is so deserving of the nomination. As one of 36 nominees – six nominees in six categories chosen from 42,000 total nominations – Kenya feels honored just to be nominated. “Even if I don’t win, to be chosen out of so many nominations is such a great honor, and I’m just grateful.” The work she does through Amazing Grace and as a community servant exudes passion as she talks about her community involvement. As a part of her company and her ministry, Kenya mentors young people in dance through her Amazing Grace Youth Ministry that serves 15-20 children ages 6-12. “It is so necessary for kids to see and do and experience more than just going to church and listening to the word. Dance does that.” She also volunteers with organizations that serve people who suffer from HIV/AIDS and mental illness. She spends time, provides lunches, and serves as a liaison between patient and doctor as a certified peer counselor. Internationally, Kenya and her company have served as mentors in Ghana with Wings of Praise and in Nairobi where they taught dance for seven days to citizens who, otherwise, would not have had the opportunity to dance. When asked where she draws her inspiration, Kenya humbly answers, “Life. Just life. I was diagnosed with severe depression three years ago. That, in itself, has been a journey in trying to stay balanced. Trying not to stay into self-pity. It has helped change my way of dancing and my creativity. And, the people that I dance with, they all have stories that inspire me more than anything.” Kenya also draws her inspiration from some of the greats in the African American dance community. “In terms of who I kind of model for influence and inspiration, I would have to say definitely [the late] Alvin Ailey [of the renowned Alvin Ailey American Dance Theater] and Katherine Dunham. I am also inspired by Atlanta-based dancers and choreographers Patdro Harris and Juel D. Lane.” Kenya M. Griffin continues to pursue balance in her busy life. “Community service helps me recharge, it is people pouring into me and empowering me. I needed a diversion from dance and from my ministry. [That’s why] I joined CLS. It gives me the opportunity to give back alongside likeminded women.” Giving plays an integral part of who Kenya is as a dancer, a servant, and a person. She offers free dance classes on the second Sunday of the month from January through April that gives ministries the opportunity to learn from professional dancers. It gives them exposure that they wouldn’t have otherwise. “My studio is a safe place. There is no judgment. I want people to feel like they’ve learned something and to grow.” When asked what she wants people to know about Kenya M. Griffin, she hesitates then softly says, “I am unbreakable. I am a very passionate and compassionate person. Very strong-willed and ready to help if I believe in the cause. I try to meet people where they are. I’m just trying to be the best person that I can be. It is God’s Amazing Grace.” We think that sums up the woman in a nutshell. n Shiwana L. Rucker CLASSY DES7GNMGZ CHRONICLES 35 ‘‘ Volunteers do not necessarily have the time; they just have the heart.” ~Elizabeth Andrew Community Outreach BY REBECCA ALEXANDER HYDE S Summer is in full swing, and so are the efforts of Classy Living Society! July began with CLS partnering with Project Open Hand Atlanta. Project Open Hand prepares packages and delivers 5500 meals every day for disabled and homebound individuals as well as seniors. Volunteers joined Project Open Hand’s packing assembly line, portioning food into individual containers and snack bags. The 3-hour volunteer effort resulted in 1350 prepared meals. CLS is a sisterhood that supports sisterhood. Sisters By Choice, a breast cancer organization that addresses the disparities surrounding breast cancer, sponsored the 12th Annual Pink Ribbon Walk at Piedmont Park and CLS, being sisters by choice as well, showed up and showed out to support the cause, yet again! Volunteers distributed water to the walkers at the water stations. 36 DES7GNMGZ CLASSY CHRONICLES Classy Living Society is all about style and class, and we are committed to sharing our personal style choices with those that are less experienced. So what do we do? We go shopping! Personal Stylists were needed for the YMCA Back to School Shopping volunteer effort, and CLS answered the call! Volunteers helped underprivileged children look great for school by being their personal stylists. The classy ladies of CLS put together outfits and helped the children with their self-esteem. Family is important, so CLS looks for opportunities to involve our families in our volunteer efforts. Atlanta Food Festival - Back to School Event was one of those efforts! The volunteer time slot was flexible, and kids were welcomed! Our sisters and their families had lots of fun! Georgia Cares strives to bring hope, build resilience and give every child the opportunity to thrive. CLS Cares as well! Child victims of Sex Trafficking and Exploitation are robbed of the freedom to make choices, have a voice, and live their lives without the horrors of abuse and rape. CLS has an ongoing commitment to give them their freedom back and assist them in becoming healthy, productive members of society. CLS partnered with Georgia Cares to put on the 5k Color Me Free Run and took a stand against Child Victims of Sex Trafficking & Exploitation. Volunteers passed out water and helped with the registration of runners. Across town in Lilburn, our sisters concluded July’s efforts by volunteering with G.E.M.S at the Back to School Fair. Volunteers helped to give out free school supplies to young ladies. Classy Living Society’s volunteer efforts consistently evolve, and August was the premiere month for our Virtual Volunteer Efforts! Not only are we making moves by being physically in the community, but we can also be there virtually! For the entire month of August, CLS offered an amazing opportunity to earn virtual volunteer hours! Virtual support of the Sisters Empowerment Network cause allowed those of us who could not be physically present, be virtually present. Sisters Empowerment Network, Inc. is a non-profit organization whose mission is to educate women and girls on how to become self-sufficient. Volunteers’ hours were earned by posting their Vision and Mission as well as their upcoming events for Sisters in Need via Facebook, Twitter, and DES7GNMGZ 37 any other social media channel, promoting their Kroger fundraising opportunity and tagging photos and videos from their upcoming or past events. Our other virtual effort for August was with ALS Association. ALS leads the way in research, care services, public education and public policy - giving help and hope to those facing the disease. CLS supported the association by posting their vision and mission on Facebook, Twitter, and any other social media channel. Volunteers also posted their hashtags, #EveryDropAddsUp, and #EveryAugustUntilACure as wells as their videos of upcoming events. Summertime is family time! Our sisters and their families came out to the Chattahoochee Nature Center to assist in providing other families with an all-around good time! Volunteers helped with crafts, face painting, greeting, assisting with sprinkler games, handing out canoe paddles and helping to seat people for puppet shows. Volunteers are an integral part of what makes AG Rhodes Health & Rehab Atlanta a huge success. Classy Living Society loves its seniors and always answers the call to be of support to the happiness and well-being of the residents. CLS came out in full force to provide meaningful activities and programs that are therapeutic in nature. Activities included BINGO, arts & crafts, holiday projects, games, parties & socials, and group visitations. The Ultimate Wine Run Supports the Achieving My Dreams Foundation. AMDF provides scholarships of up to $5,000 annually to high school students showing leadership potential and demonstrating financial need to attend an accredited four-year college or university of their choice. CLS volunteers helped with check in, race information, sales and providing the runners/walkers with their wine! Not only are the sisters of CLS willing to pack meals, but we will also deliver them! Project Open Hand prepares and delivers thousands of meals for disabled persons and seniors all over the metro Atlanta area. CLS volunteers used their vehicles and gas to deliver carefully prepared (based on the person’s diet requirements) meals to very grateful recipients. What a humbling experience! Chic is CLS! Our sisters, in their chic summer attire, chugchugged on out to the Hampton Train Depot to assist with the I Am Women’s Empowerment Conference. Volunteers assisted with setting up, clean up and ticketing. Indeed, we have a heart for those in need! CLS came out to support a great cause by partnering with the Salvation Army. Volunteers helped to sort and bag groceries for those families in need. 38 DES7GNMGZ “We are free to breathe” is a partnership of lung cancer survivors, advocates, researchers, healthcare professionals and industry leaders that are united in the belief that every person with lung cancer deserves a cure. CLS is always looking for opportunities to learn about organizations that care and so we came out to their 7th Annual 5k to do just that! Across town at the Cobb Galleria, our CLS sisters spent time at the Small Business Market Expo and Job Fair. Volunteers helped with registration and checking in participants as well as stuffing bags with expo information to hand out to the participants. August was a wrap! As summer winds down and school is back in session, CLS is sensitive to busy moms, so we kicked off September with more Virtual Volunteer Hours! Our volunteers were able to support RiteAid KidCents Foundation by posting their Vision and Mission via Facebook,Twitter, and any other social media channel. Signing up for the RiteAid Foundation wellness + with Plenti program also helps with the foundation’s fundraising efforts! September brings us to Falcons season so what do we do? We support the Atlanta Falcons Track Club with their Rise up and Run/Walk Like MADD 5K presented by Northside Hospital! This is MADD’s (Mothers Against Drunk Driving) signature fundraising event, and CLS was there to help raise awareness and funds to help eliminate drunk driving. Serving Our Seniors is one of our favorite things to do, and so we are back at AG Rhodes Atlanta in September! CLS volunteers provide a variety of enrichment and therapeutic activities for the residents such as BINGO, arts & crafts, holiday projects, games, parties and socials, and group visitations. The NFL Players Association Metro-Atlanta Chapter hosts their 20the Annual Celebrity Golf Tournament and the sisters of CLS are spot on! Golfers had the opportunity to play alongside pro sports Hall of Famers, current NFL players and celebrity entertainers to raise funds for the NFLPA Scholarship Program. The program is designed to provide additional funds to high school graduates who did not receive an athletic scholarship to attend college. Back at the Chattahoochee Nature Center, a competitive team building afternoon that includes canoeing and other activities is underway for corporate teams. Volunteers for this event were spread out to various locations and could volunteer in more than one area. CLS advocates health and wellness, so we jumped at the opportunity to volunteer for the Race for Rest 5K & Bed Race in September! All proceeds went to the Furniture Bank in support of the vision for all individuals and families to have furniture necessary to create a safe and secure environment that contributes to health and well-being. CLS volunteers assisted with some roles including handing out t-shirts, registering, water stations, etc. Across town, we are back at Project Open Hand. CLS volunteers used their vehicles and gas to deliver meals within the metro Atlanta area. Once again, in September, we are back at the Chattahoochee Nature Center for Outdoor Skills Day! This event is designed to help participants enjoy being outside this Fall. Volunteers helped to teach some basic outdoor skills, whether they were new to the outdoors or a seasoned scout. Classy Living Society wrapped up September’s volunteer efforts at Clarkston UMC Food Pantry. Our sisters helped to sort and prepare food baskets for families in need while bonding in the spirit of giving back! DES7GNMGZ 39 40 DES7GNMGZ Agnes amison ember spot light DES7GNMGZ 41 42 DES7GNMGZ A gnes Jamison is one classy lady who sees the best in everyone. Agnes is an optimist; and this trait has helped her remain a driven educator for children with special needs for 24 years. She truly believes that education is an expansive tool that can be used to effect change in the world. Agnes has a true passion for the special education population, and it is evident by the many lifelong bonds she has formed...not only with her valued students, but also with their families. She continues to receive phone calls, texts and emails from those families that she holds so dear to her heart. If asked about the many accolades and credits that she’s received over the years, her conversation will always go back to the students. They are, and always have been, her priority. Agnes was born in the small town of DeWitt, Arkansas and was the youngest of nine children. At an early age, her family knew that she would be using her spiritual gifts to help others. She and her older siblings always played school together...with Agnes being the teacher of course. She remembers how her father always wanted one of his children to teach and he got his wish with his youngest daughter. She was a natural! Agnes received her undergraduate Bachelor of Science in Education degree in Special Education at the University of Central Arkansas. She earned her Master’s degree in Foundations of Education at Troy University and her specialist degree in Educational Leadership at Nova SE University. Agnes has lived in Atlanta for 15 years and she considers herself the Number One Falcon’s Fan! She’s at every game and has “everything Falcons” at her home. Agnes has a variety of interests as she enjoys traveling, reading, cooking and especially shopping. She has 2 children...a lovely daughter Jo Elle and a handsome son Kwesi. But the love of her life is her precious gem...her grandson Kason. Kason is his grandmom’s shadow, and she doesn’t make very many moves without him. CLASSY DES7GNMGZ CHRONICLES 43 Agnes enjoys a full and abundant life of volunteering and serving others. She’s consistently volunteered at Securus House, a domestic violence shelter for women and children near Morrow, Ga. This dedicated lady is also very active in her church and she works with numerous ministries, including the children’s ministry on a regular basis. We wanted to learn more about this classy lady -- her strength, her motivation and her outlook on life... Being an educator takes up a lot of your time. How do you find a balance between working...volunteering... and having some time for yourself? Finding the right balance between work and play can be difficult if you don’t have your priorities straight. I find that if I take time out for me, all other areas in my life seem to fall into place. It may be something as simple as sitting on the deck with a good book, or spending time with my family. Keeping myself centered and grounded contributes to every aspect of my life. God first, family, church and extended family and friends. As long as I have them in my life, I have it all! How did you hear about CLS and what made you want to be part of this women’s organization? I actually heard about CLS before I even knew what it was about. I worked with a wonderful lady who was the SLP at my school. She would always come to work with great stories about what she had done over the weekend. One day she asked if I wanted to check out this website. She was sitting at her desk telling me all about CLS and I was sitting at my desk browsing the website. Well...by the time she finished her story, I had signed up!! Thanks Avis Pitts!! Besides education...what are you passionate about? I am very passionate about helping others, especially those who don’t have a voice. Working with the population that I work with can be very challenging. They are the students that are often overlooked and nobody wants to deal with them. They have pretty much been written off as troublemakers or just bad kids. In my 24 years in education, I’ve found that every child can learn. You just have to tap into who they are individually and go from there. Being an educator is a true gift that I embrace 100%. What’s your guilty pleasure and what’s a little known fact that you want us to know about you? My guilty pleasure, and also a little known fact about me, is that I love to watch westerns and old sitcoms. Give me Big Valley and some Sanford and Son reruns...and I am done! Another fun fact about me...I actually met Prince! Yes that Prince... in person 44 DES7GNMGZ CLASSY CHRONICLES in Dallas in the early 90’s. He shook my hand...don’t ask me how long it took me to wash my hand after that! What is your dream vacation spot? My dream vacation is anywhere there is a beach! I love exploring new areas and soaking up the local flavor. What’s one thing you just can’t live without? One thing I can’t live without is my natural family and my church family. My family has been through the good times and the bad times, and we always come out stronger. My mother, who passed away in 2009, always had one favorite saying, “always love one another.” My siblings and I are very close, as we try to epitomize what our mother taught us. My church family keeps me upright when the world tries to knock me down. I always have a listening ear and can talk about anything without judgment. There is no greater love that I know, than the love that Christ has for us, and I thank Him daily for blessing me with these wonderful people. Tell us about yourself in three words. Me in three words...A~adventurous, R~restorative and J~judicious. You’ve been seen doing a lot of reading. What book is at the top of your list? I’ve read several great books, as I’m an avid reader, but the best book I’ve ever read has to be the Bible. It has everything from romance to murder mysteries. It teaches life lessons and it’s the best motivational book EVER!!! It is the one book that no matter how many times I read it, I get a different understanding. We can see what drives this incredibly purposeful lady. Her passion for serving others and being a positive influence to those around her make Agnes an exceptionally insightful woman. With Agnes...we know that Class is Always In! n Avis Pitts Healthy Dining with CLS! When summer is over, and we begin to experience shorter days and crisper, cooler air, most of us retreat to comfort food - like soups! Like most people, if you are trying to make healthy choices, comfort food can be taxing to the calorie count! But fear not - comfort food can be healthy too! This month’s recipe pick is Chicken Chili with Sweet Potatoes. Spices, corn and bell pepper lend to the Southwestern flavor of this tummy warming soup - and all in one pot! Top with avocados, douse with a few splashes of hot sauce if you like it SPICY and all you can do is say …. yummmmm.... Adopted from: Eating Well @ n Janine Lattimore DES7GNMGZ 45 46 DES7GNMGZ DES7GNMGZ 47 48 DES7GNMGZ In the inimitable style of Classy Living Society, on Tuesday evening, September 27, the CLS classy ladies and their guests gathered for “Fedoras & Friends,” a social hour designed to foster sisterhood bonding, giving back to the community and an evening of fun and fellowship. The women showed the world their “hattitude,” fabulously dressed and sporting their finest fedoras. The event was held at Supply & Demand, a Prohibition-era inspired bar in the Buckhead area of Atlanta. Located on Cains Hill Place in Atlanta, Supply and Demand is tucked away in the 1,500 square foot basement area of Churchill’s British Pub. Because of its location and entrance behind Churchill’s, the mainstream flow of street traffic could quite easily miss it – adding to the exclusivity of it all. In an interview with Simply Buckhead, founder Brandon Lewis says, “The inspiration was built off of the Wall Street economic principle of supply and demand.” The plan is to only select and serve high-end beverages at the bar, to appeal to “high or discerning tastes instead of mainstream tastes.” The premise is that since this exclusive collection may be limited at times, it would spark a high demand for those beverages. Supply and Demand! (Simply Buckhead, http:// simplybuckhead.com/by-invitationonly/) At first approach, Supply and Demand’s covered patio beckons you to lounge, cigar aficiando style, in one of the stately leather chairs and enjoy a fine cognac and a stogie. A hallway leads to the main room, with its black and white subway-tiled floor and heavily wooded furniture and walls. One is instantly taken by the glamour of the place – dim lighting, historic rudiments peppered throughout, marble accoutrements, glass accents and an eclectic collection of art. It is difficult not to be struck by an instant flight of fancy – you are almost quite sure you will see a modern-day Al Capone sitting at a corner table with his mob. Large enough to accommodate a good-sized crowd, yet small enough for guests to be comfortably intimate, the timeless elegance of this speakeasy inspiration was the perfect backdrop for CLS’ Fedora & Friends event. The ladies chatted, drank, and enjoyed an assortment of pizza slices and salad on a stick (delicious!). The music ranged from R&B to old school hip-hop to reggaeton and of course, there was dancing! CLS added their own bit of ambiance to the already opulent surroundings. Cigar boxes were stacked on tables, and perched atop the stacks were cardboard six-pack beer containers stuffed full of lovely flowers. White candles added luminescence to the room, and each table housed a collection of custom-made “Fedoras & Friends” drink coasters and matchboxes sporting monogramed CLS labels. Several cigar boxes were filled with “sug-ars,” individual Twix candy bars wrapped in CLS monogrammed cigar bands (cute!). The “cigarette girls,” Crystal Danzey and Ray Herman, both members of CLS, were costumed as 1920’s era-inspired flappers and offered trays holding a collection of breath mints, cigars and other treats, plus flyers for CLS’ upcoming Red Dress Gala to the attendees. At the end of the bar, fedoras were on display among the cigar boxes, including a frame encasing a sign with the message of the evening - “Yes We Can!” Yes We Can…Yes We Did! The ladies and their guests were asked to bring 10 cans of vegetables as a donation for the give-back campaign attached to the event. Upwards of 300 cans were collected, as well as cash donations. The donated vegetables will be served during an upcoming Thanksgiving dinner that CLS plans to host for the residents of Beloved in Atlanta. A residential home for women, Beloved provides a program and a place of refuge for women seeking freedom from prostitution, trafficking and addiction. This giving campaign is in furtherance of CLS’ love/action objective to bring awareness to and end human sex trafficking. Along with yams, greens, green CLASSY DES7GNMGZ CHRONICLES 49 50 DES7GNMGZ beans and cranberry sauce, CLS will provide turkeys, macaroni and cheese and desserts for the dinner. Any cans left over will be donated to Beloved. Stay tuned for more details regarding this magnificent holiday feast. CLS would like to give a heartfelt thanks to the people who made this splendid night of fun, fedoras, frivolity and friends happen: Michael and Albro at Supply & Demand as well as our fabulous bartenders for the night, Natasha and Luke. A very special thanks to This, That & The Other, on Cobb Parkway in Smyrna, for donating the cigars and cigar boxes - they added a wonderful touch to the whimsy of the night! Hats off to you! n Janine Lattimore   CLASSY DES7GNMGZ CHRONICLES 51 52 DES7GNMGZ CLASSY CHRONICLES UPCOMING EVENTS Fourth Quarter 2016 3rd Annual Red Dress Gala Mingle Jingle Toys for Tots Soul Train Atlanta Thanksgiving Dinner at Beloved 53 Be a part of something bigger than yourself. Join Classy Living Society TODAY! 54 DES7GNMGZ Published on Oct 5, 2016
https://issuu.com/classylivingsociety/docs/classychroniclesseptoct2016issue14
CC-MAIN-2021-21
refinedweb
11,472
71.14
im trying to learn pointer n the &(no idea the specific name for it); so my question is.. im passing the memory address of P to changePTR, why p is not taken the address of o(lets assume o is dynamic allocated), or even i want to change p to NULL. but p in main is still keeping the address of k? can anyone refer sum good tutorial for learing pointer and memoery location stuffs.... they are so confusing >.< #include <iostream> using namespace std; void changePTR(int* p){ int z = 100; int* o = &z; p = o; // p = null // this doesnt work also..?? } int main(){ int k = 1; int* p = &k; int* q = p; changePTR(p); cout<<p<<" and "<<&k<<" and "<<&q<<endl; }
https://www.daniweb.com/programming/software-development/threads/359959/pointer-help
CC-MAIN-2018-30
refinedweb
122
79.9
Publication Date: December 15, 2006 Author: G. Kay Jacks, General Manager, Application, Operations and Delivery Services, Federal Student Aid Summary: HERA Operational Implementation Guidance (CPS, COD System, EDExpress Suite) – Availability of EDExpress for Windows 2006-2007, Release 4.0 Posted on 12-15-2006 Federal Student Aid is pleased to announce the availability of EDExpress for Windows 2006-2007, Release 4.0 on the U.S. Department of Education's Federal Student Aid Download (FSAdownload) Web site (located at). Release 4.0 is the second of three planned EDExpress 2006-2007 enhancement releases that implement provisions of the Higher Education Reconciliation Act of 2005 (the HERA), Pub. L. 109-171. In addition to other changes, the HERA implements two new Title IV grant programs—the Academic Competitiveness Grant (ACG) and the National Science and Mathematics Access to Retain Talent Grant (National SMART Grant). The HERA also extends Federal Direct PLUS Loan (Direct PLUS) eligibility to graduate or professional students. Note: The HERA provides for eligible graduate or professional students to receive Direct PLUS Loans on or after July 1, 2006. The HERA provision does not create a new loan program; instead, the HERA enables a new type of borrower—an eligible graduate or professional student—to borrow under the existing Direct PLUS Loan Program. In EDExpress 2006-2007, Release 3.0 and forward, a Direct PLUS loan for a graduate or professional student is referred to as a “Grad PLUS” loan. EDExpress 2006-2007, Release 4.0, enables you to export ACG and National SMART Grant origination and disbursement data for transmission to the Common Origination and Disbursement (COD) System and import responses for ACG and National SMART Grant data sent by the COD System. The COD System begins accepting ACG and National SMART Grant origination and disbursement data on December 16, 2006. Release 4.0 also resolves several EDExpress software issues present in Release 3.0 and prior versions. See “Software Issues Resolved in Release 4.0” below for further information. In addition to the Release 4.0 software, the EDExpress for Windows 2006-2007, Release 4.0 Cover Letter is available on the FSAdownload Web site. The cover letter includes an overview of Release 4.0 enhancements related to the HERA, a list of software issues resolved in Release 4.0, and a preview of enhancements related to the HERA that will be implemented in EDExpress 2006-2007, Release 5.0 (available April 2007). The HERA addenda to the EDExpress for Windows 2006-2007, Release 1.0 Desk Reference and the EDExpress for Windows 2006-2007, Release 2.0 Desk Reference, also available on the FSAdownload Web site, contain additional information and guidance regarding EDExpress 2006-2007 enhancements related to the HERA. Note: Federal Student Aid always encourages EDExpress software users to upgrade to the latest release available for a specific cycle. However, if you do not award ACG or National SMART Grant funds to your students, or you are not impacted by the software issues being resolved in Release 4.0 (as outlined below), you are not required to install Release 4.0. Software Issues Resolved In Release 4.0 In addition to implementing import and export functionality for the ACG and National SMART Grant, the following software issues, listed by module, are resolved in Release 4.0: Application Processing · Due to an address change for the U.S. Department of Education’s Collections unit, we updated the text for SAR Comment Codes 041 to 043, 065 to 067, 100 to 102, and 251 to 253. Pell · Pell Multiple Entry no longer generates a “No changes to save” error message when you attempt to modify previously entered data for a field using the Select Records option under Selection Criteria. Note: This issue only impacts multiple entry fields using a combo box (for example a drop-down arrow enabling you to select from multiple valid values) on the final grid displayed during the multiple entry process. Verification Status is an example of a common entry field that uses combo box functionality in Pell Multiple Entry. Direct Loan · Custom MPN Printer templates you have established for PLUS loans in Tools, Setup, COD, MPN Printer are now available for selection when printing Grad PLUS MPNs (by selecting File, Print, Direct Loan, MPN-Grad PLUS). · EDExpress no longer clears most of the data you have entered on the PLUS Info tab on the Direct Loan Origination tab if the origination process fails due to missing/invalid information or other origination data edits. · The Direct Loan Origination tab now correctly updates the Loan Period and Academic Year dates associated with a disbursement profile if you change the disbursement profile code on a record immediately following a failed attempt to originate the loan (using Process, Originate). · If you create a Grad PLUS loan record for a student by importing ISIR data (File, Import, Direct Loan, Loan Data-ISIR) and then delete the Grad PLUS record using File, Delete, Direct Loan (outside the student record), you can now create a new Grad PLUS loan record for the same student using the same ISIR import option. In Release 3.0, a database field was not reset following Global deletion of a Grad PLUS loan record; this prevented a subsequent ISIR import for the same student and loan type unless you selected “Prompt for Duplicates” on the import and allowed the new record to be created when prompted. · EDExpress now correctly updates the Credit Decision field on Grad PLUS loan records when you import a Credit Decision Override Response (message class CRCO07OP) sent by the COD System. · The Direct Loan export process for PLUS and Grad PLUS records now exports the value entered for the Student’s Loan Default/Grant Overpayment field to the COD System. Previously, EDExpress exported the value for the Borrower’s Loan Default/Grant Overpayment field for both the student and the borrower in COD Common Record files. · When you clear the checkbox for the Direct Loan Origination tab field “Additional Unsub Eligibility for Health Profession Programs?” on an accepted origination record that had this checkbox selected, EDExpress will now export this modified data to the COD System. Previously, schools had to use the COD Web site to clear the value for the “Additional Unsub Eligibility for Health Profession Programs?” field on an origination record if the field was selected and exported using EDExpress and accepted by the COD System. · We updated the Direct Loan Disburse tab to enable the Export to External checkbox for anticipated disbursement records (Disbursement Release Indicator = False, or cleared). This change enables you to re-export an anticipated disbursement record you have updated to an external system after including the record in a previous Direct Loan External Export (File, Export, Direct Loan, External Loan Data). · The EDExpress Direct Loan Disburse tab no longer generates a software error message when you set the Disbursement Release Indicator (DRI) to True (or selected) for the first disbursement, save the record, then click the Add Disbursement button. · EDExpress now enables you to print a Grad PLUS MPN before or after originating the loan record without adversely affecting the MPN Status field or Signed MPN Received date information you have entered. · When printing a Disclosure Statement (File, Print, Direct Loan, Disclosure Statement – Sub/Unsub) for a student record with both subsidized and unsubsidized loans, EDExpress now correctly identifies the Loan Type for each loan on the report and always prints the subsidized loan information first. Before You Install Release 4.0 Before upgrading from Release 1.0, Release 2.0, or Release 3.0 to Release 4.0, ensure you have a valid, reliable backup copy of your current production EDExpress 2006-2007 database (expres67 the checkbox selected in the Logged In column (you can disregard the Locked column). Select any user ID displayed as logged in and click OK. Clear the Logged In? checkbox and click OK. Repeat the process for each logged-in user ID except the one you are using. 3) software in one file, called Express67r4.exe, or you can download the software in twelve separate “disk” installment files which can be copied to a local area network (LAN) drive or CD-ROM. You are required to have Windows 2000 or Windows XP as your PC workstation operating system to run Release 4.0. You must also meet the minimum hardware and software configuration requirements outlined in the September 2004 Federal Register Notice, available on the IFAP Web site at. Additional details and frequently asked questions (FAQs) regarding the hardware and software requirements are available on IFAP at ifap.ed.gov/dpcletters/GEN0408.html. Other hardware, software, and LAN requirements are outlined in the 2006-2007 Installation Guide for EDExpress for Windows. Important Installation Note: You must be an Administrator on your workstation to install EDExpress 2006-2007, Release 4.0 in the Windows 2000 or Windows XP operating systems. If you are not an Administrator, you will receive a warning when you try to install Release 4.0. After an Administrator has installed Release 4.0, you can run it as a member of the Power Users group. If your database is on a network server, you must be a Power User or higher on the network (or “domain”) as well as on your workstation. No workarounds exist for these Windows rights issues. Consult with your school’s technical department if you receive a warning that an Administrator must install the EDExpress software. EDExpress for Windows 2006-2007, Release 4.0 can be installed as an upgrade to Release 1.0, Release 2.0, or Release 3.0. You must have Release 1.0, Release 2.0, or Release 3.0 installed to run an upgrade (or “custom”) installation. To upgrade to Release 4.0, select either the Stand Alone Custom or Workstation Custom option during installation, depending on your EDExpress operating environment. Do NOT mark the “Database” checkbox unless you are performing a first-time installation or want to overwrite your Release 1.0, Release 2.0, or Release 3.0 database. If you choose to overwrite your database, all data previously entered will be lost. Note: If you have not installed Release 1.0, Release 2.0, or Release 3.0 on your system, you can proceed directly to a Stand Alone Full or Network Server/Workstation Full installation of Release 4.0. Note: A Stand Alone Full or Network Server/Workstation Full installation will load a completely new, blank 2006-2007 EDExpress database to your system. If a database already exists for 2006-2007 your standalone or LAN workstation(s) to Release 4.0, reboot the PC, then log on to EDExpress 2006-2007 to allow the software to perform a one-time only database update. This update loads important changes to your database structure. If You Have Questions If you have any questions regarding downloading, installing, or using EDExpress 2006-2007, Release. If you have policy-related questions regarding the HERA, contact Federal Student Aid.
http://ifap.ed.gov/eannouncements/1215HERAOperImpGuidance.html
crawl-002
refinedweb
1,832
54.73
If you’re familiar with the UNIX networking world, you’re probably familiar with the Distributed File System (DFS), an Open Systems standard that defines the capability to build a homogenous logical file system from disparate systems. In other words, you can build a single logical file structure that appears as one file system to clients but that can actually reside on multiple computers. A primary benefit that DFS offers is the ability to simplify network access by clients, presenting shared resources under a single, common namespace. The clients don’t need to know that the files actually reside somewhere else. Windows 2000 offers two technologies that bring the same capability and benefit to Windows 2000 platforms. The Windows 2000 Distributed File System (Dfs—to differentiate it from Open Systems’ DFS) does for Windows 2000 platforms what DFS does in the UNIX world. Windows 2000’s mounted volumes offer a similar yet less powerful option for achieving much the same result on a local file system. In this Daily Drill Down, I’ll give you a detailed look at how both features can simplify your life and improve usability for your clients. Understanding reparse points and directory junctions NTFS version 5.0 introduces a new feature called reparse points that Microsoft uses to build other features into the file system, including both mounted volumes and Dfs. Reparse points are objects in the NTFS file system that carry special attribute tags that can trigger drivers other than NTFS to process the data referenced by the reparse point. Reparse points enable these external drivers to add functionality to the NTFS file system without requiring that NTFS be redesigned to accommodate the new functionality. In effect, reparse points make NTFS extensible. You can think of a reparse point as a flag that notifies NTFS that the data referenced by the flag needs to be handled by another driver. When Windows 2000 encounters a reparse point, it passes the reparse point’s attribute tag back up the file system I/O stack. The attribute uniquely identifies the purpose of the reparse point, and the installable file system drivers in turn examine the attribute to determine whether they are responsible for processing the data referenced by the reparse point. When a match is found, the driver processes the data according to its function and purpose. Data encryption is a good example of the use of reparse points. NTFS begins reading a file and comes to a reparse point, which it passes back up the I/O stack. The attribute tag for the reparse point indicates that the following data is encrypted, so the Encrypting File System (EFS) takes over and reads the encrypted data. NTFS itself doesn’t have to understand or handle encryption; it only needs to be able to pass the location of the information to EFS so it can process the data. Hierarchical Storage Management (HSM) is another feature implemented through reparse points. The reparse point marks the location of an off-line file, enabling NTFS to pass the information to Remote Storage Services (RSS) to retrieve the off-line data when it needs to be restored. Directory junctions are another feature added in NTFS 5.0. These objects mark NTFS directories with a surrogate name. The directory junction (implemented as a reparse point) grafts the surrogate name onto the original pathname, enabling redirection to take place. The result is that both local volumes and remote shares can be mapped to local NTFS folders, making possible the two features covered in this Daily Drill Down: mounted volumes and Dfs. Using mounted volumes for local drives Mounted volumes are a new feature in Windows 2000 that rely on reparse points to do their job. Mounted volumes enable you to mount a local volume to an empty, local NTFS folder, providing essentially the same benefit for local volumes that Dfs provides for network shares. They let you build a homogenous local file system structure from disparate local volumes. Mounted volumes have several useful implications. First, they enable you to apply quotas on a selected basis. Normally, quotas apply across an entire volume. However, you might want to apply a different quota level (or no quota at all) to a given set of folders. For example, assume you want to apply one set of quotas to the entire volume with two exceptions: different sets of quotas for the \Users and \Downloads folders (each with their own set of quotas). In this scenario, you could achieve the different quota levels using three different physical volumes—one primary volume, a second to map the \Users folder, and a third to map the \Downloads folder. Figure A illustrates the physical layout and the way the volumes are mapped into the directory structure of the first volume. Another situation in which mounted volumes are useful involves extending your apparent disk size without replacing the disk. For example, assume you currently have one 4-GB volume in a system and it’s nearly out of available space. The applications in the Program Files folder alone take up 2 GB of space. You need to add several applications but don’t have the space. So you install a new 12-GB drive as a second volume in the system. Next, you move the contents of the existing C:\Program Files folder to the new volume (leaving the Program Files folder empty), and then map the new volume into the C:\Program Files folder. As far as your applications or users are concerned, the Program Files folder still resides on drive C. The net effect is that you now have lots of additional space (a net of 10 GB) in C:\Program Files for more applications. Plus, the physical drive C: volume now has an additional 2 GB of space (which was originally used by C:\Program Files) for adding other OS components, documents, and so on. The advantage is that you didn’t have to replace the existing drive with a larger one, which would require either cloning your current Windows 2000 installation to the new drive or reinstalling. Instead, you perform a simple file-move operation followed by a directory mount. Rather than spend several hours achieving the desired results, you spend an hour or so, including the time spent installing the new drive. Plus, your total disk space is greater because you retained the old drive. Mounted volumes offer two other important benefits. First, they enable you to simplify what might otherwise be a confusing file system structure. Rather than have, for example, three different volumes on the system all referenced by a different drive ID, you can combine all of those volumes under a single file system structure that appears to reside on one logical volume. Second, mounted volumes enable you to overcome the 26-volume limitation imposed by using drive letters, since mounted volumes don’t require drive letters. You could achieve many of the same results by creating a volume set, which enables you to combine multiple physical volumes into a single logical volume. The disadvantage to using volume sets, however, is that they must be created on dynamic disks. Creating new volume sets with basic disks is no longer supported as it was in Windows NT. So you’d have to convert your existing basic volumes to dynamic volumes—not a problem per se but a possible complication, particularly if you have a multiboot system with other operating systems that won’t recognize dynamic disks. Plus, mounted volumes give you the additional advantages already discussed—such as selective quotas—that volume sets don’t provide. Creating a mounted volume Creating a mounted volume is an easy process. You can use an existing volume (including devices such as CD-ROM drives) or you can install a new device. Once the device is in and working, create a partition as needed and then format the volume. You don’t need to assign a drive letter to the volume. Next, create an empty folder on the NTFS volume where you want to mount the other volume. The mounted volume will appear as the contents of this folder. The mounted volume need not be an NTFS volume, but the empty folder where it is mounted must be NTFS. Finally, open the Disk Management node of the Computer Management console. Right-click the volume to be mounted and choose Change Drive Letter And Path. Click Add and select Mount In This NTFS Folder. Specify the path to the empty NTFS folder or click Browse to browse for it. Click OK, click Close, and then close the Computer Management console. To verify that the volume is mounted, open My Computer, and then open the folder where the volume is mounted. A drive icon should have replaced the folder icon. If you want to apply quotas to the mounted volume, open the Disk Management node of the Computer Management console. Right-click the mounted volume and choose Properties. Use the Quota tab to configure quotas on the volume. If the volume is identified by a drive letter, you can also get to the property sheet through My Computer. Building a Distributed File System Now that you have an understanding of what mounted volumes can do for you, understanding the advantages of Dfs should be a little easier. Dfs does for the network what mounted volumes do for the local file system. Dfs enables you to build a homogenous file system structure using volumes from various computers across the network. It enables you to present a single file system to users across the LAN, simplifying shared resource access. Rather than having to open several share points to gain access to the resources they need, users can open a single share point and have access to all resources. Their network browsing experience is simplified because they need only access a single familiar share. As far as the user is concerned, all the resources are located under a single share. In actuality, those shared resources could be located on several different servers scattered on multiple continents. Figure B illustrates a sample Dfs namespace created from shares on multiple computers. Dfs also provides flexibility for rearranging the file system. Dfs uses link tracking to manage objects in the Dfs namespace, making it possible to move objects without breaking the logical link. You can therefore move a folder that is part of a Dfs namespace from one server to another without affecting what the users see. The move is completely transparent to users. Or you might want to increase the storage capacity of a given portion of the Dfs namespace. So you install the new drive, copy the existing data to the new drive, and then modify the link to point to the new volume. The data remains up for all but a few seconds while you modify the link. This ability to move links can be an advantage with Web servers as well, enabling you to move portions of a Web site from one server to another without taking down the site. Availability, fault tolerance, and load balancing are other important advantages offered by Dfs. Because Dfs can publish the Dfs topology in Active Directory (AD), the Dfs topology is visible to all users across the domain (subject to access permissions and policies). In addition, AD-integration ensures replication of the Dfs structure across all DCs in the domain, providing a high degree of fault tolerance. If one server goes down, users can continue to access the Dfs roots from other DCs. For load balancing, Dfs enables you to bring multiple replicas of a given share under a common share point, which associates multiple shares under the same share name. In other words, a single share point in the Dfs namespace can point to multiple folders, each on a different server. This helps reduce the load on any given server because the shares are allocated randomly. To the user, the shared resources come from the same location each time, but they might actually come from different servers. You can create Dfs roots in the AD or create stand-alone Dfs roots. The latter option does not offer the replication and redundancy provided by AD-integrated Dfs roots. Understanding Dfs structure and topology A Dfs namespace is a collection of shared resources that exist under a Dfs root. The Dfs root serves essentially as a container for the namespace, much like the root folder of a volume serves as the entry point to the volume’s folders or a network share serves as the entry point to the share’s subfolders. Unlike the root folder of a volume that contains subfolders, the Dfs namespace contains links to the local and remote shares that make up the namespace. To the user, the links appear as folders under the Dfs root share. One server functions as a host server for a Dfs namespace and in the current Dfs implementation can host one Dfs root. Other servers can host root replicas of the Dfs root to provide redundancy so that the Dfs root is always available, even if the host server is down. Remember that the Dfs root is essentially a container of links, so creating a root replica doesn’t take a huge amount of space—you’re duplicating the structure of the Dfs root (the links), not the data referenced by the links. Also, a given server can host one root or one root replica, but not both. Users access shared resources in a Dfs namespace in the same way that they access individual network shares. The Dfs root functions as a regular share, and users access the Dfs namespace through that share name. For example, assume you’ve created a Dfs root named Documents on a server named DocServer. Users could browse to the root of the Dfs namespace through the UNC path \\DocServer\Documents. Users then see subfolders under that share that represent the links you’ve created in the Dfs root to shared folders that reside on the hosting server, other servers across the network, or even shares on client computers. A Dfs link connects a virtual folder name in the Dfs namespace with a remote share, called a Dfs replica or Dfs shared folder. In effect, the replicas function as subdirectories under the Dfs root. Each link can associate multiple replicas with a given part of the namespace, essentially mapping multiple shares to the same name. Dfs randomly presents to the user one of the replicas under a selected link. When a server is down and its shared resources unavailable, Dfs automatically selects another and the client continues working. Figure C illustrates a simple Dfs root with a link containing multiple replicas. It’s important to understand that the possibility for multiple replicas in a link doesn’t mean that Dfs automatically replicates the same data to multiple shares. While in most cases you would add replicas in a given link that all pointed to different copies of the same data, the replicas don’t have to point to duplicate data. You can create multiple replicas under a single link that all point to different content. If you want to ensure that all replicas offer the same data, implement a means of replicating the data from one server to another. Domain-based replicas offer this replication, as you’ll learn later. Dfs root types As mentioned previously, you can create AD-integrated (domain-based) and stand-alone Dfs roots. A domain-based Dfs root must be hosted on a domain member server or DC. Dfs automatically publishes the Dfs root topology in the AD, which provides topology replication to the DCs in the domain. Creating a domain-based Dfs root does not by itself provide replication of individual folders, however, but only replicates the Dfs root structure across the domain. You need to configure content replication separately. We’ll discuss replication in an upcoming Daily Drill Down. A stand-alone Dfs root is stored outside the AD and doesn’t provide the replication and related advantages offered by a domain-based root. You can create a stand-alone Dfs root on stand-alone, member, and domain controller servers. You can create root replicas only within the framework of the AD, meaning that you can create root replicas of domain-based Dfs roots but can’t create root replicas of stand-alone roots. Each server can host only one root, so a server that hosts its own Dfs root can’t host root replicas. Conversely, servers that host root replicas can’t host their own Dfs roots. A domain can host multiple Dfs roots, although each server in the domain can host only one. Creating a root replica creates a logical relationship between two roots on two or more servers that are referenced by the same name in the Dfs namespace. However, you can create additional directory replicas within a root replica. This means that you start out with an exact copy of the domain-based root, but changes can be introduced in any root replica that make it different from other replicas of the same root. For example, you might create physical folders in the root share of the root replica, but those folders won’t exist on the Dfs root from which the replica was created. The bottom line is that the existence of a root replica doesn’t guarantee that the replica is identical to the domain-based root from which it is created. You need to provide a means of replication and synchronization to ensure that your root replicas are identical from one replica to the next. Clients supported by Dfs There are two separate aspects of client support for Dfs: replica hosting and browsing. Replica hosting refers to a client’s ability to host a Dfs replica (a shared folder that appears in the Dfs namespace within a Dfs link). Any shared folder can be a Dfs replica since the Dfs root simply associates a link in the Dfs namespace to the shared folder and provides redirection to that share when clients access it through the Dfs namespace. Therefore, Windows 9x, Windows NT, and Windows 2000 clients can all host Dfs replicas without any special software since the computer hosting the share doesn’t have to be Dfs-aware. To browse a Dfs namespace, however, clients must be Dfs-aware. Any Dfs-aware client can browse and use either a domain-based root or a stand-alone root. Windows 98 and Windows NT 4.0 with Service Pack 4 or higher include support for Dfs. Windows 95 does not include Dfs support, but you can add it by installing the Dfs client on each Windows 95 computer that needs to access Dfs. You can download the Windows 95 client from Microsoft’s Web site. Conclusion File and print sharing has matured quite a lot. No longer are you restricted to storing files on individual disk drives or servers. Using Windows 2000’s distributed file storage and mounted volumes support, you can scale up your network without your users being affected by the changes. In this Daily Drill Down, I showed you how both features can simplify your workday and improve usability for your clients..
http://www.techrepublic.com/article/understanding-the-windows-2000-distributed-file-system/
CC-MAIN-2017-13
refinedweb
3,214
60.04
RE: [Fwd: Ready to tackle next release] If you are getting ready for a new release, I have a bunch of patches I would love to see added to NAnt. I would be willing to work with everyone as much as needed, to see that the changes make it into the release; or some variation of them - that is, if they are accepted. Here is a run down of our current changes to NAnt: I have mentioned this one previously; and it involves adding an "options" property to CompilerBase.cs. The original post had no subject and came out garbled (sorry about that), though I have filed it under RFE "[811931] - Adding an "options" property to CompilerBase.cs", where you can read about the change in more detail. Another change we made was to allow passing of "parameters" as properties to other NAnt scripts via the "nant" task. This works really well and avoids having to using the "inheritall" attribute (which can be overkill - particularly if you have scripts that call themselves externally...). You can think of this feature as adding support for the "-D:" options of nant.exe The syntax looks like this: <nant buildfile="somefile" inheritall="false" target="sometarget"> <defines> <property name="buildtarget" value="${script.build.target}" /> <property name="copytarget" value="${script.copy.target}" /> </defines> </nant> The "defines" are created as properties and accessible only from the invoked NAnt script as if they were passed with "-D:". Their values are evaluated at the time just before the new script is invoked. Note: You can still use the "inheritall" attribute as well, though anything defined will override anything inherited if there is a name collision. The patch for this change is straightforward and simple. The only part left to do is handling all the NAnt location stuff with properties, which I am not too sure about (currently, I set this to unknown), though I'm sure someone on the list can enlighten me. Our next change is the most extensive but it fixes a long out-standing issue with NAnt. Basically, we did a rewrite on how NAnt handles RESX files. Currently NAnt has the following problems: 1.) The regular expressions for determining the namespace are poor and are easily confused by comments (that have the word namespace in them, for example "// is located in the foo namespace"). 2.) The regular expressions used by different languages are executed on all the source files. For example, when compiling a "*.cs" file the regular expressions for capitalized namespace lookup (I guess for VB) is executed even when it should not; this is bad, as it picks up false positives and increase the chance of error. 3.) The biggest problem is that NAnt assumes the filename (of the source file) is the name of the class that the RESX should be associated too. This issue killed our use of NAnt (until we fixed it), as our filenames do not match the "Form" class within them; Visual Studio does not have a problem with this. Our patch fixes all these issues. For number 3, we actually added additional regular expression that extract the correct class name from the source instead of assuming it is the same as the file. This works extremely well, mainly because Visual Studio forces the Form/Control classes to always be the first class in the file (now you know why they do this, it seems that VS needs to do all this work as well...). The way we implemented it was by making a class like this: protected struct ResourceLinkage { private string _namespaceName; private string _className; public ResourceLinkage(string namespaceName, string className) { _namespaceName = namespaceName.Trim(); _className = className.Trim(); } public override string ToString() { return ...; // Outputs path to resources } public string NamespaceName { get { return _namespaceName; } set { _namespaceName = value; } } public string ClassName { get { return _className; } set { _className = value; } } } ...to store and keep track of this information. Then we changed the function that normally returns just a string, to this: protected virtual ResourceLinkage GetFormResourceLinkage(string resxPath) {} The regular expressions we use are: Regex matchNamespaceRE = new Regex(@"^\s*namespace ((\w+.)*)"); Regex matchNamespaceCapsRE = new Regex(@"^\s*Namespace ((\w+.)*)"); Regex matchClassNameRE = new Regex(@"^([\s\w]*\s)?class\s+(?<class>\w+)"); Anyway, that is the basic gist of it. There are some issues yet to be resolved. For one, I know nothing about VB (okay, I know some, but very little), and have not written the Regex patterns for it. I am also not sure that thee new "class-name" Regex use successfully for "*.cs" files will work for J#. The Regex patterns can be improved further (though these are problems with the current version of NAnt as well). /* namespace test class something here */ namespace foo { namespace bar { class foo : Form { } } } The above examples can still break things (though are not that common in practice). Fortunately, nether of these are that hard to fix and I would be willing to do the work. With these improvements, NAnt would work exactly as VS does (well..., as far as I can tell.) Lastly, we made a few tweaks to the "cl" task, but they were minor; like moving the "options" attribute to write the parameters latter in the response- file so it can be used to override undesirable NAnt settings. Anyway, if you want to add any of these enhancements to NAnt please let me know. I would be more then happy to work on them and could turn around changes very fast as I can dedicate my full time to these issues. James. Quoting nant-developers-request@...: > > - > > > -----Original Message----- > > From: Ian MacLean [mailto:ianm@...] > > Sent: Friday, October 03, 2003 2:31 PM > > To: nant-developers@... > > Subject: [nant-dev] [Fwd: Ready to tackle next release] > > > > > > The last few days, I've run into a very strange situation. I'm doing vsscheckin's on certain dll files with my build because the developers don't want to have to build all the projects constantly (and change is big now - new app). So I have to do a vsscheckout at the beginning of the build process. With one particular project, it builds the project successfully, but for some reason, doesn't replace the .dll. Not only does <solution> not replace it, but VS.Net doesn't either (unless doing rebuild). This would be cool if nothing had changed, but it has and causes later projects to fail. Is there a way to force <solution> to rebuild, or if not, a way to modify solution to do such? Thanks in advance! Eric __________________________________ Do you Yahoo!? The New Yahoo! Shopping - with improved product search -=20 > -----Original Message----- > From: Ian MacLean [mailto:ianm@...]=20 > Sent: Friday, October 03, 2003 2:31 PM > To: nant-developers@... > Subject: [nant-dev] [Fwd: Ready to tackle next release] >=20 >=20 >=20
https://sourceforge.net/p/nant/mailman/nant-developers/?viewmonth=200310&viewday=3
CC-MAIN-2017-47
refinedweb
1,125
71.34
The following packages are needed to run bocker. Because most distributions do not ship a new enough version of util-linux you will probably need to grab the sources from here and compile it yourself. Additionally your system will need to be configured with the following: /var/bocker bridge0and an IP of 10.0.0.1/24 /proc/sys/net/ipv4/ip_forward bridge0to a physical interface. For ease of use a Vagrantfile is included which will build the needed… This is not an official API support and etc. This is just a scraper that is using TikTok Web API to scrape media and related meta information. tiktok-scraper requires Node.js v10+ to run. Install from NPM npm i -g tiktok-scraper Install from YARN yarn global add tiktok-scraper $ tiktok-scraper --helpUsage: tiktok-scraper <command> [options]Commands: tiktok-scraper user [id] Scrape videos from username. Enter only username tiktok-scraper hashtag [id] Scrape videos from hashtag. Enter hashtag without # tiktok-scraper trend Scrape posts from current trends… Depix is a tool for recovering passwords from pixelized screenshots. This implementation works on pixelized images that were created with a linear box filter. python depix.py -p [pixelated rectangle image] -s [search sequence image] -o output.png The algorithm uses the fact that the linear box… Mimic is an API-compatible mock service for Openstack Compute and Rackspace’s implementation of Identity and Cloud Load balancers. It is backed by in-memory data structure rather than a potentially expensive database. Mimic helps with: The fastest way to install and start Mimic is: pip install mimic twistd -n mimic You can test the server started successfully by sending this request and checking for the welcome message: curl >> To get started with… Top-like interface for container metrics ctop provides a concise and condensed overview of real-time metrics for multiple containers as well as a single container view for inspecting a specific container. Fetch the latest release for your platform: sudo wget -O /usr/local/bin/ctop sudo chmod +x /usr/local/bin/ctop brew install ctop or sudo curl -Lo /usr/local/bin/ctop sudo chmod +x /usr/local/bin/ctop Img2css is a tool that can convert any image into a pure css image. This tool creates a single one pixel shadow per pixel in the source images.. Example # import pyinspect import pyinspect as pi # Find the functions you're looking for pi.search(pi, name='what') npm install filters.css 2. Or you can use cdn unpkg and include in the head <link href="" rel="stylesheet"> 3. Or download minified filters.min.css file and include in the head <link href="css/filters.min.css" rel="stylesheet"> filters.css can be used with any css framework. <img src="..." class="blur-3" /> Try running a simple program: // hello.ts import { hello } from "";hello("Elsa");> elsa run hello.ts Hello, Elsa High velocity native mobile development requires us to adopt continuous integration workflows, which means our reliance on manual QA has to drop significantly. Detox tests your mobile app while it’s running in a real device/simulator, interacting with it just like a real user. The most difficult part of automated testing on mobile is the tip of the testing pyramid — E2E. The core problem with E2E tests is flakiness — tests are usually not deterministic. We believe the only way to tackle flakiness head on is by moving from black box testing to gray box testing. … Full-stack developer and Open Source contributor — ·
https://id1000000.medium.com/?source=post_internal_links---------2----------------------------
CC-MAIN-2021-25
refinedweb
583
55.44
Exposing Functions to Embedded Python17 Oct 2005 So far, instead of exposing functions to Python, we have (the reverse I guess) embedded the Python interpreter in our process using Boost::Python. So, running Python from within our process is all good and well but we want the Python code to interact with our C++ code as well. We’ll add to the previous example: <code>const char* greet() { return "Hello World from C++"; } BOOST_PYTHON_MODULE(embed_test) { def("greet", greet); }</code> Here we have defined a python module embed_test which we will now expose to our embedded Python interpreter. The module has one function, “greet” in the Python module calls the C++ greet function. Now we add to the main function: <code>if(PyImport_AppendInittab("embed_test", initembed_test) == -1) throw std::runtime_error("Failed to add test module to builtins");</code> The initembed_test reference is the function name generated by the BOOST_PYTHON_MODULE macro. Once we have made Python aware of this built-in module, we can modify the python code we run in the example to print out the result of the greet function: <code>handle<> ignored((PyRun_String( "import embed_test\n" "print embed_test.greet()" , Py_file_input , main_namespace.ptr() , main_namespace.ptr()) ));</code> The techniques used here are all based around the basic functionality available in the Python C API. However, the Boost::Python library does make it easier to expose your own code to the Python interpreter. Next we’ll look at exposing classes and then move on to the use of SWIG.
http://untidy.net/blog/2005/10/17/exposing-functions-to-embedded-python/
CC-MAIN-2019-47
refinedweb
246
57
Defunctionalization Why are programs written in Java so verbose? The answer seems to be that Java does not support function pointers or functions as first class values. For example, solving an ODE in Python proceeds as follows. You define a function for the derivative, and then pass that to the solver along with some initial conditions and other parameters. Easy enough. def yDot(y, c=[1.0, 1.0], omega=0.1): return [omega * (c[1] - y[1]), omega * (y[0] - c[0])] finalValue = ode_solver(yDot, y0=[0.0, 1.0], t_final=16.0) The equivalent in Java (example taken from the Apache commons maths library) requires an entire class to be written, implementing the oddly named interface FirstOrderDifferentialEquations. private static class CircleODE implements FirstOrderDifferentialEquations { private double[] c; private double omega; public CircleODE(double[] c, double omega) { this.c = c; this.omega = omega; } public int getDimension() { return 2; } public void computeDerivatives(double t, double[] y, double[] yDot) { yDot[0] = omega * (c[1] - y[1]); yDot[1] = omega * (y[0] - c[0]); } } // then in some other class... FirstOrderIntegrator dp853 = new DormandPrince853Integrator(1.0e-8, 100.0, 1.0e-10, 1.0e-10); FirstOrderDifferentialEquations ode = new CircleODE(new double[] { 1.0, 1.0 }, 0.1); double[] y = new double[] { 0.0, 1.0 }; // initial state dp853.integrate(ode, 0.0, y, 16.0, y); // now y contains final state at time t=16.0 This is a lot of work and obfuscates the problem at hand, the definition of a derivative and a call to a solver. Java seems to be unique in its pedantic style, at least among common languages in use today. In C one can use function pointers, Fortran can pass functions, Python has first-class functions, Haskell has higher-order functions, and so on. It turns out that Java programmers are forced to do defunctionalization since Java does not support higher order functions. Here’s a quote from a blog post on plover.net:. </blockquote> In Haskell we might implement yDot as: module Defun where yDot :: [Double] -> Double -> [Double] -> [Double] yDot c omega y = [omega * (c !! 1 - y !! 1), omega * (y !! 0 - c !! 0)] The parameters c and omega are the slowest varying, so we put them before y. Since all functions in Haskell are curried, we can conveniently produce the function that we need by partially applying the c and omega values: *Defun> :t yDot [1.0, 1.0] 0.1 yDot [1.0, 1.0] 0.1 :: [Double] -> [Double] In this way yDot is a higher order function. To make it first-order we have to defunctionalize it. Following the example on plover.net we define a data structure to hole the c and omega values: data Hold = MkHold [Double] Double And we need a function to “apply” this value to get the actual yDot value. fakeApply :: Hold -> [Double] -> [Double] fakeApply (MkHold c omega) y = [omega * (c !! 1 - y !! 1), omega * (y !! 0 - c !! 0)] Basically Hold and fakeApply are equivalent to the CircleODE class above. Example: hold :: Hold hold = MkHold [1.0, 1.0] 0.1 result :: [Double] result = fakeApply hold [1.0, 1.0] Defunctionalization appears to be the cause of the excessive use of nouns in Java code, resulting in things like the Abstract Singleton Proxy Factory Bean, or the Abstract Factory design pattern. Further reading: Defunctionalization and Java: (local copy) Ken Knowles’ blog post: (local copy) Steve Yegge’s rant on execution in the kingdom of nouns: (local copy) Literate Haskell source for this post is here:.
https://carlo-hamalainen.net/2014/04/24/defunctionalization/
CC-MAIN-2020-40
refinedweb
585
65.62
The MicroPython Interactive Interpreter Mode (aka REPL)¶ This section covers some characteristics of the MicroPython Interactive Interpreter Mode. A commonly used term for this is REPL (read-eval-print-loop) which will be used to refer to this interactive prompt. Auto-indent¶ When typing python statements which end in a colon (for example if, for, while, etc.) then the prompt will change to three dots (...) and the cursor will be indented by 4 spaces. When you press return, the next line will continue at the same level of indentation for regular statements or an additional level of indentation where appropriate. If you press the backspace key then it will undo one level of indentation. If your cursor is all the way back at the beginning, pressing RETURN will then execute the code that you’ve entered. The following shows what you’d see after entering a for statement (the underscore shows where the cursor winds up): >>> for i in range(3): ... _ If you then enter an if statement, an additional level of indentation will be provided: >>> for i in range(30): ... if i > 3: ... _ Now enter break followed by RETURN and press BACKSPACE: >>> for i in range(30): ... if i > 3: ... break ... _ Finally type print(i), press RETURN, press BACKSPACE and press RETURN again: >>> for i in range(30): ... if i > 3: ... break ... print(i) ... 0 1 2 3 >>> Auto-indent won’t be applied if the previous two lines were all spaces. This means that you can finish entering a compound statement by pressing RETURN twice, and then a third press will finish and execute. Auto-completion¶ While typing a command at the REPL, if the line typed so far corresponds to the beginning of the name of something, then pressing TAB will show possible things that could be entered. For example type m and press TAB and it should expand to machine. Enter a dot . and press TAB again. You should see something like: >>> machine. __name__ info unique_id reset bootloader freq rng idle sleep deepsleep disable_irq enable_irq Pin The word will be expanded as much as possible until multiple possibilities exist. For example, type machine.Pin.AF3 and press TAB and it will expand to machine.Pin.AF3_TIM. Pressing TAB a second time will show the possible expansions: >>> machine.Pin.AF3_TIM AF3_TIM10 AF3_TIM11 AF3_TIM8 AF3_TIM9 >>> machine.Pin.AF3_TIM Interrupting a running program¶ You can interrupt a running program by pressing Ctrl-C. This will raise a KeyboardInterrupt which will bring you back to the REPL, providing your program doesn’t intercept the KeyboardInterrupt exception. For example: >>> for i in range(1000000): ... print(i) ... 0 1 2 3 ... 6466 6467 6468 Traceback (most recent call last): File "<stdin>", line 2, in <module> KeyboardInterrupt: >>> Paste Mode¶ If you want to paste some code into your terminal window, the auto-indent feature will mess things up. For example, if you had the following python code: def foo(): print('This is a test to show paste mode') print('Here is a second line') foo() and you try to paste this into the normal REPL, then you will see something like this: >>> def foo(): ... print('This is a test to show paste mode') ... print('Here is a second line') ... foo() ... File "<stdin>", line 3 IndentationError: unexpected indent If you press Ctrl-E, then you will enter paste mode, which essentially turns off the auto-indent feature, and changes the prompt from >>> to ===. For example: >>> paste mode; Ctrl-C to cancel, Ctrl-D to finish === def foo(): === print('This is a test to show paste mode') === print('Here is a second line') === foo() === This is a test to show paste mode Here is a second line >>> Paste Mode allows blank lines to be pasted. The pasted text is compiled as if it were a file. Pressing Ctrl-D exits paste mode and initiates the compilation. Soft Reset¶ A soft reset will reset the python interpreter, but tries not to reset the method by which you’re connected to the MicroPython board (USB-serial, or WiFi). You can perform a soft reset from the REPL by pressing Ctrl-D, or from your python code by executing: raise SystemExit For example, if you reset your MicroPython board, and you execute a dir() command, you’d see something like this: >>> dir() ['__name__', 'pyb'] Now create some variables and repeat the dir() command: >>> i = 1 >>> j = 23 >>>>> dir() ['j', 'x', '__name__', 'pyb', 'i'] >>> Now if you enter Ctrl-D, and repeat the dir() command, you’ll see that your variables no longer exist: PYB: sync filesystems PYB: soft reboot MicroPython v1.5-51-g6f70283-dirty on 2015-10-30; PYBv1.0 with STM32F405RG Type "help()" for more information. >>> dir() ['__name__', 'pyb'] >>> The special variable _ (underscore)¶ When you use the REPL, you may perform computations and see the results. MicroPython stores the results of the previous statement in the variable _ (underscore). So you can use the underscore to save the result in a variable. For example: >>> 1 + 2 + 3 + 4 + 5 15 >>> x = _ >>> x 15 >>> Raw Mode¶ Raw mode is not something that a person would normally use. It is intended for programmatic use. It essentially behaves like paste mode with echo turned off. Raw mode is entered using Ctrl-A. You then send your python code, followed by a Ctrl-D. The Ctrl-D will be acknowledged by ‘OK’ and then the python code will be compiled and executed. Any output (or errors) will be sent back. Entering Ctrl-B will leave raw mode and return the the regular (aka friendly) REPL. The GitHub micropython/tools/pyboard.py program uses the raw REPL to execute python files on a MicroPython board.
http://docs.openmv.io/reference/repl.html
CC-MAIN-2017-26
refinedweb
949
72.26
Pythonic way to flatten a dictionary into a list using list comprehension python flatten nested dictionary flatten list comprehension python convert nested dictionary to list python flatten a dictionary of lists python python nested lists and dictionaries python merge lists in a list flatten hierarchical dictionary python I have the following function: def create_list_from_dict1(mydict): output = [] for k, v in openint_dict.items(): output.append( (k, v['field1'], v['field2'], v['field3']) ) return output Essentially, it flattens the dictionary, so that I can perform sorting on one of the fields of the tuple in the returned list. I don't like the fact that I am having to 'hard code' the field names of the value dictionary ( 'field1', ..., 'fieldN'), and I want a more pythonic and elegant way of doing this so that this function works for all dictionaries that contain a fixed structure (non-nested) dictionary as its values. I imagine that I will have to use **kwargs and/or a lambda function, as well as list comprehension. What would be the most pythonic way to write this function? You can do it like this: fields = ("field1", "field2", "field3") output = [[k] + [mydict[k].get(x) for x in fields] for k in mydict] In that code we iterate dict keys and add them with selected subset of second-level dictionaries values. Python, Given a list of the dictionaries, the task is to convert it into single Python code to demonstrate Method #2: Using dict comprehension. This is probably the worst part in the code, yet this is pretty much the whole code. Variable names are terrible and the intent is a bit hidden. I understand that unpack returns lists so your list-comprehension generates a list of lists. So this expression is flattening a list of list of tuples and turning it into a dictionary. Python, Conversion from one data type to other is essential in various facets of programming. Method #1 : Using list comprehension. We can use list comprehension as the one-liner alternative to perform various naive tasks providing list of tuples to dictionary value lists � Python - Convert Flat dictionaries to Nested dictionary� While this works, it's clutter you can do without. This tip show how you can take a list of lists and flatten it in one line using list comprehension. The loop way #The list of lists list_of_lists = [range(4), range(7)] flattened_list = [] #flatten the lis for x in list_of_lists: for y in x: flattened_list.append(y) List comprehension way If order doesn't matter... def create_list_from_dict1(mydict): output = [] for k, v in openint_dict.items(): fields = [value for key, value in v.items()] output.append( tuple([k] + fields ) return output If order matters you either need to do as you did and call out the fields specifically...or you need to used an OrderedDict for the sub-dicts. 7 Handy Use Cases Of Dictionary Comprehensions In Python, Comprehensions in Python are syntactic constructs that are used to build sequences Flattening, inverting, merging, filtering, and more By invoking the items() method on a dictionary, you can convert it into a list of tuples of� […] Python dicts have keys() and values() methods to get a list of the keys and values. If order of the fields is not important: [(k,) + tuple(v.values()) for k, v in mydict] If the ordering of the values does matter: [(k,) + tuple([v[i] for i in sorted(v.keys())]) for k, v in mydict] Note that the second option would be identical to the first without the call to sorted(). The order depends on how things were added to the subdict, so you should use the second option as much as possible. Pythonic way to flatten nested dictionarys, dictionary_ = dict( ii for i in [unpack(key, value) for key, value in So this expression is flattening a list of list of tuples and turning it into a dictionary. instead of full list-comprehension to play it nicer with the memory. This only� Dictionary comprehension is a method for transforming one dictionary into another dictionary. During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed. A good list comprehension can make your code more expressive and thus, easier to read. def create_list_from_dict1(mydict): return [tuple([k]+list(v.values())) for k,v in openint_dict.items()] doesn't use the fields' names and produces the same result. In Python 3.5, you can just type (because starred expressions are allowed everywhere): def create_list_from_dict1(mydict): return [(k,*v.values()) for k,v in openint_dict.items()] 5. Data Structures — Python 3.8.5 documentation, If no index is specified, a.pop() removes and returns the last item in the list. List comprehensions provide a concise way to create lists. in <module> [x, x**2 for x in range(6)] ^ SyntaxError: invalid syntax >>> # flatten a list using a Another useful data type built into Python is the dictionary (see Mapping Types — dict).. When to Use a List Comprehension in Python – Real Python, Using Conditional Logic; Using Set and Dictionary Comprehensions; Using the There are a few different ways you can create lists in Python. Take this example, which uses a nested list comprehension to flatten a matrix:.. 20+ examples for flattening lists in Python, In this tutorial, you will learn flattening lists with different shapes & levels in 13 Flatten & remove duplicates; 14 Flatten a dictionary into a list; 15 Using reduce List comprehension is a way to create lists in one line of code. Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword. Here is a small example using a dictionary: Chapter 6, In this chapter we will learn how to use each type of comprehension. You will find that the List comprehensions in Python are very handy. They can also be a comprehension. One reason to do that is to flatten multiple lists into one. too can use them. Now we're ready to move on to Python's dictionary comprehensions! Now, let’s see different ways of creating a dictionary of list. Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key. - So you start with a dictionary of dictionaries? Does the order within the tuple matter? Do they need to be consistent between the tuples, even? Are the keys you're extracting values for a subset of the keys in the vdictionaries, or all of them? Could you give an example input and acceptable output? (Sorry for long comment!) - @jonrsharpe: Answers given in same order as questions: Yes, Yes, Yes, No - the keys are ticker codes, and the tuples consist of market data - Could you edit the question accordingly, and add an example? - I would replace the hard coded fields with a call to mydict.keys(). Otherwise, it seems very elegant, and just what I'm looking to do. Will try it out first though ... to make sure it works, before accepting your answer. - Take a note that dictionary in python is not ordered, so using mydict.keysyou mix your data. - @HomunculusReticulli that will give you the keys to the outer dictionary, too, which may not be the same as the inner dictionaries (still no example?) - Yes, I thought we talking about inner dictionaries, because fields hardcoded for them. - Can you explain this: tuple(v for _,? I have never come across this syntax before ... it looks like you're invoking a magic method.. what does the underscore mean? - @HomunculusReticulli per the answer, _means "we aren't using this" (the inner dict's key, in this case). It's like ... for k, v in ...but makes it clearer that kis being ignored on purpose. - Thanks for the explanation. I think I will go with your answer, as its the most pythonic. However, I may have to sub class the dict class, with my own class which will have a fields attribute to use in the function, instead of calling sorted(val.items()). The tuples are records from a database, so the order of the columns must not be changed. - @HomunculusReticulli then are you sure you have the right data structure to begin with? - Absolutely, the data is coming from a database. - The problem with this is that there's no guarantee that valuesfrom each inner dictionary will be in the same order, which the OP commented as a requirement. - Not sure, but it seems to work on a 'fixed structure'. I don't know if is garanteed. - It isn't guaranteed, that's what I'm telling you.
https://thetopsites.net/article/55092979.shtml
CC-MAIN-2021-25
refinedweb
1,476
64
Hello! I encounter the strange behavior of the Intel C++ Compiler. The following program generates "Floating point exception" if optimization (at least -O1) is enabled: #include <fenv.h> #include <stdio.h> int j = 0; int main(int argc, char *argv[]){ feenableexcept( FE_DIVBYZERO ); double r = 0.0; for(int k=0; k<2; k++) { double A[3] = {0.,0.,0.}; if(j) A[0] -= 1.0/r; printf("A = %e %e %e\n", A[0], A[1], A[2]); } } Linux, 64bit. Compiler version: icc (ICC) 16.0.1 20151021. If the optimization is disabled, no exception is generated. gcc also generates no exception. Is everything correct? Link Copied Hi, I'll look into it further. In the mean time, can you use -fp-model strict? Thanks, Viet When compiled with option -fp-model strict, the result is as it should be: A = 0.000000e+00 0.000000e+00 0.000000e+00 A = 0.000000e+00 0.000000e+00 0.000000e+00
https://community.intel.com/t5/Intel-C-Compiler/Division-by-zero-inside-if-0-clause/td-p/1138220
CC-MAIN-2021-21
refinedweb
160
71.51
. Are these string literals and other literal constants placed in TEXT segment of RAM? It’s up to the compiler to determine where to put them. It may be in the text segment, or in a different segment. But, they are definitely in the Read Only Segments Of RAM,No? Most often yes, but it’s not guaranteed on all architectures. Ok. Thanks. Just to clarify in regards to printing the address of a char with a single character. Because std::cout assumes it’s dealing with a string, does this mean that a char with a single character doesn’t have a null terminator and that’s why it keeps printing garbage until it hits a 0? Yes. Hi Alex. Consider the following code: I get the following output: In the article, you state the following: "…Multiple string literals with the same content may point to the same location." I was surprised to see two different memory addresses. I believe I’m not quite understanding what’s happening with the getName() function and how memory is being allocated for the string literal. Also, as a follow-up question, you state this in one of your comments: "Personally, I only use const char* if I’m hardcoding a string that will only be displayed (e.g. the application name). Otherwise, std::string for everything (or my own string class)." I’m wondering - why did you implement getName() as a function? If I’d like to use some sort of constant string in my code, is there any advantage of using a function over something like: I’ve really been enjoying the content so far. Thanks for everything. You’re getting different addresses because you’re printing the addresses of variables name1 and name2, not printing the address that they’re holding (which is the address of “Drew”). You need to remove the ampersands from name1 and name2 in your cout statements. In the case where you want to reuse a C-style string from different areas of the code, you really have two options: use a function like getName(), or define the string as a global constant. I used a function here just to show it could be done, but in reality I’d favor a global constant. Ah, sure enough. Fantastic. Cheers. One question. Let’s compare these two pieces of code: and Now, if I got it right, both of them are possible, but they are different assignments: in the second case I am assining a char pointer to a char pointer, in the first case, I am a char value to the dereferentiation of a char pointer, right? So, this is creating me a little confusion. How can the compiler tell the two situations apart? No. In both cases, you would be assigning a char pointer to a char pointer. The only difference is in how C++ allocated memory for the string literal. So, this is as to say that when I write a snippet like this: C++ creates an auxilliary char array with the value "Alex" and then it assigns myName to the address of that array? That would be: Is that correct? Yes (though myName should be of type char*, not char) Yes. Correct. Thank you. I’ve been pretty lost for the past several lessons, so this is probably a stupid question. Why do we need to care about what the memory address of an array or variable is? In most cases, you don’t need to care what the memory address of a variable or array is! Taking the address of a variable is done only rarely (when we need to create a pointer from a normal variable). Okay, thanks 🙂 Hello Alex, 1)As you mentioned there is no scoping issues and it has static duration.(in getName()) I have shown printed results on comment. -Does below sub function’s "int *subFun1()"returned value have automatic duration? The second function’s (getName()) returned value has static duration, as you stated above; Static storage duration objects have entire program life duration. -How we can check out that either of sub function’s (subFun1(),getName()) returned value have entire program life duration? Or -I didn’t get why this below dereferenced pointer prints 0 in main,?May be it is automatic duration. std::cout<<*ptrFun1<<‘\n’;//prints 0 So a bit confusing here; //============================================================================= #include<iostream> int* subFun1() { int x=5; int *ptr=&x; return ptr; // will ptr have automatic duration in this case? } const char * getName() { return "Alex";// it has static as you said } int main() { int *ptrFun1=subFun1(); std::cout<<*ptrFun1<<‘\n’;// prints 6 std::cout<<*ptrFun1<<‘\n’;//prints 0 const char*ch1=getName(); std::cout<<(ch1)<<‘\n’;//Alex std::cout<<(ch1)<<‘\n’;// Alex return 0; } //===================================================================================== 2) It is something new for me. I have been reading from the 1’s chapter till this one. “4.3a — Scope, duration, and linkage summary” and “4.3 — Static duration variables” chapters just mentioned few things about them. -Is it important part of c++ class? If it is so, is there any reference for us ? In subFun1(), ptr has automatic duration and will be destroyed at the end of the function. Because ptr is destroyed, this function returns an invalid address, and dereferencing it will lead to undefined behavior (hence the inconsistent results) In getName(), “Alex” has static duration because string literals are treated specially. For this reason, you can return their addresses back to the caller and use them. I don’t understand what you are asking in question #2. Can you clarify? 1a) >Because ptr is destroyed, this function returns an invalid address, and dereferencing it will lead to undefined behavior (hence the inconsistent results) -Is this a misstep if function is returning addresses of a stack-allocated local variable? For example, see below program pointer to int (ptr) returned to main. In main the address of x (&x) is destroyed and ptrFun1 now points to the address of x which is not existed.(invalid address) It works well, prints the result 6, as you see. -Even though, prints the correct result. Most probably it is random as well. (prints 6). Am I right? -Is this wrong code? int* subFun1() { int x=6; int *ptr=&x; return ptr; } int main() { int *ptrFun1=subFun1(); // ptrFun1 is holding destroyed address of ptr;(*ptrFun1 is dangling pointer) std::cout<<*ptrFun1<<‘n’;// prints : 6, *ptrFun1 is dangling pointer now } //========================================================== 1b) If subFun1() returns just address of x directly to the main(return &x) instead of returning it through pointer (return ptr), my compiler (DevC++) gives Warnning: ([Warning] address of local variable ‘a’ returned [-Wreturn-local-addr]) It seems, both of them are identical whether you return addresses of x directly (&x) or through pointer (ptr) For example: int* subFun1() int *subFun1() { { int x=6; int x=6; return &x; int *ptr=&x; return ptr; } // warning in main } // no warning in main - What is the difference? Why does it give warning only when the address of x (return &x) is returned directly not through pointer. (return ptr) //========================================================= 2) >I don’t understand what you are asking in question #2. Can you clarify? I meant, will we have a separate lesson for " weather the string literals have automatic duration or static duration when they returned to the main?. I think, it is not necessary now (because you almost explained),if you could clarify below this. The C++ standard mandates that C-style string literals have static duration. As you said string literals are treated specially. -What about C++ std::string? Does C++ standard mandate which is the type of std::string literals have static duration? -Does getName() function’s returned value have static duration, see below code? #include<iostream> std::string getName() { return "Alex" ;// does it have static duration? } int main() { std::string res=getName(); std::cout<<res; std::cout<<res; return 0; } Thanks in advance Alex! It is a great tutorial I have ever seen! 1a) Yes, you should never return a local variable by reference or address. Once that variable goes out of scope, your reference or address will point to memory that may be reused for other purposes, leading to undefined behavior. 1b) The programs work identically, but in some cases your compiler can be smarter about warning you when you’re making a mistake. If you directly return the address of a local variable, your compiler can easily detect this, and should complain. If you’re returning a pointer, the compiler has a harder time determining whether it’s pointing to something valid or not, so it may not complain. 2) Only C-style string literals have special handling. std::string is treated normally, like any other object. For the getName() case, no, the returned std::string has expression scope (it will die at the end of the expression it’s returned into). So you either need to assign the return value to another variable, or use it to initialize a const reference, which will extend the lifetime of the return value to match the lifetime of the reference. Regarding the third example when I cout *getname(), I can only see the first letter and not "Alex". Yes. getName() returns a char pointer to the C-style string. If you dereference this string (via operator*), it will give you the value that char pointer is actually pointing to, which is the first element of the array. Remove the dereference and it should work as you expect. Ok. I get the point. Thanks a lot. Hello, i have a question about the sentence: "string declared this way are persisted throughout the life of the program, we don’t have to worry about scoping issues." Why is that true? Thanks! and needless to say, incredible tutorial. The C++ standard mandates that C-style string literals have static duration (instead of automatic duration like most other locally defined values). This was probably done for efficiency reasons, as copying strings is expensive, and it would be easy to inadvertently to end up with a dangling pointer otherwise. Third paragraph from the top, you wrote: " Also because strings declared this way are persisted throughout the life of the program, we don’t have to worry about scoping issues." I think there should be a comma after "also". Agree and added. Thanks! Hey Alex! I tried this: and what I got was: Alex lex ex x (blank) Could it be that cout prints the array output from the point you specified onward, instead of only the array element? In general, no. If you remove the ampersands from in front of the array elements, it’ll print each array element (of type char) individually. However, with the ampersand, you’re passing std::cout a pointer to a char, which it will interpret as a C-style string, and print all of the array elements onwards until it encounters a null terminator. This only happens for char pointers due to the way std::cout interprets those. std::cout won’t exhibit that behavior for pointers to other types of types. Hi Alex, many thanks for the efforts put into these tutorials. They’re so much clearer on the concepts than the books I’ve came across! I understand that std::cout implicitly inteprets a char* pointer as the array’s string value. In this case, how do I find out what the memory address of the read only memory variable created as the & operator only gives me the address of the pointer? Thanks. You could try casting it to a void pointer and printing that/ Your website is awesome. Incredible! Hi Alex, you’re doing a wonderful job with these tutorials!!! In one of the comments you mentioned: "String literal “Alex” is treated as a C-style array of const chars. As you’ve learned, arrays can decay into pointers to the first element of the array. Thus, const char* myName = “Alex” assigns myName the address of the first character in “Alex”." However because std::cout prints char pointers as strings I casted the pointer to a const general pointer type using a static_cast, and found that this was indeed the case! We can see proof of this in the following code: On my machine the above printed: Alex 010A9B30 010A9B30 010A9B31 010A9B32 010A9B33 As you can see the address of "Alex", which decays into a pointer to the first element of the array (in this case ‘A’), is exactly the same as the address of ‘A’. Perhaps you could consider adding this example to the lesson (as well as your comment I’ve quoted above), to facilitate the comprehension of C-style symbolic constants. Edit: in the last paragraph I was meant to write "… to facilitate the comprehension of C-style string symbolic constants". Thanks for validating this and providing some other code for other readers of the site! Since my original comment was made as a comment, I think I’ll leave this snippet in the comment section as well. You’re welcome! The only reason I suggested adding the code to the lesson is because when I read through your lessons I don’t always read through the comments. Maybe you could make a reference to the code I’ve provided. However, I’ll leave that up to you 😉 Hi Alex, One doubt regarding your explanation, > “Multiple string literals with the same content may point to the same location. Because there’s no guarantee that this memory will be writable, best practice is to make sure the string is const.” Let’s say I have this: char *name1 = “Alex”; char *name2 = “Alex”;. I tried to execute this scenario which result in segmentation fault. #include<iostream> #include<cstring> #include<stdio.h> using namespace std; int main() { char *name1 = "Alex"; char *name2 = "Alex"; name1[1] = ‘r’; cout<<name1<<endl; cout<<name2<<endl; } Output: +++++++ Segmentation fault is the segmentation fault is because i try to change the read only memory? will compiler doesnot issue any warning regarding this? Thanks and Regards, Krishna Yes, it’s likely because these got put into read-only memory and you’re trying to change them. How do I use the same pointer accross the scopes of multiple functions Thanks If you want a pointer to be available in the scope of multiple functions, you have a few options: 1) Best option: pass it as a parameters to the functions that need it 2) Worst option: declare it as a global variable Hey Alex, thx for some awesome articles about c++ I’m a little confused about the usage of const. It states that it places the string into a read-only memory. But I think that I’m still able to change whats on that memory address. For example if I do the following. I’m pretty sure that I’m misunderstanding something here. Can you give an example of something that you can do without const that isn’t possible when you use the const keyword. cout << myName; This means we’re allocating a normal (non-const) pointer named myName to a C-style string of type const char. This means the pointer treats the value being pointed to as const. However, because the pointer itself is a non-const pointer, it can be changed to point at a different string (which is what you’re doing when you assign it to string “Doe”. With the above string, you couldn’t do this: "Because there’s no guarantee that this memory will be writable, best practice is to make sure the string is const." Do you mean unwritable? If you meant that you would WANT it to be writable, wouldn’t const defeat that purpose? EDIT: I read a post of yours above and now get it. I’d like to suggest (just an innocent suggestion, not trying to be rude) that perhaps you mention that you make it const so it doesn’t become affected by what happens to other entries. I’ve updated the wording in the article to make it a little clearer. There’s a semi-colon at the end of main() block in "std::cout and char pointers" section. Fixed, thanks! Thanks for the clarification. I understand it more clearly now. Thanks again. You’ve done a great job with this tutorial. Thanks for the reply. Does it mean that the string literal "Alex", was put in a char array "variable" somewhere in the memory address prior to assigning it to the pointer? I am somehow confused how it skips the process of assigning this string literal "Alex" in a char array "variable" initialization. But the rest of the process I now understand. Yes. String literals get placed into (usually read-only) memory at program startup. This happens automatically. I am just a little confused about the program below: In the previous lessons, you taught that pointers only hold memory address thus, we can’t initialized it with a value other than the memory address of that value. But how come the pointer "myName" is initialized with a string. Although, arrays are somehow identical with pointers as the previous lessons denotes but different is size etc., and C-strings are of array type, is this has something to do with it? Thanks. String literal “Alex” is treated as a C-style array of const chars. As you’ve learned, arrays can decay into pointers to the first element of the array. Thus, const char* myName = “Alex” assigns myName the address of the first character in “Alex”. We can then pass this to std::cout, which knows that char pointers should be printed as strings. According to the tutorial, the pointer myString in the following snippet is supposed to point to a ‘constant’ string. const char *myString = "Name"; As I understand, a ‘constant’ is not modifiable. What confuses me is that if myString points to a ‘constant’ string why can I change it using the following snippet: const char *myString = "Name"; myString = "Andy"; std::cout << myString; I do not get any compiler errors and it prints out: Andy Also I think there is something wrong with the following sentence, or there is something that I do not get it: “Multiple string literals with the same content may point to the same location. Because there’s no guarantee that this memory will be writable, best practice is to make sure the string is const.” Alright! I think I resolved my confusion. In the assignment myString="Andy"; only the pointer myString changes and points to a new string. But the constant string "Name" does not change in the memory. However, this brings up another question. After the above assignment I loose the address of the constant string "Name" which is sitting somewhere in the memory. Since this string was defined to be constant, its corresponding memory should not be assigned to another application as long as it does not go out of scope. Does this imply memory leak? > After the above assignment I loose the address of the constant string “Name” which is sitting somewhere in the memory. Yes, unless you’ve copied the address into another pointer, once you’ve assigned myString to another string literal, the address of the original string literal is lost. > Since this string was defined to be constant, its corresponding memory should not be assigned to another application as long as it does not go out of scope. Does this imply memory leak? Not really. A “memory leak” means we’ve lost track of some bit of dynamically allocated memory that now can’t be returned to the OS for reassignment to another program while your program is running. String literals aren’t dynamically allocated, and there’s no way to return them to the OS. They get set up when your program starts, and destroyed when your program ends, so your program owns that memory for the entire time it’s running, whether you’re using it or not. The thing to note here is that myString points to a const string (of type const char*). It is not a const pointer itself! This means the pointer can be changed to point at another string, which you do in your example by assigning it to a different string literal.. So when you change the value of name1, you end up inadvertently changing the value of any other string pointing to that location (in this case, name2). Because of this, it’s really only safe to use C-style strings for “read-only” purposes. I’m using Xcode 7.1 - when I try: I don’t get the error that you did. Instead I get ‘Q’ without the rest. Is this something that XCode has built-in to fix that issue? I doubt it. It’s more likely that the memory address after variable c contained a 0, which std::cout interpreted as a terminator, so it only printed the ‘Q’ and stopped. Alex I am unable to understand this "However &c has type char*". Isn’t &c an address. So how come it is a pointer. The address-of operator (&) returns the address as a pointer derived from underlying type (e.g. taking the address of an int variable returns an int pointer). hey thanks alex.. when code gets longer these small error or small imporatnt issue becomes nightmare i modified my program according to your suggestion and it saves a lot of runtime and runtime error and preincrement helps too it saves time and one thing more i m missing here was to define limit of no of shifts.. it gives some direction to while loop. if(shift>25||shift<0) break; and yes you are absolutely correct i saved my code without commenting and day after i opene it again it takes me years to realize what is going on with my code? what is this?. I will never forgot to commenting my code now i am finding how all these things are life saver. Yes, I’m always surprised how quickly I forget what my code was intended to do. A few seconds commenting here and there can save minutes or hours later. Adjactely. Hey!! alex please help me to figure out run time error in this program i just don’t know program is running smoothly but still there is some run time error. #include<iostream> #include<string> using namespace std; int main(){ int cases,count=1,shift; string a; int arr[27]; cout<<"ENTER NO OF CASEA"<<endl; cin>>cases; while(count<=cases){ cin>>a; cin>>shift; for( int i=0;i<a.size();i++){ arr[i]=a[i]; arr[i]=arr[i]-shift; if(arr[i]>90) arr[i]=arr[i]-90+64; if(arr[i]<65) arr[i]=90-64+arr[i]; a[i]=arr[i]; } cout<<a<<endl; count++; } return 0; } Thank you. What is this program supposed to do? very much thanks for reply. the problem is to shift each letter 2 places further through the alphabet (e.g. ‘A’ shifts to ‘C’, ‘R’ shifts to ‘T’, etc.). At the end of the alphabet we wrap around, that is ‘Y’ shifts to ‘A’. We can, of course, try shifting by any number. The input contains several test cases. The first line of input contains an integer variable that indicates the number of test cases. Each test case is composed by two lines. The first line contais a string that is a codified sentence. This string will contain between 1 and 50 characters, inclusive. Each character is an uppercase letter (‘A’-‘Z’), that is the codified sentence to this modified string. The second line contains the number of right shift, this value is between 0 and 25, inclusive. Okay then. First, you need much better prompting to the user as to how to use the program. Second, this program desperately needs some comments indicating what it’s doing. Third, why are you using variable arr? Why don’t you just modify variable a? Fourth, arr[i] -= arr[i] - 90 + 64; could be rewritten as arr[i] -= 32; which is much easier to understand. arr[i] -= arr[i] - 90 + 64; arr[i] -= 32; Finally, it looks like you’re handling upper case letters okay, but not lower case letters. So when do you prefer "const char* string" over "std::string string". Is it just personally preference or is there a time and place for each of them? Personally, I only use const char* if I’m hardcoding a string that will only be displayed (e.g. the application name). Otherwise, std::string for everything (or my own string class). Awesome…we’ll wait. May be a typo here: "Why did the int array print an address, but the strings printed strings? should be: "Why did the int array prints an address, but the char array printed string?" I think your wording is clearer. Updated, thanks! Can you add a lesson describing smart pointers. I found this in primer(C++ primer) but unable to understand what it is. Thanks. Already on my to-do list. Probably won’t get to it until September though. 🙁 On the first line below the "std::cout and char pointers" headline - I believe you meant to write std::cout instead of std::string. As in "At this point, you may have noticed something interesting about the way std::COUT handles pointers of different types.” Yes, thank you for pointing out the typo! Name (required) Website
http://www.learncpp.com/cpp-tutorial/6-8b-c-style-string-symbolic-constants/
CC-MAIN-2017-26
refinedweb
4,247
63.19
Posted 14 Nov 2007 Link to this post Posted 16 Nov 2007 Link to this post: public class MyWebPart : WebPart{ protected override void CreateChildControls() { base.CreateChildControls(); RadGrid grid = new RadGrid(); grid.ID = "myGrid"; grid.RadControlsDir = "~/_layouts/RadControls"; /* populate your grid based on your requirements */ Controls.Add(grid); } protected override void RenderWebPart(HtmlTextWriter output) { EnsureChildControls(); RenderChildren(output); }} All features of our grid control should be available under SharePoint environment as well. Also verify that you are using the latest grid version (5.0.1) and check whether you are using a custom Master Page and the asp:ContentPlaceHolder that contains the WebPartZone resides outside the <form> tag of the page. RadGrid needs to be inside a Form with runat=server to work properly.If so, please modify your Master Page or change the PlaceHolder / WebPartZone so that RadGrid is inside the <form> tag. This should solve your problem.Best regards, Stephent
http://www.telerik.com/forums/radgrid-in-sharepoint-site
CC-MAIN-2017-13
refinedweb
150
50.43
Among the requested features in the various forums for Azure Mobile Services, the usage of portable libraries has popped up quite often. We now have that support, which unifies the managed clients for the Windows Store and Windows Phone 8 platforms – and we’re also adding support for Windows Phone 7.5 as well. Johan Laanstra wrote a great post explaining the architecture of the new packages, so I won’t repeat what he wrote. However, since there were some differences between the Windows Phone 8 and the Windows Store SDKs, unifying them meant some breaking changes. We felt that the grief we’ll take for them is worth, given the gains we can get by the platform unification, and we also used this opportunity to make some other changes to the client SDK to make it more polished before the general availability of the service. This post will try to list to the best of my knowledge the changes which will need to be addressed for apps using the new client. Notice that we’ll still support the “non-portable” clients for some more time, but it will be discontinued likely before the Azure Mobile Services goes out of preview mode and into a general availability, This is the grouped list of changes, along with the updates one needs to make to their projects to account for them. This is the place where the majority of the changes were made. For the Windows Store SDK, conversion between the typed objects and the JSON which was actually transferred over the wire was done via a custom serializer which converted between the two formats. The serializer was fairly simple, and could only deal with simple types (numbers, strings, dates and,Boolean values). To support more complex types (unsupported primitives, arrays, complex objects), we’d need to provide a custom implementation of the IDataMemberJsonCoverter interface, and decorate the appropriate member with the [DataMemberJsonConverter] attribute. Even simple things such as enumerations were not supported. With this new client, all the custom serialization code goes away, as we’ll be using the JSON.NET serializer, and by that move we gain all of the support of that great serializer. That means that complex types, arrays, enumerations will just work. The new client also exposes the serializer settings which allow the developer to fine-tune the output data, including adding custom converters and changing policies such as default value serialization. Now for the list of changes: If I remember more or if you find one which is not listed here, please add a comment and I’ll update this post. When performing CRUD operations in a managed client, usually we’d create a data type to store our information (e.g., Person, Order, etc.) and pass them to the Insert/Read/Update/Delete operations. We could also work directly with JSON data, and the table would support those as well. In the Windows Store client the SDK used the classes in the Windows.Data.Json namespace, native to the WinRT platform. However, those classes were not present in the Windows Phone 8, so that SDK was already using the JSON.NET classes from the Newtonsoft.Json.Linq namespace (JToken / JArray / JValue / JObject). To move to a common set of classes, now all managed libraries use the JSON.NET classes, including the Windows Store apps. And the list of changes: Again, I’ll update the post if I can remember (or if you can add a comment) of any additional changes. Service filters are an advanced concept which implement a pipeline over the request / response. There is already such a pipeline in the HttpClient libraries – and since it has recently been made available for downlevel platforms (it originally only worked for .NET 4.5 and .NET 4.0) the Mobile Services SDK can now use this existing code instead of creating yet another pipeline. And the changes: Here’s an example of a service filter converted to a message handler. The filter will add a custom header to the request, and change the response status code (useful for testing the behavior on unexpected responses from the server). First the service filter. And the same code implemented with a delegating handler: For more information on the HttpClient primitives, check the blog post from the BCL team. Those are the other minor changes in the library: That should be it. Please start using the new libraries and let us know what you think! We still have some (although not much) time to react to user feedback before we have to lock the API down as we move to the general release.
http://blogs.msdn.com/b/carlosfigueira/archive/2013/03/14/azure-mobile-services-managed-client-upcoming-breaking-changes.aspx
CC-MAIN-2015-48
refinedweb
773
60.95
(8) Anubhav Chaudhary(4) Sourabh Somani(3) Sagar Pardeshi(3) Vithal Wadje(3) RamaSagar Pulidindi(3) Ashwani Tyagi(3) Raj Kumar(2) Raichand Ray(2) Akshay Phadke(2) Nimit Joshi(2) Syed Shanu(2) Sibeesh Venu(2) Harpreet Singh(2) Jignesh Trivedi(2) Jeetendra Gund(2) Abhay Shanker(2) Sourav Kayal(2) Satya Prakash(2) Mahender Pal(1) Swaraj Ketan Santra(1) Vignesh Ganesan(1) Nishan Aryal(1) Alagunila Meganathan(1) Ehsan Sajjad(1) Allen O'neill(1) Harsh D(1) Prakash Tripathi(1) Madhan Raghu(1) Sahil Saini(1) Durgaprasad Yadav(1) Shakti Saxena(1) Manpreet Singh(1) Priyaranjan K S(1) Nilesh Jadav(1) Rahul Prajapat(1) Vijay Prativadi(1) Emiliano Musso(1) Pradeep Sahoo(1) Atanas Atanasov(1) Prasham Sabadra(1) Ratnesh Singh(1) Rahul Saxena(1) Gaurav Kumar Arora(1) Anas Chaudhary(1) Ck Nitin(1) Joginder Banger(1) Sumit Bajaj(1) Abhishek Jaiswal :)(1) Christian Felix(1) Akhil Garg(1) Arunava Bhattacharjee(1) Abhishek Yadav(1) Santosh Gadge(1) Prerana Tiwari(1) Ritesh Sharma(1) Ehtesham Mehmood(1) Gagan Bansal(1) Vikrant More(1) Satendra Singh Bhati(1) Pawan Pandey(1) Veena Sarda(1) Vijai Anand Ramalingam(1) Iftikar Hussain(1) Sanjeeb Lenka(1) Ashish Verma(1) Rahul Sharma(1) Nitin Bhardwaj(1) Resources No resource found. How To Use Sort And SortByColumn Functions In Microsoft PowerApps Oct 21, 2016. In this article, we are going to see how to use Sort and SortByColumn functions in Microsoft PowerApps... CRUD, Paging, Sorting, Searching With AngularJS In MVC Apr 28, 2016. In this article you will learn about CRUD, Paging, Sorting, Searching with AngularJS in MVC.. Paging And Sorting In jTable Using MVC Apr 09, 2016. In this article I will explain paging and sorting in jTable using MVC Paging And Sorting In ASP.NET MVC Apr 06, 2016. In this article we will learn how we can perform paging and sorting in MVC.. Sort JSON Object Array Based On A Key Attribute In JavaScript Oct 19, 2015. In this article you will learn about sorting JSON Object Array based on a Key Attribute in JavaScript. GridView Sorting in ASP.Net Using C# Jul 13, 2015. This article shows how to deal with the Sorting Event in GridView. Overview of Collection, Array List, Hash Table, Sorted List, Stack and Queue Jul 04, 2015. This article provides an overview of Collections, Array Lists, Hash Tables, Sorted Lists, Stacks and Queues. Interactive Sorting For SSRS Report May 27, 2015. This article shows how to use interactive sorting for a SSRS report. Sort a JSON Array Programmatically by a Property May 27, 2015. This article shows how to sort a JSON array programmatically by a property. Sort and Filter CSV Files With DataTable and DataView May 22, 2015. In this article we will learn how to Sort and Filter CSV files with a DataTable and DataView. Using Ng-grid in AngularUI Pages May 20, 2015. This article explains the usage of ng-grid in AngularJS. Implement Search, Paging and Sort in MVC 5 May 20, 2015. This article shows how to implement searching, paging, and sorting functionality in MVC 5 web applications. jQuery Grid With ASP.Net MVC Apr 19, 2015. This article shows how to easily implement paging, sorting, filtering and CRUD operations with the jQuery Grid Plugin in ASP.NET MVC with bootstrap. Clustered Tables Vs Heap Tables in SQL Server Apr 07, 2015. This article explains the differences between Clustered Tables and Heap Tables in SQL Server. Exploring "Popular Items" of Web Part Mar 25, 2015. In this article I am exploring the “Popular Items” web part and I want to see on which managed property this web part does the sorting.. Sorting in C# Feb 28, 2015. In this article we will learn how to sort a list of simple and complex types. Paging and Sorting in MVC4 Using PagedList Feb 24, 2015. This article shows how to do paging and sorting in MVC4 using a PagedList. Discussing Natural Sorting Using jqGrid and ASP.Net Jan 24, 2015. In this article you will learn how to use Natural Sorting using jqGrid and ASP.NET. Parallel Sorting, Exact Numeric Operations and Stamped Lock in Java 8 Jan 16, 2015. This article describes some of the new features of Java 8 Find Ordered Year, Month and Day From Date in SQL Server Jan 11, 2015. In this article I'll tell you how to find year, month and day from a date separately and sort them. Garbage Collection In Depth Jan 05, 2015. This article looks at Garbage Collection in depth. WPF 4.5: Live Shaping Nov 20, 2014. In this article you will learn Live Shaping in WPF 4.5.. .NET Memory Management Oct 29, 2014. In this article, I am giving you a broad idea of how the garbage collector works in Microsoft's implementation of the .NET Framework.. Various Cache Clearing Methodologies Oct 10, 2014. This article contains various sorts of cache clearing approaches, their pros and cons and browser cache clearing options. Display and Sort Data Using GridMVC DLL Oct 07, 2014. In this demo you will learn how to use Grid.Mvc. Its a third party grid or table that you may sort your data.. Sort Dictionary in C# Oct 07, 2014. In this article you will learn how to sort a Dictionary in C#. Sorting and Filtering in Data Table Sep 15, 2014. This article explains sorting and filtering in a Data Table. All About Sorting in C# Sep 04, 2014. In this article you will learn how to use IComparable<> or IComparer<> and how it can be replaced by LINQ.. Optimized Data Binding, Paging and Sorting in ListView Control Jul 28, 2014. In this article you will learn how to optimize Data Binding, Paging and Sorting in a ListView control. Document Properties - Sort in QliView Jul 09, 2014. This article provides an introduction to sorting In QlikView applications. Sorting List of Complex Types in C# Jun 23, 2014. This article is related to sorting of lists in C# containing complex objects. Pagination, Sorting and Filtering in SPGridView Apr 22, 2014. In this article I explain how you can achieve Pagination, Sorting and Filtering in SPGridView. Paging and Sorting in ASP.NET GridView Apr 20, 2014. In this article I will tell you about Paging and Sorting in an ASP.NET GridView. Basic C# Programming Problem and Solutions: Part 3 Mar 01, 2014. This article is for the beginners who have just begun programming in the C# language with solutions for all the basic problems of C# programming. This is Part 3. Work With GridView Using Entity Framework Feb 23, 2014. This is a basic GridView (with insert, edit, delete, paging, sorting etc.) tutorial using Entity Framework. JS Grid Control SharePoint Feb 05, 2014. This article exlains the JS Grid control (aka SPGridView that inherits from the ASP.NET GridView) that is new in SharePoint 2010. Paging and Sorting in Gridview Jan 27, 2014. In this article we will learn about implementing paging and sorting in a GridView for displayinig many records in a GridView. Demonstrating Backbone.js: Create Students Directory Part 3 Jan 20, 2014. In this article we will see how to use Backbone.js in a simple student directory app with sorting. Demonstrating Backbone.js: Create Students Directory Part 2 Jan 19, 2014. In this article we will see how to use Backbone.js in a simple student directory app with sorting. Apply Sorting Using AngularJS Jan 15, 2014. In this article I will tell you how to do sorting using AngularJS. Time and Distance Delay While Reordering Elements in List Using jQuery Jan 08, 2014. This article will explain time and distance delay while reordering elements in a List using jQuery. Demonstrating Backbone.js: Create Students Directory Part 1 Jan 07, 2014. In this article we will see how to use Backbone.js in a simple student directory app with sorting. Sorting in AngularJS Jan 03, 2014. This article describes sorting and OrderBy filtering in AngularJS. Looking Deep Into Storage Structure For SQL Server Dec 25, 2013. This article is looking deep into storage structures starting with the Heap table. This is something to become familiar with as part of the basics of SQL Server internals. Paging, Searching And Sorting In ASP.NET MVC 5 Dec 20, 2013. This article explains how to do sorting, searching and paging in a MVC 5 application with Entity Framework 6 in Visual Studio 2013. Garbage Collection in Java Nov 13, 2013. Java has very strong memory management. In Java, when an object is not of some use, or we can say that we do not need that object in the future, then it destroys that specific object. The amount of memory is now free for any other use that was occupied previously. This entire process is done by the Garbage Collector in Java Apply Sort Function on Observable Array Using KnockoutJS Oct 22, 2013. In today's article I will tell you how to apply a Sort Function on an Observable Array using KnockoutJS. Generic Collection Classes in C# Sep 02, 2013. The collections the System.Collections.Generic namespace are type safe and this article explains them.. ULS Log Viewer - Part 2 Aug 06, 2013. In continuation with Part 1 on the ULS Log Viewer we will see more options to sort, filter errors in the ULS Log Viewer. ULS Log Viewer is a very basic tool to monitor errors, warning and issues in a SharePoint Farm. Sorting Data in LightSwitch 2012 Jul 30, 2013. This article shows how to sort data in a LightSwitch Application (Visual C#) in Visual Studio 2012. How to Set Custom Sort Order For Taxonomy Terms in SharePoint 2013 Jul 24, 2013. In this article you will see how to set a custom sort order for the taxonomy terms in SharePoint 2013 using the server object model. Creating List and Detail Screen Application in LightSwitch 2012 Jul 05, 2013. In this article describes how to create a List and Detail Screen in a LightSwitch application using Visual Studio 2012. Searching, Sorting and Paging Using SQL Query Jun 25, 2013. This article shows how to use a SQL query to perform searching, sorting and paging by one query. Sorting In Java Collections Work Jun 04, 2013. In this article we discuss Sorting in Java collection.. Sort and Filter Data on Screen in LightSwitch 2012 May 01, 2013. In this article you will learn how to sort and filter data on screen using query designer. Querying and Filtering Data Using LightSwitch in VisualStudio 2012 Apr 16, 2013. This article describes how to add, remove and modify a query. We also describe filtering, sorting and the use of parameters. Heap Sort In Java Apr 05, 2013. In today's article we discuss Heap Sort In Java. Radix Sort In JAVA Apr 04, 2013. In today's article we discuss the Radix Sort In Java. Shell Sort in JAVA Apr 03, 2013. In today's article we discuss Shell Sort in Java. Quick Sort in Java Apr 02, 2013. In today's article we discuss Quick Sort in Java. Merge Sort in JAVA Apr 01, 2013. In today's article we discuss the Merge Sort using Java. Selection Sort and Insertion Sort In JAVA Mar 30, 2013. In today's article you learn about Selection Sort & Insertion Sort in Java. What Is Sorting & Bubble Sort In JAVA Mar 29, 2013. In today's article we discuss what sorting is and discuss the bubble sort in detail with an example in Java. Bubble Sort Program Using C# Mar 26, 2013. In this article I explain how to write a program for doing a bubble sort using C#. Sorting in the Search Data Screen Using LightSwitch 2011 Mar 07, 2013. This article describes how to sort data in a Search Data Screen using LightSwitch 2011. Sort Array in Ascending Order in Windows Store App Feb 27, 2013. In this article explain how to sort an array in ascending order in a Windows Store App. Sort Array in Descending Order in Windows Store App Feb 27, 2013. In this article I will explain how to sort array in descending order in Windows Store App. Array Object In TypeScript: Part 5 Jan 16, 2013. In this article, you will learn about the array object method in TypeScript. About heap-sort NA File APIs for .NET Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!
http://www.c-sharpcorner.com/tags/heap-sort
CC-MAIN-2017-34
refinedweb
2,097
67.15
The first version of my article was pretty messy, and Andre helped rewrite it so that it was cleaner and pure. Why Cycle.js? It's pretty neat in how it lets you write your application in terms of data streams (implemented in RxJS) using Observables that return a VDOM tree, and it's in many ways "the next step" to what I described in my previous post "Using RxJS for data flow instead of Flux with React". There are three big differences from React: - No "component lifecycle" -- in React, I abuse the component lifecycle in order to do things after a "logical component" has been rendered, so that I can manipulate the DOM nodes in the document directly. But in return, because of the large cost of these component lifecycle events (and React-style mixins), if you want to render a large number of items, you have to get pretty creative with how you limit component rendercalls. - No component state -- in React, I might store a lot of data that only the component cares about, but then makes things more tricky to debug, as app state is a product of app state + the sum of all component states. - Write functions, not class/object definitions -- It's very convenient to just create React component definitions and stick them into other components' rendermethods and all, but it is very heavy compared to a simple function that returns VDOM trees. I think the two features in React make React very easy to use, but are quite dangerous and really annoying to debug. There are definitely a lot of people who are switching to a "props-only" approach to React components, but you still do deal with everything else being there. Well, not that we don't already restrict ourselves elsewhere. Well, we might as well get started with the actual code. Code time Initial project setup Let's get some basic stuff set up in our project: src main.js .gitignore index.html package.json webpack.config.js I use webpack to build my javascripts, babel to do my ES6 compilation, and npm to download my packages. Download away with npm i -D [module_name]: Set up your webpack config: Set up your npm start task: Write some boilerplate HTML for index.html: Updated project setup This used to use a very lazy setup, but Andre helped turn it into a proper Model-View-Intent application. ▾ src/ ▾ models/ main-model.js -- our main app model as a function of our actions stream make-visible-indices.js -- function for aggregating streams to make the visible indices stream ▾ views/ main-view.js -- the main view of our app as a function of our state stream tbody.js -- a simple function for calculating my tbody thead.js -- another simple function for calculating my thead intent.js -- a function for the intent, as a function of our DOM object that we can use to create an object of streams main.js -- the main entry point of our app Getting started/app bootstrap import Cycle from '@cycle/core'; // bring in CycleJS core stuff import CycleWeb from '@cycle/web'; // bring in CycleJS Web driver for DOM interaction and whatnot import intent from './intent'; // bring in the intent in our app import model from './models/main-model'; // same for model import view from './views/main-view'; // same for view function main({DOM}) { let actions = intent(DOM); // supply the DOM object to intent to get the actions let state$ = model(actions); // then feed the actions object of streams to model to get our current state let vtree$ = view(state$); // then feed our state into the view to get the snapshot view of that state return { DOM: vtree$ }; // return this vtree stream the DOM driver to consume } let drivers = { DOM: CycleWeb.makeDOMDriver('#app') }; let drivers = { DOM: CycleWeb.makeDOMDriver('#app') // take over the main app container to render my VDOM to }; Cycle.run(main, drivers); // run Cycle.js, like React.render in a way, using the main function defined above Intent Our application only has a single action to be handled. intent.js function intent(DOM) { let actions = { userScrolled$: DOM.get('#scroll-table-container', 'scroll') .map(e => e.srcElement.scrollTop) }; return actions; } export default intent; The DOM object comes from main, where we can use the get method of this object to get our rendered node so that we can handle scroll events. Model This is where we take the actions stream and create a state stream based on that. model.js import {Rx} from '@cycle/core'; import makeVisibleIndices$ from './make-visible-indices'; function model(actions) { let tableHeight$ = Rx.Observable.just(500); let rowHeight$ = Rx.Observable.just(30); let columns$ = Rx.Observable.just(['ID', 'ID * 10', 'Random Number']); let rowCount$ = Rx.Observable.just(10000); let scrollTop$ = actions.userScrolled$.startWith(0); let visibleIndices$ = makeVisibleIndices$( tableHeight$, rowHeight$, rowCount$, scrollTop$ ); let state$ = Rx.Observable.combineLatest( tableHeight$, rowHeight$, columns$, rowCount$, visibleIndices$, (tableHeight, rowHeight, columns, rowCount, visibleIndices) => ({tableHeight, rowHeight, columns, rowCount, visibleIndices}) ); return state$; } export default model; Making the Visible Indices Stream Of course, I'm not very original. The original algorithm was written in Eric Miller's article "Create an Infinite Scroll List with Bacon.js". // just bring in Rx from Cycle Core import {Rx} from '@cycle/core'; // get the visible indices stream as a function of the streams that make up the data for this function makeVisibleIndices$(tableHeight$, rowHeight$, rowCount$, scrollTop$) { // calculate what the first visible row will be based off the height of the rows and how far we scrolled down // limit the stream output to distinct values per click let firstVisibleRow$ = Rx.Observable.combineLatest(scrollTop$, rowHeight$, (scrollTop, rowHeight) => Math.floor(scrollTop / rowHeight) ).distinctUntilChanged(); // calculate how many rows will even be visible, i.e. how many rows fit into the height of the table let visibleRows$ = Rx.Observable.combineLatest(tableHeight$, rowHeight$, (tableHeight, rowHeight) => Math.ceil(tableHeight / rowHeight) ); // calculate the visible indices based on the above two streams and how many rows we have in our application let visibleIndices$ = Rx.Observable.combineLatest( rowCount$, visibleRows$, firstVisibleRow$, (rowCount, visibleRows, firstVisibleRow) => { let visibleIndices = []; let lastRow = firstVisibleRow + visibleRows + 1; if (lastRow > rowCount) { firstVisibleRow -= lastRow - rowCount; } for (let i = 0; i <= visibleRows; i++) { visibleIndices.push(i + firstVisibleRow); } return visibleIndices; } ); return visibleIndices$; } export default makeVisibleIndices$; My view functions And so, using the state stream we get from our model, we can render our view. views/main-view.js import Cycle from '@cycle/core'; import {h} from '@cycle/web'; import renderTHead from './thead'; import renderTBody from './tbody'; // returns a vtree stream based on this state stream function view(state$) { return state$.map(({tableHeight, rowHeight, columns, rowCount, visibleIndices}) => h( 'div#app-container', [ h( 'table#static-header-table', { style: { overflowX: 'hidden', borderBottom: '1px solid black' } }, renderTHead(columns) // get the vtree of THead as a product of columns ), h( 'div#scroll-table-container', { style: { position: 'relative', overflowX: 'hidden', borderBottom: '1px solid black', height: tableHeight + 'px', } }, h( 'table#scroll-table', { style: { height: rowCount * rowHeight + 'px' } }, renderTBody(rowHeight, visibleIndices) // same for TBody, using row heights and visible indices ) ) ] ) ); } export default view; Wrapping up As you've probably noticed, I pasted most of all 167 lines of code for this application in this article. Does that seem like a lot? The React version with components and RxJS is around the same number of lines, but uses a lot of complicated local component state to figure stuff out with the rendered DOM nodes. Overall, I really enjoyed trying out Cycle.js. It seems like a really hardcore framework at first, but it's actually quite practical and isn't too hard to use, especially if you already use React or RxJS. Though, if I had to give some complaints based on one day of use, it'd be... - Not enough fanboys -- having a huge userbase is important for being able to use other people's ideas and code (just look at React, Angular, jQuery). With a big focus in purity and reactive programming, I think this is a little punishing for people who want to write easy code, me included. - No JSX -- it's WIP, so this complaint will be addressed and go away soon, but this is important to me. Not because I need JSX, but I like using it to easily guess what I'm going to get in my output, and it's familiar. Not to mention, I can introduce React to almost any project and everyone can contribute code very easily, which will inevitably be harder with the virtual-hyperscript functions. - Not a lot of people care about reactive programming (in JS) -- I think code is simpler and easier to write using some basic Observables and Subjects with operators like Combine Latest, but a lot of people really want async single-value resolution and event emitters. I think that kind of coding is really hard to debug and follow through, but alas, that's what a lot of people code with. Maybe more articles and works like Dan Abramov's Redux will make people start to care more about different ways to do things, but who knows. Some people also love channels, but to me, that's like eating wet rice with chopsticks -- you can do it, and you can glue together chopsticks and carve out a scoop, but shit, I just want a spoon from the start. If you got this far, thanks for reading! (or for just scrolling down) Let me know on Twitter if this sucks or is kind of okay. Thanks again to Andre, who fixed this code to make it pure and much cleaner. Update #1 Andre helped fix all of my code, so I'll be rewriting a large chunk/all of this article accordingly. Update #2 Rewrote chunks of this article accordingly with the MVI bits. Update #3: React-based views Because Cycle.js is mostly just architecture that facilitates cyclical streams, it's easy to just substitute in React-based views. All of the changes are in this commit. Main differences: - I no longer have Cycle.js handling cyclical events for me, so now I use Subjects to have event handlers feed events to them. - I have the output stream output a React Element tree. - I subscribe to this output stream with a React.render for my output and target container. - I have to provide key data for React's reconciliation. There might be some real use to this other than just for having familiar React code, such as reusing some of the animation tools that are being developed for React. Otherwise, this is just a demonstration of how Cycle.js applications don't require massive buy-in to anything other than RxJS Observables. Links - Cycle.js -- - RxJS -- - My Repo for this -- Popular Posts - Using RxJS for data flow instead of Flux with React - Some reasons why you should/shouldn't consider using facebook's immutable-js with React (with Highcharts usage examples) - Making your own Flux application: The King of Boilerplate - How to make a Cycle.js + Elm hybrid Etch-a-Sketch app - Making a Haskell (Scotty) web app and putting it on Heroku
http://qiita.com/kimagure/items/d29ed7b7bdaaf6977b9a
CC-MAIN-2017-09
refinedweb
1,837
60.24
A couple of third party controls offer a way to filter the collection of the string which is most likely to be used in List Boxes or Combo Boxes or DataGrids. Here is the basic example of how one can sort the List Box value, using the string entered in the textbox. (I would skip the basics of creating WPF Application part). Have a List box (named lstEmps) with the valid string entries, as given below. For the reference, I am adding a couple of entries in the Constructor of my main Window. List<string> TestStrings = new List<string>(); lstTestFilter.Add("Developer- e1"); lstTestFilter.Add("Senior - e2"); lstTestFilter.Add("Mgr - e3"); lstTestFilter.Add("Mgr - e3"); lstTestFilter.Add("Developer- e1"); lstTestFilter.Add("Developer- e1"); lstTestFilter.Add("Developer- e1"); lstEmps.ItemsSource = TestStrings; Afterwards, define an object of CollectionView, which is a very useful class (used to sort, filter the data). Set the filter method to the one which we want to use for string finding purposes. (Make sure this method needs to have a boolean as a return type and the parameter it takes is of type Object). CollectionView view = CollectionViewSource.GetDefaultView(lstEmps.ItemsSource) as CollectionView; view.Filter = CustomFilter; //<- This makes sure that every time there is an event trigger, it tries refreshing the view it needs to call the filter. The custom filter is the substring finder method with true or false value. You can make slight modifications here in terms of the string comparison, where instead of IndexOf function, you can use String.Contains() function but remember, if you use Contains function, you will have to implement the code that handles ignoring the string cases. private bool CustomFilter(object obj) { if (string.IsNullOrEmpty(txtData.Text)) { return true; } else { return (obj.ToString().IndexOf(txtData.Text, StringComparison.OrdinalIgnoreCase) >= 0); } } Here is the text changed event, which tries to refresh the list items on each keystroke, use enter. private void txtData_TextChanged(object sender, TextChangedEventArgs e) { CollectionViewSource.GetDefaultView(lstEmps.ItemsSource).Refresh(); } How it works On each keystroke, the filter method is called where obj is the value of the items in ItemsSource of the list box. It is called for all the items in the List box. For each item in the list box’s ItemsSource, it checks if the text entered is present in the item which is being processed. If an item is present, it will only display the items containing the text. The others won’t be displayed. Output:As initially, there is no data in the textbox, it will display all the items. As soon as you hit the key characters, given below, you will only see the items containing the input string. If you like to develop the similar behavior for the List View, please refer to the link .
http://126kr.com/article/8exko5d4xvd
CC-MAIN-2017-04
refinedweb
460
58.89
I am trying to build some tools using Toolbox and Python for users who are in the ArcMap environment, in an ArcMap session. So the first thing I want to to is get a list of the feature classes and/or layers in the current "Data Frame", pass them into the Toolbox as a parameter, so that the user can then pick one (or more) of them and then begin doing stuff like comparing attributes between 2 feature classes and so forth. But the problem or challenge is that a "Workspace" is a file folder or a Geodatabase or similar and NOT a "Data Frame". And this is not handy, because to the user, the "Data Frame" is, in fact a storage place for the things they wish to do geoprocessing against. Does anyone have any ideas for developing a framework for using the Map Document, instead of traditional "Workspaces", as a place to assemble various feature classes, tables, etc. from various domains, file folders, file geodatabases, etc.? Conceptually, I need to do something like this: import arcpy mxd = arcpy.mapping.MapDocument arcpy.env.workspace = mxd And this, so I can start doing things like creating lists and other sorts of things, but in the context of the map as the current workspace. Hi Roland, There are several methods within the arcpy.mapping module which allow you to list and manipulate elements of an mxd, including listing data sources, manipulating layer and data frame properties, and even the properties of the mxd itself. For starters, a nice way to get a "quick and dirty" list of layer objects at the root level of your mxd is: import arcpy mxd = arcpy.mapping.MapDocument("Current") lyrList = arcpy.mapping.ListLayers(mxd) To create a data frame object to which you can add layers (assuming you have only one data frame): import arcpymxd = arcpy.mapping.MapDocument("Current") df = arcpy.mapping.ListDataFrames(mxd)[0] If you are dealing with lots of group layers and want to get at the data sources of all the sublayers: import arcpy mxd = arcpy.mapping.MapDocument("Current") lyrList = arcpy.mapping.ListLayers(mxd) for l in lyrList: lyrs = arcpy.mapping.ListLayers(l) for lyr in lyrs: if lyr.supports("DATASOURCE"): arcpy.addMessage(lyr.dataSource) Once you have successfully listed/created the mxd, layer, and data frame objects, they can be passed to your custom geoprocessing tool or add-in toolbar as inputs or items in a GUI combo-box, etc. I hope this is helpful and along the lines of what you were looking for. This section of the help documentation will show a lot more information about arcpy.mapping. There really is a ton you can do with it. Regards, Micah Babinski
https://community.esri.com/thread/113962-how-to-make-a-map-document-mxd-a-workspace-to-do-geoprocessing
CC-MAIN-2019-13
refinedweb
452
61.67
Hello I'm trying to understand some basics of classes that extends from other classes. I wonder if I could get some help. Assume I have the following class public class Person{ private String name; private int age; private String adress; public Person(String n, int ag, String adr){ name = n; age = ag; adress = adr; } } and this one below public class Student extends Person{ private double gpa; public Student(String n, int ag, String adr, double gpa) { super(n, ag, adr); this.gpa = gpa; } } What's the difference between these two lines of code below? The parameters are not interesting though, I'm just trying to figure out what they are instances of. Student student = new Student("name1", 20, "adress1", 50); Person student2 = new Student("name", 21, "adress2", 50); I mean in the first one it's Student student = new Student(...). On the second line there is [B]Person[/B] student2 = new Student(...). Is student2 a "Student" or "Person"? Thanks in advance. Best regards, Robin.
http://www.javaprogrammingforums.com/object-oriented-programming/26946-question-regarding-superclasses-subclasses.html
CC-MAIN-2015-11
refinedweb
165
64.41
I posted a while back on how to do your Managed Property mappings in PowerShell, so I wanted to follow up with how to add search scopes next. I have to give props to the SDK team because they have done a pretty good job documenting all of these PowerShell commands. They even provide examples which I like a lot. When trying out command sto create scopes and their associated rules, I ran into a few things that I wanted to share. You will want to put all of these commands into a .ps1 script file. You can create your script file in PowerShell-ISE or just use notepad. We start out by getting a reference to the search application. $searchapp = Get-SPEnterpriseSearchServiceApplication "Search Service Application" At this point, we are ready to create a new scope. It’s pretty simple. To create a scope, we use the New-SPEnterpriseSearchQueryScope command. Here is my command to create a scope called My Scope. One thing to note here is that DisplayInAdminUI is a required parameter. It turns out you can create hidden scopes with PowerShell even though you can’t do it through the UI. $scope = New-SPEnterpriseSearchQueryScope -Name "My Scope" -Description "My scope created in PowerShell" -SearchApplication $searchapp -DisplayInAdminUI $true We now want to create scope rules for this scope. I assign the resulting object from the above command into a variable called $scope so that we can pass it to the scope parameter of the New-SPEnterpriseSearchQueryScopeRule command. When creating a scope rule through the UI, you have four choices: All Content, Property Query, Content Source, and Web Address. We’ll start with the simplest one, All Content. For this, we just specify a RuleType value of AllContent. All commands to create new scope rules require a URL. It’s not entirely clear what this URL does since it’s not something you enter in the UI when you create a rule. From the SDK, it simply states that it “specifies the results URL that is associated with the query rule.” I guess you could give it a path to the results page in your search center. For now, I just specify the path to the server and it seems to work. New-SPEnterpriseSearchQueryScopeRule -RuleType AllContent -url -scope $scope Next, we’ll create a scope rule using the PropertyQuery Rule Type. It requires a few more parameters. The ManagedProperty parameter specifies the name of your managed property. In my example, I am going to use a property called Color. The PropertyValue parameter specifies the value. I want to see products that are red, so I’ll specify Red here. With any scope rule, you can specify whether the results from the rule should be Included, Required, or Excluded. We specify this with the FilterBehavior parameter. This parameter is required when using this PropertyType (note the SDK says it is optional). Also, when using a property query, the SearchApplication parameter is required too so just pass it the value $searchapp and it will work fine. Here is the command. New-SPEnterpriseSearchQueryScopeRule -RuleType PropertyQuery -ManagedProperty Color -PropertyValue Red -FilterBehavior Include -url -scope $scope -SearchApplication $searchapp When you execute the command it gives you some basic info about the rule you set up as well as an estimated count. Setting up a scope with a RuleType of Url took me a bit longer to figure out. This is because there is a parameter called UrlScopeType and the SDK didn’t say what value was expected there. I had to do some digging. The SDK, didn’t say what values it was expecting nor did the Get-Help command. I did some reflecting and finally found an enum that had the answer. The values it wants are Folder, HostName, or Domain. This of course makes sense when you go back and look at the UI and see the parameters you specify there. The other parameter you need to know about here is MatchingString. You specify the value to the folder, hostname, or domain you want to use. In this case I am setting up a rule for a particular subsite. New-SPEnterpriseSearchQueryScopeRule -RuleType Url -MatchingString -UrlScopeRuleType Folder -FilterBehavior Include -url -scope $scope So now we can create rules for all content, a web address, and a property query. However, if you have ever set up a scope before, you know there is one more type. That type is a content source. The SDK, didn’t have this type listed so I looked around in reflector again and found that we could specify a value of ContentSource for the RuleType parameter. However, when I tried to specify that parameter, it didn’t work. I took a look at the code and discovered that there is no code implemented to create a content source scope rule. After doing some experimenting in PowerShell, I did discover the answer, but I’ll save that for the next post where I will show you how I figured it out. Remember you can add multiple rules at a time to one scope. Just put them all in one script file and run it. Also if you need to delete your Scope, you can use the Remove-SPEnterpriseSearchQueryScope command but you have to pass it an actual scope object which you can get with the Get-SPEnterpriseSearchQueryScope command. Here is how I deleted my scopes as I was testing. $searchapp = Get-SPEnterpriseSearchServiceApplication "Search Service Application" Get-SPEnterpriseSearchQueryScope -Identity "My Scope" -SearchApplication $searchapp | Remove-SPEnterpriseSearchQueryScope You can do so much in SharePoint with PowerShell. This is just one more thing, I won’t have to manually configure any more. The SDK does a great job documenting all of the commands out there (although I would like to see that info on the UrlScopeType parameter added some time :) ). Try some of them out and you’ll be amazed at what you can accomplish. The first thing I do when creating a new project in Visual Studio (regardless of type) is change the project name, assembly name, and default namespace. I like for the names of all these to be consistent. However, I have noticed in Silverlight, you must make changes in five different places for everything to work alright otherwise you will get errors. I’m no Silverlight expert, but I thought this post would be useful for people like me who only dabble in it from time to time. When you create your new Silverlight project, right click on the project name and bring up its properties. Go ahead and change the default namespace and assembly name just like you would in any other project. In my case, I change from a namespace of SilverlightApplication1 to DotNetMafia.Silverlight.Test. Here you can see the new assembly name and default namespace. There are two other options to set here, but we will have to come back to it. At this point, we want to correct the namespace in the existing classes. Let’s start with App.xaml. I have highlighted the section, I need to change, x:Class. I’ll change it to DotNetMafia.Silverlight.Test like we see below. Now, we just need to change the namespace in the code behind file App.xaml.cs. Now, we have to do the same thing to MainPage.xaml. Change the namespace here on x:Class as well. Then, you will change the namespace of the code behind file MainPage.xaml.cs just liked we did before. At this point, your code will compile. However, it will not run. If you try to debug it you will likely get a blank page and if you are using Internet Explorer, you will probably see a script error in the toolbar. Clicking on the error, you can see the following details. I have to say they have really improved the way you view script errors. Here is the text of the error. Message: Unhandled Error in Silverlight Application Code: 2103 Category: InitializeError Message: Invalid or malformed application: Check manifest Line: 54 Char: 13 Code: 0 URI: Remember, I said we had to change an additional setting in the project properties? This is the problem here. We change the startup objects namespace but never update the project properties to match. You should be able to pick the new namespace of your startup object from the list. This is also a good time to change the name of your .XAP file if you are so inclined. Here is what my project properties looks like when I am done. At this point your application should compile and run. Now I can view my beautiful Hello World Silverlight application. Great app huh? Any how, I hope this helps should you encounter the error above or run into issues changing your namespace. It’s pretty simple to do, but you’ll definitely get errors if you don’t get all of your changes made. UPDATED 8/3/2011: DocId Enterprise Search is one of my favorite SharePoint topics to speak about. Often in my talks, I use various keyword queries to display results that people often end up asking me about. Today, I thought it would be useful to show you some of the most useful built-in keywords that you can use to troubleshoot search results or even build custom scopes with. I see people post in the forums all the time about how to do many of the queries I have in the list below, so I figure this is will be a good post to refer people to. You can use pretty much all of these with SharePoint 2010 or MOSS 2007 right out of the box (once you crawl). The ContentSource keyword is incredibly powerful. You can use it to verify that results exists for a given content source. For example, if you were having issue crawling a file share and you wanted to see if any results were present or not, you could use this keyword. Start by identifying the content source in question on your content sources page in your Search Service Application. Note the spelling of your content source exactly. If I wanted to return everything from the file share, I would issue this query. ContentSource:"File Share" On my server I get results like this. Keep in mind that you can combine these keywords with other ones. For example if I only want accounting documents on the file share, it would look like this. Accounting ContentSource:"File Share" To query all documents on the SharePoint site itself, you could use a query against the Local SharePoint Sites (Local Office SharePoint Sites on MOSS 2007) content source. Be warned that this could return a large number of results. ContentSource:"Local SharePoint Sites" Another property, more people are more familiar with is IsDocument. This handy property is a great way to filter out items that are not documents (i.e.: folders, list items, and pages). You pass a value of 1 for true. In the example below, I return all documents on my SharePoint server. IsDocument:"1" If you have spent time building custom scopes, you might be interested in the Scope keyword. This makes it easy to query everything in your scope at once. You can use this to build advanced queries or just for simple troubleshooting of the scope. In this example, I have a scope with rules only to show items from a BCS content source with a property called Color set to red. Scope:"Red Products" A lot of times people ask questions about how to just show results for a given site or site collection. Maybe even a specific document library. You can do that with contextual search, but you can also do that with the Site keyword as well. Simply pass it the URL to the specific point on your site and it will filter the results. For example, if I just want to see results from my ECM subsite, I would use the following query. Site:"" Sometimes you might want to see all documents a particular user modified. The author keyword is a great way to find things when you want to see all documents from someone that recently left the company. For example, to see all of the documents by our fictitious CFO, Christina Murphy, we would use this query. Author:"Christina Murphy" If you know you only want to see documents of a certain content type, why not query for it? You can with the ContentType keyword. For example to search all documents of my custom type called Custom Document, I would use the following query. ContentType:"Custom Document" You can also write queries based on list template such as a document library, task list, or your own custom list template with the ContentClass keyword. Simply use any known content class with the keyword (here is a list). For example, to search only items in a task list, I would issue the following query. ContentClass:"STS_ListItem_Tasks" Want to see a query that only has Excel spreadsheets? No problem. Use the FileType keyword. Don’t include the period on the extension. You can use multiple FileType keywords together to span multiple types (i.e.: xlsx and xls). FileType:"xlsx" Another keyword I will cover is Write. You use it to query documents based on modification date. You can’t take full advantage of this keyword in MOSS 2007, but in SharePoint 2010, you can do some cool things by using the new operators >,<,>=,<=. This allows you to write queries to see all documents written since the beginning of the month for example. Your date should be in quotes and make sure there is no space between the keyword and the date itself. Write>"7/1/2010" You can also query by Document Id using the DocId keyword. Here is an example looking for an item with a Document Id of YY7PPZHWQVY7-5-3. DocId:"YY7PPZHWQVY7-5-3" These are all keyword I use on a regular basis. Remember you can combine most of these together to provide vary narrow search results. You could also make use of these by writing your own advanced search control. I hope these queries are useful the next time you use Enterprise Search. If you can think of any other good ones I left out, please leave a comment. I am excited to say that I am returning to Oklahoma City next Monday (7/26) to speak about using PowerShell with SharePoint. This fun talk will show you just enough PowerShell to be dangerous. You will learn the basics of using it, how to write scripts, and even see how to build a cmdlet. The talk is at OKC CoCo at 6 pm. I look forward to seeing you all then. The. Yesterday, I showed you how to deploy a regular web part to MOSS 2007 / WSS3 that was built and packaged in Visual Studio 2010. Today, we can take that a step further and take advantage of the new Visual Web Part and deploy it the same way. If you remember, a Visual Web Part is nothing more than a glorified user control. To get started, create a new empty SharePoint project or use and existing one. If you need assistance with that, look at yesterday’s post. Then, go ahead and create a new Visual Web Part. The user control Visual Studio creates has many references to SharePoint 2010 DLLs that we simply do not need (or can use). These must be removed. Here is what it looks like when we start. <%@="VisualWebPart1UserControl.ascx.cs" Inherits="WSSWebPart.VisualWebPart1.VisualWebPart1UserControl" %> Remove any reference to a SharePoint version 14 DLL and you will have a file that looks like this. Then I’m just going to add a simple label to demonstrate our user control. Here is what it looks like after the changes. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs" Inherits="WSSWebPart.VisualWebPart1.VisualWebPart1UserControl" %> <asp:Label You can replace, the version 14 references with version 12 references if you really need them. However, I find that most of the time, I am really only using standard ASP.NET controls so they are unnecessary. That is all you have to do. Assuming you started with a solution from yesterday, you can package the project and install the .wsp file on your SharePoint 2007 server using STSADM. If you created a new project don’t forget to remember to remove the SharePoint version attribute in the Package properties (discussed in yesterday’s post). Here is what my Visual Web Part looks like running on SharePoint 2007. It’s pretty simple to do. I am able to leverage the simplicity of the Visual Web Part and take advantage of Visual Studio 2010 building my .wsp file. The more I work with Visual Studio 2010, the more I realize I can use SharePoint Project Items in previous versions of SharePoint with just a little bit of work. That. I’m filling in tonight and excited to be speaking about PowerShell. Kyle and I did this talk in Houston at SharePoint Saturday and it was a lot of fun. In this talk you’ll learn just enough to be dangerous when using PowerShell with SharePoint 2010. Come on out and see all the new ways you can mess up your SharePoint server from the command line. We’re at a new location tonight, Tulsa Tech Riverside Campus, room A-144. See you around 6:00 pm. I had the opportunity to give two talks at NWA TechFest yesterday in Rogers, AR. It was a pretty good event organized by the one and only @DavidWalker. I got to meet a lot of new people and talk about all sorts of things related to SharePoint. There were plenty of non-SharePoint people to talk to there too. As promised, I am making my slides available and they are already up on SlideShare.net. How the SharePoint 2010 Business Connectivity Services will change your life Introduction to SharePoint 2010 Enterprise Search Thanks for coming and I’m looking forward to seeing a lot of you at Tulsa TechFest this fall. Also, I’m speaking at the Tulsa SharePoint Interest Group this Monday about PowerShell, so come on by. If you build a lot of virtual SharePoint environments, you might find yourself needing some test users in Active Directory to demonstrate various things such as people search or the new social features. Sure, you can create these users by hand, but that’s very tedious. I decided to look for a programmatic way to do it. After searching the web, I found various approaches but many of them were antiquated using things like .vbs files. I wanted something a bit more modern. I wanted something in PowerShell. I stumbled upon a post by Todd Klindt which set me in the right direction. For my needs though, I needed to expand this approach just a little bit more. I want to demonstrate the Organization Brower, so I need to set the user’s manager, title, and department properties. Setting the manager property turned out to add a little bit of complexity. Before, we can work with Active Directory in PowerShell, we have to import the Active Directory module. This module is large enough to load that you actually get a progress indicator. Load it by typing the command below. Import-Module ActiveDirectory To do this, I will create a .csv file that has all of my users but one. I ran into one minor issue putting all of my users in it. If you specify the manager property on the PowerShell command we use, it requires a value and it has to be an existing user. This proved to be a problem for my fictitious CEO who did not have a manager. So let’s create my CEO first. His name is John Williams (real original I know). We will also use this as an opportunity to look at the various parameters to the New-ADUser command which creates our new account in Active Directory. New-ADUser -SamAccountName "john.williams" -UserPrincipalName "john.williams@sharepoint.local" -Name "John Williams" -DisplayName "John Williams" -GivenName "John" -SurName "Williams" -Title "CEO" -Department "Executive" -Path "OU=Test Users,DC=sharepoint,DC=local" -AccountPassword (ConvertTo-SecureString "test41;" -AsPlainText -force) -Enabled $True -PasswordNeverExpires $True -PassThru The New-ADUser commandlet has a lot of options. Only a few are required but we need to specify a few more so that when these accounts are imported into the profile store all fields are fully populated. Some of the information may seem redundant but it has to be set. When you create a new user through the Active Directory Users and Computers MMC snapin, it takes care of a lot of these defaults for you. When you create an account with PowerShell though, you have to set it yourself. Let’s look at the parameters now. SamAccountName is the traditional NT4 login name that you have come to think of. When logging in with a DOMAIN\USERNAME, it is the USERNAME. UserPrincipalName is not required but it is the Windows 2000 style login that looks like an E-mail address. Name is required and this is the name of the actual object in Active Directory (typically the user’s full name). DisplayName is optional but it should be specified because the User Profile Store in SharePoint uses it. If you don’t set the Display Name, none of your imported users in SharePoint will show a name. Many of the other parameters correspond to property names in Active Directory. GivenName is the first name. SurName is the last name. AccountPassword is the user’s password and has to be specified using the CovnertTo-SecureString commandlet. In this case I am using the password test41;. You might have noticed I skipped a few parameters. The rest really are completely optional. I just specified them because I want them to show up in People Search. This includes Title, Department, and Manager. I want my test users in a specific OU in my Active Directory, so I specify the path in LDAP notation with the Path parameter. Lastly, you need to enable the account with the Enabled parameter and for test accounts I recommend using PasswordNeverExpires. If you want more information on how to use New-ADUser, don’t forget you can use the Get-Help commandlet like this: Get-Help New-ADUser Now we’ll look at my CSV file. Here is what mine looks like. I simply started at the top of the org chart and added the users down the tree. SamAccountName,Name,GivenName,SurName,Title,Department,Manager christina.murphy,Christina Murphy,Christina,Murphy,CFO,Accounting,john.williams frank.alcock,Frank Alcock,Frank,Alcock,CIO,Information Technology,john.williams anna.stevenson,Anna Stevenson,Anna,Stevenson,Chief Legal Counsel,Legal,john.williams joy.williams,Joy Williams,Joy,Williams,Director,Human Resources,john.williams craig.johnson,Craig Johnson,Craig,Johnson,Accountant,Accounts Receivable,christina.murphy jennifer.evans,Jennifer Evans,Jennifer,Evans,Accountant,Accounts Payable,christina.murphy michael.adams,Michael Adams,Michael,Adams,IT Director,Information Technology,frank.alcock chris.white,Chris White,Chris,White,Administrator,Help Desk,michael.adams binh.le,Binh Le,Binh,Le,Technician,Help Desk,chris.white paul.smith,Paul Smith,Paul,Smith,Director of Application Development,Application Development,frank.alcock jose.cuervo,Jose Cuervo,Jose,Cuervo,Developer,Application Development,paul.smith preet.ramakrishnan,Preet Ramakrishnan,Preet,Ramakrishnan,Junior Programmer,Application Development,paul.smith richard.jackson,Richard Jackson,Richard,Jackson,Team Lead,Application Development,paul.smith The way PowerShell can read CSV files is quite cool. It automatically recognizes the header columns in the document and assigns them to variables that you can use with $_. For example, the name column in the CSV file can be accessed with $_.name. If you want to set other properties on AD user accounts, you can simply add them to your CSV file and set them later on your PowerShell command. To import the CSV file into PowerShell, use the Import-Csv command. Import-Csv .\users.csv Executing this command by itself will display what it read from your file so that you can verify everything looks correct. Here is what it looks like. If you are happy the way it looks. We can then go to the next step by using the foreach-object command to create a new user for each row it found in the CSV file. I’ll show what the rest of the script (contained in a .ps1 file) looks like and then I’ll explain what is going on. Import-Csv .\users.csv | foreach-object { $userprinicpalname = $_.SamAccountName + "@sharepoint.local" New-ADUser -SamAccountName $_.SamAccountName -UserPrincipalName $userprinicpalname -Name $_.name -DisplayName $_.name -GivenName $_.GivenName -SurName $_.SurName -Manager $_.Manager –Title $_.Title -Department $_.Department -Path "OU=Test Users,DC=sharepoint,DC=local" -AccountPassword (ConvertTo-SecureString "test41;" -AsPlainText -force) -Enabled $True -PasswordNeverExpires $True -PassThru } We start by doing the import and then piping its output to the foreach-object command. Remember, when the .csv is imported the names of the columns (specified in the first row of the CSV automatically become variables that can be access with $_. For example to get the user’s department I would do $_.Department. As I mentioned above, I wanted to set the user principal name so I create this name by concatenating my domain name @sharepoint.local to the name of the SamAccountName specified in the .CSV file. I then pass each variable to the corresponding parameters as you see above. It executes this once for each row in the file until all my accounts are created. That’s really all there is to it. Save your script as a .ps1 file and execute it in PowerShell. If all goes well, you should see a screen that is similar to the one below. When building your own user import file, remember that if you are setting the manager property, that the manager’s account has to exist in Active Directory before you set that property on employee accounts. I hope this PowerShell information is useful. Feel free to use my fictitious employees. If you add some to the list, feel free to share them. :-) UPDATE: Found a bug in my script. I left out the title. When my laptop was stolen, I was forced to rebuild a number of Virtual Machines since my new external hard disk had not come in yet for me to back them up. On my previous laptop, I was running VirtualBox 3.1.8 and my SharePoint 2010 images worked great. When I got my new laptop, I decided to grab the latest version (at the time 3.2.4). I noticed immediately that the product was rebranded from Sun VirtualBox to Oracle VirtualBox. I did have a few existing virtual hard disks in various formats (.vhd and .vmdx) so I created new virtual machines and attached them as normal. I tried to boot each one of them only to immediately receive a BSoD with a STOP error of 0x0000007F. At some point during this process, 3.2.6 came out, so I decided to upgrade. No change. After doing some research, I discovered this was hard disk controller based. I looked at my settings and realized that VirtualBox 3.2 had implemented a SATA controller and the hard disk was attached to it. I finally tracked down one of my existing configuration files to confirm that my hard disk previously were attached as IDE (PIIX4 to be specific). I reattached the hard disks to IDE and they booted fine. On my new SharePoint 2010 RTM image (Windows Server 2008 R2 x64), I noticed it wasn’t performing very well. I wondered if it had something to do with the hard disk controller, but I quickly ruled that out. What I discovered is that my CPU Utilization was almost always maxed out on the guest (the host OS was fine). The executables sqlserver.exe, owstimer.exe, and various w3wp.exe processes were consuming most of the memory. I figured it had some jobs that needed to run and let it sit overnight and the CPU utilization appeared to go down in the morning. However, as soon as I sent a single page request, the CPUs were pegged out at 100% again. The VM was pretty much unusable. I did some research and couldn’t find anything that helped. In a last ditch effort, I uninstalled 3.2.6 and went back and found version 3.1.8. I installed it, attached the same virtual hard disks, and the CPU utilization issue has been gone ever since. During the process I built another separate Virtual Machine and it had the same issue as well. Maybe it is just my issue or something else, but for now I am avoiding version 3.2.6 of VirtualBox. I haven’t had a single issue with the product yet, so this was a shock to me. I’m wondering if anyone else has had issues. I will continue to use the product but I will be skeptical of any product upgrades until I see some mention of this issue. David Walker is at it again! This time it is a TechFest in Northwest Arkansas this week on July 8th. I’m going to be doing two talks there. The first about the BCS and the second about Enterprise Search. If you’re from Tulsa, sorry you’ve already seen my BCS talk, but I won’t be offended if you go see someone else. Just tell them how great my BCS talk is. :-) After that, I’ll be talking about Enterprise Search in 2010. This intro talk will show you how to get started with Enterprise Search and most of the take-aways from the session also apply to MOSS 2007. So if you can make it come on by to the event. It should be a good one.
http://dotnetmafia.com/blogs/dotnettipoftheday/archive/2010/07.aspx
CC-MAIN-2017-13
refinedweb
5,007
65.83
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. We upgraded our primary Confluence server from 3.5.16 to 5.1.1. We are in the process of upgrading our secondary Confluence server from 3.5.16 to 5.3.4. There are different macros/plugins in use on the secondary server but we're running into issues with content not migrating to the new format (like Composition, Linking, table-plus, etc.) None of the pages have "failed" migration because a giant wiki markup box has been placed around all of the content on the page. None of the pages are marked "unmigrated-wiki-markup" either. On several pages we removed the "float" and "link-to" markup in the hopes that we could get the rest of the page to migrate properly (info is the only macro in use, the rest of content consists of headings and tables). We've attempted to re-migrate the content using these two different methods found in the documentation: with no success. Is there a way to force re-migration on pages that have all their content wrapped in a wiki markup box? If not, how do we migrate our content completely? -Teresa A quick clarification - when you say you're going from 3.5.16 to 5.1.1 (or 5.3.4), is there a reason you've skipped the recommended route of 3.5.16 -> 3.5.17 -> 5.0.2 -> 5.higher? Actually, I've found 3.5.15 or higher -> 5.0.2 works fine, so I'm not worried about that. But I've had exactly the same symptoms you have doing 3.5.x to 5.1 or above, and have never tried it again - always gone to 5.0.2 first. Have you updated your plugins before content migration? I am quite sure you did, but just a re-check. I remember we had similar issues once, and made a "force migration" tool / xwork action classes used: import com.atlassian.confluence.content.render.xhtml.migration.BatchException; import com.atlassian.confluence.content.render.xhtml.migration.macro.ContentEntityMigrationBatchTask; import com.atlassian.confluence.macro.xhtml.XhtmlWikiMarkupMacroMigrator; import com.atlassian.confluence.content.render.xhtml.migration.ContentDao; and the code for force-migration was like this: new ContentEntityMigrationBatchTask(xhtmlWikiMarkupMacroMigrator, contentDao, "Manual content migration content for pageId " + pageId).apply(entityObject, 1, 1); where entityObject is your page with un-migrated content Our upgrade path to 3.5.16 -> 4.3.7 -> 5.3.4. We successfully upgraded 3.5.16 -> 4.3.7 -> 5.1.1 in 2013 on our primary server. I'm not the person who does the Confluence upgrade, I handle the plugin upgrades and testing. I was not aware that there is a different recommended route. Will you point me to the where the recommended path is defined? Thanks! Have you see this guide: upgrade from 5.1 to 5.3.4 should be much easier after.
https://community.atlassian.com/t5/Confluence-questions/Content-dumped-into-wiki-markup-tags-on-upgrade/qaq-p/276835
CC-MAIN-2018-47
refinedweb
503
60.51
/* Data flow analysis for GNU compiler. Copyright (C) 1987, 88, contains the data flow analysis pass of the compiler. It computes data flow information which tells combine_instructions which insns to consider combining and controls register allocation. Additional data flow information that is too bulky to record is generated during the analysis, and is used at that time to create autoincrement and autodecrement addressing. The first step is dividing the function into basic blocks. find_basic_blocks does this. Then life_analysis determines where each register is live and where it is dead. ** find_basic_blocks **. ** life_analysis ** life_analysis is called immediately after find_basic_blocks. It uses the basic block information to determine where each hard or pseudo register is live. ** live-register info ** The information about where each register is live is in two parts: the REG_NOTES of insns, and the vector basic_block->global_live_at_start. basic_block->global_live_at_start has an element for each basic block, and the element is a bit-vector with a bit for each hard or pseudo register. The bit is 1 if the register is live at the beginning of the basic block. Two types of elements can be added to an insn's REG_NOTES. A REG_DEAD note is added to an insn's REG_NOTES for any register that meets both of two conditions: The value in the register is not needed in subsequent insns and the insn does not replace the value in the register (in the case of multi-word hard registers, the value in each register must be replaced by the insn to avoid a REG_DEAD note). In the vast majority of cases, an object in a REG_DEAD note will be used somewhere in the insn. The (rare) exception to this is if an insn uses a multi-word hard register and only some of the registers are needed in subsequent insns. In that case, REG_DEAD notes will be provided for those hard registers that are not subsequently needed. Partial REG_DEAD notes of this type do not occur when an insn sets only some of the hard registers used in such a multi-word operand; omitting REG_DEAD notes for objects stored in an insn is optional and the desire to do so does not justify the complexity of the partial REG_DEAD notes. REG_UNUSED notes are added for each register that is set by the insn but is unused subsequently (if every register set by the insn is unused and the insn does not reference memory or have some other side-effect, the insn is deleted instead). If only part of a multi-word hard register is used in a subsequent insn, REG_UNUSED notes are made for the parts that will not be used. To determine which registers are live after any insn, one can start from the beginning of the basic block and scan insns, noting which registers are set by each insn and which die there. ** Other actions of life_analysis ** life_analysis sets up the LOG_LINKS fields of insns because the information needed to do so is readily available. life_analysis deletes insns whose only effect is to store a value that is never used. life_analysis notices cases where a reference to a register as a memory address can be combined with a preceding or following incrementation or decrementation of the register. The separate instruction to increment or decrement is deleted and the address is changed to a POST_INC or similar rtx. Each time an incrementing or decrementing address is created, a REG_INC element is added to the insn's REG_NOTES list. life_analysis fills in certain vectors containing information about register usage: reg_n_refs, reg_n_deaths, reg_n_sets, reg_live_length, reg_n_calls_crosses and reg_basic_block. life_analysis sets current_function_sp_is_unchanging if the function doesn't modify the stack pointer. */ /* TODO: Split out from life_analysis: - local property discovery (bb->local_live, bb->local_set) - global property computation - log links creation - pre/post modify transformation */ #include "config.h" #include "system.h" #include "rtl.h" #include "basic-block.h" #include "insn-config.h" #include "regs.h" #include "hard-reg-set.h" #include "flags.h" #include "output.h" #include "except.h" #include "toplev.h" #include "recog.h" #include "insn-flags.h" #include "obstack.h" #define obstack_chunk_alloc xmalloc #define obstack_chunk_free free /* EXIT_IGNORE_STACK should be nonzero if, when returning from a function, the stack pointer does not matter. The value is tested only in functions that have frame pointers. No definition is equivalent to always zero. */ #ifndef EXIT_IGNORE_STACK #define EXIT_IGNORE_STACK 0 #endif /* The contents of the current function definition are allocated in this obstack, and all are freed at the end of the function. For top-level functions, this is temporary_obstack. Separate obstacks are made for nested functions. */ extern struct obstack *function_obstack; /* List of labels that must never be deleted. */ extern rtx forced_labels; /* Number of basic blocks in the current function. */ int n_basic_blocks; /* The basic block array. */ varray_type basic_block_info; /* The special entry and exit blocks. */ struct basic_block_def entry_exit_blocks[2] = { { NULL, /* head */ NULL, /* end */ NULL, /* pred */ NULL, /* succ */ NULL, /* local_set */ NULL, /* global_live_at_start */ NULL, /* global_live_at_end */ NULL, /* aux */ ENTRY_BLOCK, /* index */ 0 /* loop_depth */ }, { NULL, /* head */ NULL, /* end */ NULL, /* pred */ NULL, /* succ */ NULL, /* local_set */ NULL, /* global_live_at_start */ NULL, /* global_live_at_end */ NULL, /* aux */ EXIT_BLOCK, /* index */ 0 /* loop_depth */ } }; /* Nonzero if the second flow pass has completed. */ int flow2_completed; /* Maximum register number used in this function, plus one. */ int max_regno; /* Indexed by n, giving various register information */ varray_type reg_n_info; /* Size of the reg_n_info table. */ unsigned int reg_n_max; /* Element N is the next insn that uses (hard or pseudo) register number N within the current basic block; or zero, if there is no such insn. This is valid only during the final backward scan in propagate_block. */ static rtx *reg_next_use; /* Size of a regset for the current function, in (1) bytes and (2) elements. */ int regset_bytes; int regset_size; /* Regset of regs live when calls to `setjmp'-like functions happen. */ /* ??? Does this exist only for the setjmp-clobbered warning message? */ regset regs_live_at_setjmp; /* List made of EXPR_LIST rtx's which gives pairs of pseudo registers that have to go in the same hard reg. The first two regs in the list are a pair, and the next two are another pair, etc. */ rtx regs_may_share; /* Depth within loops of basic block being scanned for lifetime analysis, plus one. This is the weight attached to references to registers. */ static int loop_depth; /* During propagate_block, this is non-zero if the value of CC0 is live. */ static int cc0_live; /* During propagate_block, this contains a list of all the MEMs we are tracking for dead store elimination. ?!? Note we leak memory by not free-ing items on this list. We need to write some generic routines to operate on memory lists since cse, gcse, loop, sched, flow and possibly other passes all need to do basically the same operations on these lists. */ static rtx mem_set_list; /* Set of registers that may be eliminable. These are handled specially in updating regs_ever_live. */ static HARD_REG_SET elim_reg_set; /* The basic block structure for every insn, indexed by uid. */ varray_type basic_block_for_insn; /* The labels mentioned in non-jump rtl. Valid during find_basic_blocks. */ /* ??? Should probably be using LABEL_NUSES instead. It would take a bit of surgery to be able to use or co-opt the routines in jump. */ static rtx label_value_list; /* INSN_VOLATILE (insn) is 1 if the insn refers to anything volatile. */ #define INSN_VOLATILE(INSN) bitmap_bit_p (uid_volatile, INSN_UID (INSN)) #define SET_INSN_VOLATILE(INSN) bitmap_set_bit (uid_volatile, INSN_UID (INSN)) static bitmap uid_volatile; /* Forward declarations */ static int count_basic_blocks PROTO((rtx)); static rtx find_basic_blocks_1 PROTO((rtx, rtx*)); static void create_basic_block PROTO((int, rtx, rtx, rtx)); static void compute_bb_for_insn PROTO((varray_type, int)); static void clear_edges PROTO((void)); static void make_edges PROTO((rtx, rtx*)); static void make_edge PROTO((basic_block, basic_block, int)); static void make_label_edge PROTO((basic_block, rtx, int)); static void mark_critical_edges PROTO((void)); static void commit_one_edge_insertion PROTO((edge)); static void delete_unreachable_blocks PROTO((void)); static void delete_eh_regions PROTO((void)); static int can_delete_note_p PROTO((rtx)); static void delete_insn_chain PROTO((rtx, rtx)); static int delete_block PROTO((basic_block)); static void expunge_block PROTO((basic_block)); static rtx flow_delete_insn PROTO((rtx)); static int can_delete_label_p PROTO((rtx)); static void merge_blocks_nomove PROTO((basic_block, basic_block)); static int merge_blocks PROTO((edge,basic_block,basic_block)); static void tidy_fallthru_edge PROTO((edge,basic_block,basic_block)); static void calculate_loop_depth PROTO((rtx)); static int set_noop_p PROTO((rtx)); static int noop_move_p PROTO((rtx)); static void notice_stack_pointer_modification PROTO ((rtx, rtx)); static void record_volatile_insns PROTO((rtx)); static void mark_regs_live_at_end PROTO((regset)); static void life_analysis_1 PROTO((rtx, int, int)); static void init_regset_vector PROTO ((regset *, int, struct obstack *)); static void propagate_block PROTO((regset, rtx, rtx, int, regset, int, int)); static int insn_dead_p PROTO((rtx, regset, int, rtx)); static int libcall_dead_p PROTO((rtx, regset, rtx, rtx)); static void mark_set_regs PROTO((regset, regset, rtx, rtx, regset)); static void mark_set_1 PROTO((regset, regset, rtx, rtx, regset)); #ifdef AUTO_INC_DEC static void find_auto_inc PROTO((regset, rtx, rtx)); static int try_pre_increment_1 PROTO((rtx)); static int try_pre_increment PROTO((rtx, rtx, HOST_WIDE_INT)); #endif static void mark_used_regs PROTO((regset, regset, rtx, int, rtx)); void dump_flow_info PROTO((FILE *)); static void dump_edge_info PROTO((FILE *, edge, int)); static int_list_ptr alloc_int_list_node PROTO ((int_list_block **)); static int_list_ptr add_int_list_node PROTO ((int_list_block **, int_list **, int)); static void add_pred_succ PROTO ((int, int, int_list_ptr *, int_list_ptr *, int *, int *)); static void count_reg_sets_1 PROTO ((rtx)); static void count_reg_sets PROTO ((rtx)); static void count_reg_references PROTO ((rtx)); static void notice_stack_pointer_modification PROTO ((rtx, rtx)); static void invalidate_mems_from_autoinc PROTO ((rtx)); void verify_flow_info PROTO ((void)); /* Find basic blocks of the current function. F is the first insn of the function and NREGS the number of register numbers in use. */ void find_basic_blocks (f, nregs, file, do_cleanup) rtx f; int nregs ATTRIBUTE_UNUSED; FILE *file ATTRIBUTE_UNUSED; int do_cleanup; { rtx *bb_eh_end; int max_uid; /* Flush out existing data. */ if (basic_block_info != NULL) { int i; clear_edges (); /* Clear bb->aux on all extant basic blocks. We'll use this as a tag for reuse during create_basic_block, just in case some pass copies around basic block notes improperly. */ for (i = 0; i < n_basic_blocks; ++i) BASIC_BLOCK (i)->aux = NULL; VARRAY_FREE (basic_block_info); /* Init entry/exit data. */ ENTRY_BLOCK_PTR->aux = NULL; ENTRY_BLOCK_PTR->global_live_at_end = NULL; EXIT_BLOCK_PTR->aux = NULL; EXIT_BLOCK_PTR->global_live_at_start = NULL; } n_basic_blocks = count_basic_blocks (f); /*"); /* An array to record the active exception region at the end of each basic block. It is filled in by find_basic_blocks_1 for make_edges. */ bb_eh_end = (rtx *) alloca (n_basic_blocks * sizeof (rtx)); label_value_list = find_basic_blocks_1 (f, bb_eh_end); /* Record the block to which an insn belongs. */ /* ??? This should be done another way, by which (perhaps) a label is tagged directly with the basic block that it starts. It is used for more than that currently, but IMO that is the only valid use. */ max_uid = get_max_uid (); #ifdef AUTO_INC_DEC /* Leave space for insns life_analysis makes in some cases for auto-inc. These cases are rare, so we don't need too much space. */ max_uid += max_uid / 10; #endif VARRAY_BB_INIT (basic_block_for_insn, max_uid, "basic_block_for_insn"); compute_bb_for_insn (basic_block_for_insn, max_uid); /* Discover the edges of our cfg. */ make_edges (label_value_list, bb_eh_end); /* Delete unreachable blocks. */ if (do_cleanup) delete_unreachable_blocks (); /* Mark critical edges. */ mark_critical_edges (); /* Discover the loop depth at the start of each basic block to aid register allocation. */ calculate_loop_depth (f); /* Kill the data we won't maintain. */ label_value_list = 0; #ifdef ENABLE_CHECKING verify_flow_info (); #endif } /* Count the basic blocks of the function. */ static int count_basic_blocks (f) rtx f; { register rtx insn; register RTX_CODE prev_code; register int count = 0; int eh_region = 0; int call_had_abnormal_edge = 0; rtx prev_call = NULL_RTX; prev_code = JUMP_INSN; for (insn = f; insn; insn = NEXT_INSN (insn)) { register RTX_CODE code = GET_CODE (insn); if (code == CODE_LABEL || (GET_RTX_CLASS (code) == 'i' && (prev_code == JUMP_INSN || prev_code == BARRIER || (prev_code == CALL_INSN && call_had_abnormal_edge)))) { count++; /* If the previous insn was a call that did not create an abnormal edge, we want to add a nop so that the CALL_INSN itself is not at basic_block_end. This allows us to easily distinguish between normal calls and those which create abnormal edges in the flow graph. */ if (count > 0 && prev_call != 0 && !call_had_abnormal_edge) { rtx nop = gen_rtx_USE (VOIDmode, const0_rtx); emit_insn_after (nop, prev_call); } } /* Record whether this call created an edge. */ if (code == CALL_INSN) { rtx note = find_reg_note (insn, REG_EH_REGION, NULL_RTX); int region = (note ? XINT (XEXP (note, 0), 0) : 1); prev_call = insn; call_had_abnormal_edge = 0; /* If there is an EH region or rethrow, we have an edge. */ if ((eh_region && region > 0) || find_reg_note (insn, REG_EH_RETHROW, NULL_RTX)) call_had_abnormal_edge = 1; else if (nonlocal_goto_handler_labels && region >= 0) /* If there is a nonlocal goto label and the specified region number isn't -1, we have an edge. (0 means no throw, but might have a nonlocal goto). */ call_had_abnormal_edge = 1; } else if (code != NOTE) prev_call = NULL_RTX; if (code != NOTE) prev_code = code; else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG) ++eh_region; else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_END) --eh_region; } /* The rest of the compiler works a bit smoother when we don't have to check for the edge case of do-nothing functions with no basic blocks. */ if (count == 0) { emit_insn (gen_rtx_USE (VOIDmode, const0_rtx)); count = 1; } return count; } /* Find all basic blocks of the function whose first insn is F. Store the correct data in the tables that describe the basic blocks, set up the chains of references for each CODE_LABEL, and delete any entire basic blocks that cannot be reached. NONLOCAL_LABEL_LIST is a list of non-local labels in the function. Blocks that are otherwise unreachable may be reachable with a non-local goto. BB_EH_END is an array in which we record the list of exception regions active at the end of every basic block. */ static rtx find_basic_blocks_1 (f, bb_eh_end) rtx f; rtx *bb_eh_end; { register rtx insn, next; int call_has_abnormal_edge = 0; int i = 0; rtx bb_note = NULL_RTX; rtx eh_list = NULL_RTX; rtx label_value_list = NULL_RTX; rtx head = NULL_RTX; rtx end = NULL_RTX; /* We process the instructions in a slightly different way than we did previously. This is so that we see a NOTE_BASIC_BLOCK after we have closed out the previous block, so that it gets attached at the proper place. Since this form should be equivalent to the previous, find_basic_blocks_0 continues to use the old form as a check. */ for (insn = f; insn; insn = next) { enum rtx_code code = GET_CODE (insn); next = NEXT_INSN (insn); if (code == CALL_INSN) { /* Record whether this call created an edge. */ rtx note = find_reg_note (insn, REG_EH_REGION, NULL_RTX); int region = (note ? XINT (XEXP (note, 0), 0) : 1); call_has_abnormal_edge = 0; /* If there is an EH region or rethrow, we have an edge. */ if ((eh_list && region > 0) || find_reg_note (insn, REG_EH_RETHROW, NULL_RTX)) call_has_abnormal_edge = 1; else { /* If there is a nonlocal goto label and the specified region number isn't -1, we have an edge. (0 means no throw, but might have a nonlocal goto). */ if (nonlocal_goto_handler_labels && region >= 0) call_has_abnormal_edge = 1; } } switch (code) { case NOTE: { int kind = NOTE_LINE_NUMBER (insn); /* Keep a LIFO list of the currently active exception notes. */ if (kind == NOTE_INSN_EH_REGION_BEG) eh_list = gen_rtx_INSN_LIST (VOIDmode, insn, eh_list); else if (kind == NOTE_INSN_EH_REGION_END) eh_list = XEXP (eh_list, 1); /* Look for basic block notes with which to keep the basic_block_info pointers stable. Unthread the note now; we'll put it back at the right place in create_basic_block. Or not at all if we've already found a note in this block. */ else if (kind == NOTE_INSN_BASIC_BLOCK) { if (bb_note == NULL_RTX) bb_note = insn; else next = flow_delete_insn (insn); } break; } case CODE_LABEL: /* A basic block starts at a label. If we've closed one off due to a barrier or some such, no need to do it again. */ if (head != NULL_RTX) { /*); } bb_eh_end[i] = eh_list; create_basic_block (i++, head, end, bb_note); bb_note = NULL_RTX; } head = end = insn; break; case JUMP_INSN: /* A basic block ends at a jump. */ if (head == NULL_RTX) head = insn; else { /* ??? Make a special check for table jumps. The way this happens is truly and amazingly gross. We are about to create a basic block that contains just a code label and an addr*vec jump insn. Worse, an addr_diff_vec creates its own natural loop. Prevent this bit of brain damage, pasting things together correctly in make_edges. The correct solution involves emitting the table directly on the tablejump instruction as a note, or JUMP_LABEL. */ if (GET_CODE (PATTERN (insn)) == ADDR_VEC || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC) { head = end = NULL; n_basic_blocks--; break; } } end = insn; goto new_bb_inclusive; case BARRIER: /* A basic block ends at a barrier. It may be that an unconditional jump already closed the basic block -- no need to do it again. */ if (head == NULL_RTX) break; /*); } goto new_bb_exclusive; case CALL_INSN: /* A basic block ends at a call that can either throw or do a non-local goto. */ if (call_has_abnormal_edge) { new_bb_inclusive: if (head == NULL_RTX) head = insn; end = insn; new_bb_exclusive: bb_eh_end[i] = eh_list; create_basic_block (i++, head, end, bb_note); head = end = NULL_RTX; bb_note = NULL_RTX; break; } /* FALLTHRU */ default: if (GET_RTX_CLASS (code) == 'i') { if (head == NULL_RTX) head = insn; end = insn; } break; } if (GET_RTX_CLASS (code) == 'i') { for the eh_return_stub_label, which we know isn't part of any otherwise visible control flow. */ for (note = REG_NOTES (insn); note; note = XEXP (note, 1)) if (REG_NOTE_KIND (note) == REG_LABEL) { rtx lab = XEXP (note, 0), next; if (lab == eh_return_stub_label) ; else if ((next = next_nonnote_insn (lab)) != NULL && GET_CODE (next) == JUMP_INSN && (GET_CODE (PATTERN (next)) == ADDR_VEC || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC)) ; else label_value_list = gen_rtx_EXPR_LIST (VOIDmode, XEXP (note, 0), label_value_list); } } } if (head != NULL_RTX) { bb_eh_end[i] = eh_list; create_basic_block (i++, head, end, bb_note); } if (i != n_basic_blocks) abort (); return label_value_list; } /* Create a new basic block consisting of the instructions between HEAD and END inclusive. Reuses the note and basic block struct in BB_NOTE, if any. */ static void create_basic_block (index, head, end, bb_note) int index; rtx head, end, bb_note; { basic_block bb; if (bb_note && ! RTX_INTEGRATED_P (bb_note) && (bb = NOTE_BASIC_BLOCK (bb_note)) != NULL && bb->aux == NULL) { /* If we found an existing note, thread it back onto the chain. */ rtx after; if (GET_CODE (head) == CODE_LABEL) after = head; else { after = PREV_INSN (head); head = bb_note; } if (after != bb_note && NEXT_INSN (after) != bb_note) reorder_insns (bb_note, bb_note, after); } else { /* Otherwise we must create a note and a basic block structure. Since we allow basic block structs in rtl, give the struct the same lifetime by allocating it off the function obstack rather than using malloc. */ bb = (basic_block) obstack_alloc (function_obstack, sizeof (*bb)); memset (bb, 0, sizeof (*bb)); if (GET_CODE (head) == CODE_LABEL) bb_note = emit_note_after (NOTE_INSN_BASIC_BLOCK, head); else { bb_note = emit_note_before (NOTE_INSN_BASIC_BLOCK, head); head = bb_note; } NOTE_BASIC_BLOCK (bb_note) = bb; } /* Always include the bb note in the block. */ if (NEXT_INSN (end) == bb_note) end = bb_note; bb->head = head; bb->end = end; bb->index = index; BASIC_BLOCK (index) = bb; /* Tag the block so that we know it has been used when considering other basic block notes. */ bb->aux = bb; } /* Records the basic block struct in BB_FOR_INSN, for every instruction indexed by INSN_UID. MAX is the size of the array. */ static void compute_bb_for_insn (bb_for_insn, max) varray_type bb_for_insn; int max; { int i; for (i = 0; i < n_basic_blocks; ++i) { basic_block bb = BASIC_BLOCK (i); rtx insn, end; end = bb->end; insn = bb->head; while (1) { int uid = INSN_UID (insn); if (uid < max) VARRAY_BB (bb_for_insn, uid) = bb; if (insn == end) break; insn = NEXT_INSN (insn); } } } /* Free the memory associated with the edge structures. */ static void clear_edges () { int i; edge n, e; for (i = 0; i < n_basic_blocks; ++i) { basic_block bb = BASIC_BLOCK (i); for (e = bb->succ; e ; e = n) { n = e->succ_next; free (e); } bb->succ = 0; bb->pred = 0; } for (e = ENTRY_BLOCK_PTR->succ; e ; e = n) { n = e->succ_next; free (e); } ENTRY_BLOCK_PTR->succ = 0; EXIT_BLOCK_PTR->pred = 0; } /* Identify the edges between basic blocks., bb_eh_end) rtx label_value_list; rtx *bb_eh_end; { int i; /* Assume no computed jump; revise as we create edges. */ current_function_has_computed_jump = 0; /* By nature of the way these get numbered, block 0 is always the entry. */ make_edge (ENTRY_BLOCK_PTR, BASIC_BLOCK (0), EDGE_FALLTHRU); for (i = 0; i < n_basic_blocks; ++i) { basic_block bb = BASIC_BLOCK (i); rtx insn, x, eh_list; enum rtx_code code; int force_fallthru = 0; /* If we have asynchronous exceptions, scan the notes for all exception regions active in the block. In the normal case, we only need the one active at the end of the block, which is bb_eh_end[i]. */ eh_list = bb_eh_end[i]; if (asynchronous_exceptions) { for (insn = bb->end; insn != bb->head; insn = PREV_INSN (insn)) { if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_END) eh_list = gen_rtx_INSN_LIST (VOIDmode, insn, eh_list); } } /* Now examine the last instruction of the block, and discover the ways we can leave the block. */ insn = bb->end; code = GET_CODE (insn); /* A branch. */ if (code == JUMP_INSN) { rtx tmp; /* ??? Recognize a tablejump and do the right thing. */ (bb, XEXP (x, 0), EDGE_ABNORMAL); for (x = forced_labels; x; x = XEXP (x, 1)) make_label_edge (bb, XEXP (x, 0), EDGE_ABNORMAL); } /* Returns create an exit out. */ else if (returnjump_p (insn)) make_edge (bb, EXIT_BLOCK_PTR, 0); /* Otherwise, we have a plain conditional or unconditional jump. */ else { if (! JUMP_LABEL (insn)) abort (); make_label_edge (bb, JUMP_LABEL (insn), 0); } } /* If this is a CALL_INSN, then mark it as reaching the active EH handler for this CALL_INSN. If we're handling asynchronous exceptions then any insn can reach any of the active handlers. Also mark the CALL_INSN as reaching any nonlocal goto handler. */ if (code == CALL_INSN || asynchronous_exceptions) { int is_call = (code == CALL_INSN ? EDGE_ABNORMAL_CALL : 0); handler_info *ptr; /* Use REG_EH_RETHROW and REG_EH_REGION if available. */ /* ??? REG_EH_REGION is not generated presently. Is it inteded that there be multiple notes for the regions? or is my eh_list collection redundant with handler linking? */ x = find_reg_note (insn, REG_EH_RETHROW, 0); if (!x) x = find_reg_note (insn, REG_EH_REGION, 0); if (x) { if (XINT (XEXP (x, 0), 0) > 0) { ptr = get_first_handler (XINT (XEXP (x, 0), 0)); while (ptr) { make_label_edge (bb, ptr->handler_label, EDGE_ABNORMAL | EDGE_EH | is_call); ptr = ptr->next; } } } else { for (x = eh_list; x; x = XEXP (x, 1)) { ptr = get_first_handler (NOTE_BLOCK_NUMBER (XEXP (x, 0))); while (ptr) { make_label_edge (bb, ptr->handler_label, EDGE_ABNORMAL | EDGE_EH | is_call); ptr = ptr->next; } } }. */ for (x = nonlocal_goto_handler_labels; x ; x = XEXP (x, 1)) make_label_edge (bb, XEXP (x, 0), EDGE_ABNORMAL | EDGE_ABNORMAL_CALL); } } /* We know something about the structure of the function __throw in libgcc2.c. It is the only function that ever contains eh_stub labels. It modifies its return address so that the last block returns to one of the eh_stub labels within it. So we have to make additional edges in the flow graph. */ if (i + 1 == n_basic_blocks && eh_return_stub_label != 0) make_label_edge (bb, eh_return_stub_label, EDGE_EH); /* Find out if we can drop through to the next block. */ insn = next_nonnote_insn (insn); if (!insn || (i + 1 == n_basic_blocks && force_fallthru)) make_edge (bb, EXIT_BLOCK_PTR, EDGE_FALLTHRU); else if (i + 1 < n_basic_blocks) { rtx tmp = BLOCK_HEAD (i + 1); if (GET_CODE (tmp) == NOTE) tmp = next_nonnote_insn (tmp); if (force_fallthru || insn == tmp) make_edge (bb, BASIC_BLOCK (i + 1), EDGE_FALLTHRU); } } } /* Create an edge between two basic blocks. FLAGS are auxiliary information about the edge that is accumulated between calls. */ static void make_edge (src, dst, flags) basic_block src, dst; int flags; { edge e; /* Make sure we don't add duplicate edges. */ for (e = src->succ; e ; e = e->succ_next) if (e->dest == dst) { e->flags |= flags; return; } e = (edge) xcalloc (1, sizeof (*e)); e->succ_next = src->succ; e->pred_next = dst->pred; e->src = src; e->dest = dst; e->flags = flags; src->succ = e; dst->pred = e; } /* Create an edge from a basic block to a label. */ static void make_label_edge (src, label, flags); make_edge (src, BLOCK_FOR_INSN (label), flags); } /* Identify critical edges and set the bits appropriately. */ static void mark_critical_edges () { int i, n = n_basic_blocks; basic_block bb; /* We begin with the entry block. This is not terribly important now, but could be if a front end (Fortran) implemented alternate entry points. */ bb = ENTRY_BLOCK_PTR; i = -1; while (1) { edge e; /* (1) Critical edges must have a source with multiple successors. */ if (bb->succ && bb->succ->succ_next) { for (e = bb->succ; e ; e = e->succ_next) { /* (2) Critical edges must have a destination with multiple predecessors. Note that we know there is at least one predecessor -- the edge we followed to get here. */ if (e->dest->pred->pred_next) e->flags |= EDGE_CRITICAL; else e->flags &= ~EDGE_CRITICAL; } } else { for (e = bb->succ; e ; e = e->succ_next) e->flags &= ~EDGE_CRITICAL; } if (++i >= n) break; bb = BASIC_BLOCK (i); } } /* Split a (typically critical) edge. Return the new block. Abort on abnormal edges. ??? The code generally expects to be called on critical edges. The case of a block ending in an unconditional jump to a block with multiple predecessors is not handled optimally. */ basic_block split_edge (edge_in) edge edge_in; { basic_block old_pred, bb, old_succ; edge edge_out; rtx bb_note; int i, j; /* Abnormal edges cannot be split. */ if ((edge_in->flags & EDGE_ABNORMAL) != 0) abort (); old_pred = edge_in->src; old_succ = edge_in->dest; /* Remove the existing edge from the destination's pred list. */ { edge *pp; for (pp = &old_succ->pred; *pp != edge_in; pp = &(*pp)->pred_next) continue; *pp = edge_in->pred_next; edge_in->pred_next = NULL; } /* Create the new structures. */ bb = (basic_block) obstack_alloc (function_obstack, sizeof (*bb)); edge_out = (edge) xcalloc (1, sizeof (*edge_out)); memset (bb, 0, sizeof (*bb)); bb->local_set = OBSTACK_ALLOC_REG_SET (function_obstack); bb->global_live_at_start = OBSTACK_ALLOC_REG_SET (function_obstack); bb->global_live_at_end = OBSTACK_ALLOC_REG_SET (function_obstack); /* ??? This info is likely going to be out of date very soon. */ CLEAR_REG_SET (bb->local_set); if (old_succ->global_live_at_start) { COPY_REG_SET (bb->global_live_at_start, old_succ->global_live_at_start); COPY_REG_SET (bb->global_live_at_end, old_succ->global_live_at_start); } else { CLEAR_REG_SET (bb->global_live_at_start); CLEAR_REG_SET (bb->global_live_at_end); } /* Wire them up. */ bb->pred = edge_in; bb->succ = edge_out; edge_in->dest = bb; edge_in->flags &= ~EDGE_CRITICAL; edge_out->pred_next = old_succ->pred; edge_out->succ_next = NULL; edge_out->src = bb; edge_out->dest = old_succ; edge_out->flags = EDGE_FALLTHRU; edge_out->probability = REG_BR_PROB_BASE; old_succ->pred = edge_out; /* Tricky case -- if there existed a fallthru into the successor (and we're not it) we must add a new unconditional jump around the new block we're actually interested in. Further, if that edge is critical, this means a second new basic block must be created to hold it. In order to simplify correct insn placement, do this before we touch the existing basic block ordering for the block we were really wanting. */ if ((edge_in->flags & EDGE_FALLTHRU) == 0) { edge e; for (e = edge_out->pred_next; e ; e = e->pred_next) if (e->flags & EDGE_FALLTHRU) break; if (e) { basic_block jump_block; rtx pos; if ((e->flags & EDGE_CRITICAL) == 0 && e->src != ENTRY_BLOCK_PTR) { /* Non critical -- we can simply add a jump to the end of the existing predecessor. */ jump_block = e->src; } else { /* We need a new block to hold the jump. The simplest way to do the bulk of the work here is to recursively call ourselves. */ jump_block = split_edge (e); e = jump_block->succ; } /* Now add the jump insn ... */ pos = emit_jump_insn_after (gen_jump (old_succ->head), jump_block->end); jump_block->end = pos; if (basic_block_for_insn) set_block_for_insn (pos, jump_block); emit_barrier_after (pos); /* ... let jump know that label is in use, ... */ JUMP_LABEL (pos) = old_succ->head; ++LABEL_NUSES (old_succ->head); /* ... and clear fallthru on the outgoing edge. */ e->flags &= ~EDGE_FALLTHRU; /* Continue splitting the interesting edge. */ } } /* Place the new block just in front of the successor. */ VARRAY_GROW (basic_block_info, ++n_basic_blocks); if (old_succ == EXIT_BLOCK_PTR) j = n_basic_blocks - 1; else j = old_succ->index; for (i = n_basic_blocks - 1; i > j; --i) { basic_block tmp = BASIC_BLOCK (i - 1); BASIC_BLOCK (i) = tmp; tmp->index = i; } BASIC_BLOCK (i) = bb; bb->index = i; /* Create the basic block note. Where we place the note can have a noticable impact on the generated code. Consider this cfg: E | 0 / \ +->1-->2--->E | | +--+ If we need to insert an insn on the edge from block 0 to block 1, we want to ensure the instructions we insert are outside of any loop notes that physically sit between block 0 and block 1. Otherwise we confuse the loop optimizer into thinking the loop is a phony. */ if (old_succ != EXIT_BLOCK_PTR && PREV_INSN (old_succ->head) && GET_CODE (PREV_INSN (old_succ->head)) == NOTE && NOTE_LINE_NUMBER (PREV_INSN (old_succ->head)) == NOTE_INSN_LOOP_BEG) bb_note = emit_note_before (NOTE_INSN_BASIC_BLOCK, PREV_INSN (old_succ->head)); else if (old_succ != EXIT_BLOCK_PTR) bb_note = emit_note_before (NOTE_INSN_BASIC_BLOCK, old_succ->head); else bb_note = emit_note_after (NOTE_INSN_BASIC_BLOCK, get_last_insn ()); NOTE_BASIC_BLOCK (bb_note) = bb; bb->head = bb->end = bb_note; /* Not quite simple -- for non-fallthru edges, we must adjust the predecessor's jump instruction to target our new block. */ if ((edge_in->flags & EDGE_FALLTHRU) == 0) { rtx tmp, insn = old_pred->end; rtx old_label = old_succ->head; rtx new_label = gen_label_rtx (); if (GET_CODE (insn) != JUMP_INSN) abort (); /* ??? Recognize a tablejump and adjust all matching cases. */) if (XEXP (RTVEC_ELT (vec, j), 0) == old_label) { RTVEC_ELT (vec, j) = gen_rtx_LABEL_REF (VOIDmode, new_label); --LABEL_NUSES (old_label); ++LABEL_NUSES (new_label); } /* Handle casesi dispatch insns */ if ((tmp = single_set (insn)) != NULL && SET_DEST (tmp) == pc_rtx && GET_CODE (SET_SRC (tmp)) == IF_THEN_ELSE && GET_CODE (XEXP (SET_SRC (tmp), 2)) == LABEL_REF && XEXP (XEXP (SET_SRC (tmp), 2), 0) == old_label) { XEXP (SET_SRC (tmp), 2) = gen_rtx_LABEL_REF (VOIDmode, new_label); --LABEL_NUSES (old_label); ++LABEL_NUSES (new_label); } } else { /* This would have indicated an abnormal edge. */ if (computed_jump_p (insn)) abort (); /* A return instruction can't be redirected. */ if (returnjump_p (insn)) abort (); /* If the insn doesn't go where we think, we're confused. */ if (JUMP_LABEL (insn) != old_label) abort (); redirect_jump (insn, new_label); } emit_label_before (new_label, bb_note); bb->head = new_label; } return bb; } /* Queue instructions for insertion on an edge between two basic blocks. The new instructions and basic blocks (if any) will not appear in the CFG until commit_edge_insertions is called. */ void insert_insn_on_edge (pattern, e) rtx pattern; edge e; { /* We cannot insert instructions on an abnormal critical edge. It will be easier to find the culprit if we die now. */ if ((e->flags & (EDGE_ABNORMAL|EDGE_CRITICAL)) == (EDGE_ABNORMAL|EDGE_CRITICAL)) abort (); if (e->insns == NULL_RTX) start_sequence (); else push_to_sequence (e->insns); emit_insn (pattern); e->insns = get_insns (); end_sequence(); } /* Update the CFG for the instructions queued on edge E. */ static void commit_one_edge_insertion (e) edge e; { rtx before = NULL_RTX, after = NULL_RTX, tmp; basic_block bb; /* Figure out where to put these things. If the destination has one predecessor, insert there. Except for the exit block. */ if (e->dest->pred->pred_next == NULL && e->dest != EXIT_BLOCK_PTR) { bb = e->dest; /* Get the location correct wrt a code label, and "nice" wrt a basic block note, and before everything else. */ tmp = bb->head; if (GET_CODE (tmp) == CODE_LABEL) tmp = NEXT_INSN (tmp); if (GET_CODE (tmp) == NOTE && NOTE_LINE_NUMBER (tmp) == NOTE_INSN_BASIC_BLOCK) tmp = NEXT_INSN (tmp); if (tmp == bb->head) before = tmp; else after = PREV_INSN (tmp); } /* If the source has one successor and the edge is not abnormal, insert there. Except for the entry block. */ else if ((e->flags & EDGE_ABNORMAL) == 0 && e->src->succ->succ_next == NULL && e->src != ENTRY_BLOCK_PTR) { bb = e->src; if (GET_CODE (bb->end) == JUMP_INSN) { /* ??? Is it possible to wind up with non-simple jumps? Perhaps a jump with delay slots already filled? */ if (! simplejump_p (bb->end)) abort (); before = bb->end; } else { /* We'd better be fallthru, or we've lost track of what's what. */ if ((e->flags & EDGE_FALLTHRU) == 0) abort (); after = bb->end; } } /* Otherwise we must split the edge. */ else { bb = split_edge (e); after = bb->end; } /* Now that we've found the spot, do the insertion. */ tmp = e->insns; e->insns = NULL_RTX; /* Set the new block number for these insns, if structure is allocated. */ if (basic_block_for_insn) { rtx i; for (i = tmp; i != NULL_RTX; i = NEXT_INSN (i)) set_block_for_insn (i, bb); } if (before) { emit_insns_before (tmp, before); if (before == bb->head) bb->head = tmp; } else { tmp = emit_insns_after (tmp, after); if (after == bb->end) bb->end = tmp; } } /* Update the CFG for all queued instructions. */ void commit_edge_insertions () { int i; basic_block bb; #ifdef ENABLE_CHECKING verify_flow_info (); #endif i = -1; bb = ENTRY_BLOCK_PTR; while (1) { edge e, next; for (e = bb->succ; e ; e = next) { next = e->succ_next; if (e->insns) commit_one_edge_insertion (e); } if (++i >= n_basic_blocks) break; bb = BASIC_BLOCK (i); } } /* Delete all unreachable basic blocks. */ static void delete_unreachable_blocks () { basic_block *worklist, *tos; int deleted_handler; edge e; int i, n; n = n_basic_blocks; tos = worklist = (basic_block *) alloca (sizeof (basic_block) * n); /* Use basic_block->aux as a marker. Clear them all. */ for (i = 0; i < n; ++i) BASIC_BLOCK (i)->aux = NULL; /* Add our starting points to the worklist. Almost always there will be only one. It isn't inconcievable that we might one day directly support Fortran alternate entry points. */ for (e = ENTRY_BLOCK_PTR->succ; e ; e = e->succ_next) { *tos++ = e->dest; /* Mark the block with a handy non-null value. */ e->dest->aux = e; } /* Iterate: find everything reachable from what we've already seen. */ while (tos != worklist) { basic_block b = *--tos; for (e = b->succ; e ; e = e->succ_next) if (!e->dest->aux) { *tos++ = e->dest; e->dest->aux = e; } } /* Delete all unreachable basic blocks. Count down so that we don't interfere with the block renumbering that happens in delete_block. */ deleted_handler = 0; for (i = n - 1; i >= 0; --i) { basic_block b = BASIC_BLOCK (i); if (b->aux != NULL) /* This block was found. Tidy up the mark. */ b->aux = NULL; else deleted_handler |= delete_block (b); } /* Fix up edges that now fall through, or rather should now fall through but previously required a jump around now deleted blocks. Simplify the search by only examining blocks numerically adjacent, since this is how find_basic_blocks created them. */ for (i = 1; i < n_basic_blocks; ++i) { basic_block b = BASIC_BLOCK (i - 1); basic_block c = BASIC_BLOCK (i); edge s; /* We care about simple conditional or unconditional jumps with a single successor. If we had a conditional branch to the next instruction when find_basic_blocks was called, then there will only be one out edge for the block which ended with the conditional branch (since we do not create duplicate edges). Furthermore, the edge will be marked as a fallthru because we merge the flags for the duplicate edges. So we do not want to check that the edge is not a FALLTHRU edge. */ if ((s = b->succ) != NULL && s->succ_next == NULL && s->dest == c /* If the last insn is not a normal conditional jump (or an unconditional jump), then we can not tidy the fallthru edge because we can not delete the jump. */ && GET_CODE (b->end) == JUMP_INSN && condjump_p (b->end)) tidy_fallthru_edge (s, b, c); } /* Attempt to merge blocks as made possible by edge removal. If a block has only one successor, and the successor has only one predecessor, they may be combined. */ for (i = 0; i < n_basic_blocks; ) { basic_block c, b = BASIC_BLOCK (i); edge s; /* A loop because chains of blocks might be combineable. */ while ((s = b->succ) != NULL && s->succ_next == NULL && (s->flags & EDGE_EH) == 0 && (c = s->dest) != EXIT_BLOCK_PTR && c->pred->pred_next == NULL /* If the last insn is not a normal conditional jump (or an unconditional jump), then we can not merge the blocks because we can not delete the jump. */ && GET_CODE (b->end) == JUMP_INSN && condjump_p (b->end) && merge_blocks (s, b, c)) continue; /* Don't get confused by the index shift caused by deleting blocks. */ i = b->index + 1; } /* If we deleted an exception handler, we may have EH region begin/end blocks to remove as well. */ if (deleted_handler) delete_eh_regions (); } /* Find EH regions for which there is no longer a handler, and delete them. */ static void delete_eh_regions () { rtx insn; for (insn = get_insns (); insn; insn = NEXT_INSN (insn)) if (GET_CODE (insn) == NOTE) { if ((NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG) || (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_END)) { int num = CODE_LABEL_NUMBER (insn); /* A NULL handler indicates a region is no longer needed, as long as its rethrow label isn't used. */ if (get_first_handler (num) == NULL && ! rethrow_used (num)) { NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED; NOTE_SOURCE_FILE (insn) = 0; } } } } /* Return true if NOTE is not one of the ones that must be kept paired, so that we may simply delete them. */ static int can_delete_note_p (note) rtx note; { return (NOTE_LINE_NUMBER (note) == NOTE_INSN_DELETED || NOTE_LINE_NUMBER (note) == NOTE_INSN_BASIC_BLOCK); } /* Unlink a chain of insns between START and FINISH, leaving notes that must be paired. */ static void delete_insn_chain (start, finish) rtx start, finish; { /* Unchain the insns one by one. It would be quicker to delete all of these with a single unchaining, rather than one at a time, but we need to keep the NOTE's. */ rtx next; while (1) { next = NEXT_INSN (start); if (GET_CODE (start) == NOTE && !can_delete_note_p (start)) ; else if (GET_CODE (start) == CODE_LABEL && !can_delete_label_p (start)) ; else next = flow_delete_insn (start); if (start == finish) break; start = next; } } /* Delete the insns in a (non-live) block. We physically delete every non-deleted-note insn, and update the flow graph appropriately. Return nonzero if we deleted an exception handler. */ /* ??? Preserving all such notes strikes me as wrong. It would be nice to post-process the stream to remove empty blocks, loops, ranges, etc. */ static int delete_block (b) basic_block b; { int deleted_handler = 0; rtx insn, end; /* If the head of this block is a CODE_LABEL, then it might be the label for an exception handler which can't be reached. We need to remove the label from the exception_handler_label list and remove the associated NOTE_EH_REGION_BEG and NOTE_EH_REGION_END notes. */ insn = b->head; if (GET_CODE (insn) == CODE_LABEL) { rtx x, *prev = &exception_handler_labels; for (x = exception_handler_labels; x; x = XEXP (x, 1)) { if (XEXP (x, 0) == insn) { /* Found a match, splice this label out of the EH label list. */ *prev = XEXP (x, 1); XEXP (x, 1) = NULL_RTX; XEXP (x, 0) = NULL_RTX; /* Remove the handler from all regions */ remove_handler (insn); deleted_handler = 1; break; } prev = &XEXP (x, 1); } /* This label may be referenced by code solely for its value, or referenced by static data, or something. We have determined that it is not reachable, but cannot delete the label itself. Save code space and continue to delete the balance of the block, along with properly updating the cfg. */ if (!can_delete_label_p (insn)) { /* If we've only got one of these, skip the whole deleting insns thing. */ if (insn == b->end) goto no_delete_insns; insn = NEXT_INSN (insn); } } /* Selectively unlink the insn chain. Include any BARRIER that may follow the basic block. */ end = next_nonnote_insn (b->end); if (!end || GET_CODE (end) != BARRIER) end = b->end; delete_insn_chain (insn, end); no_delete_insns: /* Remove the edges into and out of this block. Note that there may indeed be edges in, if we are removing an unreachable loop. */ { edge e, next, *q; for (e = b->pred; e ; e = next) { for (q = &e->src->succ; *q != e; q = &(*q)->succ_next) continue; *q = e->succ_next; next = e->pred_next; free (e); } for (e = b->succ; e ; e = next) { for (q = &e->dest->pred; *q != e; q = &(*q)->pred_next) continue; *q = e->pred_next; next = e->succ_next; free (e); } b->pred = NULL; b->succ = NULL; } /* Remove the basic block from the array, and compact behind it. */ expunge_block (b); return deleted_handler; } /* Remove block B from the basic block array and compact behind it. */ static void expunge_block (b) basic_block b; { int i, n = n_basic_blocks; for (i = b->index; i + 1 < n; ++i) { basic_block x = BASIC_BLOCK (i + 1); BASIC_BLOCK (i) = x; x->index = i; } basic_block_info->num_elements--; n_basic_blocks--; } /* Delete INSN by patching it out. Return the next insn. */ static rtx flow_delete_insn (insn) rtx insn; { rtx prev = PREV_INSN (insn); rtx next = NEXT_INSN (insn); rtx note; PREV_INSN (insn) = NULL_RTX; NEXT_INSN (insn) = NULL_RTX; INSN_DELETED_P (insn) = 1; if (prev) NEXT_INSN (prev) = next; if (next) PREV_INSN (next) = prev; else set_last_insn (prev); if (GET_CODE (insn) == CODE_LABEL) remove_node_from_expr_list (insn, &nonlocal_goto_handler_labels); /* If deleting a jump, decrement the use count of the label. Deleting the label itself should happen in the normal course of block merging. */ if (GET_CODE (insn) == JUMP_INSN && JUMP_LABEL (insn) && GET_CODE (JUMP_LABEL (insn)) == CODE_LABEL) LABEL_NUSES (JUMP_LABEL (insn))--; /* Also if deleting an insn that references a label. */ else if ((note = find_reg_note (insn, REG_LABEL, NULL_RTX)) != NULL_RTX && GET_CODE (XEXP (note, 0)) == CODE_LABEL) LABEL_NUSES (XEXP (note, 0))--; return next; } /* True if a given label can be deleted. */ static int can_delete_label_p (label) rtx label; { rtx x; if (LABEL_PRESERVE_P (label)) return 0; for (x = forced_labels; x ; x = XEXP (x, 1)) if (label == XEXP (x, 0)) return 0; for (x = label_value_list; x ; x = XEXP (x, 1)) if (label == XEXP (x, 0)) return 0; for (x = exception_handler_labels; x ; x = XEXP (x, 1)) if (label == XEXP (x, 0)) return 0; /* User declared labels must be preserved. */ if (LABEL_NAME (label) != 0) return 0; return 1; } /* Blocks A and B are to be merged into a single block. The insns are already contiguous, hence `nomove'. */ static void merge_blocks_nomove (a, b) basic_block a, b; { edge e; rtx b_head, b_end, a_end; int b_empty = 0; /* If there was a CODE_LABEL beginning B, delete it. */ b_head = b->head; b_end = b->end; if (GET_CODE (b_head) == CODE_LABEL) { /* Detect basic blocks with nothing but a label. This can happen in particular at the end of a function. */ if (b_head == b_end) b_empty = 1; b_head = flow_delete_insn (b_head); } /* Delete the basic block note. */ if (GET_CODE (b_head) == NOTE && NOTE_LINE_NUMBER (b_head) == NOTE_INSN_BASIC_BLOCK) { if (b_head == b_end) b_empty = 1; b_head = flow_delete_insn (b_head); } /* If there was a jump out of A, delete it. */ a_end = a->end; if (GET_CODE (a_end) == JUMP_INSN) { rtx prev; prev = prev_nonnote_insn (a_end); if (!prev) prev = a->head; #ifdef HAVE_cc0 /* If this was a conditional jump, we need to also delete the insn that set cc0. */ if (prev && sets_cc0_p (prev)) { rtx tmp = prev; prev = prev_nonnote_insn (prev); if (!prev) prev = a->head; flow_delete_insn (tmp); } #endif /* Note that a->head != a->end, since we should have at least a bb note plus the jump, so prev != insn. */ flow_delete_insn (a_end); a_end = prev; } /* By definition, there should only be one successor of A, and that is B. Free that edge struct. */ free (a->succ); /* Adjust the edges out of B for the new owner. */ for (e = b->succ; e ; e = e->succ_next) e->src = a; a->succ = b->succ; /* Reassociate the insns of B with A. */ if (!b_empty) { BLOCK_FOR_INSN (b_head) = a; while (b_head != b_end) { b_head = NEXT_INSN (b_head); BLOCK_FOR_INSN (b_head) = a; } a_end = b_head; } a->end = a_end; /* Compact the basic block array. */ expunge_block (b); } /* Attempt to merge basic blocks that are potentially non-adjacent. Return true iff the attempt succeeded. */ static int merge_blocks (e, b, c) edge e; basic_block b, c; { /* If B has a fallthru edge to C, no need to move anything. */ if (!(e->flags & EDGE_FALLTHRU)) { /* ??? From here on out we must make sure to not munge nesting of exception regions and lexical blocks. Need to think about these cases before this gets implemented. */ return 0; /* If C has an outgoing fallthru, and B does not have an incoming fallthru, move B before C. The later clause is somewhat arbitrary, but avoids modifying blocks other than the two we've been given. */ /* Otherwise, move C after B. If C had a fallthru, which doesn't happen to be the physical successor to B, insert an unconditional branch. If C already ended with a conditional branch, the new jump must go in a new basic block D. */ } /* If a label still appears somewhere and we cannot delete the label, then we cannot merge the blocks. The edge was tidied already. */ { rtx insn, stop = NEXT_INSN (c->head); for (insn = NEXT_INSN (b->end); insn != stop; insn = NEXT_INSN (insn)) if (GET_CODE (insn) == CODE_LABEL && !can_delete_label_p (insn)) return 0; } merge_blocks_nomove (b, c); return 1; } /* The given edge should potentially a fallthru edge. If that is in fact true, delete the unconditional jump and barriers that are in the way. */ static void tidy_fallthru_edge (e, b, c) edge e; basic_block b, c; { rtx q; /* ??? In a late-running flow pass, other folks may have deleted basic blocks by nopping out blocks, leaving multiple BARRIERs between here and the target label. They ought to be chastized and fixed. We can also wind up with a sequence of undeletable labels between one block and the next. So search through a sequence of barriers, labels, and notes for the head of block C and assert that we really do fall through. */ if (next_real_insn (b->end) != next_real_insn (PREV_INSN (c->head))) return; /* Remove what will soon cease being the jump insn from the source block. If block B consisted only of this single jump, turn it into a deleted note. */ q = b->end; if (GET_CODE (q) == JUMP_INSN) { #ifdef HAVE_cc0 /* If this was a conditional jump, we need to also delete the insn that set cc0. */ if (! simplejump_p (q) && condjump_p (q)) q = PREV_INSN (q); #endif if (b->head == q) { PUT_CODE (q, NOTE); NOTE_LINE_NUMBER (q) = NOTE_INSN_DELETED; NOTE_SOURCE_FILE (q) = 0; } else b->end = q = PREV_INSN (q); } /* Selectively unlink the sequence. */ if (q != PREV_INSN (c->head)) delete_insn_chain (NEXT_INSN (q), PREV_INSN (c->head)); e->flags |= EDGE_FALLTHRU; } /* Discover and record the loop depth at the head of each basic block. */ static void calculate_loop_depth (insns) rtx insns; { basic_block bb; rtx insn; int i = 0, depth = 1; bb = BASIC_BLOCK (i); for (insn = insns; insn ; insn = NEXT_INSN (insn)) { if (insn == bb->head) { bb->loop_depth = depth; if (++i >= n_basic_blocks) break; bb = BASIC_BLOCK (i); } if (GET_CODE (insn) == NOTE) { if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG) depth++; else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END) depth--; /* If we have LOOP_DEPTH == 0, there has been a bookkeeping error. */ if (depth == 0) abort (); } } } /* Perform data flow analysis. F is the first insn of the function and NREGS the number of register numbers in use. */ void life_analysis (f, nregs, file, remove_dead_code) rtx f; int nregs; FILE *file; int remove_dead_code; { #ifdef ELIMINABLE_REGS register size_t i; static struct {int from, to; } eliminables[] = ELIMINABLE_REGS; #endif /* Record which registers will be eliminated. We use this in mark_used_regs. */ CLEAR_HARD_REG_SET (elim_reg_set); #ifdef ELIMINABLE_REGS for (i = 0; i < sizeof eliminables / sizeof eliminables[0]; i++) SET_HARD_REG_BIT (elim_reg_set, eliminables[i].from); #else SET_HARD_REG_BIT (elim_reg_set, FRAME_POINTER_REGNUM); #endif /* Allocate a bitmap to be filled in by record_volatile_insns. */ uid_volatile = BITMAP_ALLOCA (); /* We want alias analysis information for local dead store elimination. */ init_alias_analysis (); life_analysis_1 (f, nregs, remove_dead_code); end_alias_analysis (); if (file) dump_flow_info (file); BITMAP_FREE (uid_volatile); free_basic_block_vars (1); } /* Free the variables allocated by find_basic_blocks. KEEP_HEAD_END_P is non-zero if basic_block_info is not to be freed. */ void free_basic_block_vars (keep_head_end_p) int keep_head_end_p; { if (basic_block_for_insn) { VARRAY_FREE (basic_block_for_insn); basic_block_for_insn = NULL; } if (! keep_head_end_p) { clear_edges (); VARRAY_FREE (basic_block_info); n_basic_blocks = 0; ENTRY_BLOCK_PTR->aux = NULL; ENTRY_BLOCK_PTR->global_live_at_end = NULL; EXIT_BLOCK_PTR->aux = NULL; EXIT_BLOCK_PTR->global_live_at_start = NULL; } } /* Return nonzero if the destination of SET equals the source. */ static int set_noop_p (set) rtx set; { rtx src = SET_SRC (set); rtx dst = SET_DEST (set); if (GET_CODE (src) == SUBREG && GET_CODE (dst) == SUBREG) { if (SUBREG_WORD (src) != SUBREG_WORD (dst)) return 0; src = SUBREG_REG (src); dst = SUBREG_REG (dst); } return (GET_CODE (src) == REG && GET_CODE (dst) == REG && REGNO (src) == REGNO (dst)); } /* Return nonzero if an insn consists only of SETs, each of which only sets a value to itself. */ static int noop_move_p (insn) rtx insn; { rtx pat = PATTERN (insn); /* Insns carrying these notes are useful later on. */ if (find_reg_note (insn, REG_EQUAL, NULL_RTX)) return 0; if (GET_CODE (pat) == SET && set_noop_p (pat)) return 1; if (GET_CODE (pat) == PARALLEL) { int i; /* If nothing but SETs of registers to themselves, this insn can also be deleted. */ for (i = 0; i < XVECLEN (pat, 0); i++) { rtx tem = XVECEXP (pat, 0, i); if (GET_CODE (tem) == USE || GET_CODE (tem) == CLOBBER) continue; if (GET_CODE (tem) != SET || ! set_noop_p (tem)) return 0; } return 1; } return 0; } static void notice_stack_pointer_modification (x, pat) rtx x; rtx pat ATTRIBUTE_UNUSED; { if (x == stack_pointer_rtx /* The stack pointer is only modified indirectly as the result of a push until later in flow. See the comments in rtl.texi regarding Embedded Side-Effects on Addresses. */ || (GET_CODE (x) == MEM && (GET_CODE (XEXP (x, 0)) == PRE_DEC || GET_CODE (XEXP (x, 0)) == PRE_INC || GET_CODE (XEXP (x, 0)) == POST_DEC || GET_CODE (XEXP (x, 0)) == POST_INC) && XEXP (XEXP (x, 0), 0) == stack_pointer_rtx)) current_function_sp_is_unchanging = 0; } /* Record which insns refer to any volatile memory or for any reason can't be deleted just because they are dead stores. Also, delete any insns that copy a register to itself. And see if the stack pointer is modified. */ static void record_volatile_insns (f) rtx f; { rtx insn; for (insn = f; insn; insn = NEXT_INSN (insn)) { enum rtx_code code1 = GET_CODE (insn); if (code1 == CALL_INSN) SET_INSN_VOLATILE (insn); else if (code1 == INSN || code1 == JUMP_INSN) { if (GET_CODE (PATTERN (insn)) != USE && volatile_refs_p (PATTERN (insn))) SET_INSN_VOLATILE (insn); /* A SET that makes space on the stack cannot be dead. (Such SETs occur only for allocating variable-size data, so they will always have a PLUS or MINUS according to the direction of stack growth.) Even if this function never uses this stack pointer value, signal handlers do! */ else if (code1 == INSN && GET_CODE (PATTERN (insn)) == SET && SET_DEST (PATTERN (insn)) == stack_pointer_rtx #ifdef STACK_GROWS_DOWNWARD && GET_CODE (SET_SRC (PATTERN (insn))) == MINUS #else && GET_CODE (SET_SRC (PATTERN (insn))) == PLUS #endif && XEXP (SET_SRC (PATTERN (insn)), 0) == stack_pointer_rtx) SET_INSN_VOLATILE (insn); /* Delete (in effect) any obvious no-op moves. */ else if (noop_move_p (insn)) { PUT_CODE (insn, NOTE); NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED; NOTE_SOURCE_FILE (insn) = 0; } } /* Check if insn modifies the stack pointer. */ if ( current_function_sp_is_unchanging && GET_RTX_CLASS (GET_CODE (insn)) == 'i') note_stores (PATTERN (insn), notice_stack_pointer_modification); } } /* Mark those regs which are needed at the end of the function as live at the end of the last basic block. */ static void mark_regs_live_at_end (set) regset set; { int i; /* If exiting needs the right stack value, consider the stack pointer live at the end of the function. */ if (! EXIT_IGNORE_STACK || (! FRAME_POINTER_REQUIRED && ! current_function_calls_alloca && flag_omit_frame_pointer) || current_function_sp_is_unchanging) { SET_REGNO_REG_SET (set, STACK_POINTER_REGNUM); } /* Mark the frame pointer if needed at the end of the function. If we end up eliminating it, it will be removed from the live list of each basic block by reload. */ if (! reload_completed || frame_pointer_needed) { SET_REGNO_REG_SET (set, FRAME_POINTER_REGNUM); #if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM /* If they are different, also mark the hard frame pointer as live */ SET_REGNO_REG_SET (set, HARD_FRAME_POINTER_REGNUM); #endif } /* Mark all global registers, and all registers used by the epilogue as being live at the end of the function since they may be referenced by our caller. */ for (i = 0; i < FIRST_PSEUDO_REGISTER; i++) if (global_regs[i] #ifdef EPILOGUE_USES || EPILOGUE_USES (i) #endif ) SET_REGNO_REG_SET (set, i); /* ??? Mark function return value here rather than as uses. */ } /* Determine which registers are live at the start of each basic block of the function whose first insn is F. NREGS is the number of registers used in F. We allocate the vector basic_block_live_at_start and the regsets that it points to, and fill them with the data. regset_size and regset_bytes are also set here. */ static void life_analysis_1 (f, nregs, remove_dead_code) rtx f; int nregs; int remove_dead_code; { int first_pass; int changed; register int i; char save_regs_ever_live[FIRST_PSEUDO_REGISTER]; regset *new_live_at_end; struct obstack flow_obstack; gcc_obstack_init (&flow_obstack); max_regno = nregs; /* Allocate and zero out many data structures that will record the data from lifetime analysis. */ allocate_reg_life_data (); allocate_bb_life_data (); reg_next_use = (rtx *) alloca (nregs * sizeof (rtx)); memset (reg_next_use, 0, nregs * sizeof (rtx)); /* Set up regset-vectors used internally within this function. Their meanings are documented above, with their declarations. */ new_live_at_end = (regset *) alloca ((n_basic_blocks + 1) * sizeof (regset)); init_regset_vector (new_live_at_end, n_basic_blocks + 1, &flow_obstack); /* Stick these vectors into the AUX field of the basic block, so that we don't have to keep going through the index. */ for (i = 0; i < n_basic_blocks; ++i) BASIC_BLOCK (i)->aux = new_live_at_end[i]; ENTRY_BLOCK_PTR->aux = new_live_at_end[i]; /* Assume that the stack pointer is unchanging if alloca hasn't been used. This will be cleared by record_volatile_insns if it encounters an insn which modifies the stack pointer. */ current_function_sp_is_unchanging = !current_function_calls_alloca; record_volatile_insns (f); if (n_basic_blocks > 0) { regset theend; register edge e; theend = EXIT_BLOCK_PTR->global_live_at_start; mark_regs_live_at_end (theend); /* Propogate this exit data to each of EXIT's predecessors. */ for (e = EXIT_BLOCK_PTR->pred; e ; e = e->pred_next) { COPY_REG_SET (e->src->global_live_at_end, theend); COPY_REG_SET ((regset) e->src->aux, theend); } } /* The post-reload life analysis have (on a global basis) the same registers live as was computed by reload itself. Otherwise elimination offsets and such may be incorrect. Reload will make some registers as live even though they do not appear in the rtl. */ if (reload_completed) memcpy (save_regs_ever_live, regs_ever_live, sizeof (regs_ever_live)); memset (regs_ever_live, 0, sizeof regs_ever_live); /* Propagate life info through the basic blocks around the graph of basic blocks. This is a relaxation process: each time a new register is live at the end of the basic block, we must scan the block to determine which registers are, as a consequence, live at the beginning of that block. These registers must then be marked live at the ends of all the blocks that can transfer control to that block. The process continues until it reaches a fixed point. */ first_pass = 1; changed = 1; while (changed) { changed = 0; for (i = n_basic_blocks - 1; i >= 0; i--) { basic_block bb = BASIC_BLOCK (i); int consider = first_pass; int must_rescan = first_pass; register int j; if (!first_pass) { /* Set CONSIDER if this block needs thinking about at all (that is, if the regs live now at the end of it are not the same as were live at the end of it when we last thought about it). Set must_rescan if it needs to be thought about instruction by instruction (that is, if any additional reg that is live at the end now but was not live there before is one of the significant regs of this basic block). */ EXECUTE_IF_AND_COMPL_IN_REG_SET ((regset) bb->aux, bb->global_live_at_end, 0, j, { consider = 1; if (REGNO_REG_SET_P (bb->local_set, j)) { must_rescan = 1; goto done; } }); done: if (! consider) continue; } /* The live_at_start of this block may be changing, so another pass will be required after this one. */ changed = 1; if (! must_rescan) { /* No complete rescan needed; just record those variables newly known live at end as live at start as well. */ IOR_AND_COMPL_REG_SET (bb->global_live_at_start, (regset) bb->aux, bb->global_live_at_end); IOR_AND_COMPL_REG_SET (bb->global_live_at_end, (regset) bb->aux, bb->global_live_at_end); } else { /* Update the basic_block_live_at_start by propagation backwards through the block. */ COPY_REG_SET (bb->global_live_at_end, (regset) bb->aux); COPY_REG_SET (bb->global_live_at_start, bb->global_live_at_end); propagate_block (bb->global_live_at_start, bb->head, bb->end, 0, first_pass ? bb->local_set : (regset) 0, i, remove_dead_code); } /* Update the new_live_at_end's of the block's predecessors. */ { register edge e; for (e = bb->pred; e ; e = e->pred_next) IOR_REG_SET ((regset) e->src->aux, bb->global_live_at_start); } #ifdef USE_C_ALLOCA alloca (0); #endif } first_pass = 0; } /* The only pseudos that are live at the beginning of the function are those that were not set anywhere in the function. local-alloc doesn't know how to handle these correctly, so mark them as not local to any one basic block. */ if (n_basic_blocks > 0) EXECUTE_IF_SET_IN_REG_SET (BASIC_BLOCK (0)->global_live_at_start, FIRST_PSEUDO_REGISTER, i, { REG_BASIC_BLOCK (i) = REG_BLOCK_GLOBAL; }); /* Now the life information is accurate. Make one more pass over each basic block to delete dead stores, create autoincrement addressing and record how many times each register is used, is set, or dies. */ for (i = 0; i < n_basic_blocks; i++) { basic_block bb = BASIC_BLOCK (i); /* We start with global_live_at_end to determine which stores are dead. This process is destructive, and we wish to preserve the contents of global_live_at_end for posterity. Fortunately, new_live_at_end, due to the way we converged on a solution, contains a duplicate of global_live_at_end that we can kill. */ propagate_block ((regset) bb->aux, bb->head, bb->end, 1, (regset) 0, i, remove_dead_code); #ifdef USE_C_ALLOCA alloca (0); #endif } /* We have a problem with any pseudoreg that lives across the setjmp. ANSI says that if a user variable does not change in value between the setjmp and the longjmp, then the longjmp preserves it. This includes longjmp from a place where the pseudo appears dead. (In principle, the value still exists if it is in scope.) If the pseudo goes in a hard reg, some other value may occupy that hard reg where this pseudo is dead, thus clobbering the pseudo. Conclusion: such a pseudo must not go in a hard reg. */ EXECUTE_IF_SET_IN_REG_SET (regs_live_at_setjmp, FIRST_PSEUDO_REGISTER, i, { if (regno_reg_rtx[i] != 0) { REG_LIVE_LENGTH (i) = -1; REG_BASIC_BLOCK (i) = -1; } }); /* Restore regs_ever_live that was provided by reload. */ if (reload_completed) memcpy (regs_ever_live, save_regs_ever_live, sizeof (regs_ever_live)); free_regset_vector (new_live_at_end, n_basic_blocks); obstack_free (&flow_obstack, NULL_PTR); for (i = 0; i < n_basic_blocks; ++i) BASIC_BLOCK (i)->aux = NULL; ENTRY_BLOCK_PTR->aux = NULL; } /* Subroutines of life analysis. */ /* Allocate the permanent data structures that represent the results of life analysis. Not static since used also for stupid life analysis. */ void allocate_bb_life_data () { register int i; for (i = 0; i < n_basic_blocks; i++) { basic_block bb = BASIC_BLOCK (i); bb->local_set = OBSTACK_ALLOC_REG_SET (function_obstack); bb->global_live_at_start = OBSTACK_ALLOC_REG_SET (function_obstack); bb->global_live_at_end = OBSTACK_ALLOC_REG_SET (function_obstack); } ENTRY_BLOCK_PTR->global_live_at_end = OBSTACK_ALLOC_REG_SET (function_obstack); EXIT_BLOCK_PTR->global_live_at_start = OBSTACK_ALLOC_REG_SET (function_obstack); regs_live_at_setjmp = OBSTACK_ALLOC_REG_SET (function_obstack); } void allocate_reg_life_data () { int i; /* Recalculate the register space, in case it has grown. Old style vector oriented regsets would set regset_{size,bytes} here also. */ allocate_reg_info (max_regno, FALSE, FALSE); /* Because both reg_scan and flow_analysis want to set up the REG_N_SETS information, explicitly reset it here. The allocation should have already happened on the previous reg_scan pass. Make sure in case some more registers were allocated. */ for (i = 0; i < max_regno; i++) REG_N_SETS (i) = 0; } /* Make each element of VECTOR point at a regset. The vector has NELTS elements, and space is allocated from the ALLOC_OBSTACK obstack. */ static void init_regset_vector (vector, nelts, alloc_obstack) regset *vector; int nelts; struct obstack *alloc_obstack; { register int i; for (i = 0; i < nelts; i++) { vector[i] = OBSTACK_ALLOC_REG_SET (alloc_obstack); CLEAR_REG_SET (vector[i]); } } /* Release any additional space allocated for each element of VECTOR point other than the regset header itself. The vector has NELTS elements. */ void free_regset_vector (vector, nelts) regset *vector; int nelts; { register int i; for (i = 0; i < nelts; i++) FREE_REG_SET (vector[i]); } /* Compute the registers live at the beginning of a basic block from those live at the end. When called, OLD contains those live at the end. On return, it contains those live at the beginning. FIRST and LAST are the first and last insns of the basic block. FINAL is nonzero if we are doing the final pass which is not for computing the life info (since that has already been done) but for acting on it. On this pass, we delete dead stores, set up the logical links and dead-variables lists of instructions, and merge instructions for autoincrement and autodecrement addresses. SIGNIFICANT is nonzero only the first time for each basic block. If it is nonzero, it points to a regset in which we store a 1 for each register that is set within the block. BNUM is the number of the basic block. */ static void propagate_block (old, first, last, final, significant, bnum, remove_dead_code) register regset old; rtx first; rtx last; int final; regset significant; int bnum; int remove_dead_code; { register rtx insn; rtx prev; regset live; regset dead; /* Find the loop depth for this block. Ignore loop level changes in the middle of the basic block -- for register allocation purposes, the important uses will be in the blocks wholely contained within the loop not in the loop pre-header or post-trailer. */ loop_depth = BASIC_BLOCK (bnum)->loop_depth; dead = ALLOCA_REG_SET (); live = ALLOCA_REG_SET (); cc0_live = 0; mem_set_list = NULL_RTX; if (final) { register int i; /* Process the regs live at the end of the block. Mark them as not local to any one basic block. */ EXECUTE_IF_SET_IN_REG_SET (old, 0, i, { REG_BASIC_BLOCK (i) = REG_BLOCK_GLOBAL; }); } /* Scan the block an insn at a time from end to beginning. */ for (insn = last; ; insn = prev) { prev = PREV_INSN (insn); if (GET_CODE (insn) == NOTE) { /* If this is a call to `setjmp' et al, warn if any non-volatile datum is live. */ if (final && NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP) IOR_REG_SET (regs_live_at_setjmp, old); } /* Update the life-status of regs for this insn. First DEAD gets which regs are set in this insn then LIVE gets which regs are used in this insn. Then the regs live before the insn are those live after, with DEAD regs turned off, and then LIVE regs turned on. */ else if (GET_RTX_CLASS (GET_CODE (insn)) == 'i') { register int i; rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX); int insn_is_dead = 0; int libcall_is_dead = 0; if (remove_dead_code) { insn_is_dead = (insn_dead_p (PATTERN (insn), old, 0, REG_NOTES (insn)) /* Don't delete something that refers to volatile storage! */ && ! INSN_VOLATILE (insn)); libcall_is_dead = (insn_is_dead && note != 0 && libcall_dead_p (PATTERN (insn), old, note, insn)); } /* If an instruction consists of just dead store(s) on final pass, "delete" it by turning it into a NOTE of type NOTE_INSN_DELETED. We could really delete it with delete_insn, but that can cause trouble for first or last insn in a basic block. */ if (final && insn_is_dead) { PUT_CODE (insn, NOTE); NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED; NOTE_SOURCE_FILE (insn) = 0; /* CC0 is now known to be dead. Either this insn used it, in which case it doesn't anymore, or clobbered it, so the next insn can't use it. */ cc0_live = 0; /* If this insn is copying the return value from a library call, delete the entire library call. */ if (libcall_is_dead) { rtx first = XEXP (note, 0); rtx p = insn; while (INSN_DELETED_P (first)) first = NEXT_INSN (first); while (p != first) { p = PREV_INSN (p); PUT_CODE (p, NOTE); NOTE_LINE_NUMBER (p) = NOTE_INSN_DELETED; NOTE_SOURCE_FILE (p) = 0; } } goto flushed; } CLEAR_REG_SET (dead); CLEAR_REG_SET (live); /* See if this is an increment or decrement that can be merged into a following memory address. */ #ifdef AUTO_INC_DEC { register rtx x = single_set (insn); /* Does this instruction increment or decrement a register? */ if (!reload_completed && final && x != 0 && GET_CODE (SET_DEST (x)) == REG && (GET_CODE (SET_SRC (x)) == PLUS || GET_CODE (SET_SRC (x)) == MINUS) && XEXP (SET_SRC (x), 0) == SET_DEST (x) && GET_CODE (XEXP (SET_SRC (x), 1)) == CONST_INT /* Ok, look for a following memory ref we can combine with. If one is found, change the memory ref to a PRE_INC or PRE_DEC, cancel this insn, and return 1. Return 0 if nothing has been done. */ && try_pre_increment_1 (insn)) goto flushed; } #endif /* AUTO_INC_DEC */ /* If this is not the final pass, and this insn is copying the value of a library call and it's dead, don't scan the insns that perform the library call, so that the call's arguments are not marked live. */ if (libcall_is_dead) { /* Mark the dest reg as `significant'. */ mark_set_regs (old, dead, PATTERN (insn), NULL_RTX, significant); insn = XEXP (note, 0); prev = PREV_INSN (insn); } else if (GET_CODE (PATTERN (insn)) == SET && SET_DEST (PATTERN (insn)) == stack_pointer_rtx && GET_CODE (SET_SRC (PATTERN (insn))) == PLUS && XEXP (SET_SRC (PATTERN (insn)), 0) == stack_pointer_rtx && GET_CODE (XEXP (SET_SRC (PATTERN (insn)), 1)) == CONST_INT) /* We have an insn to pop a constant amount off the stack. (Such insns use PLUS regardless of the direction of the stack, and any insn to adjust the stack by a constant is always a pop.) These insns, if not dead stores, have no effect on life. */ ; else { /* Any regs live at the time of a call instruction must not go in a register clobbered by calls. Find all regs now live and record this for them. */ if (GET_CODE (insn) == CALL_INSN && final) EXECUTE_IF_SET_IN_REG_SET (old, 0, i, { REG_N_CALLS_CROSSED (i)++; }); /* LIVE gets the regs used in INSN; DEAD gets those set by it. Dead insns don't make anything live. */ mark_set_regs (old, dead, PATTERN (insn), final ? insn : NULL_RTX, significant); /* If an insn doesn't use CC0, it becomes dead since we assume that every insn clobbers it. So show it dead here; mark_used_regs will set it live if it is referenced. */ cc0_live = 0; if (! insn_is_dead) mark_used_regs (old, live, PATTERN (insn), final, insn); /* Sometimes we may have inserted something before INSN (such as a move) when we make an auto-inc. So ensure we will scan those insns. */ #ifdef AUTO_INC_DEC prev = PREV_INSN (insn); #endif if (! insn_is_dead && GET_CODE (insn) == CALL_INSN) { register int i; rtx note; for (note = CALL_INSN_FUNCTION_USAGE (insn); note; note = XEXP (note, 1)) if (GET_CODE (XEXP (note, 0)) == USE) mark_used_regs (old, live, SET_DEST (XEXP (note, 0)), final, insn); /* Each call clobbers all call-clobbered regs that are not global or fixed. Note that the function-value reg is a call-clobbered reg, and mark_set_regs has already had a chance to handle it. */ for (i = 0; i < FIRST_PSEUDO_REGISTER; i++) if (call_used_regs[i] && ! global_regs[i] && ! fixed_regs[i]) SET_REGNO_REG_SET (dead, i); /* The stack ptr is used (honorarily) by a CALL insn. */ SET_REGNO_REG_SET (live, STACK_POINTER_REGNUM); /* Calls may also reference any of the global registers, so they are made live. */ for (i = 0; i < FIRST_PSEUDO_REGISTER; i++) if (global_regs[i]) mark_used_regs (old, live, gen_rtx_REG (reg_raw_mode[i], i), final, insn); /* Calls also clobber memory. */ mem_set_list = NULL_RTX; } /* Update OLD for the registers used or set. */ AND_COMPL_REG_SET (old, dead); IOR_REG_SET (old, live); } /* On final pass, update counts of how many insns each reg is live at. */ if (final) EXECUTE_IF_SET_IN_REG_SET (old, 0, i, { REG_LIVE_LENGTH (i)++; }); } flushed: ; if (insn == first) break; } FREE_REG_SET (dead); FREE_REG_SET (live); } /* Return 1 if X (the body of an insn, or part of it) is just dead stores (SET expressions whose destinations are registers dead after the insn). NEEDED is the regset that says which regs are alive after the insn. Unless CALL_OK is non-zero, an insn is needed if it contains a CALL. If X is the entire body of an insn, NOTES contains the reg notes pertaining to the insn. */ static int insn_dead_p (x, needed, call_ok, notes) rtx x; regset needed; int call_ok; rtx notes ATTRIBUTE_UNUSED; { enum rtx_code code = GET_CODE (x); #ifdef AUTO_INC_DEC /* If flow is invoked after reload, we must take existing AUTO_INC expresions into account. */ if (reload_completed) { for ( ; notes; notes = XEXP (notes, 1)) { if (REG_NOTE_KIND (notes) == REG_INC) { int regno = REGNO (XEXP (notes, 0)); /* Don't delete insns to set global regs. */ if ((regno < FIRST_PSEUDO_REGISTER && global_regs[regno]) || REGNO_REG_SET_P (needed, regno)) return 0; } } } #endif /* If setting something that's a reg or part of one, see if that register's altered value will be live. */ if (code == SET) { rtx r = SET_DEST (x); /* A SET that is a subroutine call cannot be dead. */ if (! call_ok && GET_CODE (SET_SRC (x)) == CALL) return 0; #ifdef HAVE_cc0 if (GET_CODE (r) == CC0) return ! cc0_live; #endif if (GET_CODE (r) == MEM && ! MEM_VOLATILE_P (r)) { rtx temp; /* Walk the set of memory locations we are currently tracking and see if one is an identical match to this memory location. If so, this memory write is dead (remember, we're walking backwards from the end of the block to the start. */ temp = mem_set_list; while (temp) { if (rtx_equal_p (XEXP (temp, 0), r)) return 1; temp = XEXP (temp, 1); } } while (GET_CODE (r) == SUBREG || GET_CODE (r) == STRICT_LOW_PART || GET_CODE (r) == ZERO_EXTRACT) r = SUBREG_REG (r); if (GET_CODE (r) == REG) { int regno = REGNO (r); /* Don't delete insns to set global regs. */ if ((regno < FIRST_PSEUDO_REGISTER && global_regs[regno]) /* Make sure insns to set frame pointer aren't deleted. */ || (regno == FRAME_POINTER_REGNUM && (! reload_completed || frame_pointer_needed)) #if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM || (regno == HARD_FRAME_POINTER_REGNUM && (! reload_completed || frame_pointer_needed)) #endif #if FRAME_POINTER_REGNUM != ARG_POINTER_REGNUM /* Make sure insns to set arg pointer are never deleted (if the arg pointer isn't fixed, there will be a USE for it, so we can treat it normally). */ || (regno == ARG_POINTER_REGNUM && fixed_regs[regno]) #endif || REGNO_REG_SET_P (needed, regno)) return 0; /* If this is a hard register, verify that subsequent words are not needed. */ if (regno < FIRST_PSEUDO_REGISTER) { int n = HARD_REGNO_NREGS (regno, GET_MODE (r)); while (--n > 0) if (REGNO_REG_SET_P (needed, regno+n)) return 0; } return 1; } } /* If performing several activities, insn is dead if each activity is individually dead. Also, CLOBBERs and USEs can be ignored; a CLOBBER or USE that's inside a PARALLEL doesn't make the insn worth keeping. */ else if (code == PARALLEL) { int i = XVECLEN (x, 0); for (i--; i >= 0; i--) if (GET_CODE (XVECEXP (x, 0, i)) != CLOBBER && GET_CODE (XVECEXP (x, 0, i)) != USE && ! insn_dead_p (XVECEXP (x, 0, i), needed, call_ok, NULL_RTX)) return 0; return 1; } /* A CLOBBER of a pseudo-register that is dead serves no purpose. That is not necessarily true for hard registers. */ else if (code == CLOBBER && GET_CODE (XEXP (x, 0)) == REG && REGNO (XEXP (x, 0)) >= FIRST_PSEUDO_REGISTER && ! REGNO_REG_SET_P (needed, REGNO (XEXP (x, 0)))) return 1; /* We do not check other CLOBBER or USE here. An insn consisting of just a CLOBBER or just a USE should not be deleted. */ return 0; } /* If X is the pattern of the last insn in a libcall, and assuming X is dead, return 1 if the entire library call is dead. This is true if X copies a register (hard or pseudo) and if the hard return reg of the call insn is dead. (The caller should have tested the destination of X already for death.) If this insn doesn't just copy a register, then we don't have an ordinary libcall. In that case, cse could not have managed to substitute the source for the dest later on, so we can assume the libcall is dead. NEEDED is the bit vector of pseudoregs live before this insn. NOTE is the REG_RETVAL note of the insn. INSN is the insn itself. */ static int libcall_dead_p (x, needed, note, insn) rtx x; regset needed; rtx note; rtx insn; { register RTX_CODE code = GET_CODE (x); if (code == SET) { register rtx r = SET_SRC (x); if (GET_CODE (r) == REG) { rtx call = XEXP (note, 0); rtx call_pat; register int i; /* Find the call insn. */ while (call != insn && GET_CODE (call) != CALL_INSN) call = NEXT_INSN (call); /* If there is none, do nothing special, since ordinary death handling can understand these insns. */ if (call == insn) return 0; /* See if the hard reg holding the value is dead. If this is a PARALLEL, find the call within it. */ call_pat = PATTERN (call); if (GET_CODE (call_pat) == PARALLEL) { for (i = XVECLEN (call_pat, 0) - 1; i >= 0; i--) if (GET_CODE (XVECEXP (call_pat, 0, i)) == SET && GET_CODE (SET_SRC (XVECEXP (call_pat, 0, i))) == CALL) break; /* This may be a library call that is returning a value via invisible pointer. Do nothing special, since ordinary death handling can understand these insns. */ if (i < 0) return 0; call_pat = XVECEXP (call_pat, 0, i); } return insn_dead_p (call_pat, needed, 1, REG_NOTES (call)); } } return 1; } /* Return 1 if register REGNO was used before it was set, i.e. if it is live at function entry. Don't count global register variables, variables in registers that can be used for function arg passing, or variables in fixed hard registers. */ int regno_uninitialized (regno) int regno; { if (n_basic_blocks == 0 || (regno < FIRST_PSEUDO_REGISTER && (global_regs[regno] || fixed_regs[regno] || FUNCTION_ARG_REGNO_P (regno)))) return 0; return REGNO_REG_SET_P (BASIC_BLOCK (0)->global_live_at_start, regno); } /* 1 if register REGNO was alive at a place where `setjmp' was called and was set more than once or is an argument. Such regs may be clobbered by `longjmp'. */ int regno_clobbered_at_setjmp (regno) int regno; { if (n_basic_blocks == 0) return 0; return ((REG_N_SETS (regno) > 1 || REGNO_REG_SET_P (BASIC_BLOCK (0)->global_live_at_start, regno)) && REGNO_REG_SET_P (regs_live_at_setjmp, regno)); } /* INSN references memory, possibly using autoincrement addressing modes. Find any entries on the mem_set_list that need to be invalidated due to an address change. */ static void invalidate_mems_from_autoinc (insn) rtx insn; { rtx note = REG_NOTES (insn); for (note = REG_NOTES (insn); note; note = XEXP (note, 1)) { if (REG_NOTE_KIND (note) == REG_INC) { rtx temp = mem_set_list; rtx prev = NULL_RTX; while (temp) { if (reg_overlap_mentioned_p (XEXP (note, 0), XEXP (temp, 0))) { /* Splice temp out of list. */ if (prev) XEXP (prev, 1) = XEXP (temp, 1); else mem_set_list = XEXP (temp, 1); } else prev = temp; temp = XEXP (temp, 1); } } } } /* Process the registers that are set within X. Their bits are set to 1 in the regset DEAD, because they are dead prior to this insn. If INSN is nonzero, it is the insn being processed and the fact that it is nonzero implies this is the FINAL pass in propagate_block. In this case, various info about register usage is stored, LOG_LINKS fields of insns are set up. */ static void mark_set_regs (needed, dead, x, insn, significant) regset needed; regset dead; rtx x; rtx insn; regset significant; { register RTX_CODE code = GET_CODE (x); if (code == SET || code == CLOBBER) mark_set_1 (needed, dead, x, insn, significant); else if (code == PARALLEL) { register int i; for (i = XVECLEN (x, 0) - 1; i >= 0; i--) { code = GET_CODE (XVECEXP (x, 0, i)); if (code == SET || code == CLOBBER) mark_set_1 (needed, dead, XVECEXP (x, 0, i), insn, significant); } } } /* Process a single SET rtx, X. */ static void mark_set_1 (needed, dead, x, insn, significant) regset needed; regset dead; rtx x; rtx insn; regset significant; { register int regno; register rtx reg = SET_DEST (x); /* Some targets place small structures in registers for return values of functions. We have to detect this case specially here to get correct flow information. */ if (GET_CODE (reg) == PARALLEL && GET_MODE (reg) == BLKmode) { register int i; for (i = XVECLEN (reg, 0) - 1; i >= 0; i--) mark_set_1 (needed, dead, XVECEXP (reg, 0, i), insn, significant); return; } /* Modifying just one hardware register of a multi-reg value or just a byte field of a register does not mean the value from before this insn is now dead. But it does mean liveness of that register at the end of the block is significant. Within mark_set_1, however, we treat it as if the register is indeed modified. mark_used_regs will, however, also treat this register as being used. Thus, we treat these insns as setting a new value for the register as a function of its old value. This cases LOG_LINKS to be made appropriately and this will help combine. */ while (GET_CODE (reg) == SUBREG || GET_CODE (reg) == ZERO_EXTRACT || GET_CODE (reg) == SIGN_EXTRACT || GET_CODE (reg) == STRICT_LOW_PART) reg = XEXP (reg, 0); /* If this set is a MEM, then it kills any aliased writes. If this set is a REG, then it kills any MEMs which use the reg. */ if (GET_CODE (reg) == MEM || GET_CODE (reg) == REG) { rtx temp = mem_set_list; rtx prev = NULL_RTX; while (temp) { if ((GET_CODE (reg) == MEM && output_dependence (XEXP (temp, 0), reg)) || (GET_CODE (reg) == REG && reg_overlap_mentioned_p (reg, XEXP (temp, 0)))) { /* Splice this entry && GET_CODE (reg) == MEM) invalidate_mems_from_autoinc (insn); if (GET_CODE (reg) == MEM && ! side_effects_p (reg) /* We do not know the size of a BLKmode store, so we do not track them for redundant store elimination. */ && GET_MODE (reg) != BLKmode /* There are no REG_INC notes for SP, so we can't assume we'll see everything that invalidates it. To be safe, don't eliminate any stores though SP; none of them should be redundant anyway. */ && ! reg_mentioned_p (stack_pointer_rtx, reg)) mem_set_list = gen_rtx_EXPR_LIST (VOIDmode, reg, mem_set_list); if (GET_CODE (reg) == REG && (regno = REGNO (reg), ! && ! (regno < FIRST_PSEUDO_REGISTER && global_regs[regno])) /* && regno != STACK_POINTER_REGNUM) -- let's try without this. */ { int some_needed = REGNO_REG_SET_P (needed, regno); int some_not_needed = ! some_needed; /* Mark it as a significant register for this basic block. */ if (significant) SET_REGNO_REG_SET (significant, regno); /* Mark it as dead before this insn. */ SET_REGNO_REG_SET (dead, regno); /* A hard reg in a wide mode may really be multiple registers. If so, mark all of them just like the first. */ if (regno < FIRST_PSEUDO_REGISTER) { int n; /* Nothing below is needed for the stack pointer; get out asap. Eg, log links aren't needed, since combine won't use them. */ if (regno == STACK_POINTER_REGNUM) return; n = HARD_REGNO_NREGS (regno, GET_MODE (reg)); while (--n > 0) { int regno_n = regno + n; int needed_regno = REGNO_REG_SET_P (needed, regno_n); if (significant) SET_REGNO_REG_SET (significant, regno_n); SET_REGNO_REG_SET (dead, regno_n); some_needed |= needed_regno; some_not_needed |= ! needed_regno; } } /* Additional data to record if this is the final pass. */ if (insn) { register rtx y = reg_next_use[regno]; register int blocknum = BLOCK_NUM (insn); /* If this is a hard reg, record this function uses the reg. */ if (regno < FIRST_PSEUDO_REGISTER) { register int i; int endregno = regno + HARD_REGNO_NREGS (regno, GET_MODE (reg)); for (i = regno; i < endregno; i++) { /* The next use is no longer "next", since a store intervenes. */ reg_next_use[i] = 0; regs_ever_live[i] = 1; REG_N_SETS (i)++; } } else { /* The next use is no longer "next", since a store intervenes. */ reg_next_use[regno] = 0; /* Keep track of which basic blocks each reg appears in. */ if (REG_BASIC_BLOCK (regno) == REG_BLOCK_UNKNOWN) REG_BASIC_BLOCK (regno) = blocknum; else if (REG_BASIC_BLOCK (regno) != blocknum) REG_BASIC_BLOCK (regno) = REG_BLOCK_GLOBAL; /* Count (weighted) references, stores, etc. This counts a register twice if it is modified, but that is correct. */ REG_N_SETS (regno)++; REG_N_REFS (regno) += loop_depth; /* The insns where a reg is live are normally counted elsewhere, but we want the count to include the insn where the reg is set, and the normal counting mechanism would not count it. */ REG_LIVE_LENGTH (regno)++; } if (! some_not_needed) { /* Make a logical link from the next following insn that uses this register, back to this insn. The following insns have already been processed. We don't build a LOG_LINK for hard registers containing in ASM_OPERANDs. If these registers get replaced, we might wind up changing the semantics of the insn, even if reload can make what appear to be valid assignments later. */ if (y && (BLOCK_NUM (y) == blocknum) && (regno >= FIRST_PSEUDO_REGISTER || asm_noperands (PATTERN (y)) < 0)) LOG_LINKS (y) = gen_rtx_INSN_LIST (VOIDmode, insn, LOG_LINKS (y)); } else if (! some_needed) { /* Note that dead stores have already been deleted when possible If we get here, we have found a dead store that cannot be eliminated (because the same insn does something useful). Indicate this by marking the reg being set as dying here. */ REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_UNUSED, reg, REG_NOTES (insn)); REG_N_DEATHS (REGNO (reg))++; } else { /* This is a case where we have a multi-word hard register and some, but not all, of the words of the register are needed in subsequent insns. Write REG_UNUSED notes for those parts that were not needed. This case should be rare. */ int i; for (i = HARD_REGNO_NREGS (regno, GET_MODE (reg)) - 1; i >= 0; i--) if (!REGNO_REG_SET_P (needed, regno + i)) REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_UNUSED, gen_rtx_REG (reg_raw_mode[regno + i], regno + i), REG_NOTES (insn)); } } } else if (GET_CODE (reg) == REG) reg_next_use[regno] = 0; /* If this is the last pass and this is a SCRATCH, show it will be dying here and count it. */ else if (GET_CODE (reg) == SCRATCH && insn != 0) { REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_UNUSED, reg, REG_NOTES (insn)); } } #ifdef AUTO_INC_DEC /* X is a MEM found in INSN. See if we can convert it into an auto-increment reference. */ static void find_auto_inc (needed, x, insn) regset needed; rtx x; rtx insn; { rtx addr = XEXP (x, 0); HOST_WIDE_INT offset = 0; rtx set; /* Here we detect use of an index register which might be good for postincrement, postdecrement, preincrement, or predecrement. */ if (GET_CODE (addr) == PLUS && GET_CODE (XEXP (addr, 1)) == CONST_INT) offset = INTVAL (XEXP (addr, 1)), addr = XEXP (addr, 0); if (GET_CODE (addr) == REG) { register rtx y; register int size = GET_MODE_SIZE (GET_MODE (x)); rtx use; rtx incr; int regno = REGNO (addr); /* Is the next use an increment that might make auto-increment? */ if ((incr = reg_next_use[regno]) != 0 && (set = single_set (incr)) != 0 && GET_CODE (set) == SET && BLOCK_NUM (incr) == BLOCK_NUM (insn) /* Can't add side effects to jumps; if reg is spilled and reloaded, there's no way to store back the altered value. */ && GET_CODE (insn) != JUMP_INSN && (y = SET_SRC (set), GET_CODE (y) == PLUS) && XEXP (y, 0) == addr && GET_CODE (XEXP (y, 1)) == CONST_INT && ((HAVE_POST_INCREMENT && (INTVAL (XEXP (y, 1)) == size && offset == 0)) || (HAVE_POST_DECREMENT && (INTVAL (XEXP (y, 1)) == - size && offset == 0)) || (HAVE_PRE_INCREMENT && (INTVAL (XEXP (y, 1)) == size && offset == size)) || (HAVE_PRE_DECREMENT && (INTVAL (XEXP (y, 1)) == - size && offset == - size))) /* Make sure this reg appears only once in this insn. */ && (use = find_use_as_address (PATTERN (insn), addr, offset), use != 0 && use != (rtx) 1)) { rtx q = SET_DEST (set); enum rtx_code inc_code = (INTVAL (XEXP (y, 1)) == size ? (offset ? PRE_INC : POST_INC) : (offset ? PRE_DEC : POST_DEC)); if (dead_or_set_p (incr, addr)) { /* This is the simple case. Try to make the auto-inc. If we can't, we are done. Otherwise, we will do any needed updates below. */ if (! validate_change (insn, &XEXP (x, 0), gen_rtx_fmt_e (inc_code, Pmode, addr), 0)) return; } else if (GET_CODE (q) == REG /* PREV_INSN used here to check the semi-open interval [insn,incr). */ && ! reg_used_between_p (q, PREV_INSN (insn), incr) /* We must also check for sets of q as q may be a call clobbered hard register and there may be a call between PREV_INSN (insn) and incr. */ && ! reg_set_between_p (q, PREV_INSN (insn), incr)) { /* We have *p followed sometime later by q = p+size. Both p and q must be live afterward, and q is not used between INSN and its assignment. Change it to q = p, ...*q..., q = q+size. Then fall into the usual case. */ rtx insns, temp; basic_block bb; start_sequence (); emit_move_insn (q, addr); insns = get_insns (); end_sequence (); bb = BLOCK_FOR_INSN (insn); for (temp = insns; temp; temp = NEXT_INSN (temp)) set_block_for_insn (temp, bb); /* If we can't make the auto-inc, or can't make the replacement into Y, exit. There's no point in making the change below if we can't do the auto-inc and doing so is not correct in the pre-inc case. */ validate_change (insn, &XEXP (x, 0), gen_rtx_fmt_e (inc_code, Pmode, q), 1); validate_change (incr, &XEXP (y, 0), q, 1); if (! apply_change_group ()) return; /* We now know we'll be doing this change, so emit the new insn(s) and do the updates. */ emit_insns_before (insns, insn); if (BLOCK_FOR_INSN (insn)->head == insn) BLOCK_FOR_INSN (insn)->head = insns; /* INCR will become a NOTE and INSN won't contain a use of ADDR. If a use of ADDR was just placed in the insn before INSN, make that the next use. Otherwise, invalidate it. */ if (GET_CODE (PREV_INSN (insn)) == INSN && GET_CODE (PATTERN (PREV_INSN (insn))) == SET && SET_SRC (PATTERN (PREV_INSN (insn))) == addr) reg_next_use[regno] = PREV_INSN (insn); else reg_next_use[regno] = 0; addr = q; regno = REGNO (q); /* REGNO is now used in INCR which is below INSN, but it previously wasn't live here. If we don't mark it as needed, we'll put a REG_DEAD note for it on this insn, which is incorrect. */ SET_REGNO_REG_SET (needed, regno); /* If there are any calls between INSN and INCR, show that REGNO now crosses them. */ for (temp = insn; temp != incr; temp = NEXT_INSN (temp)) if (GET_CODE (temp) == CALL_INSN) REG_N_CALLS_CROSSED (regno)++; } else return; /* If we haven't returned, it means we were able to make the auto-inc, so update the status. First, record that this insn has an implicit side effect. */ REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_INC, addr, REG_NOTES (insn)); /* Modify the old increment-insn to simply copy the already-incremented value of our register. */ if (! validate_change (incr, &SET_SRC (set), addr, 0)) abort (); /* If that makes it a no-op (copying the register into itself) delete it so it won't appear to be a "use" and a "set" of this register. */ if (SET_DEST (set) == addr) { PUT_CODE (incr, NOTE); NOTE_LINE_NUMBER (incr) = NOTE_INSN_DELETED; NOTE_SOURCE_FILE (incr) = 0; } if (regno >= FIRST_PSEUDO_REGISTER) { /* Count an extra reference to the reg. When a reg is incremented, spilling it is worse, so we want to make that less likely. */ REG_N_REFS (regno) += loop_depth; /* Count the increment as a setting of the register, even though it isn't a SET in rtl. */ REG_N_SETS (regno)++; } } } } #endif /* AUTO_INC_DEC */ /* Scan expression X and store a 1-bit in LIVE for each reg it uses. This is done assuming the registers needed from X are those that have 1-bits in NEEDED. On the final pass, FINAL is 1. This means try for autoincrement and count the uses and deaths of each pseudo-reg. INSN is the containing instruction. If INSN is dead, this function is not called. */ static void mark_used_regs (needed, live, x, final, insn) regset needed; regset live; rtx x; int final; rtx insn; { register RTX_CODE code; register int regno; int i; retry: code = GET_CODE (x); switch (code) { case LABEL_REF: case SYMBOL_REF: case CONST_INT: case CONST: case CONST_DOUBLE: case PC: case ADDR_VEC: case ADDR_DIFF_VEC: return; #ifdef HAVE_cc0 case CC0: cc0_live = 1; return; #endif case CLOBBER: /* If we are clobbering a MEM, mark any registers inside the address as being used. */ if (GET_CODE (XEXP (x, 0)) == MEM) mark_used_regs (needed, live, XEXP (XEXP (x, 0), 0), final, insn); return; case MEM: /* Invalidate the data for the last MEM stored, but only if MEM is something that can be stored into. */ if (GET_CODE (XEXP (x, 0)) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (XEXP (x, 0))) ; /* needn't clear the memory set list */ else { rtx temp = mem_set_list; rtx prev = NULL_RTX; while (temp) { if (anti_dependence (XEXP (temp, 0), x)) { /* Splice temp) invalidate_mems_from_autoinc (insn); #ifdef AUTO_INC_DEC if (final) find_auto_inc (needed, x, insn); #endif break; case SUBREG: if (GET_CODE (SUBREG_REG (x)) == REG && REGNO (SUBREG_REG (x)) >= FIRST_PSEUDO_REGISTER && (GET_MODE_SIZE (GET_MODE (x)) != GET_MODE_SIZE (GET_MODE (SUBREG_REG (x))))) REG_CHANGES_SIZE (REGNO (SUBREG_REG (x))) = 1; /* While we're here, optimize this case. */ x = SUBREG_REG (x); /* In case the SUBREG is not of a register, don't optimize */ if (GET_CODE (x) != REG) { mark_used_regs (needed, live, x, final, insn); return; } /* ... fall through ... */ case REG: /* See a register other than being set => mark it as needed. */ regno = REGNO (x); { int some_needed = REGNO_REG_SET_P (needed, regno); int some_not_needed = ! some_needed; SET_REGNO_REG_SET (live, regno); /* A hard reg in a wide mode may really be multiple registers. If so, mark all of them just like the first. */ if (regno < FIRST_PSEUDO_REGISTER) { int n; /* For stack ptr or fixed arg pointer, nothing below can be necessary, so waste no more time. */ if (regno == STACK_POINTER_REGNUM #if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM || (regno == HARD_FRAME_POINTER_REGNUM && (! reload_completed || frame_pointer_needed)) #endif #if FRAME_POINTER_REGNUM != ARG_POINTER_REGNUM || (regno == ARG_POINTER_REGNUM && fixed_regs[regno]) #endif || (regno == FRAME_POINTER_REGNUM && (! reload_completed || frame_pointer_needed))) { /* If this is a register we are going to try to eliminate, don't mark it live here. If we are successful in eliminating it, it need not be live unless it is used for pseudos, in which case it will have been set live when it was allocated to the pseudos. If the register will not be eliminated, reload will set it live at that point. */ if (! TEST_HARD_REG_BIT (elim_reg_set, regno)) regs_ever_live[regno] = 1; return; } /* No death notes for global register variables; their values are live after this function exits. */ if (global_regs[regno]) { if (final) reg_next_use[regno] = insn; return; } n = HARD_REGNO_NREGS (regno, GET_MODE (x)); while (--n > 0) { int regno_n = regno + n; int needed_regno = REGNO_REG_SET_P (needed, regno_n); SET_REGNO_REG_SET (live, regno_n); some_needed |= needed_regno; some_not_needed |= ! needed_regno; } } if (final) { /* Record where each reg is used, so when the reg is set we know the next insn that uses it. */ reg_next_use[regno] = insn; if (regno < FIRST_PSEUDO_REGISTER) { /* If a hard reg is being used, record that this function does use it. */ i = HARD_REGNO_NREGS (regno, GET_MODE (x)); if (i == 0) i = 1; do regs_ever_live[regno + --i] = 1; while (i > 0); } else { /* Keep track of which basic block each reg appears in. */ register int blocknum = BLOCK_NUM (insn); if (REG_BASIC_BLOCK (regno) == REG_BLOCK_UNKNOWN) REG_BASIC_BLOCK (regno) = blocknum; else if (REG_BASIC_BLOCK (regno) != blocknum) REG_BASIC_BLOCK (regno) = REG_BLOCK_GLOBAL; /* Count (weighted) number of uses of each reg. */ REG_N_REFS (regno) += loop_depth; } /* Record and count the insns in which a reg dies. If it is used in this insn and was dead below the insn then it dies in this insn. If it was set in this insn, we do not make a REG_DEAD note; likewise if we already made such a note. */ if (some_not_needed && ! dead_or_set_p (insn, x) #if 0 && (regno >= FIRST_PSEUDO_REGISTER || ! fixed_regs[regno]) #endif ) { /* Check for the case where the register dying partially overlaps the register set by this insn. */ if (regno < FIRST_PSEUDO_REGISTER && HARD_REGNO_NREGS (regno, GET_MODE (x)) > 1) { int n = HARD_REGNO_NREGS (regno, GET_MODE (x)); while (--n >= 0) some_needed |= dead_or_set_regno_p (insn, regno + n); } /* If none of the words in X is needed, make a REG_DEAD note. Otherwise, we must make partial REG_DEAD notes. */ if (! some_needed) { REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_DEAD, x, REG_NOTES (insn)); REG_N_DEATHS (regno)++; } else { int i; /* Don't make a REG_DEAD note for a part of a register that is set in the insn. */ for (i = HARD_REGNO_NREGS (regno, GET_MODE (x)) - 1; i >= 0; i--) if (!REGNO_REG_SET_P (needed, regno + i) && ! dead_or_set_regno_p (insn, regno + i)) REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_DEAD, gen_rtx_REG (reg_raw_mode[regno + i], regno + i), REG_NOTES (insn)); } } } } return; case SET: { register rtx testreg = SET_DEST (x); int mark_dest = 0; /* If storing into MEM, don't show it as being used. But do show the address as being used. */ if (GET_CODE (testreg) == MEM) { #ifdef AUTO_INC_DEC if (final) find_auto_inc (needed, testreg, insn); #endif mark_used_regs (needed, live, XEXP (testreg, 0), final, insn); mark_used_regs (needed, live, SET_SRC (x), final, insn);) { if (GET_CODE (testreg) == SUBREG && GET_CODE (SUBREG_REG (testreg)) == REG && REGNO (SUBREG_REG (testreg)) >= FIRST_PSEUDO_REGISTER && (GET_MODE_SIZE (GET_MODE (testreg)) != GET_MODE_SIZE (GET_MODE (SUBREG_REG (testreg))))) REG_CHANGES_SIZE (REGNO (SUBREG_REG (testreg))) = 1; /* && (regno = REGNO (testreg), ! )) /* We used to exclude global_regs here, but that seems wrong. Storing in them is like storing in mem. */ { mark_used_regs (needed, live, SET_SRC (x), final, insn); if (mark_dest) mark_used_regs (needed, live, SET_DEST (x), final, insn); return; } } break; case RETURN: /* If exiting needs the right stack value, consider this insn as using the stack pointer. In any event, consider it as using all global registers and all registers used by return. */ if (! EXIT_IGNORE_STACK || (! FRAME_POINTER_REQUIRED && ! current_function_calls_alloca && flag_omit_frame_pointer) || current_function_sp_is_unchanging) SET_REGNO_REG_SET (live, STACK_POINTER_REGNUM); for (i = 0; i < FIRST_PSEUDO_REGISTER; i++) if (global_regs[i] #ifdef EPILOGUE_USES || EPILOGUE_USES (i) #endif ) SET_REGNO_REG_SET (live, i); break; case ASM_OPERANDS: case UNSPEC_VOLATILE: case TRAP_IF: case ASM_INPUT: { /* Traditional and volatile asm instructions must be considered to use and clobber all hard registers, all pseudo-registers and all of memory. So must TRAP_IF and UNSPEC_VOLATILE operations. Consider for instance a volatile asm that changes the fpu rounding mode. An insn should not be moved across this even if it only uses pseudo-regs because it might give an incorrectly rounded result. ?!? Unfortunately, marking all hard registers as live causes massive problems for the register allocator and marking all pseudos as live creates mountains of uninitialized variable warnings. So for now, just clear the memory set list and mark any regs we can find in ASM_OPERANDS as used. */ if (code != ASM_OPERANDS || MEM_VOLATILE_P (x)) mem_set_list = NULL_RTX; /* For all ASM_OPERANDS, we must traverse the vector of input operands. We can not just fall through here since then we would be confused by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate traditional asms unlike their normal usage. */ if (code == ASM_OPERANDS) { int j; for (j = 0; j < ASM_OPERANDS_INPUT_LENGTH (x); j++) mark_used_regs (needed, live, ASM_OPERANDS_INPUT (x, j), final, insn); }; } mark_used_regs (needed, live, XEXP (x, i), final, insn); } else if (fmt[i] == 'E') { register int j; for (j = 0; j < XVECLEN (x, i); j++) mark_used_regs (needed, live, XVECEXP (x, i, j), final, insn); } } } } #ifdef AUTO_INC_DEC static int try_pre_increment_1 (insn) rtx insn; { /* Find the next use of this reg. If in same basic block, make it do pre-increment or pre-decrement if appropriate. */ rtx x = single_set (insn); HOST_WIDE_INT amount = ((GET_CODE (SET_SRC (x)) == PLUS ? 1 : -1) * INTVAL (XEXP (SET_SRC (x), 1))); int regno = REGNO (SET_DEST (x)); rtx y = reg_next_use[regno]; if (y != 0 && BLOCK_NUM (y) == BLOCK_NUM (insn) /* Don't do this if the reg dies, or gets set in y; a standard addressing mode would be better. */ && ! dead_or_set_p (y, SET_DEST (x)) && try_pre_increment (y, SET_DEST (x), amount)) { /* We have found a suitable auto-increment and already changed insn Y to do it. So flush this increment-instruction. */ PUT_CODE (insn, NOTE); NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED; NOTE_SOURCE_FILE (insn) = 0; /* Count a reference to this reg for the increment insn we are deleting. When a reg is incremented. spilling it is worse, so we want to make that less likely. */ if (regno >= FIRST_PSEUDO_REGISTER) { REG_N_REFS (regno) += loop_depth; REG_N_SETS (regno)++; } return 1; } return 0; } /* Try to change INSN so that it does pre-increment or pre-decrement addressing on register REG in order to add AMOUNT to REG. AMOUNT is negative for pre-decrement. Returns 1 if the change could be made. This checks all about the validity of the result of modifying INSN. */ static int try_pre_increment (insn, reg, amount) rtx insn, reg; HOST_WIDE_INT amount; { register rtx use; /* Nonzero if we can try to make a pre-increment or pre-decrement. For example, addl $4,r1; movl (r1),... can become movl +(r1),... */ int pre_ok = 0; /* Nonzero if we can try to make a post-increment or post-decrement. For example, addl $4,r1; movl -4(r1),... can become movl (r1)+,... It is possible for both PRE_OK and POST_OK to be nonzero if the machine supports both pre-inc and post-inc, or both pre-dec and post-dec. */ int post_ok = 0; /* Nonzero if the opportunity actually requires post-inc or post-dec. */ int do_post = 0; /* From the sign of increment, see which possibilities are conceivable on this target machine. */ if (HAVE_PRE_INCREMENT && amount > 0) pre_ok = 1; if (HAVE_POST_INCREMENT && amount > 0) post_ok = 1; if (HAVE_PRE_DECREMENT && amount < 0) pre_ok = 1; if (HAVE_POST_DECREMENT && amount < 0) post_ok = 1; if (! (pre_ok || post_ok)) return 0; /* It is not safe to add a side effect to a jump insn because if the incremented register is spilled and must be reloaded there would be no way to store the incremented value back in memory. */ if (GET_CODE (insn) == JUMP_INSN) return 0; use = 0; if (pre_ok) use = find_use_as_address (PATTERN (insn), reg, 0); if (post_ok && (use == 0 || use == (rtx) 1)) { use = find_use_as_address (PATTERN (insn), reg, -amount); do_post = 1; } if (use == 0 || use == (rtx) 1) return 0; if (GET_MODE_SIZE (GET_MODE (use)) != (amount > 0 ? amount : - amount)) return 0; /* See if this combination of instruction and addressing mode exists. */ if (! validate_change (insn, &XEXP (use, 0), gen_rtx_fmt_e (amount > 0 ? (do_post ? POST_INC : PRE_INC) : (do_post ? POST_DEC : PRE_DEC), Pmode, reg), 0)) return 0; /* Record that this insn now has an implicit side effect on X. */ REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_INC, reg, REG_NOTES (insn)); return 1; } #endif /* AUTO_INC_DEC */ /* Find the place in the rtx X where REG is used as a memory address. Return the MEM rtx that so uses it. If PLUSCONST is nonzero, search instead for a memory address equivalent to (plus REG (const_int PLUSCONST)). If such an address does not appear, return 0. If REG appears more than once, or is used other than in such an address, return (rtx)1. */ rtx find_use_as_address (x, reg, plusconst) register rtx x; rtx reg; HOST_WIDE_INT plusconst; { enum rtx_code code = GET_CODE (x); char *fmt = GET_RTX_FORMAT (code); register int i; register rtx value = 0; register rtx tem; if (code == MEM && XEXP (x, 0) == reg && plusconst == 0) return x; if (code == MEM && GET_CODE (XEXP (x, 0)) == PLUS && XEXP (XEXP (x, 0), 0) == reg && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT && INTVAL (XEXP (XEXP (x, 0), 1)) == plusconst) return x; if (code == SIGN_EXTRACT || code == ZERO_EXTRACT) { /* If REG occurs inside a MEM used in a bit-field reference, that is unacceptable. */ if (find_use_as_address (XEXP (x, 0), reg, 0) != 0) return (rtx) (HOST_WIDE_INT) 1; } if (x == reg) return (rtx) (HOST_WIDE_INT) 1; for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--) { if (fmt[i] == 'e') { tem = find_use_as_address (XEXP (x, i), reg, plusconst); if (value == 0) value = tem; else if (tem != 0) return (rtx) (HOST_WIDE_INT) 1; } if (fmt[i] == 'E') { register int j; for (j = XVECLEN (x, i) - 1; j >= 0; j--) { tem = find_use_as_address (XVECEXP (x, i, j), reg, plusconst); if (value == 0) value = tem; else if (tem != 0) return (rtx) (HOST_WIDE_INT) 1; } } } return value; } /* Write information about registers and basic blocks into FILE. This is part of making a debugging dump. */ void dump_flow_info (file) FILE *file; { register int i; static char *reg_class_names[] = REG_CLASS_NAMES; fprintf (file, "%d registers.\n", max_regno); for (i = FIRST_PSEUDO_REGISTER; i < max_regno; i++) if (REG_N_REFS (i)) { enum reg_class class, altclass; fprintf (file, "\nRegister %d used %d times across %d insns", i, REG_N_REFS (i), REG_LIVE_LENGTH (i)); if (REG_BASIC_BLOCK (i) >= 0) fprintf (file, " in block %d", REG_BASIC_BLOCK (i)); if (REG_N_SETS (i)) fprintf (file, "; set %d time%s", REG_N_SETS (i), (REG_N_SETS (i) == 1) ? "" : "s"); if (REG_USERVAR_P (regno_reg_rtx[i])) fprintf (file, "; user var"); if (REG_N_DEATHS (i) != 1) fprintf (file, "; dies in %d places", REG_N_DEATHS (i)); if (REG_N_CALLS_CROSSED (i) == 1) fprintf (file, "; crosses 1 call"); else if (REG_N_CALLS_CROSSED (i)) fprintf (file, "; crosses %d calls", REG_N_CALLS_CROSSED (i)); if (PSEUDO_REGNO_BYTES (i) != UNITS_PER_WORD) fprintf (file, "; %d bytes", PSEUDO_REGNO_BYTES (i)); class = reg_preferred_class (i); altclass = reg_alternate_class (i); if (class != GENERAL_REGS || altclass != ALL_REGS) { if (altclass == ALL_REGS || class == ALL_REGS) fprintf (file, "; pref %s", reg_class_names[(int) class]); else if (altclass == NO_REGS) fprintf (file, "; %s or none", reg_class_names[(int) class]); else fprintf (file, "; pref %s, else %s", reg_class_names[(int) class], reg_class_names[(int) altclass]); } if (REGNO_POINTER_FLAG (i)) fprintf (file, "; pointer"); fprintf (file, ".\n"); } fprintf (file, "\n%d basic blocks.\n", n_basic_blocks); for (i = 0; i < n_basic_blocks; i++) { register basic_block bb = BASIC_BLOCK (i); register int regno; register edge e; fprintf (file, "\nBasic block %d: first insn %d, last %d.\n", i, INSN_UID (bb->head), INSN_UID (bb->end)); fprintf (file, "Predecessors: "); for (e = bb->pred; e ; e = e->pred_next) dump_edge_info (file, e, 0); fprintf (file, "\nSuccessors: "); for (e = bb->succ; e ; e = e->succ_next) dump_edge_info (file, e, 1); fprintf (file, "\nRegisters live at start:"); if (bb->global_live_at_start) { for (regno = 0; regno < max_regno; regno++) if (REGNO_REG_SET_P (bb->global_live_at_start, regno)) fprintf (file, " %d", regno); } else fprintf (file, " n/a"); fprintf (file, "\nRegisters live at end:"); if (bb->global_live_at_end) { for (regno = 0; regno < max_regno; regno++) if (REGNO_REG_SET_P (bb->global_live_at_end, regno)) fprintf (file, " %d", regno); } else fprintf (file, " n/a"); putc('\n', file); } putc('\n', file); } static void dump_edge_info (file, e, do_succ) FILE *file; edge e; int do_succ; { basic_block side = (do_succ ? e->dest : e->src); if (side == ENTRY_BLOCK_PTR) fputs (" ENTRY", file); else if (side == EXIT_BLOCK_PTR) fputs (" EXIT", file); else fprintf (file, " %d", side->index); if (e->flags) { static char * bitnames[] = { "fallthru", "crit", "ab", "abcall", "eh", "fake" }; int comma = 0; int i, flags = e->flags; fputc (' ', file); fputc ('(', file); for (i = 0; flags; i++) if (flags & (1 << i)) { flags &= ~(1 << i); if (comma) fputc (',', file); if (i < (int)(sizeof (bitnames) / sizeof (*bitnames))) fputs (bitnames[i], file); else fprintf (file, "%d", i); comma = 1; } fputc (')', file); } } /* Like print_rtl, but also print out live information for the start of each basic block. */ void print_rtl_with_bb (outf, rtx_first) FILE *outf; rtx rtx_first; { register rtx tmp_rtx; if (rtx_first == 0) fprintf (outf, "(nil)\n"); else { int i; enum bb_state { NOT_IN_BB, IN_ONE_BB, IN_MULTIPLE_BB }; int max_uid = get_max_uid (); basic_block *start = (basic_block *) alloca (max_uid * sizeof (basic_block)); basic_block *end = (basic_block *) alloca (max_uid * sizeof (basic_block)); enum bb_state *in_bb_p = (enum bb_state *) alloca (max_uid * sizeof (enum bb_state)); memset (start, 0, max_uid * sizeof (basic_block)); memset (end, 0, max_uid * sizeof (basic_block)); memset (in_bb_p, 0, max_uid * sizeof (enum bb_state)); for (i = n_basic_blocks - 1; i >= 0; i--) { basic_block bb = BASIC_BLOCK (i); rtx x; start[INSN_UID (bb->head)] = bb; end[INSN_UID (bb->end)] = bb; for (x = bb->head; x != NULL_RTX; x = NEXT_INSN (x)) { enum bb_state state = IN_MULTIPLE_BB; if (in_bb_p[INSN_UID(x)] == NOT_IN_BB) state = IN_ONE_BB; in_bb_p[INSN_UID(x)] = state; if (x == bb->end) break; } } for (tmp_rtx = rtx_first; NULL != tmp_rtx; tmp_rtx = NEXT_INSN (tmp_rtx)) { int did_output; basic_block bb; if ((bb = start[INSN_UID (tmp_rtx)]) != NULL) { fprintf (outf, ";; Start of basic block %d, registers live:", bb->index); EXECUTE_IF_SET_IN_REG_SET (bb->global_live_at_start, 0, i, { fprintf (outf, " %d", i); if (i < FIRST_PSEUDO_REGISTER) fprintf (outf, " [%s]", reg_names[i]); }); putc ('\n', outf); } if (in_bb_p[INSN_UID(tmp_rtx)] == NOT_IN_BB && GET_CODE (tmp_rtx) != NOTE && GET_CODE (tmp_rtx) != BARRIER && ! obey_regdecls) fprintf (outf, ";; Insn is not within a basic block\n"); else if (in_bb_p[INSN_UID(tmp_rtx)] == IN_MULTIPLE_BB) fprintf (outf, ";; Insn is in multiple basic blocks\n"); did_output = print_rtl_single (outf, tmp_rtx); if ((bb = end[INSN_UID (tmp_rtx)]) != NULL) fprintf (outf, ";; End of basic block %d\n", bb->index); if (did_output) putc ('\n', outf); } } } /* Integer list support. */ /* Allocate a node from list *HEAD_PTR. */ static int_list_ptr alloc_int_list_node (head_ptr) int_list_block **head_ptr; { struct int_list_block *first_blk = *head_ptr; if (first_blk == NULL || first_blk->nodes_left <= 0) { first_blk = (struct int_list_block *) xmalloc (sizeof (struct int_list_block)); first_blk->nodes_left = INT_LIST_NODES_IN_BLK; first_blk->next = *head_ptr; *head_ptr = first_blk; } first_blk->nodes_left--; return &first_blk->nodes[first_blk->nodes_left]; } /* Pointer to head of predecessor/successor block list. */ static int_list_block *pred_int_list_blocks; /* Add a new node to integer list LIST with value VAL. LIST is a pointer to a list object to allow for different implementations. If *LIST is initially NULL, the list is empty. The caller must not care whether the element is added to the front or to the end of the list (to allow for different implementations). */ static int_list_ptr add_int_list_node (blk_list, list, val) int_list_block **blk_list; int_list **list; int val; { int_list_ptr p = alloc_int_list_node (blk_list); p->val = val; p->next = *list; *list = p; return p; } /* Free the blocks of lists at BLK_LIST. */ void free_int_list (blk_list) int_list_block **blk_list; { int_list_block *p, *next; for (p = *blk_list; p != NULL; p = next) { next = p->next; free (p); } /* Mark list as empty for the next function we compile. */ *blk_list = NULL; } /* Predecessor/successor computation. */ /* Mark PRED_BB a precessor of SUCC_BB, and conversely SUCC_BB a successor of PRED_BB. */ static void add_pred_succ (pred_bb, succ_bb, s_preds, s_succs, num_preds, num_succs) int pred_bb; int succ_bb; int_list_ptr *s_preds; int_list_ptr *s_succs; int *num_preds; int *num_succs; { if (succ_bb != EXIT_BLOCK) { add_int_list_node (&pred_int_list_blocks, &s_preds[succ_bb], pred_bb); num_preds[succ_bb]++; } if (pred_bb != ENTRY_BLOCK) { add_int_list_node (&pred_int_list_blocks, &s_succs[pred_bb], succ_bb); num_succs[pred_bb]++; } } /* Convert edge lists into pred/succ lists for backward compatibility. */ void compute_preds_succs (s_preds, s_succs, num_preds, num_succs) int_list_ptr *s_preds; int_list_ptr *s_succs; int *num_preds; int *num_succs; { int i, n = n_basic_blocks; edge e; memset (s_preds, 0, n_basic_blocks * sizeof (int_list_ptr)); memset (s_succs, 0, n_basic_blocks * sizeof (int_list_ptr)); memset (num_preds, 0, n_basic_blocks * sizeof (int)); memset (num_succs, 0, n_basic_blocks * sizeof (int)); for (i = 0; i < n; ++i) { basic_block bb = BASIC_BLOCK (i); for (e = bb->succ; e ; e = e->succ_next) add_pred_succ (i, e->dest->index, s_preds, s_succs, num_preds, num_succs); } for (e = ENTRY_BLOCK_PTR->succ; e ; e = e->succ_next) add_pred_succ (ENTRY_BLOCK, e->dest->index, s_preds, s_succs, num_preds, num_succs); } void dump_bb_data (file, preds, succs, live_info) FILE *file; int_list_ptr *preds; int_list_ptr *succs; int live_info; { int bb; int_list_ptr p; fprintf (file, "BB data\n\n"); for (bb = 0; bb < n_basic_blocks; bb++) { fprintf (file, "BB %d, start %d, end %d\n", bb, INSN_UID (BLOCK_HEAD (bb)), INSN_UID (BLOCK_END (bb))); fprintf (file, " preds:"); for (p = preds[bb]; p != NULL; p = p->next) { int pred_bb = INT_LIST_VAL (p); if (pred_bb == ENTRY_BLOCK) fprintf (file, " entry"); else fprintf (file, " %d", pred_bb); } fprintf (file, "\n"); fprintf (file, " succs:"); for (p = succs[bb]; p != NULL; p = p->next) { int succ_bb = INT_LIST_VAL (p); if (succ_bb == EXIT_BLOCK) fprintf (file, " exit"); else fprintf (file, " %d", succ_bb); } if (live_info) { int regno; fprintf (file, "\nRegisters live at start:"); for (regno = 0; regno < max_regno; regno++) if (REGNO_REG_SET_P (BASIC_BLOCK (bb)->global_live_at_start, regno)) fprintf (file, " %d", regno); fprintf (file, "\n"); } fprintf (file, "\n"); } fprintf (file, "\n"); } /* Free basic block data storage. */ void free_bb_mem () { free_int_list (&pred_int_list_blocks); } /* Compute dominator relationships. */ void compute_dominators (dominators, post_dominators, s_preds, s_succs) sbitmap *dominators; sbitmap *post_dominators; int_list_ptr *s_preds; int_list_ptr *s_succs; { int bb, changed, passes; sbitmap *temp_bitmap; temp_bitmap = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks); sbitmap_vector_ones (dominators, n_basic_blocks); sbitmap_vector_ones (post_dominators, n_basic_blocks); sbitmap_vector_zero (temp_bitmap, n_basic_blocks); sbitmap_zero (dominators[0]); SET_BIT (dominators[0], 0); sbitmap_zero (post_dominators[n_basic_blocks - 1]); SET_BIT (post_dominators[n_basic_blocks - 1], 0); passes = 0; changed = 1; while (changed) { changed = 0; for (bb = 1; bb < n_basic_blocks; bb++) { sbitmap_intersect_of_predecessors (temp_bitmap[bb], dominators, bb, s_preds); SET_BIT (temp_bitmap[bb], bb); changed |= sbitmap_a_and_b (dominators[bb], dominators[bb], temp_bitmap[bb]); sbitmap_intersect_of_successors (temp_bitmap[bb], post_dominators, bb, s_succs); SET_BIT (temp_bitmap[bb], bb); changed |= sbitmap_a_and_b (post_dominators[bb], post_dominators[bb], temp_bitmap[bb]); } passes++; } free (temp_bitmap); } /* Given DOMINATORS, compute the immediate dominators into IDOM. */ void compute_immediate_dominators (idom, dominators) int *idom; sbitmap *dominators; { sbitmap *tmp; int b; tmp = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks); /* Begin with tmp(n) = dom(n) - { n }. */ for (b = n_basic_blocks; --b >= 0; ) { sbitmap_copy (tmp[b], dominators[b]); RESET_BIT (tmp[b], b); } /* Subtract out all of our dominator's dominators. */ for (b = n_basic_blocks; --b >= 0; ) { sbitmap tmp_b = tmp[b]; int s; for (s = n_basic_blocks; --s >= 0; ) if (TEST_BIT (tmp_b, s)) sbitmap_difference (tmp_b, tmp_b, tmp[s]); } /* Find the one bit set in the bitmap and put it in the output array. */ for (b = n_basic_blocks; --b >= 0; ) { int t; EXECUTE_IF_SET_IN_SBITMAP (tmp[b], 0, t, { idom[b] = t; }); } sbitmap_vector_free (tmp); } /* Count for a single SET rtx, X. */ static void count_reg_sets_1 (x) rtx x; { register int regno; register rtx reg = SET_DEST (x); /* Find the register that's set/clobbered. */ while (GET_CODE (reg) == SUBREG || GET_CODE (reg) == ZERO_EXTRACT || GET_CODE (reg) == SIGN_EXTRACT || GET_CODE (reg) == STRICT_LOW_PART) reg = XEXP (reg, 0); if (GET_CODE (reg) == PARALLEL && GET_MODE (reg) == BLKmode) { register int i; for (i = XVECLEN (reg, 0) - 1; i >= 0; i--) count_reg_sets_1 (XVECEXP (reg, 0, i)); return; } if (GET_CODE (reg) == REG) { regno = REGNO (reg); if (regno >= FIRST_PSEUDO_REGISTER) { /* Count (weighted) references, stores, etc. This counts a register twice if it is modified, but that is correct. */ REG_N_SETS (regno)++; REG_N_REFS (regno) += loop_depth; } } } /* Increment REG_N_SETS for each SET or CLOBBER found in X; also increment REG_N_REFS by the current loop depth for each SET or CLOBBER found. */ static void count_reg_sets (x) rtx x; { register RTX_CODE code = GET_CODE (x); if (code == SET || code == CLOBBER) count_reg_sets_1 (x); else if (code == PARALLEL) { register int i; for (i = XVECLEN (x, 0) - 1; i >= 0; i--) { code = GET_CODE (XVECEXP (x, 0, i)); if (code == SET || code == CLOBBER) count_reg_sets_1 (XVECEXP (x, 0, i)); } } } /* Increment REG_N_REFS by the current loop depth each register reference found in X. */ static void count_reg_references (x) rtx x; { register RTX_CODE code; retry: code = GET_CODE (x); switch (code) { case LABEL_REF: case SYMBOL_REF: case CONST_INT: case CONST: case CONST_DOUBLE: case PC: case ADDR_VEC: case ADDR_DIFF_VEC: case ASM_INPUT: return; #ifdef HAVE_cc0 case CC0: return; #endif case CLOBBER: /* If we are clobbering a MEM, mark any registers inside the address as being used. */ if (GET_CODE (XEXP (x, 0)) == MEM) count_reg_references (XEXP (XEXP (x, 0), 0)); return; case SUBREG: /* While we're here, optimize this case. */ x = SUBREG_REG (x); /* In case the SUBREG is not of a register, don't optimize */ if (GET_CODE (x) != REG) { count_reg_references (x); return; } /* ... fall through ... */ case REG: if (REGNO (x) >= FIRST_PSEUDO_REGISTER) REG_N_REFS (REGNO (x)) += loop_depth; return; case SET: { register rtx testreg = SET_DEST (x); int mark_dest = 0; /* If storing into MEM, don't show it as being used. But do show the address as being used. */ if (GET_CODE (testreg) == MEM) { count_reg_references (XEXP (testreg, 0)); count_reg_references (SET_SRC (x));) { count_reg_references (SET_SRC (x)); if (mark_dest) count_reg_references (SET_DEST (x)); return; } }; } count_reg_references (XEXP (x, i)); } else if (fmt[i] == 'E') { register int j; for (j = 0; j < XVECLEN (x, i); j++) count_reg_references (XVECEXP (x, i, j)); } } } } /* Recompute register set/reference counts immediately prior to register allocation. This avoids problems with set/reference counts changing to/from values which have special meanings to the register allocators. Additionally, the reference counts are the primary component used by the register allocators to prioritize pseudos for allocation to hard regs. More accurate reference counts generally lead to better register allocation. F is the first insn to be scanned. LOOP_STEP denotes how much loop_depth should be incremented per loop nesting level in order to increase the ref count more for references in a loop. It might be worthwhile to update REG_LIVE_LENGTH, REG_BASIC_BLOCK and possibly other information which is used by the register allocators. */ void recompute_reg_usage (f, loop_step) rtx f; int loop_step; { rtx insn; int i, max_reg; /* Clear out the old data. */ max_reg = max_reg_num (); for (i = FIRST_PSEUDO_REGISTER; i < max_reg; i++) { REG_N_SETS (i) = 0; REG_N_REFS (i) = 0; } /* Scan each insn in the chain and count how many times each register is set/used. */ loop_depth = 1; for (insn = f; insn; insn = NEXT_INSN (insn)) { /* Keep track of loop depth. */ if (GET_CODE (insn) == NOTE) { /* Look for loop boundaries. */ if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END) loop_depth -= loop_step; else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG) loop_depth += loop_step; /* If we have LOOP_DEPTH == 0, there has been a bookkeeping error. Abort now rather than setting register status incorrectly. */ if (loop_depth == 0) abort (); } else if (GET_RTX_CLASS (GET_CODE (insn)) == 'i') { rtx links; /* This call will increment REG_N_SETS for each SET or CLOBBER of a register in INSN. It will also increment REG_N_REFS by the loop depth for each set of a register in INSN. */ count_reg_sets (PATTERN (insn)); /* count_reg_sets does not detect autoincrement address modes, so detect them here by looking at the notes attached to INSN. */ for (links = REG_NOTES (insn); links; links = XEXP (links, 1)) { if (REG_NOTE_KIND (links) == REG_INC) /* Count (weighted) references, stores, etc. This counts a register twice if it is modified, but that is correct. */ REG_N_SETS (REGNO (XEXP (links, 0)))++; } /* This call will increment REG_N_REFS by the current loop depth for each reference to a register in INSN. */ count_reg_references (PATTERN (insn)); /* count_reg_references will not include counts for arguments to function calls, so detect them here by examining the CALL_INSN_FUNCTION_USAGE data. */ if (GET_CODE (insn) == CALL_INSN) { rtx note; for (note = CALL_INSN_FUNCTION_USAGE (insn); note; note = XEXP (note, 1)) if (GET_CODE (XEXP (note, 0)) == USE) count_reg_references (SET_DEST (XEXP (note, 0))); } } } } /* Record INSN's block as BB. */ void set_block_for_insn (insn, bb) rtx insn; basic_block bb; { size_t uid = INSN_UID (insn); if (uid >= basic_block_for_insn->num_elements) { int new_size; /* Add one-eighth the size so we don't keep calling xrealloc. */ new_size = uid + (uid + 7) / 8; VARRAY_GROW (basic_block_for_insn, new_size); } VARRAY_BB (basic_block_for_insn, uid) = bb; } /* Record INSN's block number as BB. */ /* ??? This has got to go. */ void set_block_num (insn, bb) rtx insn; int bb; { set_block_for_insn (insn, BASIC_BLOCK (bb)); } /* Verify the CFG consistency. This function check some CFG invariants and aborts when something is wrong. Hope that this function will help to convert many optimization passes to preserve CFG consistent. Currently it does following checks: - test head/end pointers - overlapping of basic blocks - edge list corectness - headers of basic blocks (the NOTE_INSN_BASIC_BLOCK note) - tails of basic blocks (ensure that boundary is necesary) - scans body of the basic block for JUMP_INSN, CODE_LABEL and NOTE_INSN_BASIC_BLOCK - check that all insns are in the basic blocks (except the switch handling code, barriers and notes) In future it can be extended check a lot of other stuff as well (reachability of basic blocks, life information, etc. etc.). */ void verify_flow_info () { const int max_uid = get_max_uid (); const rtx rtx_first = get_insns (); basic_block *bb_info; rtx x; int i; bb_info = (basic_block *) alloca (max_uid * sizeof (basic_block)); memset (bb_info, 0, max_uid * sizeof (basic_block)); /* First pass check head/end pointers and set bb_info array used by later passes. */ for (i = n_basic_blocks - 1; i >= 0; i--) { basic_block bb = BASIC_BLOCK (i); /* Check the head pointer and make sure that it is pointing into insn list. */ for (x = rtx_first; x != NULL_RTX; x = NEXT_INSN (x)) if (x == bb->head) break; if (!x) { fatal ("verify_flow_info: Head insn %d for block %d not found in the insn stream.\n", INSN_UID (bb->head), bb->index); } /* Check the end pointer and make sure that it is pointing into insn list. */ for (x = bb->head; x != NULL_RTX; x = NEXT_INSN (x)) { if (bb_info[INSN_UID (x)] != NULL) { fatal ("verify_flow_info: Insn %d is in multiple basic blocks (%d and %d)", INSN_UID (x), bb->index, bb_info[INSN_UID (x)]->index); } bb_info[INSN_UID (x)] = bb; if (x == bb->end) break; } if (!x) { fatal ("verify_flow_info: End insn %d for block %d not found in the insn stream.\n", INSN_UID (bb->end), bb->index); } } /* Now check the basic blocks (boundaries etc.) */ for (i = n_basic_blocks - 1; i >= 0; i--) { basic_block bb = BASIC_BLOCK (i); /* Check corectness of edge lists */ edge e; e = bb->succ; while (e) { if (e->src != bb) { fprintf (stderr, "verify_flow_info: Basic block %d succ edge is corrupted\n", bb->index); fprintf (stderr, "Predecessor: "); dump_edge_info (stderr, e, 0); fprintf (stderr, "\nSuccessor: "); dump_edge_info (stderr, e, 1); fflush (stderr); abort (); } if (e->dest != EXIT_BLOCK_PTR) { edge e2 = e->dest->pred; while (e2 && e2 != e) e2 = e2->pred_next; if (!e2) { fatal ("verify_flow_info: Basic block %i edge lists are corrupted\n", bb->index); } } e = e->succ_next; } e = bb->pred; while (e) { if (e->dest != bb) { fprintf (stderr, "verify_flow_info: Basic block %d pred edge is corrupted\n", bb->index); fprintf (stderr, "Predecessor: "); dump_edge_info (stderr, e, 0); fprintf (stderr, "\nSuccessor: "); dump_edge_info (stderr, e, 1); fflush (stderr); abort (); } if (e->src != ENTRY_BLOCK_PTR) { edge e2 = e->src->succ; while (e2 && e2 != e) e2 = e2->succ_next; if (!e2) { fatal ("verify_flow_info: Basic block %i edge lists are corrupted\n", bb->index); } } e = e->pred_next; } /* OK pointers are correct. Now check the header of basic block. It ought to contain optional CODE_LABEL followed by NOTE_BASIC_BLOCK. */ x = bb->head; if (GET_CODE (x) == CODE_LABEL) { if (bb->end == x) { fatal ("verify_flow_info: Basic block contains only CODE_LABEL and no NOTE_INSN_BASIC_BLOCK note\n"); } x = NEXT_INSN (x); } if (GET_CODE (x) != NOTE || NOTE_LINE_NUMBER (x) != NOTE_INSN_BASIC_BLOCK || NOTE_BASIC_BLOCK (x) != bb) { fatal ("verify_flow_info: NOTE_INSN_BASIC_BLOCK is missing for block %d\n", bb->index); } if (bb->end == x) { /* Do checks for empty blocks here */ } else { x = NEXT_INSN (x); while (x) { if (GET_CODE (x) == NOTE && NOTE_LINE_NUMBER (x) == NOTE_INSN_BASIC_BLOCK) { fatal ("verify_flow_info: NOTE_INSN_BASIC_BLOCK %d in the middle of basic block %d\n", INSN_UID (x), bb->index); } if (x == bb->end) break; if (GET_CODE (x) == JUMP_INSN || GET_CODE (x) == CODE_LABEL || GET_CODE (x) == BARRIER) { fatal_insn ("verify_flow_info: Incorrect insn in the middle of basic block %d\n", x, bb->index); } x = NEXT_INSN (x); } } } x = rtx_first; while (x) { if (!bb_info[INSN_UID (x)]) { switch (GET_CODE (x)) { case BARRIER: case NOTE: break; case CODE_LABEL: /* An addr_vec is placed outside any block block. */ if (NEXT_INSN (x) && GET_CODE (NEXT_INSN (x)) == JUMP_INSN && (GET_CODE (PATTERN (NEXT_INSN (x))) == ADDR_DIFF_VEC || GET_CODE (PATTERN (NEXT_INSN (x))) == ADDR_VEC)) { x = NEXT_INSN (x); } /* But in any case, non-deletable labels can appear anywhere. */ break; default: fatal_insn ("verify_flow_info: Insn outside basic block\n", x); } } x = NEXT_INSN (x); } }
http://opensource.apple.com//source/gcc/gcc-926/gcc/flow.c
CC-MAIN-2016-36
refinedweb
17,866
59.94
The Event Loop and Dart Written by Kathy Walrath September 2013 (updated October 2013) Asynchronous code is everywhere in Dart. Many library functions return Future objects, and you can register handlers to respond to events such as mouse clicks, file I/O completions, and timer expirations. This article describes Dart’s event loop architecture, so that you can write better asynchronous code with fewer surprises. You’ll learn options for scheduling future tasks, and you’ll be able to predict the order of execution. Before reading this article, you should be familiar with the basics of Futures and Error Handling. Basic conceptsBasic concepts If you’ve written UI code, you’re probably familiar with the concepts of the event loop and the event queue. They ensure that graphics operations and events such as mouse clicks are handled one at a time. Event loops and queuesEvent loops and queues An event loop’s job is to take an item from the event queue and handle it, repeating these two steps for as long as the queue has items. The items in the queue might represent user input, file I/O notifications, timers, and more. For example, here’s a picture of the event queue that contains timer and user input events: All of that might be familiar from non-Dart languages you know. Now let’s talk about how it fits into the Dart platform. Dart’s single thread of executionDart’s single thread of execution Once a Dart function starts executing, it continues executing until it exits. In other words, Dart functions can’t be interrupted by other Dart code. As the following figure shows, a Dart app starts execution when its main isolate executes the app’s main() function. After main() exits, the main isolate’s thread begins to handle any items on the app’s event queue, one by one. Actually, that’s a slight oversimplification. Dart’s event loop and queuesDart’s event loop and queues A Dart app has a single event loop with two queues—the event queue and the microtask queue. The event queue contains all outside events: I/O, mouse events, drawing events, timers, messages between Dart isolates, and so on. The microtask queue is necessary because event-handling code sometimes needs to complete a task later, but before returning control to the event loop. For example, when an observable object changes, it groups several mutation changes together and reports them asychronously. The microtask queue allows the observable object to report these mutation changes before the DOM can show the inconsistent state. The event queue contains events both from Dart and from elsewhere in the system. Currently, the microtask queue contains only entries originating from within Dart code, but we expect the web implementation to plug into the browser microtask queue. (For the latest status, see dartbug.com/13433.) As the following figure shows, when main() exits, the event loop starts its work. First, it executes any microtasks, in FIFO order. Then it dequeues and handles the first item on the event queue. Then it repeats the cycle: execute all microtasks, and then handle the next item on the event queue. Once both queues are empty and no more events are expected, the app’s embedder (such as the browser or a test framework) can dispose of the app. Although you can predict the order of task execution, you can’t predict exactly when an event loop will take a task off the queue. The Dart event handling system is based on a single-threaded cycle; it isn’t based on ticks or any other kind of time measurement. For example, when you create a delayed task, an event is enqueued at the time you specify. However, that event can’t be handled until everything before it in the event queue (as well as every single task in the microtask queue) is handled. Tip: Chain futures to specify task orderTip: Chain futures to specify task order If your code has dependencies, make them explicit. Explicit dependencies help other developers to understand your code, and they make your program more resistant to code refactoring. Here’s an example of the wrong way to code: // BAD because of no explicit dependency between setting and using // the variable. future.then(...set an important variable...); Timer.run(() {...use the important variable...}); Instead, write code like this: // BETTER because the dependency is explicit. future.then(...set an important variable...) .then((_) {...use the important variable...}); The better code uses then() to specify that the variable must be set before it can be used. (You can use whenComplete() instead of then() if you want the code to execute even if an error occurs.) If using the variable takes time and can be done later, consider putting that code in a new Future: // MAYBE EVEN BETTER: Explicit dependency plus delayed execution. future.then(...set an important variable...) .then((_) {new Future(() {...use the important variable...})}); Using a new Future gives the event loop a chance to process other events from the event queue. The next section gives details on scheduling code to run later. How to schedule a taskHow to schedule a task When you need to specify some code to be executed later, you can use the following APIs provided by the dart:async library: - The Future class, which adds an item to the end of the event queue. - The top-level scheduleMicrotask() function, which adds an item to the end of the microtask queue. Examples of using these APIs are in the next section under Event queue: new Future() and Microtask queue: scheduleMicrotask(). Use the appropriate queue (usually: the event queue)Use the appropriate queue (usually: the event queue) Whenever possible, schedule tasks on the event queue, with Future. Using the event queue helps keep the the microtask queue short, reducing the likelihood of the microtask queue starving the event queue. If a task absolutely must complete before any items from the event queue are handled, then you should usually just execute the function immediately. If you can’t, then use scheduleMicrotask() to add an item to the microtask queue. For example, in a web app use a microtask to avoid prematurely releasing a js-interop proxy or ending an IndexedDB transaction or event handler. Event queue: new Future()Event queue: new Future() To schedule a task on the event queue, use new Future() or new Future.delayed(). These are two of the Future constructors defined in the dart:async library. To immediately put an item on the event queue, use new Future(): // Adds a task to the event queue. new Future(() { // ...code goes here... }); You can add a call to then() or whenComplete() to execute some code immediately after the new Future completes. For example, the following code prints “42” when the new Future’s task is dequeued: new Future(() => 21) .then((v) => v*2) .then((v) => print(v)); To enqueue an item after some time elapses, use new Future.delayed(): // After a one-second delay, adds a task to the event queue. new Future.delayed(const Duration(seconds:1), () { // ...code goes here... }); Although the preceding example adds the task to the event queue after one second, that task can’t execute until the main isolate is idle, the microtask queue is empty, and previously enqueued entries in the event queue are gone. For example, if the main() function or an event handler are running an expensive computation, the task can’t execute until after that computation completes. In that case, the delay might be much more than one second.. Microtask queue: scheduleMicrotask()Microtask queue: scheduleMicrotask() The dart:async library defines scheduleMicrotask() as a top-level function. You can call scheduleMicrotask() like this: scheduleMicrotask(() { // ...code goes here... }); Due to bugs 9001 and 9002, the first call to scheduleMicrotask() schedules a task on the event queue; this task creates the microtask queue and enqueues the function specified to scheduleMicrotask(). As long as the microtask queue has at least one entry, subsequent calls to scheduleMicrotask() correctly add to the microtask queue. Once the microtask queue is empty, it must be created again the next time scheduleMicrotask() is called. The upshot of these bugs: The first task that you schedule with scheduleMicrotask() seems like it’s on the event queue. A workaround is to put your first call to scheduleMicrotask() before your first call to new Future(). This creates the microtask queue before executing other tasks on the event queue. However, it doesn’t stop external events from being added to the event queue. It also doesn’t help when you have a delayed task. Another way to add a task to the microtask queue is to invoke then() on a Future that’s already complete. See the previous section for more information. Use isolates or workers if necessaryUse isolates or workers if necessary. You can also use more isolates than CPUs if that’s a good architecture for your app. For example, you might use a separate isolate for each piece of functionality, or when you need to ensure that data isn’t shared. Test your understandingTest your understanding Now that you’ve read all about scheduling tasks, let’s test your understanding. Remember, you shouldn’t depend on Dart’s event queue implementation to specify task order. The implementation might change, and Future’s then() and whenComplete() methods are a better alternative. Still, won’t you feel smart if you can answer these questions correctly? Question #1Question #1 What does this sample print out? import 'dart:async'; void main() { print('main #1 of 2'); scheduleMicrotask(() => print('microtask #1 of 2')); new Future.delayed(new Duration(seconds:1), () => print('future #1 (delayed)')); new Future(() => print('future #2 of 3')); new Future(() => print('future #3 of 3')); scheduleMicrotask(() => print('microtask #2 of 2')); print('main #2 of 2'); } The answer: main #1 of 2 main #2 of 2 microtask #1 of 2 microtask #2 of 2 future #2 of 3 future #3 of 3 future #1 (delayed) That order should be what you expected, since the example’s code executes in three batches: - code in the main() function - tasks in the microtask queue (scheduleMicrotask()) - tasks in the event queue (new Future() or new Future.delayed()) Keep in mind that all the calls in the main() function execute synchronously, start to finish. First main() calls print(), then scheduleMicrotask(), then new Future.delayed(), then new Future(), and so on. Only the callbacks—the code in the closure bodies specified as arguments to scheduleMicrotask(), new Future.delayed(), and new Future()—execute at a later time. Question #2Question #2 Here’s a more complex example. If you can correctly predict the output of this code, you get a gold star. import 'dart:async'; void main() { print('main #1 of 2'); scheduleMicrotask(() => print('microtask #1 of 3')); new Future.delayed(new Duration(seconds:1), () => print('future #1 (delayed)')); new Future(() => print('future #2 of 4')) .then((_) => print('future #2a')) .then((_) { print('future #2b'); scheduleMicrotask(() => print('microtask #0 (from future #2b)')); }) .then((_) => print('future #2c')); scheduleMicrotask(() => print('microtask #2 of 3')); new Future(() => print('future #3 of 4')) .then((_) => new Future( () => print('future #3a (a new future)'))) .then((_) => print('future #3b')); new Future(() => print('future #4 of 4')); scheduleMicrotask(() => print('microtask #3 of 3')); print('main #2 of 2'); } The output, assuming bugs 9001/9002 aren’t fixed: main #1 of 2 main #2 of 2 microtask #1 of 3 microtask #2 of 3 microtask #3 of 3 future #2 of 4 future #2a future #2b future #2c future #3 of 4 future #4 of 4 microtask #0 (from future #2b) future #3a (a new future) future #3b future #1 (delayed) Like before, the main() function executes, and then everything on the microtask queue, and then tasks on the event queue. Here are a few interesting points: - When the then() callback for future 3 calls new Future(), it creates a new task (#3a) that’s added to the end of the event queue. - All the then() callbacks execute as soon as the Future they’re invoked on completes. Thus, future 2, 2a, 2b, and 2c execute all in one go, before control returns to the embedder. Similarly, future 3a and 3b execute all in one go. - If you change the 3a code from then((_) => new Future(...))to then((_) {new Future(...); }), then “future #3b” appears earlier (after future #3, instead of future #3a). The reason is that returning a Future from your callback is how you get then() (which itself returns a new Future) to chain those two Futures together, so that the Future returned by then() completes when the Future returned by the callback completes. See the then() reference for more information. Annotated sample and outputAnnotated sample and output Here are some figures that might clarify the answer to question #2. First, here’s the annotated program source: And here’s what the queues and output look like at various points in time, assuming no external events come in: SummarySummary You should now understand Dart’s event loops and how to schedule tasks. Here are some of the major concepts of event loops in Dart: - A Dart app’s event loop executes tasks from two queues: the event queue and the microtask queue. - The event queue has entries from both Dart (futures, timers, isolate messages, and so on) and the system (user actions, I/O, and so on). - Currently, the microtask queue has entries only from Dart, but we expect it to be merged with the browser microtask queue. - The event loop empties the microtask queue before dequeuing and handling the next item on the event queue. - Once both queues are empty, the app has completed its work and (depending on its embedder) can exit. - The main() function and all items from the microtask and event queues run on the Dart app’s main isolate. When you schedule a task, follow these rules: - If possible, put it on the event queue (using new Future() or new Future.delayed()). - Use Future’s then() or whenComplete() method to specify task order. - To avoid starving the event loop, keep the microtask queue as short as possible. - To keep your app responsive, avoid compute-intensive tasks on either event loop. - To perform compute-intensive tasks, create additional isolates or workers. As you write asynchronous code, you might find these resources helpful: - Futures and Error Handling - dart:async - Asynchronous Programming section of the library tour - dart:async API reference
https://webdev.dartlang.org/articles/performance/event-loop
CC-MAIN-2018-26
refinedweb
2,415
62.07
.event;23 24 /**25 * Indicates that a file has been added.26 * @author Robert Greig27 */28 public class FileAddedEvent extends CVSEvent {29 /**30 * The path of the file that has been added31 */32 protected String path;33 34 /**35 * Construct a FileAddedEvent36 * @param source the source of the event37 */38 public FileAddedEvent(Object source, String path) {39 super(source);40 this.path = path;41 }42 43 /**44 * Get the path of the file that has been added45 */46 public String getFilePath() {47 return path;48 }49 50 /**51 * Fire the event to the event listener. Subclasses should call the52 * appropriate method on the listener to dispatch this event.53 * @param listener the event listener54 */55 protected void fireEvent(CVSListener listener) {56 listener.fileAdded(this);57 }58 } Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/netbeans/lib/cvsclient/event/FileAddedEvent.java.htm
CC-MAIN-2017-17
refinedweb
141
70.02
fclose man page fclose — close a stream Synopsis #include <stdio.h> int fclose(FILE *stream); Description The fclose() function flushes the stream pointed to by stream (writing any buffered output data using fflush(3)) and closes the underlying file descriptor. Return Value Upon). Attributes For an explanation of the terms used in this section, see attributes(7)..16 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Referenced By abort(3), close(2), explain(1), explain_fclose(3), explain_fclose_or_die(3), fcloseall(3), fflush(3), fmemopen(3), fopen(3), fopencookie(3), fpurge.3bsd(3), funopen.3bsd(3), gawk(1), open_memstream(3), popen(3), setbuf(3), stdio(3), xdr(3).
https://www.mankier.com/3/fclose
CC-MAIN-2018-43
refinedweb
124
58.99
Provided by: manpages_5.02-1_all NAME epoll - I/O event notification facility SYNOPSIS #include <sys/epoll.h> DESCRIPTION The epoll API performs a similar task to poll(2): monitoring multiple file descriptors to see if I/O is possible on any of them. The epoll API can be used either as an edge- triggered or a level-triggered interface and scales well to large numbers of watched file descriptors. The The epoll event distribution interface is able to behave both as edge-triggered (ET) and as level-triggered (LT). The difference between the two mechanisms can be described as follows. Suppose that this scenario happens: 1. The file descriptor that represents the read side of a pipe (rfd) is registered on the epoll instance.: i with nonblocking file descriptors;) EPOLLWAKEUP flag. When the EPOLLWAKEUP flag is set in the events field for a struct epoll_event, the system will be kept awake from the moment the event is queued, through the epoll_wait(2) call which returns the event until the subsequent epoll_wait(2) call. If the event should keep the system awake beyond that time, then a separate wake_lock should be taken before the second epoll_wait(2) call. /proc interfaces The following interfaces can be used to limit the amount of kernel memory consumed by epoll: /proc/sys/fs/epoll/max_user_watches (since Linux 2.6.28) This specifies a limit on the total number of file descriptors that a user can register across all epoll instances on the system. The limit is per real user ID. Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel, and roughly 160 bytes on a 64-bit kernel. Currently, the default value for max_user_watches is 1/25 (4%) of the available low memory, divided by the registration cost in bytes. Example for suggested usage While the usage of epoll when employed as a level-triggered interface does have the same semantics as poll(2), the edge-triggered usage requires more clarification to avoid stalls in the application event loop. In this example, listener is a nonblocking. #define MAX_EVENTS 10 struct epoll_event ev, events[MAX_EVENTS]; int listen_sock, conn_sock, nfds, epollfd; /* Code to set up listening socket, 'listen_sock', (socket(), bind(), listen()) omitted */ epollfd = epoll_create1(0); if (epollfd == -1) { perror("epoll_create1"); exit(EXIT_FAILURE); } ev.events = EPOLLIN; ev.data.fd = listen_sock; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == -1) { perror("epoll_ctl: listen_sock"); exit(EXIT_FAILURE); } for (;;) { nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1); if (nfds == -1) { perror("epoll_wait"); exit(EXIT_FAILURE); } for (n = 0; n < nfds; ++n) { if (events[n].data.fd == listen_sock) { conn_sock = accept(listen_sock, (struct sockaddr *) &addr, &addrlen); if (conn_sock == -1) { perror("accept"); exit(EXIT_FAILURE); } setnonblocking(conn_sock); ev.events = EPOLLIN | EPOLLET; ev.data.fd = conn_sock; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &ev) == -1) { perror("epoll_ctl: conn_sock"); exit(EXIT_FAILURE); } }? Yes, but be aware of the following point. A file descriptor is a reference to an open file description (see open(2)). Whenever a file. A file descriptor is removed from an)? Receiving an event from epoll_wait(2) should suggest to you that such file descriptor is ready for the requested I/O operation. You must consider it ready until the next (nonblocking) be detected by checking the amount of data read from / written to the target file descriptor. For example, if you call read(2) by asking to read a certain amount of data and read(2) returns a lower number of bytes, you can be sure of having exhausted the read I/O space for the file descriptor. The same is true when writing using write(2). (Avoid this latter technique if you cannot guarantee that the monitored file descriptor always refers to a stream-oriented file.) Possible pitfalls and ways to avoid them o Starvation (edge-triggered) If there is a large amount of I/O space, it is possible that by trying to drain it the other files will not get processed causing starvation. (This problem. VERSIONS The epoll API was introduced in Linux kernel 2.5.44..02 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
https://manpages.ubuntu.com/manpages/eoan/man7/epoll.7.html
CC-MAIN-2021-43
refinedweb
689
54.32
#include <XnCppWrapper.h> Detailed Description Purpose: The NodeWrapper class is the base class for all OpenNI production node classes in C++, for example, the xn::ProductionNode class and the xn::Generator class. The NodeWrapper class is the C++ API wrapper around the OpenNI C XnNodeHandle API. Remarks: A fundamental OpenNI concept that is critical to understand about nodes and node creation is that all C++ objects are "smart pointers" to the actual nodes. The reason why OpenNI is designed this way is so that the same node can be used to produce data (or provide information) for more than just one (dependant) node or for more than just one software component. When instantiating an object of this class, it doesn't point to any actual node. In order to create an actual node, use one of the Create() methods (e.g. DepthGenerator::Create()). Constructor & Destructor Documentation Ctor - Parameters: - Member Function Documentation References a production node, increasing its reference count by 1.For full details and usage, see xnProductionNodeAddRef Gets the underlying C handle. This method checks that this object points to an actual node (that has been 'created') and does not point to NULL. Returns TRUE if the object points to a node, i.e., the node has been 'created'; FALSE otherwise. Remarks This method is a very important for managing nodes in the production graph. This check is concerned with the stage before actually creating the node, i.e., before invoking the node's Create() method. Checks if two node references do not point to the same actual node. - Parameters: - Checks if two node references point to the same actual node - Parameters: - Unreference a production node, decreasing its reference count by 1. If the reference count reaches zero, the node will be destroyed. Replaces the object being pointed. Friends And Related Function Documentation The documentation for this class was generated from the following file: Generated on Wed May 16 2012 10:16:07 for OpenNI 1.5.4 by
https://documentation.help/OpenNI/classxn_1_1_node_wrapper.html
CC-MAIN-2021-49
refinedweb
330
54.63
Scikit Learn is the popular python library for building a machine learning model. Its features are classification, regression, clustering algorithms. You can use it for data preprocessing, Hot encoding and many things using it. I have seen the new programmers who want to learn machine learning are unable to install Scikit learn properly. In this tutorial of “How to,” you will learn how to install Scikit Learn in Pycharm ? You have to just follow the simple steps for easy installation. How to Check Scikit Learn is Installed or not? If you write import sklearn you will see the underline with red color. It means that you have not installed scikit learn in Pycharm. Below are the steps you have to follow for the successful installation. Steps to Install Scikit Learn in Pycharm Step 1 : Go to File and Click on the Setting. Step 2: There you will see the Project: your_project_name. Click on it and then project an interpreter. Step 3: You will see all the list of installed packages in the current project. There you will not see scikit learn packages. You have to search and install it. Step 4: Click on + icon right side of the step3 window and type scikit learn in the search window. When you get the scikit-learn package select it and click on install packages. It will successfully install the packages. Step 5: If you are getting error like the below then the final step is to install the sklearn using the terminal . Step 6: Go the terminal of the Pycharm and use the pip command to install the scikit learn. pip install scikit-learn It will successfully install the scikit- learn package in Pycharm. How to test Installation of Scikit Learn ? After the installation using the above steps To check whether scikit learn is installed or not. You can use the following code and run it. import sklearn print(sklearn.__version__) Other Questions Asked by the Readers Question: I am getting no module named sklearn error. How to solve this issue? To solve this import error problem you have to install the scikit-learn python module. You can follow the above steps if you are installing in your Pycharm. But if you want to install using pip then use the following command. pip install -U scikit-learn It will update the existing sklearn module if available or install it if it is not available. For the python 3.xx version use pip3 pip3 install -U scikit-learn Join our list Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
https://www.datasciencelearner.com/how-to-install-scikit-learn-in-pycharm/
CC-MAIN-2021-39
refinedweb
433
75.71
Actually permissions are of 2 types: 1.Model level permissions 2.object level permissions If you want to give permissions on all cars, then Model-level is appropriate, but if you Django to give permissions on a per-car basis you want Object-level. You may need both, and this isn't a problem as we'll see. For Model permissions, Django will create permissions in the form 'appname.permissionname_modelname' for each model. If you have an app called 'drivers' with the Car model then one permission would be 'drivers.delete_car'. The permissions that Django automatically creates will be create, change, and delete.Read permission is not included in CRUD operation.Django decided to change CRUD's 'update' to 'change' for some reason. You can use the metaclass to add more permissions to a model.: 'perms' of a model object called entity in the app def has_model_permissions( entity, model, perms, app ): for p in perms: if not entity.has_perm( "%s.%s_%s" % ( app, p, model.__name__ ) ): return False return True Here entity is the Entity object to check permissions on (Group or User), model is the instance of a model(entity), perms is a list of permissions as strings to check (e.g. ['read', 'change']) for respective object, models in a project. add: user.has_perm('drivers.add_book') change: user.has_perm('drivers.change_book') delete: user.has_perm('drivers.delete_book') With the help of model django.contrib.auth.models.Group,we can categorizing users so you can apply permissions to group....
https://micropyramid.com/blog/understanding-django-permissions-and-groups/
CC-MAIN-2018-34
refinedweb
248
51.44
Over the past few months of slinging Ruby here at thoughtbot, I’ve picked up quite a few ~~stupid ruby tricks~~ smart ruby techniques that really help out your code. If you’ve got your own, feel free to leave a comment. Destructuring yielded arrays def touch_down yield [3, 7] puts "touchdown!" end touch_down do |(first_down, second_down)| puts "#{first_down} yards on the run" puts "#{second_down} yards passed" end => "3 yards on the run" => "7 yards passed" => "touchdown!" At first glance, this barely looks like valid Ruby. But somehow, it just makes sense: it splits up the array. If you’re going to pull out the values of the array inside of the block, why not just do it when you’re defining the block-level variables? This doesn’t seem to work nicely (in 1.8.7 at least) for Hashes, though. Pulling out elements of an array >> args = [1, 2, 3] >> first, *rest = args >> first => 1 >> rest => [2, 3] I knew about splitting up arrays before into individual arguments, but I didn’t know that you could easily get an array of the rest. Perhaps this is Lisp inspired? The Hash#fetch method >> items = { :apples => 2, :oranges => 3 } => items = {:apples=>2, :oranges=>3} >> items.fetch(:apples) => 2 >> items.fetch(:bananas) { |key| "We don't carry #{key}!"} => We don't carry bananas! This is just a nice little way to provide some default behavior that might be nicer than checking if the value exists in the hash first. The Hash#new method with a block >> smash = Hash.new { |hash, key| hash[key] = "a #{key} just got SMASHED!" } => {} >> smash[:plum] = "cannot smash." => {:plum=>"cannot smash."} >> smash[:watermelon] => {:plum=>"cannot smash.", :watermelon=>"a watermelon just got SMASHED!"} This is a really neat way to cache unknown values for Hashes (read: memoization!) I also heard it’s awesome for implementing a Fibonacci sequence. The Array#sort_by method >> cars = %w[beetle volt camry] => ["beetle", "volt", "camry"] >> cars.sort_by { |car| car.size } => ["volt", "camry", "beetle"] So, Array#sort_by sorts based on the return value of the block. It’s like a built in #map and #sort that rules even more with some Symbol#to_proc magic. The String#present? method >> "brain".present? => true >> "".present? => false I’m sure most Rails developers know about blank? from ActiveSupport, but what about present?. Yeah, it blew my mind too. I like being as positive as possible in conditionals, so toss out those !something.blank? calls today and start using this.
https://robots.thoughtbot.com/stupid-ruby-tricks
CC-MAIN-2018-13
refinedweb
411
76.52
Sequential model-based optimization with a scipy.optimize interface Scikit. Approximated objective function after 50 iterations of gp_minimize. Plot made using skopt.plots.plot_objective. Important links - Static documentation - Static documentation - Example notebooks - can be found in the examples directory. - Issue tracker - - Releases - Install The latest released version of scikit-optimize is v0.5.2, which you can install with: pip install scikit-optimize This installs an essential version of scikit-optimize. To install scikit-optimize with plotting functionality, you can instead do: pip install 'scikit-optimize[plots]' This will install matplotlib along with scikit-optimize. In addition there is a conda-forge package of scikit-optimize: conda install -c conda-forge scikit-optimize Using conda-forge is probably the easiest way to install scikit-optimize on Windows. Getting started Find the minimum of the noisy function f(x) over the range -2 < x < 2 with skopt: import numpy as np from skopt import gp_minimize def f(x): return (np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) + np.random.randn() * 0.1) res = gp_minimize(f, [(-2.0, 2.0)]) For more control over the optimization loop you can use the skopt.Optimizer class: from skopt import Optimizer opt = Optimizer([(-2.0, 2.0)]) for i in range(20): suggested = opt.ask() y = f(suggested) opt.tell(suggested, y) print('iteration:', i, suggested, y) Development The library is still experimental and under heavy development. Checkout the next milestone for the plans for the next release or look at some easy issues to get started contributing. The development version can be installed through: git clone cd scikit-optimize pip install -e. Run all tests by executing pytest in the top level directory. To only run the subset of tests with short run time, you can use pytest -m 'fast_test' (pytest -m 'slow_test' is also possible). To exclude all slow running tests try pytest -m 'not slow_test'. This is implemented using pytest attributes. If a tests runs longer than 1 second, it is marked as slow, else as fast. All contributors are welcome! Making a Release The release procedure is almost completely automated. By tagging a new release travis will build all required packages and push them to PyPI. To make a release create a new issue and work through the following checklist: - update the version tag in setup.py - update the version tag in init.py - update the version tag mentioned in the README - check if the dependencies in setup.py are valid or need unpinning - check that the CHANGELOG.md is up to date - did the last build of master succeed? - create a new release - ping conda-forge Before making a release we usually create a release candidate. If the next release is v0.X then the release candidate should be tagged v0.Xrc1 in setup.py and init.py. Mark a release candidate as a "pre-release" on GitHub when you tag it.
https://pythonawesome.com/sequential-model-based-optimization-with-a-scipy-optimize-interface/
CC-MAIN-2020-05
refinedweb
485
51.75
Here is the link for Amazon: Python for Data Analysis Just to get started, the book suggested getting the all-in-one package from Enthought, then install Pandas package from Pypi. Easy as it sounds, I find the actual steps a little bit different. 1. For Windows and Mac users, there are dmg and exe packages, just need to pick the right one matching your Python version. I use Python 2.7 (lots of packages are not updated to 3 yet). My Windows path for Python27 is C:\Python27, I still want to keep it so I chose C:\Python27EPD and all the later packages picked up the right path right away. 2. When trying to install Pandas (sudo easy_install pandas or packages), it gave an error of requiring Numpy > 1.6. The all-in-one package has some lower number, you can find out by: import numpy numpy.version.version() So better off just download the package, I just picked the latest stable code: For Ubuntu, I used 'sudo apt-get install -U numpy' to get the latest version. 3. Now time to download and install Pandas: 4. Checking now, click on PyLab icon: 5. Then try to import Pandas module and do a simple plot: import pandas plot(arange(10)) # note that this would work regardless of pandas since this is matplotlib. 6. You should see this pop up on the screen, and you can change the graph interactively: Looking forward to know more about data analysis with Python... Stay tuned.. Great Article Final Year Projects for CSE in Python FInal Year Project Centers in Chennai Python Training in Chennai Python Training in Chennai
https://blog.pythonicneteng.com/2012/08/data-analysis-with-python-installation.html
CC-MAIN-2022-27
refinedweb
276
77.77
Created on 2020-05-28 00:06 by vstinner, last changed 2020-06-26 14:58 by p-ganssle. Currently, "import datetime" starts by importing time, math, sys and operator modules, and then execute 2500 lines of Python code, define 7 classes, etc. For what? Just to remove all classes, functions, etc. to replace them with symbols from _decimal module: --- try: from _datetime import * except ImportError: pass else: # Clean up unused names del (_DAYNAMES, _DAYS_BEFORE_MONTH, _DAYS_IN_MONTH, _DI100Y, _DI400Y, _DI4Y, _EPOCH, _MAXORDINAL, _MONTHNAMES, _build_struct_time, _check_date_fields, _check_time_fields, _check_tzinfo_arg, _check_tzname, _check_utc_offset, _cmp, _cmperror, _date_class, _days_before_month, _days_before_year, _days_in_month, _format_time, _format_offset, _index, _is_leap, _isoweek1monday, _math, _ord2ymd, _time, _time_class, _tzinfo_class, _wrap_strftime, _ymd2ord, _divide_and_round, _parse_isoformat_date, _parse_isoformat_time, _parse_hh_mm_ss_ff, _IsoCalendarDate) # XXX Since import * above excludes names that start with _, # docstring does not get overwritten. In the future, it may be # appropriate to maintain a single module level docstring and # remove the following line. from _datetime import __doc__ --- I would prefer to use the same approach than the decimal module which also has large C and Python implementation. Lib/decimal.py is just: --- try: from _decimal import * from _decimal import __doc__ from _decimal import __version__ from _decimal import __libmpdec_version__ except ImportError: from _pydecimal import * from _pydecimal import __doc__ from _pydecimal import __version__ from _pydecimal import __libmpdec_version__ --- Advantages: * Faster import time * Avoid importing indirectly time, math, sys and operator modules, whereas they are not used IMO it also better separate the C and the Python implementations. Attached PR implements this idea. Currently, "import datetime" imports 4 modules: ['_operator', 'encodings.ascii', 'math', 'operator'] With the PR, "import datetime" imports only 1 module: ['encodings.ascii'] Import performance: [ref] 814 us +- 32 us -> [change] 189 us +- 4 us: 4.31x faster (-77%) Measured by: env/bin/python -m pyperf timeit -s 'import sys' 'import datetime; del sys.modules["datetime"]; del sys.modules["_datetime"]; del datetime' Note: I noticed that "import datetime" imports the math module while working on minimizing "import test.support" imports, bpo-40275. What do decimals have to datetime? > What do decimals have to datetime? Oops. Sorry, I was confused between "datetime" and "decimal" when I created this issue. I fixed the issue title. My idea is to mimick Lib/decimal.py design for Lib/datetime.py. I basically agree with this — this is one of the reasons I structured the zoneinfo module the way I did rather than mimicking the pattern in datetime. I believe that there are other modules that have similar situations like heapq, but datetime is probably the worst offender.. As it is now, I would be shocked if this didn't break *someone*, because people are always relying on weird implementation details (knowingly or unknowingly), but I think it's worth doing; it's good to tackle it this early in the cycle. @vstinner What do you think about restructuring into a folder-based submodule rather than _pydatetime.py? It's way more likely to break someone, but I think it might be the better way to organize the code, and I don't want to have to go through *two* refactors of this sort. > I believe that there are other modules that have similar situations like heapq, but datetime is probably the worst offender. heapq seems to be a little bit different. _heapq is not a drop-in replacement of heapq.py. For example, nlargest() seems to only be implemented in pure Python. >. I have no idea what are the side effects of converting datetime.py file into a package. A single file _pydatetime.py seems more convenient to me. I'm aware of _strptime.py but I don't see it as a datetime submodule and I don't see the value of moving it as a datetime submodule. I'm fine with _datetime accessing _strptime module. It sounds more complex to me if _datetime would be imported by datetime which contains datetime._strptime. I see a higher risk of subtle import issues, since datetime has two implementations (C and Python). But it may be wrong :-) Also, all other stdlib modules which have a C implementation are designed with files, not folders: io.py (_io and _pyio) and decimal.py (_decimal and _pydecimal) are good examples. I mostly case about reducing the number of indirect imports and import performance. I don't have a strong opinion about file vs folder. > As it is now, I would be shocked if this didn't break *someone*, because people are always relying on weird implementation details (knowingly or unknowingly), but I think it's worth doing; it's good to tackle it this early in the cycle. I'm fine with breaking applications relying on implementation details. Also, we can adjust the code to fix such corner cases later if it's needed, possible and justified :-) About _strptime, I see that the time.strptime() imports internally the _strptime module. If we move _strptime inside datetime: does it mean that calling time.strptime() would have to import the datetime module? It doesn't sound right to me. I see the time as the low-level interface: it should not rely on the high-level interface. I prefer to separate _strptime module from the datetime module. > bout _strptime, I see that the time.strptime() imports internally the _strptime module. Ah, sorry, my remark about including `_strptime` was off the cuff — I thought it was only used in `datetime`, which is why I said "possibly _strptime". If it's used for `time` as well, we should leave it where it is. As for deciding between moving to `datetime/` and moving to `_pydatetime`, I think we should send an e-mail to Python-Dev about it to get a wider perspective, because the import machinery is a lot of black magic, and I know that there are large proprietary code bases out there that pile weird stuff on top of it. I'm not sure I can fully appreciate the trade-offs. The biggest advantage I see to moving `datetime` into its own folder is that it gives us a lot more freedom to expand into smaller sub-modules in the future. For example, in `zoneinfo`, we have zoneinfo/_common.py (), which is some logic shared between the C and Python implementations; `_zoneinfo.c` is able to rely directly on `_common.py` without importing `zoneinfo/_zoneinfo.py` (which saves us a bunch of other module imports as well). Right now the C implementation of `datetime` only directly imports `time` and `_strptime`, but I could imagine future enhancements that would be stupidly inconvenient to implement in C, but where we wouldn't want to implement all of _pydatetime just to get a pure-Python implementation. Having a namespace available for such packages would be useful.
https://bugs.python.org/issue40799
CC-MAIN-2021-17
refinedweb
1,113
55.64
This file contains important information you will need to know if you are going to hack on the GNU Classpath project code. This document contains important information you'll want to know if you want to hack on GNU Classpath, Essential Libraries for Java, to help create free core class libraries for use with virtual machines and compilers for the java programming language. The GNU Classpath Project is dedicated to providing a 100% free, clean room implementation of the standard core class libraries for compilers and runtime environments for the java programming language. It offers free software developers an alternative core library implementation upon which larger java-like programming environments can be built. The GNU Classpath Project was started in the Spring of 1998 as an official Free Software Foundation project. Most of the volunteers working on GNU Classpath do so in their spare time, but a couple of projects based on GNU Classpath have paid programmers to improve the core libraries. We appreciate everyone's efforts in the past to improve and help the project and look forward to future contributions by old and new members alike. Although GNU Classpath is following an open development model where input from developers is welcome, there are certain base requirements that need to be met by anyone who wants to contribute code to this project. They are mostly dictated by legal requirements and are not arbitrary restrictions chosen by the GNU Classpath team. You will need to adhere to the following things if you want to donate code to the GNU Classpath project: The GNU Classpath project needs volunteers to help us out. People are needed to write unimplemented core packages, to test GNU Classpath on free software programs written in the java programming language, to test it on various platforms, and to port it to platforms that are currently unsupported. While pretty much all contributions are welcome (but see see section Requirements) it is always preferable that volunteers do the whole job when volunteering for a task. So when you volunteer to write a Java package, please be willing to do the following: Writing good documentation, tests and fixing bugs should be every developer's top priority in order to reach the elusive release of version 1.0. The goal of the Classpath project is to produce a free implementation of the standard class library for Java. However, there are other more specific goals as to which platforms should be supported. Classpath is targeted to support the following operating systems: While free operating systems are the top priority, the other priorities can shift depending on whether or not there is a volunteer to port Classpath to those platforms and to test releases. Eventually we hope the Classpath will support all JVMs that provide JNI or CNI support. However, the top priority is free JVMs. A small list of Compiler/VM environments that are currently actively incorporating GNU Classpath is below. A more complete overview of projects based on GNU classpath can be found online at the GNU Classpath stories page. As with OS platform support, this priority list could change if a volunteer comes forward to port, maintain, and test releases for a particular JVM. Since gcj is part of the GNU Compiler Collective it is one of the most important targets. But since it doesn't currently work out of the box with GNU Classpath it is not the easiest target. When hacking on GNU Classpath the easiest solution is to use compilers and runtime environments that work out of the box with it, such as the Eclipse compiler, ecj, and the runtime environments jamvm and cacao. Both Jikes RVM and Kaffe use an included version of GNU Classpath by default, but Kaffe can now use a pre-installed version and Jikes RVM supports using a CVS snapshot as well as the latest release. Working directly with targets such as Jikes RVM, gcj and IKVM is possible but can be a little more difficult as changes have to be merged back into GNU Classpath proper, which requires additional work. Due to a recent switch to the use of 1.5 language features within GNU Classpath, a compiler compatible with these features is required. At present, this includes the Eclipse compiler, ecj, and the OpenJDK compiler. GNU Classpath currently implements the majority of the 1.4 and 1.5 APIs (binary compatibility is above 95% for both, but does not take into account internal implementations of features such as graphic and sound support). There is support for some 1.6 APIs but this is still nascent. Please do not create classes that depend on features in other packages unless GNU Classpath already contains those features. GNU Classpath has been free of any proprietary dependencies for a long time now and we like to keep it that way. Finishing, polishing up, documenting, testing and debugging current functionality is of higher priority then adding new functionality. If you want to hack on Classpath, you should at least download and install the following tools and try to familiarize yourself with them. In most cases having these tools installed will be all you really need to know about them. Also note that when working on (snapshot) releases only a 1.5 compiler (plus a free VM from the list above and the libraries listed below) is required. The other tools are only needed when working directly on the CVS version. All of these tools are available from gnudist.gnu.org via anonymous ftp, except CVS which is available from and the Eclipse Compiler for Java, which is available from. Except for the Eclipse Compiler for Java, they are fully documented with texinfo manuals. Texinfo can be browsed with the Emacs editor, or with the text editor of your choice, or transformed into nicely printable Postscript. Here is a brief description of the purpose of those tools. GNU make ("gmake") is required for building Classpath. The GNU Compiler Collection. This contains a C compiler (gcc) for compiling the native C code and a compiler for the java programming language (gcj). You will need at least gcc version 2.95 or higher in order to compile the native code. There is currently no released version of gcj that can compile the Java 1.5 programming language used by GNU Classpath. The Eclipse Compiler for Java. This is a compiler for the Java 1.5 programming language. It translates source code to bytecode. The Eclipse Foundation makes "ecj.jar" available as the JDT Core Batch Compiler download. A version control system that maintains a centralized Internet repository of all code in the Classpath system. This tool automatically creates `Makefile.in' files from `Makefile.am' files. The `Makefile.in' is turned into a `Makefile' by autoconf. Why use this? Because it automatically generates every makefile target you would ever want (`clean', `install', `dist', etc) in full compliance with the GNU coding standards. It also simplifies Makefile creation in a number of ways that cannot be described here. Read the docs for more info. Automatically configures a package for the platform on which it is being built and generates the Makefile for that platform. Handles all of the zillions of hairy platform specific options needed to build shared libraries. The free GNU replacement for the standard Unix macro processor. Proprietary m4 programs are broken and so GNU m4 is required for autoconf to work though knowing a lot about GNU m4 is not required to work with autoconf. Larry Wall's scripting language. It is used internally by automake. Manuals and documentation (like this guide) are written in texinfo. Texinfo is the official documentation format of the GNU project. Texinfo uses a single source file to produce output in a number of formats, both online and printed (dvi, info, html, xml, etc.). This means that instead of writing different documents for online information and another for a printed manual, you need write only one document. And when the work is revised, you need revise only that one document. For any build environment involving native libraries, recent versions of autoconf, automake, and libtool are required if changes are made that require rebuilding `configure', `Makefile.in', `aclocal.m4', or `config.h.in'. When working from CVS you can run those tools by executing autogen.sh in the source directory. For building the Java bytecode (.class files), you can select which compiler should be employed using `--with-javac' or `--with-ecj' as an argument to configure; the present default is ecj if found. Instead of ecj, you can also use javac, which is available at openjdk.dev.java.net/compiler. For compiling the native AWT libraries you need to have the following libraries installed (unless `--disable-gtk-peer' is used as an argument to configure): GTK+ is a multi-platform toolkit for creating graphical user interfaces. It is used as the basis of the GNU desktop project GNOME. gdk-pixbuf is a GNOME library for representing images. hosts the XTest Extension (libXtst). It is necessary for GdkRobot support in java.awt. There is a bug in earlier versions of at-spi, atk, and gail, which are used for GNOME accessibility. Prior to version 1.18.0 of these packages, gtk graphical applications should be run without accessibility (clear the GTK_MODULES environment variable). For building the Qt AWT peer JNI native libraries you have to specify `--enable-qt-peer' and need the following library: Qt version 4.0.1 or higher. The Qt library is a cross-platform graphics toolkit. Please note that at the moment most operating systems do not ship Qt version 4.0.1 by default. We recommend using GNU Classpath' Qt support only for its developers and bug reporters. See the wiki for details on how to get it to work. For building the X AWT peers you have to specify where to find the Escher library on your system using the `--with-escher=ABS.PATH' option. You will need the following library: Escher version 0.2.3 or higher. The Escher library is an implementation of X protocol and associated libraries written in the Java programming language. For building the ALSA midi provider code you will need the following library: ALSA libraries. The ALSA project provides sound device drivers and associated libraries for the Linux kernel. Building the ALSA midi provider code can be disabled by passing `--disable-alsa' to configure. For building the DSSI midi synthesizer provider code you will need the following libraries: DSSI library for audio processing plugins. liblo, the Lightweight OSC implementation. LADSPA, the Linux Audio Developer's Simple Plugin API. JACK, a low latency audio server. libsndfile, an audio file I/O library. fluidsynth, a real-time SoundFont 2 based soft-synth. The GConf-based backend for java.util.prefs needs the following library headers: GConf version 2.6.0 (or higher). GConf is used for storing desktop and application configuration settings in GNOME. The GStreamer backend for javax.sound.sampled (The Java Sound API, not including the MIDI portion) needs the following library headers: GStreamer version 0.10.10 (or higher). You will also need at least gstreamer-base and gstreamer-plugins-base. More plugins can be used to allow streaming of different sound types but are not a compile time requirement. See README.gstreamer in the source distribution for more informations. For building gcjwebplugin you'll need the Mozilla plugin support headers and libraries, which are available at. For enabling the com.sun.tools.javac support in tools.zip you will need a jar file containing the Eclipse Java Compiler. Otherwise com.sun.tools.javac will not be included in `tools.zip'. For building the xmlj JAXP implementation (disabled by default, use configure --enable-xmlj) you need the following libraries: libxml2 version 2.6.8 or higher. The libxml2 library is the XML C library for the Gnome desktop. libxslt version 1.1.11 or higher. The libxslt library if the XSLT C library for the Gnome desktop. GNU Classpath comes with a couple of libraries included in the source that are not part of GNU Classpath proper, but that have been included to provide certain needed functionality. All these external libraries should be clearly marked as such. In general we try to use as much as possible the clean upstream versions of these sources. That way merging in new versions will be easier. You should always try to get bug fixes to these files accepted upstream first. Currently we include the following 'external' libraries. Most of these sources are included in the `external' directory. That directory also contains a `README' file explaining how to import newer versions. Can be found in `external/jsr166'. Provides java.util.concurrent and its subpackages. Upstream is Doug Lea's Concurrency Interest Site. Can be found in `external/relaxngDatatype'. Provides org.relaxng.datatype and its subpackages. Upstream is. Can be found in `external/sax'. Provides org.xml.sax and its subpackages. Upstream is. Can be found in `external/w3c_dom'. Provides org.w3c.dom and its subpackages. Upstream locations are listed in `external/w3c_dom/README'. Can be found in `native/fdlibm'. Provides native implementations of some of the Float and Double operations. Upstream is libgcj, they sync again with the 'real' upstream. See also java.lang.StrictMath. This package was designed to use the GNU standard for configuration and makefiles. To build and install do the following: Run the configure script to configure the package. There are various options you might want to pass to configure to control how the package is built. Consider the following options, configure --help gives a complete list. compile Java source (default=`yes'). compile JNI source (default=`yes'). compile GTK native peers (default=`yes'). compile Qt4 native peers (default=`no'). fully qualified class name of default AWT toolkit (default=`no'). compile native libxml/xslt library (default=`no'). enable to use JNI native methods (default=`yes'). enable build of local Unix sockets. define what to install `(zip|flat|both|none)' (default=`zip'). enable build of the X/Escher peers, with the escher library at `/path/to/escher', either in the form of a JAR file, or a directory containing the .class files of Escher. whether to compile C code with `-Werror' which turns any compiler warning into a compilation failure (default=`no'). generate documentation using gjdoc (default=`no'). Regenerate the parsers with jay, must be given the path to the jay executable use prebuilt glibj.zip class library specify jar file containing the Eclipse Java Compiler build the experimental GStreamer peer (see `README.gstreamer') For more flags run configure --help. Type gmake to build the package. There is no longer a dependency problem and we aim to keep it that way. Type gmake install to install everything. This may require being the superuser. The default install path is /usr/local/classpath you may change it by giving configure the `--prefix=<path>' option. Report bugs to classpath@gnu.org or much better to the GNU Classpath bug tracker at Savannah. Happy Hacking! Once installed, GNU Classpath is ready to be used by any VM that supports using the official version of GNU Classpath. Simply ensure that `/usr/local/classpath/share/classpath' is in your CLASSPATH environment variable. You'll also have to set your LD_LIBRARY_PATH variable (or similar system configuration) to include the Classpath native libraries in `/usr/local/classpath/lib/classpath'. *NOTE* All example paths assume the default prefix is used with configure. If you don't know what this means then the examples are correct. More information about the VMs that use GNU Classpath can be found in the `README' file. In order build the X peers you need the Escher library version 0.2.3 from escher.sourceforge.net. Unpack (and optionally build) the Escher library following the instructions in the downloaded package. Enable the build of the X peers by passing `--with-escher=/path/to/escher' to configure where `/path/to/escher' either points to a directory structure or JAR file containing the Escher classes. For Unix systems it is preferable to also build local socket support by passing `--enable-local-sockets', which accelerates the network communication to the X server significantly. In this release you have to enable the X peers at runtime by setting the system property awt.toolkit=gnu.java.awt.peer.x.XToolkit by passing `-Dawt.toolkit=gnu.java.awt.peer.x.XToolkit' to the java command when running an application. Compilation is accomplished using a compiler's @file syntax. For our part, we avoid placing make style dependencies as rules upon the compilation of a particular class file and leave this up to the Java compiler instead. The `--enable-maintainer-mode' option to configure currently does very little and shouldn't be used by ordinary developers or users anyway. On Windows machines, the native libraries do not currently build, but the Java bytecode library will. GCJ trunk is beginning to work under Cygwin. For C source code, follow the GNU Coding Standards. The standards also specify various things like the install directory structure. These should be followed if possible. For Java source code, please follow the GNU Coding Standards, as much as possible. There are a number of exceptions to the GNU Coding Standards that we make for GNU Classpath as documented in this guide. We will hopefully be providing developers with a code formatting tool that closely matches those rules soon. For API documentation comments, please follow How to Write Doc Comments for Javadoc. We would like to have a set of guidelines more tailored to GNU Classpath as part of this document. Here is a list of some specific rules used when hacking on GNU Classpath java source code. We try to follow the standard GNU Coding Standards for that. There are lots of tools that can automatically generate it (although most tools assume C source, not java source code) and it seems as good a standard as any. There are a couple of exceptions and specific rules when hacking on GNU Classpath java source code however. The following lists how code is formatted (and some other code conventions): Don't write: But write: NullPointerExceptionas an alternative to simply checking for null. It is clearer and usually more efficient to simply write an explicit check. For instance, don't write: If your intent above is to check whether `foo' is null, instead write: Note that Jikes will generate warnings for redundant modifiers if you use +Predundant-modifiers on the command line. +Pmodifier-order. serialVersionUIDin Serializableclasses in Classpath. This field should be declared as private static final. Note that a class may be Serializablewithout being explicitly marked as such, due to inheritance. For instance, all subclasses of Throwableneed to have serialVersionUIDdeclared. throwsclause of a method. However, if throwing an unchecked exception is part of the method's API, you should mention it in the Javadoc. There is one important exception to this rule, which is that a stub method should be marked as throwing gnu.classpath.NotImplementedException. This will let our API comparison tools note that the method is not fully implemented. Object.equals, remember that instanceoffilters out null, so an explicit check is not needed. ifand whilewhich have always been part of the Java programming language, but you should be careful about accidentally using words which have been added in later versions. Notable examples are assert(added in 1.4) and enum(added in 1.5). Jikes will warn of the use of the word enum, but, as it doesn't yet support the 1.5 version of the language, it will still allow this usage through. A compiler which supports 1.5 (e.g. the Eclipse compiler, ecj) will simply fail to compile the offending source code. Some things are the same as in the normal GNU Coding Standards: There are a lot of people helping out with GNU Classpath. Here are a couple of practical guidelines to make working together on the code smoother. The main thing is to always discuss what you are up to on the mailinglist. Making sure that everybody knows who is working on what is the most important thing to make sure we cooperate most effectively. We maintain a Task List which contains items that you might want to work on. Before starting to work on something please make sure you read this complete guide. And discuss it on list to make sure your work does not duplicate or interferes with work someone else is already doing. Always make sure that you submit things that are your own work. And that you have paperwork on file (as stated in the requirements section) with the FSF authorizing the use of your additions. Technically the GNU Classpath project is hosted on Savannah a central point for development, distribution and maintenance of GNU Software. Here you will find the project page, bug reports, pending patches, links to mailing lists, news items and CVS. You can find instructions on getting a CVS checkout for classpath at. You don't have to get CVS commit write access to contribute, but it is sometimes more convenient to be able to add your changes directly to the project CVS. Please contact the GNU Classpath savannah admins to arrange CVS access if you would like to have it. Make sure to be subscribed to the commit-classpath mailinglist while you are actively hacking on Classpath. You have to send patches (cvs diff -uN) to this list before committing. We really want to have a pretty open check-in policy. But this means that you should be extra careful if you check something in. If at all in doubt or if you think that something might need extra explaining since it is not completely obvious please make a little announcement about the change on the mailinglist. And if you do commit something without discussing it first and another GNU Classpath hackers asks for extra explanation or suggests to revert a certain commit then please reply to the request by explaining why something should be so or if you agree to revert it. (Just reverting immediately is OK without discussion, but then please don't mix it with other changes and please say so on list.) Patches that are already approved for libgcj or also OK for Classpath. (But you still have to send a patch/diff to the list.) All other patches require you to think whether or not they are really OK and non-controversial, or if you would like some feedback first on them before committing. We might get real commit rules in the future, for now use your own judgement, but be a bit conservative. Always contact the GNU Classpath maintainer before adding anything non-trivial that you didn't write yourself and that does not come from libgcj or from another known GNU Classpath or libgcj hacker. If you have been assigned to commit changes on behalf of another project or a company always make sure they come from people who have signed the papers for the FSF and/or fall under the arrangement your company made with the FSF for contributions. Mention in the ChangeLog who actually wrote the patch. Commits for completely unrelated changes they should be committed separately (especially when doing a formatting change and a logical change, do them in two separate commits). But do try to do a commit of as much things/files that are done at the same time which can logically be seen as part of the same change/cleanup etc. When the change fixes an important bug or adds nice new functionality please write a short entry for inclusion in the `NEWS' file. If it changes the VM interface you must mention that in both the `NEWS' file and the VM Integration Guide. All the "rules" are really meant to make sure that GNU Classpath will be maintainable in the long run and to give all the projects that are now using GNU Classpath an accurate view of the changes we make to the code and to see what changed when. If you think the requirements are "unworkable" please try it first for a couple of weeks. If you still feel the same after having some more experience with the project please feel free to bring up suggestions for improvements on the list. But don't just ignore the rules! Other hackers depend on them being followed to be the most productive they can be (given the above constraints). Sometimes it is necessary to create branch of the source for doing new work that is disruptive to the other hackers, or that needs new language or libraries not yet (easily) available. After discussing the need for a branch on the main mailinglist with the other hackers explaining the need of a branch and suggestion of the particular branch rules (what will be done on the branch, who will work on it, will there be different commit guidelines then for the mainline trunk and when is the branch estimated to be finished and merged back into the trunk) every GNU Classpath hacker with commit access should feel free to create a branch. There are however a couple of rules that every branch should follow: If any of these rules are unclear please discuss on the list first. To keep track of who did what when we keep an explicit ChangeLog entry together with the code. This mirrors the CVS commit messages and in general the ChangeLog entry is the same as the CVS commit message. This provides an easy way for people getting a (snapshot) release or without access to the CVS server to see what happened when. We do not generate the ChangeLog file automatically from the CVS server since that is not reliable. A good ChangeLog entry guideline can be found in the Guile Manual at. Here are some example to explain what should or shouldn't be in a ChangeLog entry (and the corresponding commit message): The second line should be blank. All other lines should be indented with one tab. So don't write: Just state: In this case the reason for the change was added to this guide. But explain what changed and in which methods it was changed: The above are all just guidelines. We all appreciate the fact that writing ChangeLog entries, using a coding style that is not "your own" and the CVS, patch and diff tools do take some time to getting used to. So don't feel like you have to do it perfect right away or that contributions aren't welcome if they aren't "perfect". We all learn by doing and interacting with each other. When you write code for Classpath, write with three things in mind, and in the following order: portability, robustness, and efficiency. If efficiency breaks portability or robustness, then don't do it the efficient way. If robustness breaks portability, then bye-bye robust code. Of course, as a programmer you would probably like to find sneaky ways to get around the issue so that your code can be all three ... the following chapters will give some hints on how to do this. The portability goal for Classpath is the following: For almost all of Classpath, this is a very feasible goal, using a combination of JNI and native interfaces. This is what you should shoot for. For those few places that require knowledge of the Virtual Machine beyond that provided by the Java standards, the VM Interface was designed. Read the Virtual Machine Integration Guide for more information. Right now the only supported platform is Linux. This will change as that version stabilizes and we begin the effort to port to many other platforms. Jikes RVM runs Classpath on AIX, and generally the Jikes RVM team fixes Classpath to work on that platform. At the moment, we are not very good at reuse of the JNI code. There have been some attempts, called libclasspath, to create generally useful utility classes. The utility classes are in the directory `native/jni/classpath' and they are mostly declared in `native/jni/classpath/jcl.h'. These utility classes are currently only discussed in Robustness and in Native Efficiency. There are more utility classes available that could be factored out if a volunteer wants something nice to hack on. The error reporting and exception throwing functions and macros in `native/jni/gtk-peer/gthread-jni.c' might be good candidates for reuse. There are also some generally useful utility functions in `gnu_java_awt_peer_gtk_GtkMainThread.c' that could be split out and put into libclasspath. Native code is very easy to make non-robust. (That's one reason Java is so much better!) Here are a few hints to make your native code more robust. Always check return values for standard functions. It's sometimes easy to forget to check that malloc() return for an error. Don't make that mistake. (In fact, use JCL_malloc() in the jcl library instead-it will check the return value and throw an exception if necessary.) Always check the return values of JNI functions, or call ExceptionOccurred to check whether an error occurred. You must do this after every JNI call. JNI does not work well when an exception has been raised, and can have unpredictable behavior. Throw exceptions using JCL_ThrowException. This guarantees that if something is seriously wrong, the exception text will at least get out somewhere (even if it is stderr). Check for null values of jclasses before you send them to JNI functions. JNI does not behave nicely when you pass a null class to it: it terminates Java with a "JNI Panic." In general, try to use functions in `native/jni/classpath/jcl.h'. They check exceptions and return values and throw appropriate exceptions. For methods which explicitly throw a NullPointerException when an argument is passed which is null, per a Sun specification, do not write code like: Instead, the code should be written as: Explicitly comparing foo to null is unnecessary, as the virtual machine will throw a NullPointerException when length() is invoked. Classpath is designed to be as fast as possible - every optimization, no matter how small, is important. You might think that using native methods all over the place would give our implementation of Java speed, speed, blinding speed. You'd be thinking wrong. Would you believe me if I told you that an empty interpreted Java method is typically about three and a half times faster than the equivalent native method? Bottom line: JNI is overhead incarnate. In Sun's implementation, even the JNI functions you use once you get into Java are slow. A final problem is efficiency of native code when it comes to things like method calls, fields, finding classes, etc. Generally you should cache things like that in static C variables if you're going to use them over and over again. GetMethodID(), GetFieldID(), and FindClass() are slow. Classpath provides utility libraries for caching methodIDs and fieldIDs in `native/jni/classpath/jnilink.h'. Other native data can be cached between method calls using functions found in `native/jni/classpath/native_state.h'. Here are a few tips on writing native code efficiently: Make as few native method calls as possible. Note that this is not the same thing as doing less in native method calls; it just means that, if given the choice between calling two native methods and writing a single native method that does the job of both, it will usually be better to write the single native method. You can even call the other two native methods directly from your native code and not incur the overhead of a method call from Java to C. Cache jmethodIDs and jfieldIDs wherever you can. String lookups are expensive. The best way to do this is to use the `native/jni/classpath/jnilink.h' library. It will ensure that jmethodIDs are always valid, even if the class is unloaded at some point. In 1.1, jnilink simply caches a NewGlobalRef() to the method's underlying class; however, when 1.2 comes along, it will use a weak reference to allow the class to be unloaded and then re-resolve the jmethodID the next time it is used. Cache classes that you need to access often. jnilink will help with this as well. The issue here is the same as the methodID and fieldID issue-how to make certain the class reference remains valid. If you need to associate native C data with your class, use Paul Fisher's native_state library (NSA). It will allow you to get and set state fairly efficiently. Japhar now supports this library, making native state get and set calls as fast as accessing a C variable directly. If you are using native libraries defined outside of Classpath, then these should be wrapped by a Classpath function instead and defined within a library of their own. This makes porting Classpath's native libraries to new platforms easier in the long run. It would be nice to be able to use Mozilla's NSPR or Apache's APR, as these libraries are already ported to numerous systems and provide all the necessary system functions as well. Security is such a huge topic it probably deserves its own chapter. Most of the current code needs to be audited for security to ensure all of the proper security checks are in place within the Java platform, but also to verify that native code is reasonably secure and avoids common pitfalls, buffer overflows, etc. A good source for information on secure programming is the excellent HOWTO by David Wheeler, Secure Programming for Linux and Unix HOWTO. Sun has produced documentation concerning much of the information needed to make Classpath serializable compatible with Sun implementations. Part of doing this is to make sure that every class that is Serializable actually defines a field named serialVersionUID with a value that matches the output of serialver on Sun's implementation. The reason for doing this is below. If a class has a field (of any accessibility) named serialVersionUID of type long, that is what serialver uses. Otherwise it computes a value using some sort of hash function on the names of all method signatures in the .class file. The fact that different compilers create different synthetic method signatures, such as access$0() if an inner class needs access to a private member of an enclosing class, make it impossible for two distinct compilers to reliably generate the same serial #, because their .class files differ. However, once you have a .class file, its serial # is unique, and the computation will give the same result no matter what platform you execute on. Serialization compatibility can be tested using tools provided with Japitools. These tools can test binary serialization compatibility and also provide information about unknown serialized formats by writing these in XML instead. Japitools is also the primary means of checking API compatibility for GNU Classpath with Sun's Java Platform. Sun has a practice of creating "alias" methods, where a public or protected method is deprecated in favor of a new one that has the same function but a different name. Sun's reasons for doing this vary; as an example, the original name may contain a spelling error or it may not follow Java naming conventions. Unfortunately, this practice. There are a number of specification sources to use when working on Classpath. In general, the only place you'll find your classes specified is in the JavaDoc documentation or possibly in the corresponding white paper. In the case of java.lang, java.io and java.util, you should look at the Java Language Specification. Here, however, is a list of specs, in order of canonicality: You'll notice that in this document, white papers and specification papers are more canonical than the JavaDoc documentation. This is true in general. The Classpath directory structure is laid out in the following manner: Here is a brief description of the toplevel directories and their contents. Contains the source code to the Java packages that make up the core class library. Because this is the public interface to Java, it is important that the public classes, interfaces, methods, and variables are exactly the same as specified in Sun's documentation. The directory structure is laid out just like the java package names. For example, the class java.util.zip would be in the directory java-util. Internal classes (roughly analogous to Sun's sun.* classes) should go under the `gnu/java' directory. Classes related to a particular public Java package should go in a directory named like that package. For example, classes related to java.util.zip should go under a directory `gnu/java/util/zip'. Sub-packages under the main package name are allowed. For classes spanning multiple public Java packages, pick an appropriate name and see what everybody else thinks. This directory holds native code needed by the public Java packages. Each package has its own subdirectory, which is the "flattened" name of the package. For example, native method implementations for java.util.zip should go in `native/classpath/java-util'. Classpath actually includes an all Java version of the zip classes, so no native code is required. Each person working on a package get's his or her own "directory space" underneath each of the toplevel directories. In addition to the general guidelines above, the following standards should be followed: Java uses the Unicode character encoding system internally. This is a sixteen bit (two byte) collection of characters encompassing most of the world's written languages. However, Java programs must often deal with outside interfaces that are byte (eight bit) oriented. For example, a Unix file, a stream of data from a network socket, etc. Beginning with Java 1.1, the Reader and Writer classes provide functionality for dealing with character oriented streams. The classes InputStreamReader and OutputStreamWriter bridge the gap between byte streams and character streams by converting bytes to Unicode characters and vice versa. In Classpath, InputStreamReader and OutputStreamWriter rely on an internal class called gnu.java.io.EncodingManager to load translators that perform the actual conversion. There are two types of converters, encoders and decoders. Encoders are subclasses of gnu.java.io.encoder.Encoder. This type of converter takes a Java (Unicode) character stream or buffer and converts it to bytes using a specified encoding scheme. Decoders are a subclass of gnu.java.io.decoder.Decoder. This type of converter takes a byte stream or buffer and converts it to Unicode characters. The Encoder and Decoder classes are subclasses of Writer and Reader respectively, and so can be used in contexts that require character streams, but the Classpath implementation currently does not make use of them in this fashion. The EncodingManager class searches for requested encoders and decoders by name. Since encoders and decoders are separate in Classpath, it is possible to have a decoder without an encoder for a particular encoding scheme, or vice versa. EncodingManager searches the package path specified by the file.encoding.pkg property. The name of the encoder or decoder is appended to the search path to produce the required class name. Note that EncodingManager knows about the default system encoding scheme, which it retrieves from the system property file.encoding, and it will return the proper translator for the default encoding if no scheme is specified. Also, the Classpath standard translator library, which is the gnu.java.io package, is automatically appended to the end of the path. For efficiency, EncodingManager maintains a cache of translators that it has loaded. This eliminates the need to search for a commonly used translator each time it is requested. Finally, EncodingManager supports aliasing of encoding scheme names. For example, the ISO Latin-1 encoding scheme can be referred to as "8859_1" or "ISO-8859-1". EncodingManager searches for aliases by looking for the existence of a system property called gnu.java.io.encoding_scheme_alias.<encoding name>. If such a property exists. The value of that property is assumed to be the canonical name of the encoding scheme, and a translator with that name is looked up instead of one with the original name. Here is an example of how EncodingManager works. A class requests a decoder for the "UTF-8" encoding scheme by calling EncodingManager.getDecoder("UTF-8"). First, an alias is searched for by looking for the system property gnu.java.io.encoding_scheme_alias.UTF-8. In our example, this property exists and has the value "UTF8". That is the actual decoder that will be searched for. Next, EncodingManager looks in its cache for this translator. Assuming it does not find it, it searches the translator path, which is this example consists only of the default gnu.java.io. The "decoder" package name is appended since we are looking for a decoder. ("encoder" would be used if we were looking for an encoder). Then name name of the translator is appended. So EncodingManager attempts to load a translator class called gnu.java.io.decoder.UTF8. If that class is found, an instance of it is returned. If it is not found, a UnsupportedEncodingException. To write a new translator, it is only necessary to subclass Encoder and/or Decoder. Only a handful of abstract methods need to be implemented. In general, no methods need to be overridden. The needed methods calculate the number of bytes/chars that the translation will generate, convert buffers to/from bytes, and read/write a requested number of characters to/from a stream. Many common encoding schemes use only eight bits to encode characters. Writing a translator for these encodings is very easy. There are abstract translator classes gnu.java.io.decode.DecoderEightBitLookup and gnu.java.io.encode.EncoderEightBitLookup. These classes implement all of the necessary methods. All that is necessary to create a lookup table array that maps bytes to Unicode characters and set the class variable lookup_table equal to it in a static initializer. Also, a single constructor that takes an appropriate stream as an argument must be supplied. These translators are exceptionally easy to create and there are several of them supplied in the Classpath distribution. Writing multi-byte or variable-byte encodings is more difficult, but often not especially challenging. The Classpath distribution ships with translators for the UTF8 encoding scheme which uses from one to three bytes to encode Unicode characters. This can serve as an example of how to write such a translator. Many more translators are needed. All major character encodings should eventually be supported. There are many parts of the Java standard runtime library that must be customized to the particular locale the program is being run in. These include the parsing and display of dates, times, and numbers; sorting words alphabetically; breaking sentences into words, etc. In general, Classpath uses general classes for performing these tasks, and customizes their behavior with configuration data specific to a given locale. In Classpath, all locale specific data is stored in a ListResourceBundle class in the package gnu/java/locale. The basename of the bundle is LocaleInformation. See the documentation for the java.util.ResourceBundle class for details on how the specific locale classes should be named. ListResourceBundle's are used instead of PropertyResourceBundle's because data more complex than simple strings need to be provided to configure certain Classpath components. Because ListResourceBundle allows an arbitrary Java object to be associated with a given configuration option, it provides the needed flexibility to accomodate Classpath's needs. Each Java library component that can be localized requires that certain configuration options be specified in the resource bundle for it. It is important that each and every option be supplied for a specific component or a critical runtime error will most likely result. As a standard, each option should be assigned a name that is a string. If the value is stored in a class or instance variable, then the option should name should have the name name as the variable. Also, the value associated with each option should be a Java object with the same name as the option name (unless a simple scalar value is used). Here is an example: A class loads a value for the format_string variable from the resource bundle in the specified locale. Here is the code in the library class: In the actual resource bundle class, here is how the configuration option gets defined: Note that each variable should be private, final, and static. Each variable should also have a description of what it does as a documentation comment. The getContents() method returns the contents array. There are many functional areas of the standard class library that are configured using this mechanism. A given locale does not need to support each functional area. But if a functional area is supported, then all of the specified entries for that area must be supplied. In order to determine which functional areas are supported, there is a special key that is queried by the affected class or classes. If this key exists, and has a value that is a Boolean object wrappering the true value, then full support is assumed. Otherwise it is assumed that no support exists for this functional area. Every class using resources for configuration must use this scheme and define a special scheme that indicates the functional area is supported. Simply checking for the resource bundle's existence is not sufficient to ensure that a given functional area is supported. The following sections define the functional areas that use resources for locale specific configuration in GNU Classpath. Please refer to the documentation for the classes mentioned for details on how these values are used. You may also wish to look at the source file for `gnu/java/locale/LocaleInformation_en' as an example. Collation involves the sorting of strings. The Java class library provides a public class called java.text.RuleBasedCollator that performs sorting based on a set of sorting rules. Booleanwrappering trueto indicate that this functional area is supported. Note that some languages might be too complex for RuleBasedCollator to handle. In this case an entirely new class might need to be written in lieu of defining this rule string. The class java.text.BreakIterator breaks text into words, sentences, and lines. It is configured with the following resource bundle entries: Booleanwrappering trueto indicate that this functional area is supported. Stringarray of word break character sequences. Stringarray of sentence break character sequences. Stringarray of line break character sequences. Date formatting and parsing is handled by the java.text.SimpleDateFormat class in most locales. This class is configured by attaching an instance of the java.text.DateFormatSymbols class. That class simply reads properties from our locale specific resource bundle. The following items are required (refer to the documentation of the java.text.DateFormatSymbols class for details io what the actual values should be): Booleanwrappering trueto indicate that this functional area is supported. Stringarray of month names. Stringarray of abbreviated month names. Stringarray of weekday names. Stringarray of abbreviated weekday names. Stringarray containing AM/PM names. Stringarray containing era (i.e., BC/AD) names. Stringdefining date/time pattern symbols. DateFormat.SHORT DateFormat.MEDIUM DateFormat.LONG DateFormat.FULL DateFormat.SHORT DateFormat.MEDIUM DateFormat.LONG DateFormat.FULL Note that it may not be possible to use this mechanism for all locales. In those cases a special purpose class may need to be written to handle date/time processing. NumberFormat is an abstract class for formatting and parsing numbers. The class DecimalFormat provides a concrete subclass that handles this is in a locale independent manner. As with SimpleDateFormat, this class gets information on how to format numbers from a class that wrappers a collection of locale specific formatting values. In this case, the class is DecimalFormatSymbols. That class reads its default values for a locale from the resource bundle. The required entries are: Booleanwrappering trueto indicate that this functional area is supported. String. String. String. String. String. String. String. String. String. String. Note that several of these values are an individual character. These should be wrappered in a String at character position 0, not in a Character object..
http://www.gnu.org/software/classpath/docs/hacking.html
crawl-002
refinedweb
8,021
56.55
Opened 14 years ago Closed 14 years ago Last modified 14 years ago #7894 closed (duplicate) Support handler optimisations for file downloads Description Sometimes a django app wants to return a file in a response. You can currently do this by returning the data or an iterator for the data in the content of an HttpResponse. However WSGI provides an optional mechanism for higher performance file transmission... ...and I imagine mod_python is capable of a similar speed up. In order to flag to the handler that the response is suitable for this speedup I suggest a new HttpResponseFileWrapper object that wraps a file like object. This response falls back to providing its content via an iterator that reads in block_size (a extra optional parameter) bytes at a time. The speedup mechanism can also use the block_size as a suggestion for reading data from the filelike object. So for example... from django.http import HttpResponseFileWrapper def view(request): return HttpResponseFileWrapper(open('foo.pdf'), block_size=8192) Attachments (3) Change History (14) Changed 14 years ago by comment:1 Changed 14 years ago by The mod_python package cannot do the same thing for an open file like object. The closest thing in mod_python is req.sendfile() which takes a file name. In Trac they abstract the interface up to the file name level. Thus for mod_python it then just calls req.sendfile(). For WSGI, if wsgi.file_wrapper is available Trac opens file in raw mode 'rb' (you didn't use raw mode and so would not behave right on Windows), and then creates returnable object using hook provided by WSGI adapter. For where wsgi.file_wrapper not available, a FileWrapper class similar to that specified in WSGI spec is used instead. Do note though that Trac was actually forgetting to do the latter for generic WSGI adapter and fix has only just been committed to their subversion repository. Note that mod_python doesn't set any headers, for content length, so application has to do that as well as set content type headers etc. For WSGI, better off ensuring content length also set in headers, although for mod_wsgi it will set content length header for file like object corresponding to real actual file if it can. If you want to support range headers, mod_python does allow offset and length arguments. For WSGI, where wsgi.file_wrapper is not available, the FileWrapper example could be modified to support a length, with offset achieved by doing a file seek if actual file before supplying it to FileWrapper. Where wsgi.file_wrapper does exist it gets a bit more complicated. This is because mod_wsgi is only WSGI adapter that will honour Content-Length in response headers for wsgi.file_wrapper and only send that amount of data from file. Other implementations that support wsgi.file_wrapper just send remainder of file thus meaning more data could be returned than should and client would have to be relied upon to ignore any extra. Question looks to have arisen out of this ticket, but see: Changed 14 years ago by Updated patch with API updated to allows mod_python support and optional length & offset comment:2 Changed 14 years ago by The response now takes a file path as a required argument, and optional offset and length parameters. Note that some WSGI adaptors can't deal with the length and the file_wrapper speedup and so the wsgi handler defaults to response's iterator if it doesn't know whether the adaptor supports this (currently only mod_wsgi does). from django.http import HttpResponseFileWrapper def view(request): return HttpResponseFileWrapper('foo.bin', block_size=8192, offset=500, length=120000) The patch also added modpython support but I haven't had a chance to check this :) Also the logic in the wsgi handler is getting hairy so tests are needed but didn't see any obvious way of introducing them yet. comment:3 Changed 14 years ago by Haven't looked complete code properly yet, but are you sure: 450 class HttpResponseFileWrapper(HttpResponse): 451 def __init__(self, file_path, block_size=8192, length=None, offset=0, **kwargs): 452 content_length = length or os.path.getsize(file_path) 453 HttpResponse.__init__(self, content=FileWrapper(file_path, block_size, content_length, offset), **kwargs) 454 self.file_path = file_path 455 self.block_size = block_size 456 self.length = length 457 self.offset = offset 458 self['Content-Length'] = content_length is correct. Thing I am worried about is setting of Content-Length response header. You set it to actual size of file and don't take into consideration the offset or length from offset that user code may have specified. comment:4 Changed 14 years ago by BTW, I don't know what is reality as don't actually use Django, but occasionally see comments to effect that 'django.views.static.serve' only works for development server. Eg, in thread: Thus, one is pushed to serve static files with Apache when using mod_python or mod_wsgi. Could 'django.views.static.serve' be made to use the extension being added per this ticket so that it works with mod_python and mod_wsgi, with where possible the speed ups offered by mod_python and mod_wsgi being used. Changed 14 years ago by Fixed incorrect content length when only supplying an offset, added tests for wsgi handler, patched serve generic function to use comment:5 Changed 14 years ago by The file_wrapper_response3.diff patch fixes the content length header if only an offset has been provided (as pointed out by grahamd above in comment 3). This patch also changes the 'django.views.static.serve' generic function (as suggested by grahamd in comment 4) to use the HttpResponseFileWrapper, however this is just a speedup in case the development server is using a wsgi adaptor provides the wsgi.file_wrapper. The HttpResponseFileWrapper is only meant to be used in cases where some view logic is needed in combination with serving a file, serving static files is obviously best down directly by the webserver. comment:6 Changed 14 years ago by comment:7 Changed 14 years ago by comment:8 Changed 14 years ago by comment:9 Changed 14 years ago by comment:10 Changed 14 years ago by comment:11 Changed 14 years ago by Milestone post-1.0 deleted Provides the HttpResponseFileWrapper and support for the wsgi file_wrapper speedup as well as a fix to achieve this is the simple_server
https://code.djangoproject.com/ticket/7894
CC-MAIN-2022-40
refinedweb
1,047
52.9
NAMEstrcmp, strncmp - compare two strings SYNOPSIS #include <string.h> int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); DESCRIPTIONThe strcmp() function compares the two strings s1 and s2. The locale is not taken into account (for a locale-aware comparison, see strcoll(3)). The comparison is done using unsigned characters. strcmp() returns an integer indicating the result of the comparison, as follows: - 0, if the s1 and s2 are equal; - a negative value if s1 is less than s2; - a positive value if s1 is greater than s2. The strncmp() function is similar, except it compares only the first (at most) n bytes of s1 and s2. RETURN VALUEThe strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2. ATTRIBUTESFor an explanation of the terms used in this section, see attributes(7). CONFORMING TOPOSIX.1-2001, POSIX.1-2008, C89, C99, SVr4, 4.3BSD. NOTESPOSIX.1 specifies only that: The sign of a nonzero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the strings being compared. In glibc, as in most other implementations, the return value is the arithmetic result of subtracting the last compared byte in s2 from the last compared byte in s1. (If the two characters are equal, this difference is 0.) EXAMPLESThe program below can be used to demonstrate the operation of strcmp() (when given two arguments) and strncmp() (when given three arguments). First, some examples using strcmp(): $ ./string_comp ABC ABC <str1> and <str2> are equal $ ./string_comp ABC AB # 'C' is ASCII 67; 'C' - ' ' = 67 <str1> is greater than <str2> (67) $ ./string_comp ABA ABZ # 'A' is ASCII 65; 'Z' is ASCII 90 <str1> is less than <str2> (-25) $ ./string_comp ABJ ABC <str1> is greater than <str2> (7) $ ./string_comp $'\201' A # 0201 - 0101 = 0100 (or 64 decimal) <str1> is greater than <str2> (64) The last example uses bash(1)-specific syntax to produce a string containing an 8-bit ASCII code; the result demonstrates that the string comparison uses unsigned characters. And then some examples using strncmp(): $ ./string_comp ABC AB 3 <str1> is greater than <str2> (67) $ ./string_comp ABC AB 2 <str1> and <str2> are equal in the first 2 bytes Program source /* string_comp.c Licensed under GNU General Public License v2 or later. */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { int res; if (argc < 3) { fprintf(stderr, "Usage: %s <str1> <str2> [<len>]\n", argv[0]); exit(EXIT_FAILURE); } if (argc == 3) res = strcmp(argv[1], argv[2]); else res = strncmp(argv[1], argv[2], atoi(argv[3])); if (res == 0) { printf("<str1> and <str2> are equal"); if (argc > 3) printf(" in the first %d bytes\n", atoi(argv[3])); printf("\n"); } else if (res < 0) { printf("<str1> is less than <str2> (%d)\n", res); } else { printf("<str1> is greater than <str2> (%d)\n", res); } exit(EXIT_SUCCESS); }
https://man.archlinux.org/man/strcmp.3.en
CC-MAIN-2021-10
refinedweb
524
69.62
Paranoid Penguin - Application Proxying with Zorp, Part II Listing 7. policy.py, Part II (Instance Definitions) def blue(): Service("blue_http", HttpProxy, router=TransparentRouter()) Service("blue_ssh", PlugProxy, router=TransparentRouter()) Listener(SockAddrInet('10.0.1.254', 50080), "blue_http") Listener(SockAddrInet('10.0.1.254', 50022), "blue_ssh") def purple(): pass def red(): Service("red_http", HttpProxy, router=DirectedRouter(SockAddrInet('192.168.1.242', 80), forge_addr=TRUE)) Listener(SockAddrInet('169.254.1.254', 50080), "red_http") Otherwise, the definition should consist of one or more Service lines, specifying a service name referenced in one or more zone definitions, and a Zorp proxy module, either a built-in proxy included in the global import statements or defined in a custom class. The last field in a Service line is a router, which specifies where proxied packets should be sent. You can see in Listing 7 that for the red_http service, we've used the forge_addr=TRUE option to pass the source IPs of Web clients intact from the Internet to our Web server. Without this option, all Web traffic hitting the DMZ appears to originate from the firewall itself. Although in Listing 7 we're using only the HttpProxy and the PlugProxy (a general-service UDP and TCP proxy that copies application data verbatim), Zorp GPL also has proxies for FTP, whois, SSL, telnet and finger. As I mentioned before, you also can create custom classes to alter or augment these proxies. It's easy to create, for example, an HTTP proxy that performs URL filtering or an SSL proxy stacked on an HTTP proxy so HTTPS traffic can be proxied intelligently. Unfortunately, these are advanced topics I can't cover here; fortunately, all of Zorp's Python proxy modules are heavily commented. The TransparentRouter referenced in Listing 7 simply proxies the packets to the destination IP and port specified by the client. But in the red instance's red_http service, we see that a DirectedRouter, which requires a mandatory destination IP and port, may be specified instead. Each Service line in a service-instance definition must have a corresponding Listener line. This line tells Zorp to which local (firewall) IP address and port the service should be bound. It may seem counterintuitive that the ports specified in Listing 7's Listener statements are high ports: 50080 instead of 80 and 50022 instead of 22. But remember, each proxy receives its packets from the kernel through Netfilter, not directly from clients. Accordingly, these high ports must correspond to those specified in your tproxy table Netfilter rules (Listing 1). I mentioned that unlike HttpProxy, which is a fully application-aware proxy that enforces all relevant Internet RFCs for proper HTTP behavior, PlugProxy is a general-service proxy (GSP). Using PlugProxy still gives better protection than does packet filtering on its own, because the very act of proxying, even without application intelligence, insulates your systems from low-level attacks that Netfilter may not catch on its own. And with that, we've scratched the dense surface of Zorp GPL. This is by far the most complex tool I've covered in these pages, but I think you'll find Zorp to be well worth the time you invest in learning how to use it. Resources The English-language home for Balabit, creators of Zorp:. The root download directory for ZorpOS contains some tools that make using Zorp GPL much easier, including iptables-utils, a TPROXY-enabled Linux kernel and iptables command. In fact, these are the free parts of the Debian distribution included with Zorp Pro, which is why everything in ZorpOS is in the form of Debian packages. If you aren't a Debian user, everything you want is in the subdirectories of pool; at the top of each package's subdirectory are tar.gz files containing source code. If you are a Debian user, you can use the URL as an apt-get source:. The Zorp Users' Mailing List is an amazingly quick and easy way to get help using Zorp, whether Pro or GPL. This URL is the site for subscribing to it or browsing its archives. Note that Balabit is a Hungarian company and its engineers (and some of the most helpful Zorp users) operate in the CET (GMT+1) time zone:. Mick Bauer, CISSP, is Linux Journal's security editor and an IS security consultant in Minneapolis, Minnesota. He's the author of Building Secure Servers With Linux (O'Reilly & Associates, 2002).
http://www.linuxjournal.com/article/7347?page=0,3&quicktabs_1=0
CC-MAIN-2017-51
refinedweb
738
51.68
Our current system saves files that match the name of their parent group. So a group named "My Devices" saves an image called "My+Devices.jpg". This worked great, and even though there was some trouble with the name getting converted somewhere along the line of PHP and JS to "My%20Devices.jpg", I was able to just convert spaces to plus signs before that happened. Now we need to account for other special characters, like apostrophes so that a group can be named "Joe's Devices". I need some way to convert that to something that can be a file name. BUT I can't just strip out the special characters or there could be a collision if someone uses a group name of "Joes Devices" (without the apostrophe). I tried urlencode() and rawurlencode(), but those use percent signs, which are great for URLs but not so much for file names. I thought base64_encode() would be better even though it's a much longer string. But it includes equal signs which are no good for filenames. Is there a way to convert a string to a filename-friendly string, one that can be decoded back to it's original string? Or do I need to recode this feature completely and use an ID match or something? Your quest is very similar to questions around creating url-safe base64 encoded strings. See this answer for one example: My solution would be a variation of this. In one of my apps I have this wrapper function: function base64_safe_encode($input, $stripPadding = false) { $encoded = strtr(base64_encode($input), '+/=', '-_~'); return ($stripPadding) ? str_replace("~","",$encoded) : $encoded; } Now you can generate a filename or url safe base64 encoded string that is easily reversible. Note there is an option to strip the padding at the end of the string if you like, PHP does not require the padding characters to be present when you decode. The decode function is then quite simple: function base64_safe_decode($input) { return base64_decode(strtr($input, '-_~', '+/=')); }
https://codedump.io/share/VrirDqM130jv/1/converting-string-in-php-to-be-used-as-file-namewithout-stripping-special-characters
CC-MAIN-2018-05
refinedweb
332
70.63
User talk:Cbrowne Contents I've currently got the bot tracking nicely, and have worked out how to collect and store as much data as I can get from the scanner (x,y,heading,velocity,energy). I know I can also get distance, but if I've understood Pattern Matching correctly I have no real need to store the distance to the bot at the time of scanning. Anyway, does it make sense to do this for my fire power? onBulletHit(BulletHitEvent e) { increaseFirePower(); } onBulletMissed(BulletMissedEvent e) { decreaseFirePower(); } My motivation is that the bot should conserve energy if it keeps missing, but ramp up the firepower as it scores consecutive hits. Increase and Decrease functions can be pretty much anything (I've currently got them behaving linearly, but there's probably a more optimal equation for the increase/decrease functions). I think this function is moderately better than simply firing 3.0 all the time, but I haven't looked into the alternatives used by other bots. I'm probably doing a lot of wheel reinvention, but hopefully that's to be expected from a newbie bot author, heh. *wipes sweat from brow* Yes, it does make sense, although mostly it is dependent on hitrate instead of hit/miss. The are some more things to keep in mind regarding bulletpower. First of all, heavier bullets travel slower. Next to that, you do not want to disable yourself, you'll be a Sitting Duck with 0.0 energy. You can choose your bulletpower depending on distance, when you are close, fire full power as the chance of hitting is bigger. There has been grown a consensus to have the default bulletpower somewhere between 1.7 and 2.4, mostly due to a (theoretical) discussion years ago (somewhere on the old wiki). This number would be an optimum to minimize the energyloss while still be able to punch hard enough. The best way is to pick an opponent and try different (extreme?) powerschemes, so you can see what is happening and come up with something you like. And it gives much more satisfaction that you create by yourself even out of ideas of others, than just to copy some things from others you don't understand. That makes some sense to me, too, though I'd also advise experimenting with different schemes to find out what works best. I think everyone has to find their own balance of reinventing wheels and learning from other bots and the wiki. There are lots of trade-offs either way. But yes, certainly some of that is expected. =) Yes, my current calculations for targeting messed up a bit so I discovered on my own that heavier bullets travel slower. They're still messed up, but that was just one facet of their messing up that is now (hopefully) less messed up. If the consensus is to always fire between 1.7 and 2.4, might it be sensible to "cap" my firepower within those numbers? And instead fire less often if I keep missing past 1.7 (I was planning on implementing a "fire less often" extension anyway, since I'm firing a heck of a lot of shots with minimum power at the moment, mostly because my implementation of pattern matching is both incomplete and horribly broken). I'm still not 100% sure how you get disabled. Is it purely from trying to do too much in a single turn, or are there other things that cause it? Particularly when low on energy, firing very low power bullets makes sense because they're faster (easier to hit with) and give you more chances to land some shots and stage a comeback. The opponent could be firing higher power bullets, miss a few shots, and you're right back in it. So I wouldn't completely restrict myself from going below 1.7, but that sounds like a reasonable setup until you get low on energy. Oh, and you can disable yourself by firing yourself down to 0 energy, or by taking a ridiculously long time on a turn. If it's the latter, it should say something in the console about stopping your bot for not doing anything in a "reasonable amount of time". Yeah, I've had a few disables from infinite loops before, but I didn't realise you also got disabled if you fired down to 0 energy. although that makes sense, since if it didn't disable you at that point you could either commit suicide or fire bullets for free. I'm currently working on a deltas-based GF system, where I store the "deltas" of previous guesses and attempt to smooth the deltas to be as close to each other as possible (I don't much care if they're close to zero yet, but ultimately if I can determine with some degree of accuracy that the deltas are always offset by a constant or linear amount from zero, I can adjust the function using that offset, so I just want to get the delta function as close to flat as I can, currently). This should give me a fairly accurate gun, unless I'm very much mistaken? The only "magic" being the smoothing function, which would attempt to compensate for over/under guesses by increasing or decreasing the guess offset from the enemy's current position. Taking into account things like bullet velocity (which is a non-linear function, thanks to my "firepower" calculations, eugh) and distance from self to guess to then compute an optimal firing angle. Thing is, with this system I'm not sure which is a better delta to use. You get more information from a delta that is the distance between your guess and the robot's actual position on that turn (provided you can get both pieces of information, and heaven help us if we can't) but a delta between the gun angle you used and the gun angle you -should've- used might provide more information to the next step (trying to get that delta as low as possible). Of course, all of this could be surplus to requirement, but any help would be appreciated. My AdvancedRobot, Thor, is currently using a static boolean "scanning" to determine whether to turn the radar or not. This should provide a degree of locking by setting "scanning" to false when we scan a robot, setting it to "true" after we execute, and turning if it's true. I know it's a naive approach and doesn't lock very well, but it doesn't appear to lock -at all- currently. Is it my methodology that's flawed, or should I hunt for a bug in the code? (No point debugging if I'm going about it the wrong way from the start). I think the way most of us do it is to simply scan towards the last known location of the enemy every single tick, making sure we overshoot by a little bit in case they move. I've never put too much effort into radar myself (at least 1v1 radar), because extremely simple solutions tend to work perfectly... You need to turn it every tick, it's just a question of clockwise or counter-clockwise. The area covered by the sweep of the radar from last tick to this tick is the area that is scanned. So once you scan, you want to reverse the direction you turn the radar, not stop turning it. Edit: Also, there's an option in Robocode to display the radar arcs, which would help you see exactly what's going on. Ah, so I need to refactor "scanning" to function more as a "turn radar left" boolean (if true, turn radar left, if false turn right) and then just toggle it when I find a robot, would that work? Yep, that would work fine. That kind of scan type is known as an 'Infinity lock' - there's more on it here: One_on_One_Radar. That kind of radar algorithm will skip scans occasionally, so there are a few others on that page which are usually used on bots that aren't in severely limited codesize tournaments. Personally, I recommend the 'turn multiplier lock', it works perfectly and is quick and easy to implement. Last edit: 15:57, 11 October 2011 Wow, that one is excellent. I'm not quite grokking it yet, but experiments have shown that it performs much smoother than my previous implementation. Now to get the gun to point in the right direction. I've implemented a function, "turnGunTo" which (in theory) turns the gun to a given (absolute) heading. I'm struggling to get it to work, though, as the gun just appears to spin continuously. Here's my function: public void turnGunTo(double newHeading) { double oldHeading = getGunHeadingRadians(); // use of normalRelativeAngle means we don't have to decide left or right setTurnGunLeft(Utils.normalRelativeAngle(calculateTurnAmount(newHeading,oldHeading))); } And, for reference, the calculateTurnAmount() function: public double calculateTurnAmount(double newHeading,double oldHeading) { // turn amount is a segment of a full circle, calculated by (circle - leftAngle) + rightAngle; return (FULL_CIRCLE - Math.max(newHeading, oldHeading)) + Math.min(newHeading, oldHeading); } What am I doing wrong? Also, is the method abstraction superfluous? It seems so, but in some ways it makes it a little bit more semantically-obvious what I'm trying to achieve. I think rather just go with this: public void turnGunTo(double newHeading) { double oldHeading = getGunHeadingRadians(); // use of normalRelativeAngle means we don't have to decide left or right setTurnGunLeft(Utils.normalRelativeAngle(newHeading-oldHeading)); } You can even move the getGunHeadingRadians() into the brackets if you want, and get rid of oldHeading, although that might be going a bit far =). Utils.normalRelativeAngle() will automatically clean up the full circle/double circle/no circle thing for you. It might be setTurnGunRight though... you'll have to check. Well the reason I was using oldHeading was because it was originally passed into turnGunTo, but since it's called turnGunTo, and therefore only ever applies to the Gun, I realised I could [read: should] get the value inside the function itself. Shouldn't it be setTurnGunLeftRadians() (or setTurnGunRightRadians())? I'm still working on checking which one I want, and what value I want to pass into it (currently calling it with: turnGunTo(Utils.normalRelativeAngle(getGunHeadingRadians() - e.getBearingRadians())); inside my onScannedRobot() function) You're being uncharacteristically helpful for a random stranger on the internet. Am I supposed to give you cookies or something? :) Ah yes, it should be radians. I suggest you read up on e.getBearingRadians() - I think it returns something relative to what your getHeadingRadians() returns. So the absolute bearing from you to your enemy would be getHeadingRadians() + e.getBearingRadians(), which (I think) is what you need to call your turnGunTo function with. And you don't need to give me a cookie, just work on your bot and provide some more competition =) I might also be procrastinating for my final B.Eng. thesis - it's due in 2 weeks ;-) Of course, it's me rather stupidly thinking I should compare it to getGunHeadingRadians() instead of getHeadingRadians() - the signing I already worked out was the wrong way around, but thank you for pointing that out too. I don't know about providing any competition, but I'll give it the best shot I can! If I can ever grok Wave Surfing...
http://robowiki.net/wiki/User_talk:Cbrowne
CC-MAIN-2019-13
refinedweb
1,901
60.55
printf "%d days, %d hours, %d minutes and %d seconds\n",(gmtime 196364 +)[7,2,1,0]; [download] I love IOs answer but in the spirit of TIMTOWDI here is how to roll your own. This illustrates one of the uses for the modulus operator: my $sec = 196364; print "days ", int($sec/(24*60*60)), "\n"; print "hours ", ($sec/(60*60))%24, "\n"; print "mins ", ($sec/60)%60, "\n"; print "secs ", $sec%60, "\n"; [download] You could use Time::Duration. The question was intriguing enough to me to re-invent a wheel for the sake of learning. Cheers - L~R If you only need an approximate answer, I'll invoke the "or something like that" clause and change 196364 into '2.3d' print sec2human(196364), "\n"; sub sec2human { my $secs = shift; if ($secs >= 365*24*60*60) { return sprintf '%.1fy', $secs/(365 +*24*60*60) } elsif ($secs >= 24*60*60) { return sprintf '%.1fd', $secs/( + 24*60*60) } elsif ($secs >= 60*60) { return sprintf '%.1fh', $secs/( + 60*60) } elsif ($secs >= 60) { return sprintf '%.1fm', $secs/( + 60) } else { return sprintf '%.1fs', $secs + } } [download] Here is a method of going back to seconds from a string like "2 days, 6 hours, 32 minutes and 44 seconds": sub dhms2sec { my $in = shift; $in =~ s/(and|,)//g; $in =~ s/(\w+)s/\1/g; my %y = reverse split(/\s+/,$in); return ($y{'second'}) + ($y{'minute'} * 60) + ($y{'hour'} * 60*60) + ($y{'day'} * 60*60*24); } [download] The DateTime project has created a DateTime::Duration object, as well as DateTime::Format::Duration. Please (register and) log in if you wish to add an answer Lots Some Very few None Results (227 votes), past polls
http://www.perlmonks.org/index.pl?node_id=101511
CC-MAIN-2016-07
refinedweb
277
76.05
For a number of years, mobile developers have had to grapple with maintaining multiple code bases of their apps—one for each platform. And for a number of years, that meant developing simultaneously for iOS, Android, Windows Phone, and even Blackberry. Fortunately, that didn’t last. Today, the mobile platform wars yielded two winners: iOS and Android. Even so, developers dread having to maintain dual code bases for their apps unless it’s totally necessary. Companies are also trying to avoid maintaining multiple code bases; otherwise they need to have separate teams of developers specializing in each platform. In recent years, cross-platform development frameworks have emerged as the life savers for developers, with Xamarin taking the lead with its Xamarin suite of development frameworks for cross-platform mobile development. And more recently, Facebook’s React Native proves to be a hit with mobile developers, allowing developers to create mobile apps using JavaScript, a language that’s already familiar to a lot of full-stack developers. Not wanting to be left out of the burgeoning mobile market, in late 2018, Google announced Flutter 1.0, its latest cross-platform framework for developing iOS and Android apps. In this article, I’ll give you an introduction to Flutter. By the end of this article, you ‘ll be on your way to developing some exciting mobile apps using Flutter! Getting Started with Flutter Flutter is Google’s portable UI toolkit for building natively compiled mobile, Web, and desktop apps using Google’s Dart programming language. Flutter has the following major components: - Flutter engine: Written in C++, provides low-level rendering support using Google’s Skia graphics library - Foundation Library: Written in Dart, provides a base layer of functionality for apps and APIs to communicate with the engine - Widgets: Basic building blocks for UI In the next couple of sections, I’ll show you how to install Flutter and start writing your first Flutter application. Once you’ve gotten started with the basics, you’ll create a news reader application that demonstrates how easy it is to write compelling mobile apps with Flutter. Installing Flutter To develop cross-platform iOS and Android mobile apps with Flutter, you need to use a Mac. For this article, I’m going to base my examples on the Mac. Before you get started, you need to ensure that you have the following components installed: - Xcode - Android Studio To install Flutter on your Mac, head over to this page:. The instructions on this page are pretty clear and self-explanatory, and I won’t repeat them here. For the development environment, you can use Android Studio or Visual Studio Code. I prefer Visual Studio Code. To configure Visual Studio Code to support your Flutter development, check out this page:. Creating Your First Flutter Project Once the SDK and tools are set up, you are ready to create your first Flutter application. The easiest way is to type the following command in Terminal: $ flutter create hello_world Note that Flutter project names must be in lower case and you can use the underscore character (_) if you need to use a separator for the project name (just don’t use camel case). The above command creates a folder named hello_world containing a number of files forming your project. To examine the content of the Flutter project created for you, open the hello_world project using Visual Studio Code. You can open up your Flutter project by dragging the project folder into Visual Studio Code. Figure1 shows the content of the Flutter project. Of particular interest are the following files/folders: - The main.dart file in the lib folder: This is the main file of your Flutter application. - The ios folder: This is the shell iOS application that runs on your iOS device/simulator. - The android folder: This is the shell Android application that runs on your Android device/emulator. - The pubspec.yaml file: This file contains references to the various packages needed by your application. To run the application, you need the following: - iOS Simulator(s) and/or Android emulator(s) - iOS device(s) and/or Android devices(s) The easiest way to test the application is to use the iOS Simulator and Android emulator. For the Android emulator, open Android Studio and create an AVD. For iOS Simulator, the simplest way to launch it is to use the following command in Terminal: import '$ open -a simulator Once the iOS Simulator and Android emulator are launched, you can run the flutter application using the following command: $ cd hello_world$ flutter run -d all The above command runs the application on all connected devices/simulators/emulators. If you want to know which devices/simulators/emulators are connected, use the following command: $ flutter devices You should see something like the following (I have bolded the device IDs): import 'pack2 connected devices: Android SDK built for x86 • emulator-5554• android-x86 • Android 9 (API 28) (emulator)iPhone X? • 95080E0D-F31B-4938-9CE7-01830B07F7D0• ios • com.apple.CoreSimulator.SimRuntime.iOS-12-2 (simulator) ), ), ), ),); To run the application on a particular device, use the following command: $ flutter run -d <device_id> The <device_id> is highlighted. When the application has successfully loaded onto the simulator and emulator, you should see them, as shown in Figure 2. Understanding How Flutter Works To learn how Flutter works, it’s good to look at the main.dart file in the hello_world project and see how the various components work. Frankly, it’s not the easiest way to learn Flutter because the various statements in the file can be quite overwhelming for the beginning developer. That’s why I’ll start off with the bare minimum and build up the application from scratch. Widgets Unlike other cross-platform development frameworks (like Xamarin and React Native), Flutter doesn’t use the platform’s native widgets. For example, in React Native, the <view> element is translated natively into the UIView element on iOS and the View element on Android. Instead, Flutter provides a set of widgets (including Material Design and Cupertino—iOS—widgets), managed and rendered directly by Flutter’s framework and engine. Figure3 shows how Flutter works. Widgets are rendered onto a Skia canvas and sent to the platform. The platform displays the canvas and sends events back to the app. Flutter doesn’t rely on the device’s OEM widgets. It renders every view’s components using its own high-performance rendering engine. In Flutter, UI are represented as widgets. Widgets describe how the view should look, given its current configuration and state. When the state changes, the widget rebuilds its description and the framework compares it with the previous description to determine the minimal changes needed to update the UI. Types of Widgets In Flutter, there are two main types of widgets: - Statelesswidgets: Changing the properties of stateless widgets has no effect on the rendering of the widget. - Statefulwidgets: Changing the properties of stately widgets triggers the life cycle hooks and updates its UI using the new state. Before you look at how to create stateless and stateful widgets, let’s erase the entire content of the main.dart file and replace it with the following statements: import 'package:flutter/material.dart'; void main() => runApp( Center( child: Container( margin: const EdgeInsets.all(10.0), color: Color(0xFFFFBF00), width: 300.0, height: 100.0, child: Center( child:Text( 'Hello, CODE Mag!', textDirection: TextDirection.ltr, style:TextStyle( color:Color(0xFF000000), fontSize:32, ) ), ), ), ),); The main() function is the main entry point for your application. The runApp() function has a widget argument; this argument will become the root widget for the whole app. In this example, Container (which is a widget) is the root widget of the application. As the name implies, the Container widget is used to contain other widgets, and in this case, it contains the Center widget, which, in turn, contains the Text widget and displays the string "Hello, CODE Mag!" Hot-reload has no effect on the root widget; in general, when you perform a hot-reload, the main() function won’t be re-executed and no changes will be observed. If you’ve run the application previously from Terminal, you don’t need to stop the application in order for the application to be updated. Flutters supports two types of update: - Hot reload(press"r"in Terminal). This option allows you to update the UI without restarting the application. - Hot restart(press"R"in Terminal). This option allows you to restart the application. Figure4 shows what happens when you press "R" to hot-restart the application. For this example, hot-reload has no effect as all of the UIs are defined in the root widget. You’ll see hot-reload in action later on when I discuss stateless and stateful widgets. Figure5 shows the application running on the simulator and emulator. Using the MaterialApp and CupertinoApp Classes The example in the previous section has a dark background and doesn’t look like a traditional iOS or Android application. Flutter provides two main convenience widgets that wrap your widgets in the design styles for the iOS and Android platforms: - MaterialApp: The MaterialApp class represents an application that uses material design. It implements the Material design language for iOS, Android, and Web. - CupertinoApp: The CupertinoApp class represents an application that uses Cupertino design. It implements the current iOS design language based on Apple's Human Interface Guidelines. Let’s now wrap the widget using the MaterialApp class: import 'package:flutter/material.dart'; void main() => runApp( MaterialApp( title: 'Material App Demo', home: Scaffold( appBar: AppBar( title: Text('Material App Demo'), ), body: Center( child: Container( margin: const EdgeInsets.all(10.0), color: Color(0xFFFFBF00), width: 300.0, height: 100.0, child: Center( child:Text( 'Hello, CODE Mag!', textDirection: TextDirection.ltr, style:TextStyle( color:Color(0xFF000000), fontSize:32, ) ), ), ), ), ), )); Hot restarting the app shows the application displayed in MaterialApp style (see Figure 6). In addition to the MaterialApp, you can also use the CupertinoApp class to make your application look like a native iOS application: import 'package:flutter/cupertino.dart'; void main() => runApp( CupertinoApp( title: 'Cupertino App Demo', home: CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: const Text('Cupertino App Demo'), ), child: Center( child: Container( margin: const EdgeInsets.all(10.0), color: Color(0xFFFFBF00), width: 300.0, height: 100.0, child: Center( child:Text( 'Hello, CODE Mag!', textDirection: TextDirection.ltr, style:TextStyle( color:Color(0xFF000000), fontSize:32, ) ), ), ), ), ) ), ); Figure7 shows how the application looks when you use the CupertinoApp class. Stateless Widgets So far, you have a pretty good idea of how UI in Flutter is created using widgets. In the previous section, the UI was created all in the runApp() function. A much better way to build the UI is to "componentize" the widget into independent widgets so that they can be reused. So now let’s try to reorganize the code so that the UI is written as a stateless widget. To create a stateless widget: - Name the new Widget class and extend it from StatelessWidget. - Implement the build() method, with one argument of type BuildContext and return type of Widget. Here is the template for a stateless widget: class MyCustomWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Center( ... ); } } Listing1 shows the previous UI rewritten as a stateless widget. Hot restart the application and you should see the same output as shown in Figure 7. Now, add another instance of the MyCustomWidget to the main.dart file:"), ], ), ) ),); Hot restart the application and you should see that there are now two instances of MyCustomWidget (see Figure 8). Do you still remember about the hot-reload that I mentioned earlier? Modify the color in the stateless widget as follows: When you now hot reload the app (press "r" in Terminal), you’ll see the colors of the MyCustomWidget change immediately (see Figure 9). Stateful Widgets Stateless widgets are useful for displaying UI elements that don’t change during runtime. However, if you need to dynamically change the UI during runtime, you need to create stateful widgets. Stateful widgets don’t exist by themselves: They require an extra class to store the state of the widget. To create a stateful widget: - Name the new Widget class and extend it from StatefulWidget. - Create another class that extends from the State class, of the type that extends from the StatefulWidget base class. This class will implement the build() method, with one argument of type BuildContext and return type of Widget. This class will maintain the state for the UI to be updated dynamically. - Override the createState() function in the StatefulWidget subclass and return an instance of the State subclass (created in the previous step). The following shows the template for creating a stateful widget: class MyCustomStatefulWidget extends StatefulWidget { //---constructor with named // argument: country--- MyCustomStatefulWidget( {Key key, this.country}) : super(key: key); //---used in _DisplayState--- final String country; @override _DisplayState createState() => _DisplayState();} class _DisplayState extends State<MyCustomStatefulWidget> { @override Widget build(BuildContext context) { return Center( //---country defined in StatefulWidget // subclass--- child: Text(widget.country), ); }} Using the earlier example, let’s now create a stateful widget by appending the code in bold (as shown in Listing 2) to main.dart. To make use of the stateful widget, add it to the runApp() function, like this: import 'package:flutter/cupertino.dart';"), MyCustomStatefulWidget(key:Key("1"), country:"Singapore"), MyCustomStatefulWidget(key:Key("2"), country:"USA"), ], ), ) ),); Performing a hot restart yields the UI, as shown in Figure 10. Clicking on the blue strip increments the counter. Observe the following: - The MyCustomStatefulWidget class has a property named country. This value is initialized through the named argument in the constructor: MyCustomStatefulWidget({Key key, this.country}). - The country property is used in the _DisplayState class, and it can be referenced by prefixing it with the widget keyword. - Our stateful widget tree contains the widgets, as shown in Figure 11. - The value of counter is displayed within the Text widget. When the GestureDetector detects a tap on the blue strip on the widget, it calls the setState() function to change the value of counter. - Modifying the value of counter using the setState() function causes the build() function to be called again; and those widgets that reference the counter variable are updated automatically Building the News Reader Project By now, you should have a good understanding of how Flutter works. The best way to learn a new framework is to build a sample app and see how the various components fall in place, so let’s now build a complete working application. For this project, you’ll create a news application that displays the news headline in a ListView, as shown in Figure 12. When the user taps on a particular headline, the application navigates to another page and loads the details of the news in a WebView (see Figure 13). For fetching the news headlines, you can use the following API:<api_key> You can apply for your own free News API key from. Creating the Project Let’s first start by creating the project: $ cd ~$ flutter create news_reader Adding the Package For this project, you need to use the HTTP package so that you can connect to the News API. Add the following statement in bold to the pubspec.yaml file: dependencies: flutter: sdk: flutter http: Once you save the changes to the pubspec.yaml file, Visual Studio automatically fetches the package and installs it on your local drive. Alternatively, you can use the following command to manually download the packages: $ flutter packages get Importing the Packages In the main.dart file. add the following statements in bold: import 'package:flutter/material.dart'; // for Future classimport 'dart:async'; // for httpimport 'package:http/http.dart' as http; // for JSON parsingimport 'dart:convert'; Updating the Title of the App Make the following modifications to the main.dart file: void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'News Headline', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'News Headline'), ); }} Accessing the News API The News API returns a JSON string containing a summary of the various news headlines. The first thing you need to do is to examine the structure of the JSON result returned and see which of the parts you need to retrieve for your application. Access the News API using<api_key>. Once the result is obtained, paste the result into a JSON formatter, such as. Figure 14 shows the JSON result formatted. In particular, you’re interested in extracting the following: - All of the articles referenced by the articles key - For each article, extract the values of title, description, url, and urlToImage Populating the ListView Add the statements in bold to the main.dart file as shown in Listing 3. A Future object represents the results of asynchronous operations Here is what you’ve added to the main.dart file: - You created a variable named _news and initialized it as a map object with the one key. articles, and set it to an empty list. Later you’ll connect it to the News API, retrieve the news article that you want, and assign the values to the _news variable. - You overrode the initState() function so that when the page is loaded, it calls the downloadHeadlines() function to download the content from the News API. - The fetchNews() function connects to the News API and returns a Future object of type http.Response. - The convertToJSON() function converts the content downloaded from the News API and encodes it into a JSON object. - The _buildItemsForListView() function returns a ListTile containing the UI for each row in the ListView. At this point, each row contains an image and a title for the news. - You use the ListView.builder() function to build the ListView, passing it the number of rows to create, as well as the function (_buildItemsForListView) that populates each row of the ListView. The ListTile class represents a row in the ListView. The title argument typically takes in a Text widget, but it can take any widget. You can now test the application on the iOS Simulator and Android emulator. Type the following command in Terminal: $ cd news_reader$ flutter run -d all The applications should now look like Figure 15. Implementing Pull-to-Refresh The next thing to do is to implement pull-to-refresh so that you can update the news feed by pulling down the ListView and then releasing it. Add the statements in bold to the main.dart file as shown in Listing 4. To ensure that the ListView supports pull-to-refresh, use the RefreshIndicator widget and set its child to the ListView.builder() function. Then, set its onRefresh argument to the _handleRefresh() function, which calls the downloadHeadlines() function again to download the news content. Customizing the Content of the ListTile Instead of displaying an image and the news title on each row, it would be better to display the news title and its description, followed by a smaller image. Add the statements in bold to the main.dart file that are shown in Listing 5. Here, you use the leading argument of ListTile class to display an icon using the CircleAvatar class. The title argument is then set to a Column object, which in turn contains the title and description of the article. You also added a Divider object, which displays a faint line between the rows. Perform a hot-reload of the app. You should now see updated ListView, as shown in Figure 16. Converting to a Navigational Application Now that the ListView displays the list of articles, it would be nice if the user could tap on an article to read more about it. For this, you’re going to create a details page that will be used to display the content of the article. Add the following statements in bold to the main.dart file: import 'package:flutter/material.dart'; // for Future class import 'dart:async'; // for http import 'package:http/http.dart' as http; // for JSON parsing import 'dart:convert'; // to store the data to pass to another widget class NewsContent { final String url; NewsContent(this.url);} void main() => runApp(MyApp());... The NewsContent class is used to store the URL of the article so that it can be passed to the details page. Append the following block of code to the end of the main.dart file:: Text('$url'), ), ); }} The DetailsPage takes in the data passed into it (which is the URL of the article) and displays it in the center of the page. Add the statements in bold to the main.dart file that are shown in Listing 6. The onTap argument specifies that when the user taps on a row in the Listview, it navigates (using the Navigator.push() function) to the next page (DetailsPage) and passes it the data (NewsContent). Redeploy the application. Select a particular news headline and you should see the details page as shown in Figure 17. Adding a WebView Displaying the URL of the article in the details page is not very useful to the reader. What you really want to do is to use a WebView to display the content of the article. Add the following bolded statement to the pubspec.yaml file: dependencies: flutter: sdk: flutter http: webview_flutter: The above statement adds the webview_flutter package to the project. To use WebView on iOS, you need to add the following bolded statements to the Info.plist file located in the ios/Runner folder: <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ""><plist version="1.0"><dict> ... <key>UIViewControllerBasedStatusBarAppearance</key> <false/> <key>io.flutter.embedded_views_preview</key> <true/></dict></plist> Add the following bolded statements to the main.dart file: import 'package:flutter/material.dart'; // for Future class import 'dart:async'; // for http import 'package:http/http.dart' as http; // for JSON parsing import 'dart:convert'; import 'package:webview_flutter/webview_flutter.dart'; // to store the data to pass to another widget class NewsContent { final String url; NewsContent(this.url);} ...: WebView(initialUrl: url, javascriptMode: JavascriptMode.unrestricted,) ), ); }} Redeploy the application. Select a particular news headline and you should see the news loaded in the WebView (see Figure 18). Displaying a Spinner Now that the app is almost complete, let’s add a final touch to it. When the article is loading in the WebView, let’s display a spinner so that the user can be visually aware that the page is still loading. Once the entire article is loaded, the spinner disappears. For this purpose, you can use the flutter_spinkit package, which is a collection of loading indicators written for Flutter. In particular, let’s use the SpinKitFadingCircle widget. Add the following statement in bold to the pubspec.yaml file: dependencies: flutter: sdk: flutter http: webview_flutter: flutter_spinkit: To display the spinner, use the Stack widget to overlay the WebView widget with the Container widget, which in turn contains the SpinKitFadingCircle widget when the WebView is loading, and an empty Container widget when the loading is complete, like this: Stack( children: <Widget>[ WebView( //---access data in the statefulwidget--- initialUrl: widget.data.url, javascriptMode: JavascriptMode.unrestricted, //---when the loading of page is done--- onPageFinished: (url) { setState(() { displaySpinner = false; }); }, ), Container( child: displaySpinner ? SpinKitFadingCircle( itemBuilder: (_, int index) { return DecoratedBox( decoration: BoxDecoration( color: index.isEven ? Colors.red : Colors.green, ), ); }, ): Container() ) ]) Because of the need to dynamically hide the SpinKitFadingCircle widget when the WebView has finished loading, it’s necessary to rewrite the DetailsPage class as a StatefulWidget. Add the following bolded statements to the main.dart file from Listing 7. Redeploy the application. Select a particular news headline and you should see the SpinKitFadingCircle widget displaying (see Figure 19). Summary Learning a new framework is always challenging. But I do hope that this article has made it easier for you to get started with Flutter. Let me know what you are using now (Xcode, Android Studio, Xamarin, or React Native) and if you plan to switch over to Flutter. You can reach me on Twitter @weimenglee or email me at weimenglee@learn2develop.net.
https://www.codemag.com/Article/1909091/Cross-Platform-Mobile-Development-Using-Flutter
CC-MAIN-2020-24
refinedweb
3,989
54.93
Including variables in a JupyterLab Notebook's Markdown cells seems like a basic thing. Turns out it is not. It's simply not yet supported out of the box. Here is how to do it anyways. Moreover, learn how to selectively hide code (input) cells when exporting your Notebook. Improve the aesthetics and dynamic capabilities of your Notebook by using this simple approach. Let's get started! Think of creating a JupyterLab Notebook for a statistical analysis and wanting to share it, e.g. by publishing it on your blog. Often times you will add text to accompany your code by using Markdown cells. Now, imagine that you want to use some result from the code output in order to comment on it. Instead of doing this: num_observations = 105 print("The data consists of {} observations".format(num_observations)) The data consists of 105 observations It would not only be more concise but also better looking if you could include the value of num_observations in your text. Hence, your text would dynamically update when the variable value changes. This is a common feature and is supported by RStudio within R Markdown for example. Surprisingly, Jupyter Notebooks do not support the inclusion of variables in Markdown Cells out of the box. If you still use Jupyter Notebooks there is a readily solution: the Python Markdown extension. It is part of the nbextensions package which is easy to install and configure. However, JupyterLab users run out of luck because nbextensions is not compatible with JupyterLab anymore. But bear with me ... from IPython.display import Markdown as md # Instead of setting the cell to Markdown, create Markdown from withnin a code cell! # We can just use python variable replacement syntax to make the text dynamic md("The data consists of {} observations. Bla, Bla, ....".format(num_observations)) The data consists of 105 observations. Bla, Bla, .... Nice! Still, there are two issues with this: - The code cell is inconvenient to type in because the syntax is a bit cumbersome and there are no line breaks - While the output is as expected the code cell (input) is also visible which kind of ruins the whole thing The first issue can be somewhat resolved by adding automatic line wrapping to code cells. Go to Settings -> Advanced Settings Editor in the left panel select Notebook and add the following to your User Preferences: { "codeCellConfig": { "lineWrap": "on" } } The second issue is a bit more tricky to solve. If you just want to hide the code cell in your own Notebook, that's easy: select the disruptive code cell and click View -> Collapse Selected Code. The cell is hidden and only the output remains creating a nice reading flow. Unfortunately, when exporting your Notebook this setting is ignored. We can work around this problem by using some tricks. First, we need to add a tag to the input cell that bothers us. You can do this by selecting the Notebook Tools tab on the left and opening up Advanced Tools: In the Cell Metadata box enter the following: { "tags": ["hide"] } A more convenient way to add tags is using the JupyterLab extension jupyterlab-celltags. You can install it by enabling Settings -> Enable Extension Manager (Experimental), selecting the Extension Manager form the left panel and searching for it. After enabling this extension you can simply add and edit your tags like here: After we have successfully tagged our target cell we need to tell nbconvert (the utility which does any conversion from .ipynb to e.g. HTML in Jupyter) to ignore it. When converting from the command line we can do it like this: jupyter nbconvert your_nb.ipynb --TagRemovePreprocessor.remove_input_tags='{"hide"}' This will export your Notebook to HTML (the default) in the same folder and remove all input cells tagged with hide. Mission accomplished! Your result should now look like this: The data consists of 105 observations. Bla, Bla, .... If you prefer to export your Notebook via JupyterLab and File -> Export Notebook as ... you need to add our change to the config file. For this, create / edit the file ~/.jupyter/jupyter_notebook_config.py residing in your home folder. At the bottom of the file add this: c.TagRemovePreprocessor.remove_input_tags = {"hide"} After restarting JupyterLab and exporting your file, it should give you the desired result as well. Finally, let's see how we can get this to work with a static site generator like Pelican which I use for this blog. In Pelican, you can write whole blog posts using only Jupyter Notebooks which is fantastic for sharing your analysis in a super convenient way. For that, you need a plugin that can convert your Notebook and make it work with Pelican. The one I prefer is ipynb2pelican. There are a few others which work pretty much the same: they all use nbconvert to turn your .ipynb file to a HTML file that fits the styles of your template. Because ipynb2pelican uses a modified preprocessor of nbconvert we need to explicitly set our configuration for this utility. In this case, we need to edit /pelican/base/folder/plugins/ipynb2pelian/preprocess.py. First, add the following line to the import headers: from nbconvert.preprocessors import TagRemovePreprocessor Then, add the following line inside the config_pres() function: TagRemovePreprocessor.remove_input_tags = {"hide"} After that, when ipynb2pelican calls nbconvert it will respect our setting. Done! If your situation is different, e.g. you use a different Pelican plugin or even a different site generator look for the .py file which contains this import: from nbconvert.preprocessors import Preprocessor Adjust the file in the same manner as described above. Now, you know how to include variables in your Jupyter Notebook's Markdown cells. In addition, you learned how to selectively hide input cells when converting your notebook, e.g. for sharing it on your blog.
https://data-dive.com/jupyterlab-markdown-cells-include-variables
CC-MAIN-2021-21
refinedweb
962
64.71
for connected embedded systems setbuffer() Assign block buffering to a stream Synopsis: #include <unix.h> void setbuffer( FILE *iop, char *abuf, size_t asize ); Arguments: - iop - The stream that you want to set the buffering for. - abuf - NULL, or a pointer to the buffer that you want the stream to use. - asize - The size of the buffer.];. Classification: Caveats: A common source of error is allocating buffer space as an automatic variable in a code block, and then failing to close the stream in the same block. See also: fclose(), fflush(), fopen(), fread(), freopen(), getc(), malloc(), printf(), putc(), puts(), setbuf(), setlinebuf(), setvbuf()
http://www.qnx.com/developers/docs/6.3.2/neutrino/lib_ref/s/setbuffer.html
crawl-003
refinedweb
101
71.44
. Having. Of course, in my case that's often me, and since relief usually doesn't come from berating oneself, I'm guilty of sending the occasional long crabby missive to the people who are currently responsible for maintaining things that I'm probably responsible for bollocksing up in the first place. It's not a particularly endearing habit. I sent the following to Swing's technical lead, Shannon Hickey, and he confirmed that the details, though twisted with bile, are essentially correct. So in the interest of furthering my own therapy, and also to ensure that some record of this will be stored away in Google's indices till the end of time, I thought I'd share. I would think that a fairly common idiom in a Swing application would be to popup a dialog in response to selecting a menu item. Given Matisse, we'll assume that the JDialog has been created with the IDE, rather than some JOptionPane convenience method, and given rudimentary aesthetics, assume the dialog should be centered over the menu item's frame. Accomplishing this seems to be much too difficult: public void showMyDialog(ActionEvent e) { // How to find the Dialog's Frame owner? Window dialogOwner = null; JDialog dialog = new MyDialog(dialogOwner, true); // true => modal Dialog dialog.pack(); // How to center the Dialog? dailog.setVisible(true); } The first problem to deal with is mapping from the menu item's ActionEvent to the frame that contains the menu item. The frame will be the dialog's owner as well as the component we're going to center the dialog relative to. There seems to be an overabundance of SwingUtilities methods that address this trivial problem: Window getWindowAncestor(Component c) Window windowForComponent(Component c) Component getRoot(Component c) To find the Frame that owns a JMenuItem, we have to follow the JPopupMenu's "invoker" property, which gets us back into the component hierarchy. So to find the frame that corresponds to an ActionEvent one must write (!): Frame frameForActionEvent(ActionEvent e) { if (e.getSource() instanceof Component) { Component c = (Component)e.getSource(); while(c != null) { if (c instanceof Frame) { return (Frame)c; } c = (c instanceof JPopupMenu) ? ((JPopupMenu)c).getInvoker() : c.getParent(); } } return null; } It would more useful to have written windowForActionEvent but sadly support for creating Dialogs whose owner is a Window (the parent class for Frames and Dialogs) only appeared in Java SE 6, and I needed code that worked for Java SE 5. It's also worth noting that this works for Applets too, although you'd be forgiven for not guessing that this is true. Applets do have a Frame parent that's created by the Java plugin and whose bounds are the same as the Applet (Panel) itself. windowForActionEvent But we're still not done, because we must also center the dialog over the frame. Naturally there are other useful positions for the dialog. Centering a dialog over its frame happens to be what started me on this quest. I have it on good authority that Windows.setLocationRelativeTo() is the handy method for this job. The javadoc for this method isn't promising: Sets the location of the window relative to the specified component. Sets the location of the window relative to the specified component. OK so far. Except it sounds like I'm going to have to compute the relative origin of my dialog and deal with edge (of the screen) conditions. Yech. If the component is not currently showing, or c is null, the window is placed at the center of the screen. The center point can be determined with GraphicsEnvironment.getCenterPoint [sic] If the component is not currently showing, or c is null, the window is placed at the center of the screen. The center point can be determined with GraphicsEnvironment.getCenterPoint [sic] Huh? What does "the component" refer to in this sentence? I assume they're not referring to this Window and I have to wonder what "showing" means in this context. Is is the same thing as getVisible() being true? If not, do I have to hope that my menu item is still "showing" when this method is called? And what's this advice about getCenterPoint (and where's the period)? In my case the Window and its menu item are visible, so I'm hoping none of this stuff applies. Because I don't really understand it. getVisible() getCenterPoint. This, no doubt, means that the method will endeavor to find a location for my dialog that respects the relative location I've specified, without making part of the dialog appear off-screen. Good, I think. So I still appear to be stuck with computing an origin for my dialog that centers it relative to its owner. Before I code that, I try leaving the origin of the new dialog at 0,0, which is the default: public void showMyDialog(ActionEvent e) { Window dialogOwner = frameForActionEvent(e); JDialog dialog = new MyDialog(dialogOwner, true); dialog.pack(); aboutBox.setLocationRelativeTo(dialogOwner); dialog.setVisible(true); } Miraculously, this works. The dialog appears centered over the dialogOwner unless that would cause the dialog to appear off-screen. I have no idea why it works, since according to the "spec" (and the name of the method) I should have had to compute an appropriate relative origin for the dialog. But I guess I don't. Frankly, I think this whole mess is a mini-travesty. If I'm going to show a dialog, I should be able to do so without writing code that digs around the component hierarchy and without experimentally determining what something as simple (and not terribly useful) as Window.setLocationRelativeTo() does. There, that feels a little better. A seven year old bug that covers the menu item to frame lookup problem is still open. Given the fact that it's accumulated exactly 0 votes in that time, perhaps no one has ever cared about the problem quite as much as I do at this moment. I would think that a cleaner way to handle this case would be some static methods that handled the entire idiom, for example: public void showMyDialog(AWTEvent event) { Window dialogOwner = Window.eventToWindow(event); JDialog dialog = new MyDialog(dialogOwner, true); Window.showModalDialog(dialog); // Center dialog relative to its owner } And Shannon suggested that the method name might be rationalized as implying that the Window is be moved to a location that makes its relationship to the component parameter obvious. Typically that means centering the Window relative to the component. In return for that tortured explanation, I had to agree to file an RFE about the Window.setLocationRelativeTo() javadoc. I haven't done so yet. But I will. Window.setLocationRelativeTo() Thanks for listening. Tuesday morning this week, I was seated in the vast Moscone keynote cavern, with 15,000 other Java developers, taking in the start of another JavaOne conference. The keynotes and demos were entertaining and I hope you didn't miss the HUGE Swing Aerith demo at the conclusion of the morning. Sadly I did, although I've seen quite a lot of it over last few weeks. I had to dart out early, because my first-ever JavaOne musical gig started at about 10:30 and I had to get my bass and set up in time for the big Dukelele show. That's right, Dukelele. A Ukelele painted like so: A group of us played music in front of the JavaOne store at one end of the corridor that connects the Moscone's North and South subterranean chambers. In addition to me, the band was Hideya Kawahara and Yuichi Sakuraba playing Ukeleles (Dukeleles!) and singing, Mark Anenberg on a guitar-shaped drum synthesizer, Chet Haase on a laptop powered keyboard, and Kaoru Nakamura playing a keyboard/harmonica hybrid called a Pianaca. And to top if off, Duke danced and hugged people. We started playing as the keynote audience began flooding past and to our delight, many of them stopped to listen. Tragically, the Moscone Fire Marshall did not share our joy. After about 10 minutes he swooped in and put a stop to the show. I guess we were a fire hazard, or at least Hideya was. He was really putting his heart into singing and playing and I suspect that the Fire Marshall was afraid that he might suddenly burst into flames. Another rock and roll show, shut down by the man. Not exactly Altamont Speedway, but definitely a strange and abrupt ending to our little performance. Fortunately one of our colleagues videotaped the whole thing and so now you can check it out on YouTube.com. No animals were harmed in the making of this video. We played again, in the afternoon, outside on the sidewalk. It was a bit breezy and most of the people who drifted by gave us an odd look and then slipped indoors. One was exception was Tim Boudreau, who took in the entire set and then threw a quarter in our tip jar. Except we didn't have a tip jar. Our friend the Fire Marshall seemed to be pleased that we finished without spontaneously combusting. Cautious man that he is, he kept a sharp eye on the proceedings from a safe distance, clutching his fire extinguisher in one hand, and a fistful of swag from the Motorola booth in the other. Next year we'll bring our own fire protection. One aspect of many docking GUIs is support for reconfiguring tiled subwindows by dragging shared subwindow edges. MultiSplitPane and MultiSplitLayout support arbitraily complex tiled layouts that can be reconfigured interactively and programatically.. Every now and then someone drops by to ask about the slick chat/IM demo components that were shown in the Extreme GUI Makeover JavaOne session last year. The Swing components created for those demos where hacked together in order to show what's possible and sadly, they're not available as production quality components just yet. I certainly like the idea of resuable, configurable/extensible, chat client GUI parts. If I were building that kind of application I'd be happy to avoid starting from scratch. This blog is a brief look at one such part. You can try it out by pressing the launch button. BuddyCellRenderer is an attempt to build a somewhat reusable JList CellRenderer for Chat/IM buddy lists. It's job is to render an object that represents a Buddy roughly like this: screen name [status] short message [icon] Here "status" is one of online, offline, or away. Away status means that the user is online but busy. The "screen name" is the Buddy's name, "short message" is an optional short message from the Buddy, and icon is a picture that represents the Buddy. All of this is quite conventional. These elements appear in most chat/IM application buddy-lists in one form or another. If a "short message" isn't provided we change the layout just slightly: [status] screen name [icon] The BuddyListCellRenderer must also provide a Buddy-specific tooltip that's displayed if the user lingers over one BuddyList element. JList renders list elements or "cells" by delegating to an implementation of ListCellRenderer. ListCellRenderers have only one method, getListCellRendererComponent(), which returns a Component that the JList uses to paint a single list element. The JList really just uses the cell renderer component's paint() method to draw or "rubber stamp" a list element. The getListCellRendererComponent() method is passed the JList model's "value" for each list element, and its responsibility is to return a component that's been configured to display that value. The default ListCellRenderer is quite simple. It just uses the same JLabel for every list element, roughly like this: JLabel label = new JLabel(); Component getListCellRendererComponent(JList l, Object value, ...) { jLabel.setText(value.toString()); return jLabel; } To display the properties of a Buddy in the way we've layed out above will require more than just a JLabel. BuddyCellRenderer uses a JPanel with subcomponents for the various properties and GridBagLayout to define the layout. A generic ListCellRenderer that configures our JPanel composite to display a Buddy value is difficult because we don't want to dictate the type of the Buddy object but we do need to extract its status, screen name, icon, and message. What's needed is an adapter that extracts the properties needed by the BuddyCellRenderer from the app-specific Buddy object. The BuddyListCellRenderer.Adapter class does this. The way it works is easiest to explain with an example. Lets assume that our chat/IM application has a Buddy class that looks like this: class MyBuddy { boolean isOnline() { ... } boolean isAway() { ... } String getScreenName() { ... } ImageIcon getIcon() { ... } } A JList ListModel that encapsulated the list of MyBuddy objects would have to be created; I will not delve into that here. The adapter for MyBuddy objects could be defined and used like this: class MyBuddyAdapter extends BuddyCellRenderer.Adapter { private MyBuddy getBuddy() { return (MyBuddy)getValue(); } public String getName() { return getBuddy().getScreenName(); } public String getMessage() { return getBuddy().getMessage(); } public ImageIcon getBuddyIcon() { return getBuddy().getIcon(); } public Status getStatus() { if (getBuddy().isAway()) { return Status.AWAY; } else if (getBuddy().isOnline()) { return Status.ONLINE; } else { return Status.OFFLINE; } } } BuddyCellRenderer cellRenderer = new BuddyCellRenderer(); cellRenderer.setAdapter(new MyBuddyAdapter()); myBuddyJList.setCellRenderer(cellRenderer); That's pretty much all there is to it. The BuddyCellRenderer scales (and caches) the Icons provided by the Adapter if they're bigger than BuddyCellRenderer.getBuddyIconSize(). It also caches the "grayed out" version of the icon that's used when a Buddy's status is offline. Alternating rows are rendered in an off-white color to help with readability and the whole thing is layed out internally with the old Swing layout veteran: GridBagLayout. BuddyCellRenderer.getBuddyIconSize() If you'd like to try making some changes to BuddyCellRenderer and the demo, you can download a NetBeans project with the source code and the jar files here: Download BuddyList NetBeans Project ... I've been trying to think of a way to humbly announce that no lesser authority than Evans Data Corporation has reported that Swing is the dominant GUI Toolkit for Northern American developers. It's difficult to present this new statistic with the grace and humility of good sportsmanship because, after nearly 8 years of steady growth: "Java Swing with 47% use, has surpassed WinForms as the dominant GUI development toolkit, an increase of 27% since fall 2004." That's a direct quote from the Spring 2005 report. You may want to read it again (I have). There are more developers building applications using Swing and Java SE than WinForms and .NET. Despite the titanic resources marshalled by Microsoft to assert dominance over their own desktop platform, the Swing community has grown into an unstoppable force. Microsoft has often been referred to as an "eight hundred pound gorilla". Thanks to the persistence and enthusiasm of Swing developers everywhere, we've thrown the gorilla and the cage off the island. We're the new alpha male, we're the King Kong of GUI toolkits. We are the force to be reckoned with. We are number one!. I realize that was a little over the top. I'm supposed to be humble and quietly confident about our success and not indulge in all of this vulgar gloating and boasting and jumping up and down on the desk shouting, we're number one, we're number one, we're number ... Sorry about that. I'll just remain calm from here on in. You'll have to trust me when I say that I'm reporting the following from a peaceful and serene perspective. The use of both Swing and AWT have grown dramatically in the last year and, quoting from the report, "Java GUI development is clearly experiencing substantial growth". So it is. I would guess that there are at least two trends at work here. People are writing Swing clients to augment or replace browser clients for network services, and developers really do care about platform portability. Sometimes portability is just about spanning different versions of Windows but more often than not, it's about covering the growing "alternative" desktop market. Users want applications that provide entertainment or communication or educational experiences that are worthy of the fine computer hardware they're seated in front of, and the zippy internet service they're connected to. Developers are choosing Swing to deliver those experiences and here, at camp Swing headquarters, we couldn't be happier. It's good to be king and it's hard to be humble. I feel a T-shirt coming. Thanks to Jeff Dinkins for another bit of just-in-time artwork!
https://community.oracle.com/blogs/hansmuller
CC-MAIN-2015-48
refinedweb
2,760
54.63
1. What is Java:comp/env exactly? Is it related to Java EE only? For example, I create a JNDI data source named jdbc/sqlSource in, say, glassfish so I would typically access that DS in a web app deployed in glassfish. How about trying to access this DS from a desktop application ? How can I access this data source from a stand alone java SE client? 2. I've heard about Global JNDI Namespace. What is that and does it vary from one app server to another? I mean to say, does every app server has got its own global JNDI namespace?Is it right to say that the objects registered under a Global JNDI namespace can be accessed from code running in another JVM? 3. I recently saw some examples using java:app, java:comp, and java:global. What is the relation of these three with java:comp?
http://www.coderanch.com/t/481699/EJB-JEE/java/Numerous-questions-JNDI
CC-MAIN-2015-18
refinedweb
150
66.94
This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. Imagine you have a class like this: 1: public class Person 2: { 3: public virtual String FirstName 4: { 5: get; 6: set; 7: } 8: 9: public virtual String LastName 10: { 11: get; 12: set; 13: } 14: 15: public virtual String FullName 16: { 17: get 18: { 19: return(String.Concat(this.FirstName, " ", this.LastName)); 20: } 21: } 22: } You might be tempted to issue a query such as this: 1: var people = session.Query<Person>().Where(x => x.FullName == "Ricardo Peres").ToList(); Unfortunately, this will not work, because FullName is not a mapped property, and will result in an exception being thrown. You have three options: Regarding option 1, you can define this property using mapping by code as: 1: mapper.Class<Person>(p => 2: { 3: p.Property(x => x.FullName, x => 4: { 5: x.Formula("FirstName + ' ' + LastName"); 6: x.Generated(PropertyGeneration.Always); 7: x.Insert(false); 8: x.Update(false); 9: }); 10: } Whereas for option 2, you have to have all entities materialized and then apply the condition: 1: var people = session.Query<Person>().ToList().Where(x => x.FullName == "Ricardo Peres"); As for option 3, it’s pretty straightforward: 1: var people = session.Query<Person>().Where(x => x.FirstName == "Ricardo" && x.LastName == "Peres").ToList(); There may be far more complex cases, however, when you will not be able to do this so easily, for example, if you have complex logic in your composite property.
http://weblogs.asp.net/ricardoperes/nhibernate-pitfalls-querying-unmapped-properties-with-linq
CC-MAIN-2015-06
refinedweb
249
58.18
16261/how-to-read-file-from-subprocess-open-in-python I want to read the output for a file spawned through subprocess.popen in Python. How can I do it? You can't "split a file", but you can read ...READ MORE You can not directly import an excel/csv ...READ MORE Hyperledger Fabric supports only 2 types of ...READ MORE Any modification to the Ethereum Blockchain will ...READ MORE What is the argument utxos int the ...READ MORE This should work: #!/usr/bin/env python import getpass import json import requests ...READ MORE This was a bug. They've fixed it. ...READ MORE Just remove the json_encode call, and it should work: $resp ...READ MORE You can not directly read the content ...READ MORE Hey buddy, this works: /** * Track temperatures ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/16261/how-to-read-file-from-subprocess-open-in-python?show=16263
CC-MAIN-2020-29
refinedweb
140
80.48
." Awful default "X" icon (Score:1, Interesting) Visual Improvements? (Score:1, Interesting):So? It still sucks. they should be, but because of that small error, it makes the desktop look slightly askew, and adds to the screen clutter appearance. Other than appearance and "feel" I have no problem using KDE. Re:The important part: Mono (Score:1, Interesting):candy (Score:5, Interesting) Don't fade borders if you're compositing a complete window. Faded borders are the graphical equivalent of an ellipsis. And definitely don't add a drop shadow to something you've already faded to white. It looks ridiculous. Re:The important part: Mono (Score:3, Interesting) The GTK+ theme engine is lacking. (Score:1, Interesting) One of the main causes is their use of C. It doesn't promote a solid rendering class hierary, as is offered by GUI toolkits that are written a language like C++ (eg. Qt, wxWidgets), Objective-C (eg. Cocoa), Java (eg. Swing, SWT), or Smalltalk (eg. Squeak). This in turn makes it quite difficult for anyone who wants to develop a theme of any complexity. Like you mention, just changing the colors (which is easy enough) is not enough. You need to be able to render button and text fields with shadows. You need to have certain corners be sharp, while others rounded. The toolkit engine of GTK+ allows for both, but doens't easily allow for both to be used concurrently. That's just a small example of the problems that exist when writing a GTK+ theme engine. What needs to be done is an analysis of what successful GUI toolkits, like Qt, have done. Adopting the techniques of their engine is perhaps the best thing that the GTK+ developers can do at this point. Re:The important part: Mono (Score:1, Interesting) I use Linux 100% of the time at home AND at work. I only develop on linux for linux. I could really give a shit less about Microsoft and what they do. I do enjoy Mono though. Re:But does it have a useable file-save dialogue? (Score:5, Interesting) have been put into place over the last 20 years, and especially by allowing users to set options as they want - not what the designers think is "best for them". The "we know best" attitude is condescending and hinders usability. The "proper" way to do it is to have everytthing come "out of the box" with basic defaults but let the user "open up" the interface as they learn it. If you're really worried about your poor users provide a "reset to defaults" option. The parent post simply points out some obvious problems with GNOME, the fact it got modded Troll points out some problems with blinkered moderation. And yes I am a GNOME user - I have an Ubuntu desktop at home. I mostly like GNOME but it always, always sends me into a swearing frenzy due to basic usability problems. Re:Almost sounds like KDE 3... MOD INSIGHTFUL (Score:2, Interesting) Re:The important part: Mono (Score:1, Interesting) Just like Java is a standard. Java isn't standardized [wikipedia.org] by anyone other than Sun. C#, on the other hand, is standardized by ECMA and ISO [wikipedia.org], not Microsoft. Could you explain why grammar parsing is not possible in C#? There isn't any kind of magic that C++ can do with strings that other languages can't. Sure, there might be libraries to do grammar parsing for you that are written in C++, but there isn't any reason these libraries couldn't be written in another language or that bindings for other languages couldn't be written. I love and use C++; I just don't like this "anything but Microsoft" criticism of C# just because a Microsoft employee created it. If you're going to discuss a language, let's talk about its technical merits, not the employer of its creator. The advantages that C++ has over higher-level languages are primarily (A) it's C compatible, and (B) it allows really low-level control (like C does). (A) is a non-issue once bindings have been written for a C library. (B) is a valid advantage, but it's really only important in things like operating systems or applications where performance is really critical. This applies to only a small minority of software nowadays. It is true that C++ has gained a lot of the features that other languages have with the Boost libraries. However, the nature of C++ makes it so that, even with Boost, code is more cumbersome than in high-level languages. Take, for example, passing a function as an argument to another function. Let's say I need to pass a function called "clickHandler", which is a member of the class window, whose prototype looks like: void clickHandler(Event ev); I want to pass this function to another function called registerHandler (which makes it so when the user clicks on the window, clickHandler gets called). Using boost, my function call looks like: , this, _1)); registerHandler(boost::bind(&window::clickHandler and registerHandler's prototype has to look like: void registerHandler(boost::function<void (Event)> func); Now, let's say you try to do the same thing in Python. Your function call will look like: registerHandler(self.clickHandler) and registerHandler's definition will look like: def registerHandler(handler): I don't know the language well enough to know what this looks like in C#, but my point here is that yes, you can do things in C++ that you can do in higher level languages, but it's often much more unwieldly and difficult. It took me a really long time to figure out how all that syntax for Boost and C++ works the first time I learned it; if you look at the C++ code above, you certainly can't say it's blindingly obvious that that's how it should work. When I learned how to do this in Python, all I had to learn was "Functions in Python are objects." and that's enough information to write the code. Not only that, the Python code is much more flexible; if I change clickHandler's interface, I also have to change registerHandler's interface and the (potentially) function call, whereas I don't have to do anything if I change registerHandler's interface in Python (beyond any necessary changes to the logic (not syntax) of the code). The idea of higher-level languages is that you don't have to micromanage tasks like how a function is passed as an object; you can focus on the bigger picture, which is that you simply want to pass the function. Sure, C++ is more powerful in that you can micromanage things like this if you want to, but usually you won't want to, and with languages like C#, Java, Python and others, you don't. Processors have gotten a lot faster and memory has become much more abundant since C++ was created in the 1980s, and the tradeoff between the computer clock cycles and programmer "cycles" has shifted. This is why GNOME and other software projects are making increased use of higher level languages. Re:candy (Score:1, Interesting) When I see a system that configures itself so flawlessly as for example win XP or os X, and is so stable, dynamic and fast as linux, im happy. Right now, im sorry, im NOT. Windows XP is very underestimated by many Linux powerusers, in the sence of easy-too-use and compability. Yet STILL... (Score:5, Interesting) (I still use gnome every day.) Re:candy (Score:2, Interesting) I'm with you. Sure, there might have been issues with maintenance of the Sawfish code, amongst other things, but metacity still has a couple of glaring holes they refuse to fill in. My own pet peeve is Metacity's refusal to remember the size or positioning of windows. I know the developers claim it's the application's job to do this, but I don't agree. Seems obvious to me, but who am I to insist that a window manager's job is to manage windows? ;) Are the dependencies still growing like topsy? (Score:3, Interesting) When the number of dependencies required to run Gnome on mainstream distributions DECREASES, that'll impress me. Until then I am unlikely to care what new eye-candy it's sporting. Re:Technically great (Score:3, Interesting) Pretty easy, actually. Using Inkscape, for example, if you already have the main icon drawn: Takes less than a minute. Sure it would take a bit more work than just copying and pasting the same grey oval, but not much, and it's literally the same process for every icon, once the main part is drawn.
https://slashdot.org/story/06/09/07/0240207/gnome-216-released/interesting-comments
CC-MAIN-2016-40
refinedweb
1,472
62.27
set of three positions individually to see whether they're sufficient to explain spottiness. For each of the $O(M^3)$ possible positions, we check whether there's any matching set of bases that appears at that position in both a spotty and a non-spotty cow. If we're considering a set of positions $(i, j, k)$, we first iterate over every non-spotty cow, and recording whether we can find an A, C, G, or T in each of the positions $i$, $j$, and $k$. We do the same for the spotty cows, and check at each step if we've already found a non-spotty cow with the same set of three bases. If we find a spotty cow that shares the same set of three bases with a non-spotty cow in this position, then these three positions don't comprise a valid candidate for explaining spottiness. If we can't find any of these overlaps, then this set of three positions can successfully be used. The most difficult part of this problem might be keeping track of which sets of three bases we've already seen. Luckily, there's a trick to make it a lot easier! We can convert 'A' to 0, 'C' to 1, 'G' to 2, and 'T' to 3. Then we can compare two positions $(i_1, j_1, k_1)$ and $(i_2, j_2, k_2)$ by comparing the values of $16 \cdot i_1 + 4 \cdot j_1 + k_1$ and $16 \cdot i_2 + 4 \cdot j_2 + k_2$. The positions will be equal to each other if and only if these values will be equal -- for the same reason that you can compare two numbers in base 4 by comparing each of their digits. The total runtime is $O(NM^3)$, which is fast enough to receive full credit. Here's Brian Dean's code: #include <iostream> #include <fstream> #include <cmath> using namespace std; int N, M; string spotty[500], plain[500]; int S[500][50], P[500][50], A[64]; bool test_location(int j1, int j2, int j3) { bool good = true; for (int i=0; i<N; i++) A[S[i][j1]*16 + S[i][j2]*4 + S[i][j3]] = 1; for (int i=0; i<N; i++) if (A[P[i][j1]*16 + P[i][j2]*4 + P[i][j3]]) good = false; for (int i=0; i<N; i++) A[S[i][j1]*16 + S[i][j2]*4 + S[i][j3]] = 0; return good; } int main(void) { ifstream fin ("cownomics.in"); ofstream fout ("cownomics.out"); fin >> N >> M; for (int i=0; i<N; i++) { fin >> spotty[i]; for (int j=0; j<M; j++) { if (spotty[i][j]=='A') S[i][j] = 0; if (spotty[i][j]=='C') S[i][j] = 1; if (spotty[i][j]=='G') S[i][j] = 2; if (spotty[i][j]=='T') S[i][j] = 3; } } for (int i=0; i<N; i++) { fin >> plain[i]; for (int j=0; j<M; j++) { if (plain[i][j]=='A') P[i][j] = 0; if (plain[i][j]=='C') P[i][j] = 1; if (plain[i][j]=='G') P[i][j] = 2; if (plain[i][j]=='T') P[i][j] = 3; } } int answer = 0; for (int j1=0; j1<M; j1++) for (int j2=j1+1; j2<M; j2++) for (int j3=j2+1; j3<M; j3++) if (test_location(j1,j2,j3)) answer++; fout << answer << "\n"; return 0; }
http://usaco.org/current/data/sol_cownomics_silver_open17.html
CC-MAIN-2017-13
refinedweb
566
66.91
MASM32 Downloads The lines are wrapped. What's your screen resolution? Mine is 1366x768, and even with enlarged fonts they are not long enough to wrap. Or did you mean something else? Well, yes the lines wrap, but I just thought you might find it useful to see your work on another's system. Maybe the colors and fonts are different for instance. include \masm32\MasmBasic\MasmBasic.inc ; download if 0 ; copy the line below, then hit F6 to get the db version chartab dw "10","01","12","21","13","31" ; expected output: chartab db "0","1","1","0","2","1","1","2","3","1","1","3" endif Init ; *** translate Masm dw format to db for use with UAsm *** Let esi=Clip$() ; get string from clipboard (limit is about 160k) lea ecx, [2*Len(esi)] ; the byte format is longer, so we need a bigger buffer Let edi=New$(ecx) push esi push edi .Repeat lodsb If_ al=="w" Then mov al, "b" ; dw->db stosb .Break .if !al .if al==34 push [esi] lodsb movsb ; first digit mov al, 34 stosb mov al, "," stosb mov al, 34 stosb pop eax stosb ; second digit movsb ; second quote .endif .Until 0 pop edi pop esi Inkey "Before: ", esi, CrLf$, "After: ", edi, CrLf$, "Copy to clipboard? (y)", CrLf$ If_ eax=="y" Then SetClip$ ediEndOfCode Good practice is: In the box is more easy to copy!! I have a choice of wrapped comments or uncommented code, I choose having wrapped comments. Recall Utf8$(wCL$()), L$() ; translate the file supplied through the (Unicode) commandline to a text array (if the file is Unicode, the strings will be in UTF-8 format; if needed, you can get Unicode back with wRec$(L$(n)) - see also ConvertCp$) I am trying to figure out if it's worthwhile to look for the debugger paths when doing a fresh install of MasmBasic. Currently, the default paths are hardcoded (see: integrated debugging) to\Masm32\x64Dbg\release\x64\x64dbg.exe for 64-bit debugging\Masm32\OllyDbg\ollydbg.exe for 32-bit code.Therefore the question: Where are your debuggers located? include \masm32\MasmBasic\MasmBasic.inc Init PrintLine GetRegVal("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug", "Debugger") SetReg64 Inkey GetRegVal("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug", "Debugger")EndOfCode Unchangeable folder paths in this case better Quote from: LiaoMi on October 10, 2017, 05:39:20 AMUnchangeable folder paths in this case better Why that? I have three versions, clean current release, stable version for work, and the current version with plug-ins, this package is always updated by adding plugins or changing the settings. Therefore, the exact binding for me is better
http://masm32.com/board/index.php?PHPSESSID=3fc99124e2268f13f013469a2f588f5e&topic=5314.30
CC-MAIN-2018-39
refinedweb
442
60.85
This is your resource to discuss support topics with your peers, and learn from each other. 07-23-2008 04:48 PM I think there are some missing objects in the packaged files: I am compiling a class that extends from ObjectListField as follows: public class RunnableObjectListField extends ObjectListField and getting: cannot access net.rim.device.api.ui.component.ListFieldMeasureCa class file for net.rim.device.api.ui.component.ListFieldMeasureCa Earl 07-24-2008 09:49 AM 08-26-2008 11:31 AM - edited 08-26-2008 11:36 AM Are there any ticket numbers that we can use so we can track when these missing objects might be fixed? Do you know of any estimated resolution dates for this or workarounds? We have a single class in our app that extends ObjectListField, but it's used in several different spots. We would like to be able to go forward with our Bold testing/development, but we'd prefer not to have to rewrite sections of our app that were already working, just to avoid this issue. Not unless it's absolutely necessary. Any feedback you can provide would be greatly appreciated. 08-26-2008 02:14 PM This issue exists in the current beta release of the 4.6.0 BlackBerry JDE. It does not affect the 4.6.0 BlackBerry handheld software, so there should be no issue with running the application (only building it). Therefore you can build the application in previous versions of the BlackBerry JDE and test using the BlackBerry Bold simulator.
http://supportforums.blackberry.com/t5/Java-Development/Using-ObjectListField-in-4-6-JDE-beta/m-p/22594
CC-MAIN-2015-06
refinedweb
257
63.8
I have this method def forest(sword, armour, ring) true false forest false, false, false sword=true && armour=true forest sword-truth-value, armour-truth-value, ring-truth-value? To achieve what you are looking for, you should wrap the forest method in a class and define each argument as an instance variable. class Forest attr_accessor :sword, :armour, :ring def initialize(sword = false, armour = false, ring = false) @sword = sword @armour = armour @ring = ring end end So now, you can declare an instance of Forest, forest = Forest.new All the variables default to false, unless you explicitly write true. With the attr_accessor, you can access and set all the variables. forest.sword #=> false forest.sword = true forest.sword #=> true
https://codedump.io/share/VUXbVoL2cG6M/1/ruby-method-arguments---can-they-change-truth-value-automatically
CC-MAIN-2017-39
refinedweb
118
73.27
How to Effectively Map SQL Data to a NoSQL Store - | - - - - - - Read later Reading List Traditionally we know that: - SQL databases are limited to a single machine but provide strong transactions, schemas, and querying; - NoSQL databases abandon transactions and schemas in order to provide scale and fault tolerance. FoundationDB's SQL Layer combines both: An open-source SQL database that is linearly scalable, fault tolerant, and has true ACID transactions. What used to be opposing sides of a divide are now available as a unified system. This is important for many companies that have: - New applications planning for massive scale; - Existing applications hitting database scale; - Many applications that should be consolidated to work against a single, fault-tolerant, virtualized database substrate. In this article, I'll describe FoundationDB and explain how the FoundationDB SQL Layer maps SQL data to the FoundationDB Key-Value Store back end. The NoSQL Database: FoundationDB’s Key-Value Store FoundationDB is a distributed key-value store with global ACID transactions and high performance. In the setup of your system, you can define the level of data replication, which provides fault tolerance: when a server or part of the network breaks down, the database will keep operating and so will your application. The Key-Value + SQL Architecture We developed the architecture to support multiple layers on top of the Key-Value Store. Each of these layers can provide a different data model, such as SQL, Document, or Graph against the same FoundationDB back end. Many users also build their own custom layers. The architecture diagram below highlights different key aspects. At the bottom is the FoundationDB cluster. It operates as a single logical database, regardless of the size of the cluster. The SQL Layer runs as a stateless intermediary on top of Key-Value Store. It communicates with the application using SQL, and uses the FoundationDB client API to communicate with the Key-Value Store. Because the SQL Layer is stateless, any number of SQL Layers can run in parallel. The SQL Layer brings Google F1 capabilities to the Key-Value Store The SQL Layer is a sophisticated translation layer between SQL and the key-value API. Starting with a SQL statement, it transforms it to the most efficient key-value execution, much as a compiler translates code to a lower-level execution format. It is compliant with the ANSI SQL 92 standard. Developers can leverage the product in combination with ORM’s, a REST API, or access it directly using the SQL Layer command line interface. From a codebase point of view, the SQL Layer is completely separated from the Key-Value Store. It communicates with the Key-Value Store using the FoundationDB Java bindings. For those interested, the open-source code is available on FoundationDB’s SQL Layer GitHub repo. Currently, the only comparable system is Google’s F1, a SQL engine build on top of their Spanner technology. The SQL Layer is built from a set of components as shown in the simplified diagram below. Queries are sent from applications using one of the supported SQL clients. The statements are parsed and transformed into a tree of planning nodes. The optimizer computes the best execution plan and expresses it as a tree of operators that will be executed by the execution framework. In the execution phase, requests for data are sent to the storage abstraction layer, which uses the Java Key-Value API to transfer data to and from the FoundationDB cluster. The database modeled is stored in the Information Schema, which is used by the different components. Mapping SQL Data to a Key-Value Store The SQL Layer needs to manage two types of data, namely metadata of the information schema, which describes the tables present and the indexes available. Secondly, it needs to store actual data, including table content, indexes, and sequences. We will start with a description on how the data is stored into the Key-Value Store. At a basic level, each key is a pointer to unique row in a table, and the value contains the data for that row. The assignment of keys is determined using the construct of a Table-Group, which is a grouping of one or more tables. This concept will later be discussed in more detail. The SQL Layer creates a directory for every Table-Group using the Key-Value Store Directory Layer, a tool to manage the keyspace for users. The Directory Layer assigns a short byte-array as a unique key for every individual directory, while maintaining separate metadata to facilitate look-up by name. The example below demonstrates the mapping of the directories, with examples of keys that could be assigned for the given statements: CREATE TABLE schema_a.table1(id INT PRIMARY KEY, c CHAR(10)); CREATE TABLE schema_a.table2(id INT PRIMARY KEY); Some of the directories that are defined in the Key-Value Store are: To store data, three types of formats are available, ‘Tuple’, Row_Data’, and ‘Protobuf’. When using the default ‘Tuple’ storage format, a row is stored as a single key-value pair. The key is a tuple formed by concatenating the directory prefix, the position of a table within the Table-Group, and the primary key. The value is a tuple formed from all of the columns in the row. For example, the following inserts to the tables from the previous example would yield the given keys and values: INSERT INTO schema_a.table1 VALUES (1, 'hello'), (2, 'world'); INSERT INTO schema_a.table2 VALUES (5); Knowing the structure of the keys in the Key-Value Store, you can read data from the store directly. This will be demonstrated using the FoundationDB Python API. In the SQL Layer, keys and values are encoded with the '.pack()' method, and can be decoded with the '.unpack()' method. The example below shows how you can retrieve and decode data. import fdb fdb.api_version(200) db = fdb.open() directory = fdb.directory.open(db,('sql','data','table','schema_a','table1')) for key, value in db[directory.range()]: print fdb.tuple.unpack(key), ' --> ', fdb.tuple.unpack(value) The code above prints something similar to: (215, 1, 1) --> (1, u'hello') (215, 1, 2) --> (2, u'world') Let's take a closer look at Table-Groups. A single table belongs to its own group. An additional table can be added to the group if it creates a ‘grouping foreign key’ that references the first table. When we add a grouping foreign key to a table, the child table is interleaved within the directory of the parent table. The table is now part of the Table-Group named after the root table. The data of two different tables are interleaved in the same directory. This enables fast range scans and makes access to an object and joins within the Table-Group almost free. To demonstrate the principle, we continue our example with the following SQL statements: CREATE TABLE schema_a.table3(id INT PRIMARY KEY, id_1 INT, GROUPING FOREIGN KEY (id_1) REFERENCES schema_a.table1(id)); INSERT INTO schema_a.table3 VALUES (100, 2), (200, 2), (300, 1); This yields the following results: directory = fdb.directory.open(db,('sql','data','table','schema_a','table1')) for key, value in db[directory.range()]: print fdb.tuple.unpack(key), ' --> ', fdb.tuple.unpack(value) (215, 1, 1) --> (1, u'hello') (215, 1, 1, 2, 300) --> (300, 1) (215, 1, 2) --> (2, u'world') (215, 1, 2, 2, 100) --> (100, 2) (215, 1, 2, 2, 200) --> (200, 2) The inserted rows of the third table are interleaved with the rows in the first table, as the keys of the third table are in the namespace range of the first table rows. The two extra values in the key refer to the position within the Table-Group and the primary key in the third table. Joins of table 1 and 3 on the reference key do not need standard join processing; a linear scan is all that is needed. This way of ordering yields a significant advantage over traditional relational database systems. Indexes make practical use of the fact that keys have ordering. All table indexes only have a key value containing two parts. An index is located in the directory of the table it belongs to, in a subdirectory with the name of the index. This is the first part of the key tuple. The second part is a combination of the values of the columns on which the index is set, followed by the remaining values of the columns necessary to identify the row of the entry. For example, we can add an index to our table on column c. CREATE INDEX index_on_c ON schema_a.table1(c) STORAGE_FORMAT tuple; Using Python to read the content of the index, we need to add the following in the Python interpreter: directory = fdb.directory.open(db, ('sql', 'data', 'table', 'schema_a', 'table1', 'index_on_c')) for key, value in db[directory.range()]: print fdb.tuple.unpack(key), ' --> ', fdb.tuple.unpack(value) This will print something similar to the output below. It shows the two parts of the key: the byte value of directory from the index, and the column c value on which the index was created, followed by its primary key value. This last part links the indexed value to a specific row. The value belonging to the index key is empty. (20127, u'hello', 1) --> () (20127, u'world', 2) --> () To fine-tune the behavior of the SQL Layer, three storage formats are available: the described tuple format, a column keys format, and a protobuf format. The column keys format will create a separate key-value pair for every column value in a row. The protobuf storage format will generate a protobuf message for every row. The metadata also needs to be stored and organized. The SQL Layer uses protobuf messages to communicate the structure of the SQL-based data. The structure is formed by the schemas, groups, tables, columns, indexes, foreign keys, etc. Mixed-mode SQL and NoSQL The SQL Layer can be combined with direct (application-level) use of the Key-Value API when the latter is read-only. The data is accessible via the Key-Value API but adding or modifying data in the key ranges used by the SQL Layer can easily corrupt the system. Some examples of problems that arise are: the lack of maintenance of indexes, lack of constraint enforcement and no verification of data and metadata versions. Generic benefits, even for performing reads, are not clear as the SQL Layer adds very little overhead. In general, performance costs are network latency dominated. Conclusion The marriage between SQL and NoSQL is clear example of a mutually beneficial relationship. The SQL layer profits from the scalability, fault tolerance and the global ACID transaction properties of the FoundationDB Key-Value Store, and likewise could your application, try it! For applications that need to execute a lot of small reads and writes of data, FoundationDB offers a scalable and secure solution, SQL or NoSQL. About the Author Sytze Harkema is a software engineer working for FoundationDB since March 2014. He is focused on developing the SQL Layer, making it the best storage solution for scalable SQL applications. Sytze studied at TU Delft (the Netherlands) and Harvard (USA). Rate this Article - Editor Review - Chief Editor Action
https://www.infoq.com/articles/map-sql-nosql
CC-MAIN-2018-47
refinedweb
1,878
54.42