text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava regardless of any other intentions. A concrete class implementing both interfaces can... above in the hierarchy). Java programming language allows an abstract class... programming language, Marker interfaces are those interfaces that don't have any corejava - Java Beginners corejava pass by value semantics Example of pass by value semantics in Core Java. Hi friend,Java passes parameters to methods using pass... arguments to the method call is passed to the method as its parameters. Note very Corejava - Java Interview Questions . Tokenize an input string by using both split & StrinTokenizer and store... having only numeric values by using Pattern class. Hi Friend, 4 CoreJava Project CoreJava Project Hi Sir, I need a simple project(using core Java, Swings, JDBC) on core Java... If you have please send to my account Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava programming language consists of one or more abstract methods that must...; Inheritance In java programming language, multiple... to introduce the single inheritance in java programming language Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava of these are part of every object created in java language programming. These methods Help Very Very Urgent - JSP-Servlet Help Very Very Urgent Respected Sir/Madam, I am sorry..Actually... of the ID from Combo box,both Employee ID and Employee Name text box must be filled... requirements.. Please please Its Very very very very very urgent... Thanks Interview Questions corejava how to merge the arrays of sorting i want source code of this one plz--------------------------------------------- Hi Friend, Try the following code: public class MergeSort{ public static void main corejava Java programming tutorial for very beginners Java programming tutorial for very beginners Hi, After completing my 12th Standard in India I would like to learn Java programming language. Is there any Java programming tutorial for very beginners? Thanks Hi Learning the Java Language Learning the Java Language Hi, I am beginner in Java and I want to learn Java very quickly. Tell me which url will help me in Learning the Java Language? Thanks Hi, Please see Java Tutorials section. Thanks displaying both image and records problem in jsp and servlet - JSP-Servlet displaying both image and records problem in jsp and servlet hello... and picutre on the web browser. i will be very happy if i can get the code for this as urgent as possible. Thanks for your cooperation. dipo. Hi How beneficial the Functions of the Management and place. The role of manager or management is very crucial at this point as he hi roseindia - Java Beginners hi roseindia what is java? Java is a platform independent object oriented programming language which ensures portability,security etc..., Threading, collections etc. For Further information, you can go for very good Learning programming language - Java Beginners Learning programming language Hi, I am srikanth i want to learn java programming language without knowing C language.I am very new to programming and i want to learn this language.Can you suggest me to learn the language Programming help Very Urgent - JSP-Servlet Programming help Very Urgent Respected Sir/Madam, Actually my code..... Now what I require is: When I click or select any of the ID from Combo box,both... Please please its very urgent.. Thanks/Regards, R.Ragavendran..   Where to learn java programming language and want to learn Java and become master of the Java programming language? Where to learn java programming language? Thanks Hi, Java is Object.... These tutorials and example will help you in learning Java programming language very About Java Programming Language About Java Programming Language Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose programming... with some coding, its better.. PLEASE SEND ME THE CODING ASAP BECAUSE ITS VERY VERY URGENT.. Thanks/Regards, R.Ragavendran... Hi friend, Code multi language multi language Hello friends please help me Hi how can i do a java program using swing that changes the language like malayalam/tamil etc with languages on a drop down menu I am using netbeans IDE hi... - Struts also its very urgent Hi Soniya, I am sending you a link. I hope...hi... Hi Friends, I am installed tomcat5.5 and open the browser and type the command but this is not run please let me - Struts please help me. its very urgent Hi friend, Some points to be remember...Hi Hi Friends, I want to installed tomcat5.0 version please help me i already visit ur site then i can't understood that why i installed all - Java Beginners hi all hi, i need interview questions of the java asap can u please sendme to my mail Hi, Hope you didnt have this eBook. You.../Good_java_j2ee_interview_questions.html?s=1 Regards, Prasanth HI About JSP Expression Language - JSP-Servlet About JSP Expression Language Hi i am new to JSP i am now going...! Nice problem but you do not need to worry as you have made a very small mistake...- - - - - - - - - - - - - - - - - - - - - - -<%@ page language="java" import="java.util.*" Ask Java Questions Online programming language used on the Web for both client and server processing. Unlike C... learners and professionals as Roseindia Technologies, a front running software... is tough but a powerful language used in various software fields including Java as a general purpose language Java as a general purpose language Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose Java as a general purpose language Java as a general purpose language Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose programming Roseindia JSF Tutorial source code available for the learners at single place. Roseindia JSF Tutorials are aimed to guide the learners with complete coverage of JSF topics required... Tutorials are available for the learners willing to learn Java Server Faces (JSF bi language support - Struts bi language support Hi, Expert how can i use hindi font support in struts application multiple language selection multiple language selection Hi how can i do a java program using swing that changes the language like malayalam/tamil etc with languages on a drop down menu Very Big Problem - Java Beginners Very Big Problem Write a 'for' loop to input the current meter reading and the previous meter reading and calculate the electic bill.... Please give my answer in a for loop only and as soon as you can. Hi Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava Ask C/C++ Questions online language, but both the languages are popular among programmers. C is a general... of both high level language and low level language. It is widely used for creating video gaming and hardware design. Both C and C++ is very popular Hibernate Query Language Hibernate Query Language Explain Hibernate Query Language(HQL) of Hibernate? Hi Samar, Hibernate Query Language is a library for mapping relational database to java classes. It is similar in visual aspect to SQL Java Programming Language Java Programming Language Hi, For beginner which programming concepts is important? Discuss the importance of Java programming language. In the discussion please let's know how to use Java in developing web applications Language Translate Probelm Language Translate Probelm I want to build an application showing... providing language translation. translate api converts - "What is your name.... Hi... - Java Beginners and send me..... its very urgent Hi friend, Plz specify the technology.. go How to Insert image and data both together in database in JSP/Servlet ? How to Insert image and data both together in database in JSP/Servlet ? //form.jsp <%@ page language="java" %> <HTML> <HEAD><TITLE>Display file upload form to the user</TITLE></HEAD> < C Language - Java Beginners answer for the above questions since it is very much needed urgently hi, - Java Beginners hi, what is the need for going to java.how java differ form .net.What is the advantage over .net.Is there any disadvantage in java Hi... where as .Net is not. 3)Java is a language as well as provides run time Hi.... - Java Beginners Hi.... I hv 290 data and very large form..In one form it is not possible to save in one form so i want to break in to part....And i give...; Hi friend, Some points to be member to solve the problem : When Be a Sun Certified Java Programmer will also be quite beneficial for the learners. Our trainers’ tip and tricks... is a hard nut to crack for most of the java learners and only extraordinary...). The pattern of the question is multiple choice and drag & drop in both hi plzz reply hi plzz reply in our program of Java where we r using the concept of abstraction Plz reply i m trying to learn java ... means in language of coding we r not using abstraction this will be used only for making ideas What is Hibernate Query Language (HQL)? What is Hibernate Query Language (HQL)? Hi, What is Hibernate Query Language (HQL)? thanks Ple help me its very urgent Ple help me its very urgent Hi.. I have one string 1)'2,3,4' i want do like this '2','3','4' ple help me very urgent struts internationalization for Korean language struts internationalization for Korean language Hi All, Please suggest me an example where struts is implemented for korean locale using struts internationalization concept. Regards Nagaraju on hibernate query language - Hibernate on hibernate query language Display the contents of 2 fields in a table in a single column using SQL statement.Thanks! Hi friend,read for more information, Hi, Hi, Hi,what is the purpose of hash table Java as an Internet Language Java as an Internet Language Java is an object oriented language and a very simple language... a general purpose language that had many features to support it as the internet hi - JSP-Servlet Form Code in JSP and Servlet Hi, I am looking for a form code in JSP and Servlet. HI,Here is the form code:----<html><title>registration form</title><head><script Is Java a pure object oriented language? Is Java a pure object oriented language? Hi, Is Java a pure object oriented language? thanks Hi No, Java is an object oriented programming language but not purely a object oriented language. In OOPs programming.
http://www.roseindia.net/tutorialhelp/comment/2221
CC-MAIN-2015-06
en
refinedweb
All Panaceas Become Poison AllPanaceasBecomePoison was the title of a CoEvolutionQuarterly ? I read maybe 20 years ago. I think of it today with regard to C++. I loved C. A neat, flexible, concise, expressive little language. But with warts. You could do big things in it, but the maintainability was not good. When C++ 1.0 came out, the old cfront/glockenspiel stuff, I looked at it, liked the flavour and the symmetry, but dismissed it - immature, a toy, not something to do real work in. But I kept watching, and as I watched the language grew, and it grew strong. I liked C++ 2.x - an expressive, detailed, efficient, brutal language. Still heavy to maintain, but far better than C, and really easy to get to from C. I loved the C++ of the ARM, a language a C programmer could learn in a week, and master in six months. It was ugly under the covers, but it was manageable and did what it was told. I used it and boosted it and built big useful things with it and made money with it. But Bjarne and Andy and co. were still monkeying with it. Monkeying with it was their business. They stooped to conquer. So we had RTTI, and namespaces, and bags of kludgy keywords like "explicit", "export", and "typename". And STL and the "improved" Standard Library. The ARM doubled in size to become "The C++ Programming Language, Third Edition" - the kitchen sink of kitchen sinks. And you really can't use C++ without an OODBMS, or COM, or CORBA, and now, swelp me, a bunch of UmlCaseVultures with the demonstrated and chronic inability to design an efficient drawing tool. And the language went to a committee. So now we've got this bloated mutant bastard that looks almost but not quite entirely unlike C. Each little bit of it, especially STL, is cute in its own way. But the parts don't fit together without a lot of non-C experience, and even then there's plenty of warts. C++ warts tower over the old C warts. Over ten years since I first played with C++, I consult in it, teach in it, make my money with it, build in it ... and loathe it. The panacea that cured the old C diseases has become a poison that kills projects at the root. At least it didn't turn into something almost but not quite entirely unlike tea. Well, I just woke up to this. What's woken me up is Perl. I'd tinkered with perl like I used to tinker with awk and sed and shell, but never took it seriously. A scripting language - something for neat cgi scripts, sure, but no more. Nothing large. Immature. A toy. Then a few months ago I stumbled across Ward's WikiBase , and that made me go and buy a couple of books just to get up to speed. I never intended to use perl for real, just wanted to get competent with it for competency's sake and to play with. But I read the PerlBooks and now I can see that large things can be done easily in Perl. Sure, I've still got a learning curve. It took me a week to learn and six months before full fluency. There was all that CPAN stuff to grok, and the builtin syntax is intricate and often perverse. But it's clean - woman and man, this language is so damned pure compared with C++. And expressive. And concise. And flexible. And extensible. And easy to teach. And fun! Every time you want to use a feature in some way - damned if it doesn't work that way! Or if it doesn't, you can make it work that way! In short, Perl reminds me of nothing so much as C. It has none of C's warts, but it has its elegance . Perl has everything that ought to have been in C++, and none of the hypercomplex claptrap that ended up in there. But there's still an efficiency issue. Until Perl can be properly compiled I think what's best is to combine the two - write most of your stuff in perl, and then rewrite the tight loops in C++. Just write little things in C++ - it's no longer fit for the big stuff. AlternateHardAndSoftLayers . I still expect one day Perl will go the same way. AllPanaceasBecomePoison . -- PeterMerel . Well, that was six months ago. Now Python's my fave and Perl seems big and kludgy. I remember feeling the same way about other languages; that this , at last, suits me best of all. Perhaps a more rational way to think about it is HorsesForCourses ? Um, ObjectiveCee that is ... Um, XformsTechnology ... Um, RubyLanguage ... Maybe I'm just slow of mind ... but you know, the problem I'm really trying to describe is caused by everything generative eventually becoming ExtremelyInterstrangled . It'll happen to ruby too, just you watch. And at every step there'll be a bunch of hoary grey-beards singing out "ya shoulda programmed in [Forth|Lisp|Smalltalk] all along like we toldja!". Which prompts a good question: HowComeLispAndSmalltalkAintPoisonYet ? C++ is my milk language. I used to sleep with the ARM under my pillow. I see C++ as a solid feat of engineering, where engineering is understood to be the science of intelligent tradeoffs. There is an inner elegance to C and C++ in that they present a consistent model: an underlying machine that everything can be understood in terms of. STL takes advantage of it. That said, I feel cheated. At OOPSLA97, I walked into a room and saw WardAndKent speaking. I felt out of place because I was probably the only one there who had never programmed in Smalltalk. Nonetheless, it dawns on me more and more (especially with exposure to Java) that C++ has so many options that it forces undue hesitation in work. Man, the simple things... I downloaded JUnit a few weeks ago and thought it would be cool to port it to C++. I looked at it and saw the stack trace, the garbage collection, the reflection and the dynamic loading that you get for free, and I felt like I've wasted too much time. I never wanted to believe the people who maligned C and C++. After all, I had work to do, right? I needed speed, and C++ is the lingua franca. Man. -- MichaelFeathers I think Java is turning toxic fast . Problem is not the syntax with java, it's the libraries - ugh. Pretty much agree on Java. About what Michael says, you can beat the hesitation problem by sticking to a dialect, there are good tracing facilities in the OSE library, STL Allocators can be made to auto-ref-count just fine, an OODBMS will reflect and CORBA/COM will manage the dynamic loading okay. So as long as you can figure out a way to graft all those bits together and convince someone to pay you to do it, your only worry will be how to stick to a dialect. Heh.'' -- PeterMerel . Yeah. I don't mind having lots of stuff (libraries). I just don't like the lag between intention and realization which is consumed by building infrastructure that other languages give you for free, and spending time considering how the infrastructure that you introduce will affect your portability and future options. -- MichaelFeathers I guess I can pretend to credit myself for being a faster learner. I tried for 6 months to get my C programmer to use C++ back in 1988, because C++ was the obvious choice for an OO C programmer and naturally we couldn't ship in Smalltalk:-). He kept stalling for some reason, and in those 6 months I looked at the discussions being waged on the C++ bulletin boards - like, where is my pointer pointing, and I looked at the different sort of thing happening on the Smalltalk boards, like, classes being exchanged and here's some cool code try it, and I thought then, as I think now.... LifesJustTooShort . Go where you love, and if you love the insides of C++ and DCOM, power to you. I also love all the carpenters and garbage truck crews in the world. -- AlistairCockburn Hmm. This seems a lot milder than the opinion in your book. Change of heart or just diplomacy? -- PeterMerel Well, the above version is my historical-recounting-for-polite-society version. What I wrote in the book is my reasonably-toned-professional-consultant-recommendation , a strong but softened (at the reviewers' requests) phrasing that lies in the middle of the politeness spectrum. My lets-be-fair-to-everyone version is: "C++ and Smalltalk are two different work media. Some artists choose to WorkWithClay , some choose to WorkWithStone . When you choose to work in stone, you have to work differently than when you work in clay. You have to plan better, you have to be more careful as you go, you can't afford to keep changing your mind." My lets-be-scientific version is: "C++ was a nice experiment, we learned a lot about contravariance and the limitation of using classes as types... Now let's declare the experiment over, or else treat it like recombinant DNA experiments - only to be continued under strictest isolation and not let out of the lab." The least polite version I save for late night discussion over beer and say, "I wish they would just drop the whole thing into the deepest part of the ocean with a heavy weight." and then I say, as I said above, LifesJustTooShort . I guess if I was going to offend anyone with my C++ views, I probably have managed it by now ... Actually, I really did try to get this guy to use C++, and quite hard, too. He was remarkably stubborn. Just kept saying, "when there is a preprocessor that generates properly IBM-C compatible code." Over a six-month time frame in 1988 the vendors kept promising and never delivered. By the end of the six month period I had read enough on the bulletin boards that I went back and told him he could keep using C - which he wrote in an 'object-based' fashion, and thanked him for being stubborn. I have thanked him many times since then for saving the project. I think if we had used C++ our project would have died the common death I describe in the book. -- AlistairCockburn I'm confused. WhatAreTypes ? -- MichaelFeathers Perhaps the problem lies not with the decisions of the language designers and developers, who are trying to facilitate real requirements with mechanisms as elegant as possible, but with the decisions of the program designers and developers who feel compelled to use every feature of the language without good reason or insight. I've been happily programming in pre-standard C++ for ten years, content to go slow in adopting new language mechanisms while trying to become faster at getting things done. Why would someone try out a language feature they don't need or don't appreciate, then use that as an excuse to abandon the language? I still don't see any need for exceptions (are there really that many practical things you can do once they're raised beyond printing an error message and possibly aborting?) but I haven't let that stop me from programming without them. -- ScottJohnston The problem comes when you want to re-use software written by other folks, who do use the features that you see no need for. Now, suddenly, you have a need, and the use of these misfeatures spreads like a cancer throughout the programming community. Soon enough, everyone is using these misfeatures, and now you find yourself in a situation where (A) you can't remove the misfeature because everyone's using it, and (B) you can't remove the misfeature because everyone who simply can't remember coding without it will rise in rebellion and burn your house down. When Bjarne attempted to fix some of the template syntax in C++, he was virtually mauled to death. When things like this happen, it is time to abandon the language. --SamuelFalvo ? The following quote seems appropriate here: What seems to have been lost over the years [...] is the common understanding of what the design center of the language is. While it is clear that the original design center as enunciated by Stroustrup is no longer sufficient to guide the development of the language, there has been no discussion of a replacement for that design center. Indeed, it is not at all clear that the current community of users is even in agreement about what the language ought to be capable of doing and, perhaps more important, what it should not attempt to do. The lack of a clearly articulated, generally accepted design center for the language has resulted in a lack of a set of principles that can be used to judge the direction of language change. The danger is that the language will attempt to become something that does everything, with the result that it will do nothing well. In his book Wonderful Life , Stephen Gould argues that one should not confuse biological evolution with progress. The forces that shape the survival of one species over another, Gould points out, are far more random than what is required to allow one to claim that species for recently evolved are in any way more advanced or superior to those from which they evolved. Without a clear design center than can be used to determine a notion of progress in the evolution of a language, the changes that have been made [...] take on many of the aspects of biological evolution. The language has been used able to adapt itself to the changing environment of the increasing number of users. But with no goal for the language, the evolution of the language can only be seen as change, not progress towards that goal. -- JimWaldo ? , The Evolution of C++ : Language Design in the Marketplace of Ideas , September 1993 ISBN 026273107X (A Usenix Association Book) The danger is that the language will attempt to become something that does everything, with the result that it will do nothing well. - don't most language designers strive to preserve the existing features of a language as they add new features? How can a language that once did something well be evolved in this manner to do nothing well? Isn't CommonLisp still good at list manipulation? Wouldn't FORTRANXX still be usable by a FORTRAN77 programmer? Are programming languages really that much like biological organisms where a price has to unconditionally be paid (by the whole community) for each new experimental appendix? Maybe that is so, if all of a sudden you are swamped with new frameworks to adapt that use the latest language features with no choice in the matter. Is that what people have experienced with C++? -- ScottJohnston One of the great skills in using any language is knowing what not to use, what not to say. C, C++, Smalltalk, Lisp, it doesn't matter ... you can use them well or poorly. A big part of using them well is not using big chunks of what's there ... whether built-in language bits or available classes or frameworks. There's that simplicity thing again ... -- RonJeffries Hey, look, we figured out how to get energy out of sunlight. So, we dump a little oxygen in the atmosphere... -- EarlyPhotosynthesizer ? CategoryCpp CategoryAntiPattern EditText of this page (last edited June 11, 2009 ) or FindPage with title or text search
http://c2.com/cgi-bin/wiki?AllPanaceasBecomePoison
CC-MAIN-2015-06
en
refinedweb
Re: Refresh the cache Gordon, Jack wrote: We were told by our vendor to clear the cache. That may not be the right term, but the process that they have us do is to remove the folders from the following directory: D:\Tomcat 4.1\work\Standalone\localhost OK - you can't do that without stopping Tomcat. Mark Re: Tomcat 6 classpath issue wskent wrote: I have the following jars in my web projects \web\WEB-INF\lib dirdectory - log4j-1.2.13.jar, mysql-connector-java-5.0.5.jar, servlet-api-2.4.jar, standard-1.1.2.jar When I retrieve the classpath using - String classPath = System.getProperty(java.class.path,.); Re: [NOT-FIXED]SEVERE: Error listenerStart -- without entering the listener Ken Bowen wrote: Ok, I fixed that (see below), but that does seem to change the problem at all. The catalina.out trace is the same. Have a look at the files in the logs directory. One of them should have more information (like the stacktrace from the failed listener). Mark Re: [NOT-FIXED]SEVERE: Error listenerStart -- without entering the listener Ken Bowen wrote: That's what's frustrating. I'm using a new Tomcat unzip with simple JULI logging So what is the log4j message doing in this trace? Mark - To start a new topic, e-mail: users@tomcat.apache.org To Re: No available certificate or key corresponds to the SSL cipher suites which are enabled [EMAIL PROTECTED] Re: Problem with POST to servlet: 16384 bytes maximum? Sam Wun wrote: Hi, I am wondering how to fix the following attached error (mvn command run)? I tried to follow the instruction shown in the following website, but got error. 1. Don't hijack threads. 2. Read the FAQ, Re: DefaultServlet doesn't set charset Mark Re: Possible virus uploaded to Tomcat 5.5.3 Re: Possible virus uploaded to Tomcat 5.5.3 Re: Possible virus uploaded to Tomcat 5.5.3 And a follow up question - are you using the invoker servlet at all? Mark - To start a new topic, e-mail: users@tomcat.apache.org To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] Re: Problems with NoClassDefFound Error in tomcat 6 Tom Cat wrote: Hello, Re: Possible virus uploaded to Tomcat 5.5.3 War Re: Problems with NoClassDefFound Error in tomcat 6 Tom Cat wrote: No, I didn't have Tidy.jar in the webapp's classpath. I moved it into the WEB-INF/lib folder and am still getting a NoClassDefFound error. Any help? Did you reload your webapp? Mark - To start a new topic, Re: Possible virus uploaded to Tomcat 5.5.3 War Re: https j_security_check Julio César Chaves Fernández wrote: but my problem is when the user and password are right ... i doesn't takes me to the site but leaves me again in the login page Are you logging in over https? Mark - To start a new Re: Possible virus uploaded to Tomcat 5.5.3 - SOLVED Folks, Just a short note to let you know that Warren and I have been working this off-list and have identified how this attack was launched. I'd like to take this opportunity to publicly thank Warren for taking the time to work with me on this when he had a lot more important things to do Re: Possible virus uploaded to Tomcat 5.5.3 - SOLVED Same, Re: Strange startorder of webapps Tobias Kaefer wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi! I have a strange problem with Tomcat 6.0.16 and the start order of my webapps. I just switched form 32bit-Windows XP to 64bit-Linux on my development system. On the Windows system everything works as expected: ROOT webapp Re: Possible hack tool kit on tomcat 6.0.16 Mehrotra, Anurag wrote: Could there be some kind of backdoor entry happening in the code. Unlikely. This is the sixth report like this I have seen. So far, we have got to the bottom of two and in both cases the manager app was the route in. Whilst a Tomcat flaw is possible (and check out Re: Re-opening the browser Christopher Schultz wrote: Tokajac, Tokajac wrote: | But when i submit the (activated) username and password, i got the | -- | HTTP Status 408 - The time allowed for the login process has been exceeded. | If you wish to Re: Re-opening the browser Christopher Schultz wrote: Mark, Mark Thomas wrote: | If you go directly to the login page Tomcat can't tell the difference | between that situation and when you go to a protected page, are | redirected to the login page and then take so long to log in the session | times out (the page you need Re: Load order for Global Resources Dave Bender wrote: Is the order that Tomcat 6.0.x loads/instantiates Custom Resources definable? I am afraid not. If so, how? If not, is there a way to ensure that one custom resource is loaded prior to another one? Not that I am aware of. I think the order is going to be be defined by the Re: Load order for Global Resources Dave Bender wrote: Thanks. Some replies: I think the order is going to be be defined by the order in which the xml parser returns them. Has there been any change to the parser from version 4.x to version 6.x? If so, maybe that'll explain the problem. If not, in theory, we should be getting Re: Tomcat 5.5 4.1 Security Release David Rees wrote: I posted a couple messages to the user/dev lists last week asking the same question, There is no need to cross-post. but still haven't seen any mention of a plan to release a new 5.5.x or 4.1.x to fix the security issues posted at the beginning of the month. Is there a plan Re: where can i get tocat admin package tunzaw wrote: Hi Where can i get tomcat admin package? I want to use. When i attempt to use this url ,tomcat say tomcat admin tool do not already install.Where can i download tomcat admin package? Have you tried the download pages? Mark Re: Tomcat failover Ofer Kalisky wrote: Is there a reason why no one is answering this? Mark - Original Message - From: Ofer Kalisky To: Tomcat Users List Sent: Monday, August 11, 2008 3:26 PM Subject: Tomcat failover Hi, I have a Re: tomcat5.5 site configuration. Shahar Cohen wrote: Rmove this line: # Host name=localhost appBase=webapps / Change this line: Host name=10.10.10.12 appBase=webapps to: Host name=localhost appBase=webapps Mark - To start a new topic, e-mail: Re: FW: Mail could not be delivered [EMAIL PROTECTED] wrote: Hello Team, I tried to unsubscribe from this email list, but got mail undelivered message, could someone unsubscribe me from this email list, so that I could use or subscribe with my new email ID. You used the wrong address to unsubscribe. The correct address ([EMAIL Re: change configuration Frank Uccello wrote: I am new to tomcat I was wondering how to I change tomcat 5.5 running on Linux box to state auto developed = false also on tom cat 4 Assuming you mean automatic deployment, see It is pretty much the same on Tomcat Re: ssl certificate Alonzo Wilson wrote: After importing the signed certificate using keytool -import -alias tomcat1 -trustcacerts -file tsat.cer -keystore .keystore is there a way to make the new certificate active besides stopping and starting tomcat? Tomcat version? Mark Re: ssl certificate. Mark - To start a new topic, Re: CGIServlet in Tomcat 6 Martin Gainty wrote: grant tomcat access to CGIServlet.jar edit $TOMCAT_HOME/conf/catalina.policy grant codeBase file:${catalina.home}/webapps/YourWebApp/WEB-INF/lib/CGIServlet.jar { permission java.security.AllPermission; }; HTH That won't help at all. The CGIServlet bypasses the Re: where can i get tocat admin package Angus Mezick wrote: I am having the same problem. I have looked here: and in the lower directories. No mention of the admin pack. Where would it be hiding? Even if I look at 6.0 in the archives, there is no admin app. Has it not been ported Re: How to set jvmRoute outside of server.xml Bill Shaffer wrote: Re: Default error page generation logic in tomcat R Re: removal of product name/version Christopher Schultz wrote: Tommy, Tommy Pham wrote: | Thanks all for the reply. Somehow I missed that attribute. Looks | I'll have to define the error-pages. If I specify in the web.xml in | the conf folder, does apply to all web apps deployed for that | host/virtual host? See also: Re: ssl certificate restarting Tomcat will be a lot simpler. Mark Mark Thomas [EMAIL PROTECTED] 8/12/2008 5:05 PM Re: where to place context configuration Robert Dietrick wrote: Hi, I just noticed that I had a Context definition in both $CATALINA_HOME/conf/Catalina/localhost/mywebapp.xml and in $CATALINA_HOME/webapps/mywebapp.war/META-INF/context.xml. In both of these context definitions, I define a JNDI database connection pool with the Re: where to place context configuration Robert Dietrick wrote: I would very much prefer to use only the one in mywebapp/META-INF/contex.xml, as this is much less invasive (does not require changing/adding anything to tomcat's global config directories). But this doesn't seem to work. That isn't the way it is designed. I can Re: ssl certificate connections but you can't restart the server that way. If you need that level of availability, look into a simple httpd Tomcat cluster. Mark Mark Thomas [EMAIL PROTECTED] 8/14/2008 11:17 AM Alonzo Wilson wrote: Please explain. How does adding a new connector restart tomcat and activate Re: Tomcat Marketing - At last! Johnny Kewl wrote: I see someone has stuck this up Someone hasn't been reading the documentation. That page has existed (in one form or another) for well over 4 years. who ever did it... well done, its about time, TC is under marketed... and its Re: customer specific settings of webapps Paul Hammes wrote: Hi all, I have a webapplication wich is distributed in one war for different customers. Unfortunately there are customer specific settings I normally would like to define in the enclosed web.xml. Because this would lead to, that I have to pack one war per customer, I Re: how to populate database with SHA hash for DIGEST DIGLLOYD INC wrote: Chris, I accept your point. It's too bad the Tomcat how to docs don't mention this in a brief note. I'm not on the tomcat developer group, otherwise I'd fix it. That doesn't stop you creating a patch. Create Re: Basic Authentication with Tomcat Tom Cat wrote: url-pattern/myAdmin/admin.html/url-pattern This should be: url-pattern/admin.html/url-pattern I think this should be enough to require authentication when someone goes to on the local machine. And yet, it allows everyone Re: Post form with x-www-form-urlencoded content type and Coyote Connector André Warnier wrote: Lenparam2=b You Re: NullPointerException 5.5.17 Request.setAttribute(Request.java:1376) Adam Jenkins wrote: Hi All, I'be been tearing my hair out for a couple of weeks over this one and would appreciate any assistance anyone could give. It's a bit of a unique scenario, so it'll take me a little while to explain: We have a legacy struts app, forwarding to a jsf app (details of Re: tomcat 5.5 Unicode issues! Shahar Cohen wrote: Hi, Well I didn’t quite understand you all the way but trying to use your example lats say I have a file named Hello%20There.html when I try to access this file I get 404. Probably because the tomcat recognize the character % as illegitimate. So is there a way to tell Re: Dual-Independent Tomcat servers, on Single Win32 host sharing IIS server. John Re: Instructions for setting up CGI Ted Byers wrote: I looked at the page for setting up CGI on Tomcat 6, but the paragraph that follows leads to some confusion. Remove the XML comments from around the CGI servlet and servlet-mapping configuration in $CATALINA_BASE/conf/web.xml. Apparently the jar the XML file refers to no Re: Another confused person trying to get jconsole to monitor tomcat. I've got all of these in $CATALINA_OPTS and they do show up in the java Re: Tomcat can't see a new function Daniel L. Gross wrote: org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:420) You really, really want to avoid using the InvokerServlet. Mark - To start a new topic, e-mail: users@tomcat.apache.org Re: Another confused person trying to get jconsole to monitor tomcat. Dominic Mitchell wrote: On 21 Aug 2008, at 09:25, Mark Thomas wrote: Re: Remastering tomcat installer .., Re: How to run Tomcat with multiple JVM's? Parks, Lincoln R. wrote: I have two applications that need two different JVM's to run. I am on a Windows 2k environment. One application needs JVM 1.5 to run and the other needs 1.4 to run. Is there a way to have Tomcat 5.5 run but utilize the different JVM's for each application? When I Re: tomcat instances on different ports running as different users can anyone shutdown? The simple solution (from Filip): Set the shutdown port to -1. Use kill to stop Tomcat. Mark - To start a new topic, e-mail: users@tomcat.apache.org To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: Re: After IIS6 Tomcat6 Integration it has Chinese coding problem! francin wrote: After I integration IIS and Tomcat successfully, I only have a problem how it can resolve the Chinese coding problem? The detail of the problem is : If my url contains Chinese the tomcat returns HTTP 400 ! How to solve it? Re: Tomcat does not unpack WAR file (Tomcat 5.5.20) Peter wrote: I may be going slightly off-topic for this thread, but I have 2 questions regarding the ROOT.xml ROOT.xml fragment file... should provide answers to your questions. Mark Re: Instructions for setting up CGI Ted Byers wrote: Mark, OK, Thanks. But the information provided isn't quite complete. I had done everything the documentation you point to said, and kept getting internal server errors until I edited (on the suggestion of a colleague) context.xml and changed Context to Context Re: Tomcat6 relative contexts trevor paterson (RI) wrote: Prior to tomcat6 you could happily deploy a 'bar.war' to a context like '/foo/bar' simply by including a context.xml file in the META-INF directory of the war with content Context path='/foo/bar'/. Actually, that won't quite have done what you think it did. Re: Tomcat6 relative contexts destroy all copies and inform the sender. -Original Message- From: Mark Thomas [mailto:[EMAIL PROTECTED] Sent: 25 August 2008 16:45 To: Tomcat Users List Subject: Re: Tomcat6 relative contexts trevor paterson (RI) wrote: Prior to tomcat6 you could happily deploy a 'bar.war Re: IIS6 and Tomcat6 Integration Problem with jk2 ! francin wrote: In some reason , I should use jk2 to integrate IIS and Tomcat, everything I have done follow the step: but the IIS return the following logs: Error: [jk_isapi_plugin.c (713)]: Re: public class SessionTestServlet extends WebContainerServlet implements Serializable { private static final long serialVersionUID = 1L; public ApplicationInstance newApplicationInstance() { return Ch Praveena wrote: Hi all, I am trying to cluster an application. I found the following exception stack trace. Hope there are very experts in this group, who involved in designing of Tomcat container and utilizing the tomcat too. Please respond me who ever have a very good idea Re: Authentication Issues Erik Rumppe wrote: For right now I am using BASIC authentication. There are 3 roles defined in the tomcat-users.xml file. To access different areas of my application requires different levels of roles. I want my users to be able to click on a link and if they don't meet the role requirement Re: Failed to override global naming resources in specific app! William wrote: Hi, description webapp definition cannot override global one, even though override attribute set to true. Why? Is that the right way to define resource for common use and redefine it within specific webapp? scenario version: 5.5.20 global definition in Re: FW: CVE-2008-2370 Query , Frank (Dimension Data) Subject: FW: CVE-2008-2370 Query -Original Message- From: Mark Thomas [mailto:[EMAIL PROTECTED] Sent: 26 August 2008 19:05 To: Frank Mott (Europe) Cc: Apache Tomcate private security list Subject: Re: CVE-2008-2370 Query Frank Mott (Europe) wrote: I am Re: antioJarLocking not working Aaron Axelsen wrote: Is there a trick to get antiJarLocking and antiResourceLocking to work with tomcat 6? I have the following in the config: Host name=nix-tester.mcs.uww.edu appBase=D:/path/to/webroots/docs ~unpackWARs=true autoDeploy=true ~Context path= docBase=. debug=5 Re: antioJarLocking not working Aaron Axelsen wrote: Is there any reason its going to look in temp-Foo5? That is how the antiresource locking works. It copies the entire war to a temp location with a unique name and runs it from there. If you reload it would probably use temp-Foo6 etc. Mark Re: antioJarLocking not working Aaron Axelsen wrote: I understand how it works - the problem is that the folder is not actually getting created. I double checked permissions - and the apache user does have full permissions to that tomcat 6 folder. Any thoughts? The name of the war is temp Foo5.war. I can see folders Re: antioJarLocking not working way to find the file. Mark Mark Thomas wrote: | Aaron Axelsen wrote: | I understand how it works - the problem is that the folder is not | actually getting created. I double checked permissions - and the apache | user does have full permissions to that tomcat 6 folder. Any thoughts Re: Securing Tomcat: HELP losintikfos wrote: Hi Experts, I am trying to secure my tomcat manager web console from been seen from the internet. For example if i open the browser and type the internet address of the server, it displays the console where ever i am in the world and therefore want to hide it from been Re: Tomcat 5.5 won't use APR Gregor Schneider wrote: Hm, rather quiete here about my problem... Is there anybody on this list who is using Tomcat together with APR on any Linux and could let me know about his/her configs? Is the right listener defined in web.xml? Mark Re: Tomcat 5.5 won't use APR Gregor Schneider wrote: Hi Mark, On Thu, Aug 28, 2008 at 1:15 PM, Mark Thomas [EMAIL PROTECTED] wrote: Is the right listener defined in web.xml? hm, what do you mean by right listener? and what web.xml? I figure you mean $catalina_home/conf/web.xml? As a how-two I used the tomcat-docs Re: antioJarLocking not working Johnny Kewl wrote: - Original Message - From: Aaron Axelsen [EMAIL PROTECTED] To: Tomcat Users List users@tomcat.apache.org Sent: Thursday, August 28, 2008 10:19 PM Subject: Re: antioJarLocking not working The jar's its probably having issues with are jruby-complete-1.1.3.jar Re: Securing Tomcat: HELP [EMAIL PROTECTED] wrote: Actually the context xml is present in CATALINA_HOME\webapps\manager\META-INF dir. You can edit it and add the valve and it should work: Context antiResourceLocking=false privileged=true Valve className=org.apache.catalina.valves.RemoteAddrValve Re: Monitor contanier sam wun wrote: Hi there, What can I use to monitor tomcat container? Please do not hijack threads. Mark Thanks - To start a new topic, e-mail: users@tomcat.apache.org To unsubscribe, e-mail: [EMAIL Re: Securing Tomcat: HELP losintikfos wrote: Sorry mark did miss up something here! what did you mean by Those characters needs to be escaped? Are you saying i should do something like this: allow=127.\0.\0.\1 ? Yes. But it should be allow=127\.0\.0\.1 Mark markt-2 wrote: [EMAIL PROTECTED] wrote: Re: version 5.5 vs 6.0 Alex Howansky wrote: Hello group, I'm wondering if you might be able to share a bit of your expertise with me. Is there any reason to choose 5.5 over 6.0 if you have no specific requirement to do so? I.e., if you were tasked with developing a completely new application from the ground up, Re: Default application or HTML redirect Mostafa Mossaad wrote: I have an application (MyApp) deployed using a MyApp.war file inside the /webapp folder. I've tried a lot of things, like modifying the server.xml Bad idea. and web.xml file, and playing with the Welcome-File tags, Nope, not these Re: Default application or HTML redirect : Mark Thomas [mailto:[EMAIL PROTECTED] Sent: Saturday, August 30, 2008 1:07 AM To: Tomcat Users List Subject: Re: Default application or HTML redirect Mostafa Mossaad wrote: I have an application (MyApp) deployed using a MyApp.war file inside the /webapp folder Re: Installing Tomcat (stock) with Tomcat (rpm) Ken Bowen wrote: Eduardo, First, do you mean (1) run multiple versions of tomcat simultaneously? Or just (2) that you will have multiple (different) versions of tomcat installed, and you can switch between them? I'm not sure you can do (1) very easily. As long as you use different ports Re: Tomcat Native library for Windows Brian Clark wrote: Re: Trying to build tomcat 6.0.18 Jack Woehr wrote: Martin Gainty wrote: Jack- did you take chucks advice and build with JDK 1.5 ? Yes .. now I've got a different problem :) Clean out the build area and start again. With a 1.5 JDK it should be as simple as ant download ant Mark Re: JDBCRealm.getRoles causes NullPointerException DIGLLOYD INC wrote: Aug 31, 2008 5:30:48 PM org.apache.catalina.connector.CoyoteAdapter service SEVERE: An exception or error occurred in the container during the request processing java.lang.NullPointerException at Re: Problems with Context/ Paul Pepper wrote: A discussion regarding the use of the Context/ element, within server.xml and $CATALINA_BASE/conf/[enginename]/[hostname]/, grew from a thread with subject Problem with JNDI environment entry resources: In that thread Re: question Steve Ochani wrote: On 3 Sep 2008 at 10:36, Jojo Nadir wrote: hi how are you, I have a probleme in the installation process of tomcat 5.5 under Windows 98 (I have an old computer), it always get me a message containing the following files with some number like this : jvm.dll and 1329 Re: virtual host and cgi-bin Sathish Vadhiyar wrote: Hi, I have set up a virtual host named app in my server.xml as: Host name=app.com appBase=webapps/app Context path= docBase=./ /Host appBase must not equal docBase. Rename webapps/app to webapps-app/ROOT and use the following Host name=app.com Re: Tomcat 5.5. META-INF/context.xml ignored when deploying as war. Eric Berry wrote: Hello, Re: Need help with Tomcat MBean support Steve Cohen wrote: Thank you very much - this is exactly what I was looking for. And a word to the Tomcat team - Documentation would be much improved by simply mentioning the two links provided by Mr. Hall. Patches are always welcome. Mark Re: Tomcat 5.5. META-INF/context.xml ignored when deploying as war. Eric Berry wrote: Mark, thanks for the reply. You appear to have misunderstood. Which part of the doc did you get this from and I'll see if it can be made clearer. From my understanding of the the order of precedence. [quote] *Context* elements may be explicitly defined: - in Re: Tomcat 5.5. META-INF/context.xml ignored when deploying as war. Eric Berry wrote: Ok cool. Thank you very much for clearing that up for me. The first time I deployed the war, there wouldn't have been a context in any of the 3 locations mentioned above. As you said, it would have copied the context.xml file from the war into the 3rd location as Re: Tomcat 6: 20 minutes on 10 minutes off duty cycle Bryan McGinty wrote: using mod_proxy_ajp. This worked well. I'd use mod_proxy_http given a free choice. But anyway... Has anyone seen this sort of behaviour when upgrading to Tomcat 6? If not, does anyone have any idea of how I may be able to determine the cause of this behaviour? Use a Re: question : encounter java.net.SocketTimeoutException: Read timed out occasionally James Wang wrote: Hi all, we are encountering java.net.SocketTimeoutException: Read timed out occasionally, wondering if it's something related to network problem, Would highly appreciate if someone can help, following are the program stack If the client is IE, the server httpd and you are Re: Deploying an app from remote url (tomcat manager) Noble Paul നോബിള് नोब्ळ् wrote: hi , I tried the to deploy a war from an http url I tried the following syntax jar:! I haven't got a system handy to test with but do you need the final '/'? That would make the URL: Re: Upgrading to 6.0.18 Yoryos wrote: Hello Does anyone knows if with a simple replacement of the jars of CATALINA_HOME/lib can I upgrade from 6.0.14 to 6.0.18? No. It won't pick up changes to the startup scripts, the security policy file, the documentation, server.xml, global web.xml, global config.xml etc. I Re: Tomcat 5.5. META-INF/context.xml ignored when deploying as war. Eric Berry wrote: Mark, Chuck, Thank you both very much for the detailed explanations. I can certainly see how this would definitely speed development along, and how - in most cases - the context.xml is unnecessary. I myself, have rarely used them unless as Mark mentioned, I needed Re: Tomcat 6 and corruption of text in French error pages André-John Mas wrote: Hi, I have Tomcat 6 installed on a French version of Windows XP. When error pages, such as the 404 error page, appear the French text is corrupted. For example, instead of the expected: La ressource demandée (/manager/html) n'est pas disponible. I get: La Re: Yet another context logging question Caldarale, Charles R wrote: From: Jonathan Mast [mailto:[EMAIL PROTECTED] Subject: Yet another context logging question Foo has a subdirectory bar which I would now like to be it's own Context and AccessLogValue. Such a configuration is not supported - webapps may not be nested. Whatever Re: Virtual Hosting of Mutliple Domains Alan Hancock wrote: I added a host entry in the format of. Its a very simple site with only an index.html so that I can get the config straight before loading a bunch of content. There is no domain specific context given. I created a folder in the format mydomain.com is the Re: question : encounter java.net.SocketTimeoutException: Read timed out occasionally . James Wang. On Fri, Sep 5, 2008 at 10:26 PM, Mark Thomas [EMAIL PROTECTED] wrote: James Wang wrote: Hi all, we are encountering java.net.SocketTimeoutException: Read timed out occasionally, wondering if it's something related to network problem, Would highly appreciate if someone can
https://www.mail-archive.com/search?l=users@tomcat.apache.org&q=from:%22Mark+Thomas%22
CC-MAIN-2021-39
en
refinedweb
I faced a problem with calling conv1d.forward in DLL on CUDA. In the following C++ code snippet line 4 ‘conv1d.forward’ crashes with stack overflow. The full CPP file (27 lines) is at the bottom of this message. auto Net = torch::nn::Conv1d(torch::nn::Conv1dOptions(21, 2, 3)); Net->to(device); torch::Tensor X = torch::rand({ 5,21,25 }).to(device); torch::Tensor Y = Net->forward(X); Having experimented on two PCs with different GPU types I found the problem is consistently reproduced if all of the following criteria are met: - DLL. The same code in console EXE application runs normally. - GPU/CUDA. There is no problem running the same code on CPU - Convolutional layer. No problem with other layer types, e.g. linear. I tried debugging DLL in Visual Studio (debugger window screenshot attached). Call stack suggests that stack overflow happens inside cudnn_cnn_infer64_8.dll module. This is part of Nvidia CUDNN library. I am not sure if this error is part of Pytorch or Nvidia CUDNN. If anyone has any suggestion on how to resolve this please respond. #include <torch/torch.h> #define XLExport extern "C" __declspec(dllexport) XLExport int _stdcall MLP_DLL(); int _stdcall MLP_DLL() { std::ofstream log("output.txt"); torch::Device device(torch::kCPU); if (torch::cuda::is_available()) { log << "Cuda found" << std::endl; device = torch::Device(torch::kCUDA); } auto Net = torch::nn::Conv1d(torch::nn::Conv1dOptions(21, 2, 3)); Net->to(device); torch::Tensor X = torch::rand({ 5,21,25 }).to(device); log << " starting forward" << std::endl; torch::Tensor Y = Net->forward(X); log << "Y = " << std::endl; log << Y << std::endl; return 0; }
https://discuss.pytorch.org/t/stack-overflow-conv1d-forward-in-dll-on-cuda/130149
CC-MAIN-2021-39
en
refinedweb
that support programmed I/O are assigned one or more regions of bus address space that map to addressable regions of the device. These mappings are described as pairs of values in the reg property associated with the device. Each value pair describes a segment of a bus address. Drivers identify a particular bus address mapping by specifying the register number, or regspec, which is an index into the devices' reg property. The reg property identifies the busaddr and size for the device. Drivers pass the register number when making calls to DDI functions such as ddi_regs_map_setup(9F). Drivers can determine how many mappable regions have been assigned to the device by calling ddi_dev_nregs(9F). The data format of the host can have different endian characteristics than the data format of the device. In such a case, data transferred between the host and device would need to be byte-swapped to conform to the data format requirements of the destination location. Devices with the same endian characteristics of the host require no byte-swapping of the data. Drivers specify the endian characteristics of the device by setting the appropriate flag in the ddi_device_acc_attr(9S) structure that is passed to ddi_regs_map_setup(9F). The DDI framework then performs any required byte-swapping when the driver calls a ddi_getX routine like ddi_get8(9F) or a ddi_putX routine like ddi_put16(9F) to read or write to device memory. Platforms can reorder loads and stores of data to optimize performance of the platform. Because reordering might not be allowed by certain devices, the driver is required to specify the device's ordering requirements when setting up mappings to the device. This structure describes the endian and data order requirements of the device. The driver is required to initialize and pass this structure as an argument to ddi_regs_map_setup(9F). typedef struct ddi_device_acc_attr { ushort_t devacc_attr_version; uchar_t devacc_attr_endian_flags; uchar_t devacc_attr_dataorder; } ddi_device_acc_attr_t; Specifies DDI_DEVICE_ATTR_V0 Describes the endian characteristics of the device. Specified as a bit value whose possible values are: DDI_NEVERSWAP_ACC – Never swap data DDI_STRUCTURE_BE_ACC – The device data format is big-endian DDI_STRUCTURE_LE_ACC – The device data format is little-endian Describes the order in which the CPU must reference data as required by the device. Specified as an enumerated value, where data access restrictions are ordered from most strict to least strict. DDI_STRICTORDER_ACC – The host must issue the references in order, as specified by the programmer. This flag is the default behavior. DDI_UNORDERED_OK_ACC – The host is allowed to reorder loads and stores to device memory. DDI_MERGING_OK_ACC – The host is allowed to merge individual stores to consecutive locations. This setting also implies reordering. DDI_LOADCACHING_OK_ACC – The host is allowed to read data from the device until a store occurs. DDI_STORECACHING_OK_ACC – The host is allowed to cache data written to the device. The host can then defer writing the data to the device until a future time. Note - The system can access data more strictly than the driver specifies in devacc_attr_dataorder. The restriction to the host diminishes while moving from strict data ordering to cache storing in terms of data accesses by the driver. Drivers typically map all regions of a device during attach(9E). The driver maps a region of device memory by calling ddi_regs_map_setup(9F), specifying the register number of the region to map, the device access attributes for the region, an offset, and size. The DDI framework sets up the mappings for the device region and returns an opaque handle to the driver. This data access handle is passed as an argument to the ddi_get8(9F) or ddi_put8(9F) family of routines when reading data from or writing data to that region of the device. The driver verifies that the shape of the device mappings match what the driver is expecting by checking the number of mappings exported by the device. The driver calls ddi_dev_nregs(9F) and then verifies the size of each mapping by calling ddi_dev_regsize(9F). The following simple example demonstrates the DDI data access interfaces. This driver is for a fictional little endian device that accepts one character at a time and generates an interrupt when ready for another character. This device implements two register sets: the first is an 8-bit CSR register, and the second is an 8-bit data register. Example 7-1 Mapping Setup #define CSR_REG 0 #define DATA_REG 1 /* *, CSR_REG, (caddr_t *)&(pio_p->csr), 0, sizeof (Pio_csr), &dev_acc_attr, &pio_p->csr_handle) != DDI_SUCCESS) { mutex_destroy(&pio_p->mutex); ddi_soft_state_free(pio_softstate, instance); return (DDI_FAILURE); } /* * Map in the data register (register 1) */ if (ddi_regs_map_setup(dip, DATA_REG, (caddr_t *)&(pio_p->data), 0, sizeof (uchar_t), &dev_acc_attr, &pio_p->data_handle) \ != DDI_SUCCESS) { mutex_destroy(&pio_p->mutex); ddi_regs_map_free(&pio_p->csr_handle); ddi_soft_state_free(pio_softstate, instance); return (DDI_FAILURE); }
https://docs.oracle.com/cd/E26502_01/html/E29051/devaccess-4.html
CC-MAIN-2021-39
en
refinedweb
Mechanics for Scientists and Engineers ePrep Course for University Preparation Mechanics for Scientists and Engineers ePrep course is one of the ten ePrep courses specially developed to help NSF, NSmen and others to better prepare themselves for studies in universities in Singapore, or overseas. Poor foundation in mechanics, especially for those without going through A-level physics, has been a big source of difficulties faced by those doing conventional engineering such as mechanical or civil engineering, and physical sciences. This university preparatory course on mechanics is developed in collaboration with the publishers of the popular physics textbook by Serway and Jewett. The course comes with the textbook at no additional cost, together with excellent learning materials provided by the publishers and a retired NTU professor as the tutor. In order to further assist the students in preparing for their university studies, additional learning materials on many other subjects are also provided. These include materials on physics, mathematics (algebra, calculus, and statistics, etc.), business finance, engineering economy, economics, corporate finance, biotechnology, biology (or life science), business ethics, Python Programming, discrete mathematics, etc. Samples of these materials can be found below. While this university preparatory course on physics was designed to help NSFs, it is now opened to everybody and it is highly recommended, especially for those who do not have a strong foundation in physics but are doing engineering, science or technological courses. Audio: Fuller Intro to Mechanics for Scientists and Engineers ePrep Course Mechanics for Scientists and Engineers ePrep Course – The Learning Contents I. Compulsory Chapters Calculu II. Optional Chapters What You Get in Mechanics for Scientists and Engineers ePrep Course I. Free Textbook “Physics for Scientists and Engineers” is a very popular physics textbook, authored by RA Serway and JW Jewett, Jr, 10th Ed. II. Free Consultation A retired NTU professor is acting as the tutor for this NTU ePrep course. You can consult him via email or WhatsApp. III. Materials Online 1. Notes, video lessons and PowerPoint files. 2. Answers/solutions to all questions/problems in the textbook. 3. Online exercises. 4. Problems and solutions in files. 5. Bonus learning materials in various branches of mathematics, including calculus, algebra, geometry, trigonometry, probability and Statistics, as well as on other subjects such as physics, biotechnology, life science, business finance, corporate finance, engineering economy, economics, Python programming, discrete mathematics, business and engineering ethics, and psychology. IV. Digital Certificate A digital certificate will be issued if you have successfully completed this NTU ePrep course and passing all the tests at the end of each of the ten compulsory chapters. Mechanics for SCientists and Engineers ePrep Course Sample Materials 1. Video Lesson (Position and Velocity Vectors) 2. Problem and Solution (Motion of Satellite) Question: An artificial satellite circles the Earth in a circular motion at a location where the acceleration is 9.00 m/s2. Determine the orbital period of the satellite. Solution: Mechanics for Scientists and Engineers Samples of Bonus Materials 1. Video Lesson on Business Finance (Hedge Funds) 2. Video Lesson on Corporate Finance (Managing Working Capital) 3. Cross-Word Puzzle on Biotechnology (Genetically Modified Organisms) 4. Worked Example on Engineering Economy (Cost Concepts and Design Economics) Question: A lash adjuster keeps the pressure constant on engine valves, thereby increasing fuel efficiency in automobile engines. The relationship between price (p) and monthly demand (D) for lash adjusters made by the Wicks Company is given by this equation: D = (2,000 − p)/0.10. What is the demand (Dˆ ) when total revenue is maximized? What important data are needed if maximum profit is desired? Answer: 5. Python Programming (Plotting a Sine Curve) Code:import matplotlib import matplotlib.pyplot as plt import numpy as np # Data for plotting pi = 22/7 theta = np.arange(0.0, 2*pi, 0.05) #uniformly from 0 to 2 pi in step of 0.05 sine = 1 + np.sin(theta) plt.plot(theta, sine) plt.show() Output: Plot for y = 1 + sin (theta) 6. Economics (Analyzing Changes in Equilibriums) Three Steps to Analyzing Changes in equilibrium: Step 1. Decide whether the event shifts the supply or demand curve (or perhaps both). Step 2. Decide in which direction the curve shifts. Step 3. Use the supply-and-demand diagram to see how the shift changes the equilibrium price and quantity. Three steps explained using the market for milk. 1 Example: A Change in Demand — the effect of hot weather on the market for Change in tastes and increase in demand at any given price. 2 Example: A Change in Supply – drought drives up the price of animal feed for dairy cattle. Higher costs reduce supply at any given price. 3 Example: A Change in Both Supply and Demand – 1. Suppose that the hot weather and the rise in animal feed occur during the same time period. 4 Example: A Change in Both Supply and Demand – 2. Forecasters predict a heat wave for some weeks. Hot weather is likely to increase demand for milk and so the demand curve will shift to the right. However, sellers’ expectations that sales of milk will increase as a result of the forecasts mean that they take steps to expand the production of milk. 7. Discrete Mathematics (Converse and Contraposition of Statements) Question: Solution: Remarks: These samples of bonus materials on other subjects illustrate how comprehensive and broad-base the course is for preparing students for their university studies. While not all the materials are of interest to the students who take up this ePrep course on Mechanics, they can choose what are beneficial to them and ignore the rest. Who should take this ePrep Course It is a very important fundamental course for students doing physical science and traditional engineering degrees. Many of these students do not have a strong foundation and face difficulties in their studies. Even for those not going to any university due to various reasons, this is an opportunity to prove that they are capable of completing a university-level course. Everyone is welcome and there is no pre-requisite. We will provide the necessary guidance when needed.
https://eprepcourses-sg.online/mechanics-eprep/
CC-MAIN-2021-39
en
refinedweb
Key Takeaways - Most production applications need to persist & retrieve data. Prisma is a pretty genius way to achieve that. - With SvelteKit, you get client & server-side data fetching - the best of both worlds. - This all even works if JavaScript is disabled in the browser. - Template GitHub repo: What are you going to learn? We are going to start with a default SvelteKit application. Once initialized, we will learn how to install and configure Prisma before we will use the PrismaClient to perform create, read, update & delete (CRUD) actions against a local SQLite database. Things you need to know In order to get the most out of this post, I expect you are aware of the following technologies: The foundation Let's start with the basics: A SvelteKit demo app. I recommend you first create a GitHub, GitLab or Bitbucket project and start a development environment with Gitpod. Alternatively, you can follow along on your local computer. npm init svelte@next svelte-with-prisma When prompted, select the following options: - "Which Svelte app template?" SvelteKit demo app - "Use TypeScript?" Yes - "Add ESLint for code linting?" No - "Add Prettier for code formatting?" Yes When complete, please follow the "Next steps" listed in the terminal to install dependencies and start the SvelteKit demo app. If you've followed along so far, you can copy & paste the following commands: cd svelte-with-prisma npm install npm run dev -- --open That's how quickly you get started with SvelteKit. In your browser, you notice the "TODOS" navigation item. If you play with this list, items are persisted on svelte.dev and deleted after a while. Next, we are going to add Prisma to persist todo items in a local SQLite database. Add Prisma Prisma.io states "Prisma helps app developers build faster and make fewer errors with an open source ORM for PostgreSQL, MySQL and SQLite." From my personal experience, this statement is certainly true. Let's go and experience it for yourself. Install & initialize Prisma First things first: npm i -D prisma because, well... without dependencies we won't get very far 😉. Next, we are going to initialize Prisma. For that, we use npx to execute commands. npx prisma init ⚠️ This currently overwrites an existing .gitignorefile. Keep an eye on 8496. This creates a prisma directory at the root of the project. In it, you find the schema.prisma file. At this point, I recommend you install the prisma.prisma VS Code extension. It adds syntax highlighting, formatting, auto-completion, jump-to-definition and linting for .prisma files. Define the Todo model Open the prisma/schema.prisma file and add the following model definition to the end of the file: model Todo { uid String @id @default(cuid()) created_at DateTime text String done Boolean } Psst... How do we know what fields to define? Well, we take a peek at the Todo type definition in src/routes/todos/index.svelte 😉. Configure a SQLite database Open the .env file (that file was created by the npx prisma init command earlier). In it, set the DATABASE_URL to "file:./dev.db" We also have to open the prisma/schema.prisma file to update the datasource.db.provider to sqlite. Check the reference docs for more details on the above two values and what other databases are supported. Create the database and tables We're making great progress! Let's now use the Prisma CLI to create our SQLite database and create a schema based on the Todo model we defined earlier. It's easy: npx prisma db push Give that five seconds ⏳. I recommend you read through the console output, I find it highly interesting. For one, it gives us a good deal of detail about what's going on. However, it also contains the following output which is one of the reasons I'm mind-blown by Prisma: ✔ Generated Prisma Client (2.28.0) to ./node_modules/@prisma/client So much goodness! Basically, they use the Todo model to auto-generate a bunch of TypeScript definitions and Javascript code which we are going to import in just a second. In other words, the "Prisma helps app developers build faster and make fewer errors" sentence on the Prisma website is not just some marketing speech, it is truly genius! Ok, I'm done being a fanboy about it, let's move on and thanks for your patience there with me 😅. One last thing, please add prisma/dev.db to your .gitignore file since we don't want to commit the dev database to version control. Use the PrismaClient to interact with the database The SvelteKit demo app nicely encapsulates all API features in the src/routes/todos/_api.ts file. To be more precise, the actual CRUD logic happens at. We are going to modify the _api.ts file slightly to deal with CRUD right there and use the PrismaClient instead of delegating to a backend API. Move the Todo type so we can reuse it First and foremost, let's move the Todo Typescript type. By default, it's defined and used in the src/routes/todos/index.svelte file. However, with the changes we're going to make to the API, we are also going to need that type in the src/routes/todos/_api.ts file. - Cut the Todotype from src/routes/todos/index.svelte - Paste it below the importstatements in src/routes/todos/_api.ts, and prefix it with export - Use the following import in the src/routes/todos/index.sveltefile: import type { Todo } from "./_api"; Update the API to use Prisma Open the src/routes/todos/_api.ts file and add the following import: import { PrismaClient } from '@prisma/client'; Remember? That's the generated code I was so excited about earlier 😀. Next, we need a new instance of the PrismaClient (add this below the import statements): const prisma = new PrismaClient(); Moving right along, it's time to update the api method signature to tell Typescript that the data parameter is of type Todo. export async function api(request: Request<Locals>, resource: string, data?: Todo) { The following code: const res = await fetch(`${base}/${resource}`, { method: request.method, headers: { 'content-type': 'application/json' }, body: data && JSON.stringify(data) }); needs to be replaced with this: let body = {}; let status = 500; switch (request.method.toUpperCase()) { case "DELETE": await prisma.todo.delete({ where: { uid: resource.split("/").pop() } }); status = 200; break; case "GET": body = await prisma.todo.findMany(); status = 200; break; case "PATCH": body = await prisma.todo.update({ data: { done: data.done, text: data.text }, where: { uid: resource.split("/").pop() } }); status = 200; break; case "POST": body = await prisma.todo.create({ data: { created_at: new Date(), done: false, text: data.text, } }); status = 201; break; } We're getting there 💪. In the if statement right below the code we've just added, remove the res.ok && since we no longer have a res variable. Lastly, change the return statement to the following: return { status, body }; Let's test Start your SvelteKit demo app with npm run dev and navigate to in your browser. If you use Gitpod, hold CTRL / CMD pressed and click on the URL in the terminal, it'll open a new browser window with the SvelteKit demo app. Click on the "TODOS" navigation link and add a few todos, rename some, mark others as done. In a new terminal, open the Prisma Studio with npx prisma studio. The studio opens in a new browser tab. Click on the Todo model and validate that the data matches what you see in the SvelteKit demo app. Congratulations 🎉! Bonus - definitely read this Disable JavaScript in your browser and test the todo list again. This is how the web is supposed to work - without JavaScript! We used to develop websites like that, then we spent a decade thinking it's a great idea to move everything into JavaScript and thanks to Svelte & SvelteKit, we now once again develop web applications that work the way the web was intended to work. JavaScript's purpose is to enhance the web experience, not break everything if JavaScript is disabled. Conclusion With a few modifications to a default SvelteKit demo app, we managed to configure Prisma to persist todo items. There is of course a lot more you can do with Prisma, and with SvelteKit for that matter. The source code at should get you a long way towards your own web app. If you found this interesting, you may also like (wow... is this an e-commerce website 😂?!) my current project called Webstone. Webstone is a full-stack web application boilerplate with a CLI to automate tedious tasks like adding new pages, updating the database (of course it uses Prisma 😉). It's in early development, but do hit that star button on GitHub which helps me get motivated to spend more time on the project 🙏. 👋 Discussion (3) Great read Mike! Thanks for sharing Awesome read! Followed! Excited to hear more about Prisma with Svelte + Realtime API . Thanks for sharing this. Hearing so much good stuff about Prisma lately that I have to try this out
https://practicaldev-herokuapp-com.global.ssl.fastly.net/mikenikles/sveltekit-prisma-a-match-made-in-digital-heaven-2g0f
CC-MAIN-2021-39
en
refinedweb
This is our first free surface example problem. We discuss the non-dimensionalisation of the free surface boundary conditions and their implementation in oomph-lib, and demonstrate the solution of a single layer relaxation problem. Free surfaces occur at the interface between two fluids. Such interfaces require two boundary conditions to be applied: The kinematic condition states that the fluid particles at the surface remain on the surface for all times. If the surface is parametrised by intrinsic coordinates and , then the Eulerian position vector which describes the surface at a given time can be written as . The kinematic condition is then given by where is the (dimensional) velocity of the fluid and is the outer unit normal to the free surface. Using the same problem-specific reference quantities for the velocity, , length, , and time, , that were used to non-dimensionalise the Navier–Stokes equations, we scale the dimensional quantities such that The non-dimensional form of the kinematic boundary condition is then given by where the Strouhal number is The dynamic boundary condition requires the stress to be continuous across a flat interface between two fluids. Referring to the sketch above, we define the lower fluid to be fluid 1 and the upper fluid to be fluid 2. The traction exerted by fluid 1 onto fluid 2, , is equal and opposite to that exerted by fluid 2 onto fluid 1, , and therefore . The traction in fluid ( ) is given by where is the stress tensor in fluid and is the outer unit normal to fluid . Since must equal , we have where we have arbitrarily chosen to use as the unit normal. On curved surfaces, surface tension creates a pressure jump across the interface, where is the surface tension and is equal to twice the mean curvature of the surface. Therefore the dynamic boundary condition is given by where if the centre of curvature lies inside fluid In certain cases, such as the example problem below, we wish to model the fluid above the interface as totally inviscid. In this case, the stress tensor in fluid 2 reduces to , where is the (non-dimensional) constant pressure above the free surface. The dynamic boundary condition therefore becomes where we have dropped the explicit references to fluid 1 since it is understood that the stress tensor and unit normals refer to those of the (one and only) viscous fluid in the problem. We shall now discuss how the free surface boundary conditions are implemented in oomph-lib. In addition to solving for the fluid velocity and pressure (as in all Navier–Stokes examples), we have additional degrees of freedom in our problem due to the fact that the position of the free surface is unknown. The Navier–Stokes elements in oomph-lib are based on the Arbitrary Lagrangian Eulerian (ALE) form of the Navier-Stokes equations, and so can be used to solve problems in moving domains. This allows us to discretise our domain using a boundary fitted mesh, which will need to deform in response to the motion of the free surface. This is achieved by treating the interior of the mesh as a fictitious elastic solid, and solving a solid mechanics problem for the (unknown) nodal positions. This technique, which will subsequently be referred to as a `pseudo-solid node-update strategy', employs wrapper elements to existing fluid and solid equation classes. The specific element used in this example is a PseudoSolidNodeUpdateElement<QCrouzeixRaviartElement<2>, QPVDElement<2,3> > element, which takes two template arguments. The first is the standard element type used to solve the fluid problem, and the second is the element type which solves the equations that are used to control the mesh deformation. The deformation of the free surface boundary is imposed by introducing a field of Lagrange multipliers at the free surface, following the method outlined in Cairncross et al., `A finite element method for free surface flows of incompressible fluids in three dimensions. Part I. Boundary fitted mesh motion' (2000). These new unknowns are stored as nodal values, and so the vector of values at each node is resized accordingly. Since this introduces further degrees of freedom into the problem, we require an additional equation: the kinematic boundary condition (1). We discretise this equation by attaching FaceElements to the boundaries of the "bulk" elements that are adjacent to the free surface. The specific FaceElement used in this example is an ElasticLineFluidInterfaceElement<ELEMENT>, which takes the bulk element type as a template argument. This allows the user of the driver code to easily change the bulk element type, since the appropriate FaceElement type is automatically used. These FaceElements are applied in the same way as all other surface elements (e.g. NavierStokesTractionElements, UnsteadyHeatFluxElements, etc.), and a general introduction can be found in another tutorial. Within a finite element framework, the dynamic boundary condition is incorporated as contributions to each of the momentum equations at the free surface. We refer to Ruschak, `A method for incorporating free boundaries with surface tension in finite element fluid-flow simulators' (1980), for details on the formulation, which can also be found in our free surface theory document. Since both Taylor–Hood and Crouzeix–Raviart elements are implemented such that the normal stresses between elements are balanced, applying the dynamic boundary condition in cases in which we are solving the Navier–Stokes equations on both sides of the interface is as straightforward as adding the appropriate surface tension contributions to the relevant momentum equations at the interface. In cases such as the example below, where we have an inviscid fluid above the free surface, we need to add the appropriate external pressure contributions (if any) as well. Both of these contributions are automatically added to the appropriate momentum equations using the same FaceElements which are used to discretise the kinematic boundary condition (see above). The Capillary number defaults to 1.0 and other values may be set using the function: The Strouhal number defaults to 1.0 and other values may be set using the function: The external pressure defaults to zero and other values may be set using the function: where p_ext_data_pt is (a pointer to) the Data in which the value of the external pressure is stored. We note that the external pressure is represented by Data because it may be an unknown in certain problems, although it is simply a constant parameter in the example below. It can be accessed using the function: The way in which the dynamic condition is incorporated within our finite element structure is discussed in more detail in the comments at the end of this tutorial. We will illustrate the solution of the unsteady two-dimensional Navier–Stokes equations using the example of a distorted free surface which is allowed to relax. The domain is periodic in the direction. The figure below shows a contour plot of the pressure distribution with superimposed streamlines, taken from an animation of the flow field, for the parameters and . At time the free surface is fixed in its deformed shape, but as the simulation begins the restoring forces of surface tension and gravitational acceleration act to revert it to its undeformed flat state. The surface oscillates up and down, but the motion is damped as the energy in the system is dissipated through viscous forces. Eventually the interface settles down to its equilibrium position. This viscous damping effect can be seen in the following time-trace of the height of the fluid layer at the edge of the domain. The free surface boundary conditions for the Cartesian Navier–Stokes equations have been validated against an analytical test case, and we present the results in the figure below. For sufficiently small amplitudes, , we can linearise the governing equations by proposing that we can write the fluid velocities and pressure, , and , as well as the `height' of the interface, , in the form , where the barred quantities correspond to the `base' state, chosen here to be the trivial solution . Once the linearised forms of the governing equations and boundary conditions have been determined we propose a separable solution of the form and Substituting the above ansatz into the governing equations results in a system of coupled ordinary differential equations for , and which we solve to find their general solutions up to a set of unknown constants , , and . By substituting these general forms into the set of (linearised and separated) boundary conditions we obtain a linear system of five equations in the five unknowns , , , and , from which we can assemble a homogeneous linear system of the form where is a matrix whose entries are the coefficients of the unknowns in our five conditions. This system only has a non-trivial solution if , and solving this equation gives us as a function of . This is a dispersion relation and describes how wave propagation varies as a function of its wavenumber. More specifically, the real part of is the growth rate of the wave and the imaginary part is its frequency. This analytical result can now be compared to numerical results computed for given values of the wavenumber . We choose an initial deflection amplitude of and determine the growth rate and frequency of the oscillation from a time-trace of the left-hand edge of the interface. As usual, we use a namespace to define the dimensionless parameters , , and , and we create a vector which will define the direction in which gravity acts. We will need to pass the Strouhal number to the interface elements, but the product of the Strouhal number and the Reynolds number to the bulk elements. To avoid potentially inconsistent parameters, we compute rather than defining it explicitly. Because the mesh is to be updated using a pseudo-solid node-update strategy, we also require the Poisson ratio for the generalised Hookean constitutive law. We start by computing the product of the Reynolds and Strouhal numbers before specifying the (non-dimensional) length of time for which we want the simulation to run and directions. To remain consistent with the example code we shall from now on refer to as and as . At this point we define the direction in which gravity acts: vertically downwards. Finally, we build the problem using the `pseudo-solid' version of QCrouzeixRaviartElements and the BDF<2> timestepper, before calling unsteady_run(...). This function solves the system at each timestep using the Problem::unsteady_newton_solve(...) function before documenting the result. Since we are solving the unsteady Navier–Stokes equations, the Problem class is very similar to that used in the Rayleigh channel example. We specify the type of the element and the type of the timestepper (assumed to be a member of the BDF family) as template parameters, before passing(...). The nodal positions are unknowns in the problem and hence are updated automatically, so there is no need to update the mesh before performing a Newton solve. However, since the main use of the methodology demonstrated here is in free-boundary problems where the solution of the solid problem merely serves to update the nodal positions in response to the motion of the free surface, we reset the nodes' Lagrangian coordinates to their Eulerian positions before every solve, by calling SolidMesh::set_lagrangian_nodal_coordinates(). This makes the deformed configuration stress-free and tends to stabilise the computation, allowing larger domain deformations to be computed. The problem class stores pointers to the specific bulk mesh and the surface mesh, which will contain the interface elements, as well as a pointer to a constitutive law for the pseudo-solid mesh. The width of the domain is also stored since it is used by the function deform_free_surface(...) when setting up the initial mesh deformation. Finally we store an output stream in which we record the height of the interface at the domain edge. The constructor starts by copying the width of the domain into the private member data of the problem class, before building the timestepper. Next we build the bulk mesh. The mesh we are using is the ElasticRectangularQuadMesh<ELEMENT>, which takes the bulk element as a template argument. The boolean argument in the mesh constructor, which is set to `true' here, indicates whether or not the domain is to be periodic in . The surface mesh is also built, although it is empty at this point. Having created the bulk elements, we now create the interface elements. We first build an empty mesh in which to store them, before looping over the bulk elements adjacent to the free surface and `attaching' interface elements to their upper faces. These newly-created elements are then stored in the surface mesh. Now that the interface elements have been created, we combine the bulk and surface meshes into a single mesh. On the solid bottom boundary ( ) we pin both velocity components so that there is no penetration of the wall by the fluid or flow along it. On the left and right symmetry boundaries ( and ) we pin the component of the velocity but leave the component unconstrained. We do not apply any velocity boundary conditions to the free surface (the top boundary). We pin the vertical displacement of the nodes on the bottom boundary (since these must remain stationary) and pin the horizontal displacement of all nodes in the mesh. Next we create a generalised Hookean constitutive equation for the pseudo-solid mesh. This constitutive equation is discussed in another tutorial. We loop over the bulk elements and pass them pointers to the Reynolds and Womersley numbers, and , the product of the Reynolds number and the inverse of the Froude number, , the direction of gravity, , and the constitutive law. In addition we pass a pointer to the global time object, created when we called Problem::add_time_stepper_pt(...) above. Next we create a pointer to a Data value for the external pressure , before pinning it and assigning an arbitrary value. We then loop over the interface elements and pass them a pointer to this external pressure value as well as pointers to the Strouhal and Capillary numbers. Finally, we apply the problem's boundary conditions (discussed later on) before setting up the equation numbering scheme using the function Problem::assign_eqn_numbers(). This function sets the initial conditions for the problem. We loop over all nodes in the mesh and set both velocity components to zero. No initial conditions are required for the pressure. We then call the function Problem::assign_initial_values_impulsive() which copies the current values at each of the nodes, as well as the current nodal positions, into the required number of history values for the timestepper in question. This corresponds to an impulsive start, as for all time none of the fluid is moving and the shape of the interface is constant. This function sets the boundary conditions for the problem. Since the Dirichlet conditions are homogeneous this function is not strictly necessary as all values are initialised to zero by default. At the beginning of the simulation the free surface is deformed by a prescribed function (9). To do this we define a function, deform_free_surface(...), which cycles through the bulk mesh's Nodes and modifies their positions accordingly, such that the nodes on the free surface follow the prescribed interface shape (9) and the bulk nodes retain their fractional position between the lower and the (now deformed) upper boundary. As expected, this member function documents the computed solution. We first output the value of the current time to the screen, before recording the continuous time and the height of the free surface at the domain boundary in the trace file. We note that as the domain is periodic the height of the free surface must be the same at both the left and right boundaries. We then output the computed solution. Finally, we output the shape of the interface. The function unsteady_run(...) is used to perform the timestepping procedure. We start by deforming the free surface in the manner specified by equation (9). determine the number of timesteps to be performed and document the initial conditions, and then perform the actual timestepping loop. For each timestep the function unsteady_newton_solve(dt) is called and the solution documented. As discussed in an earlier tutorial, the finite element solution of the Navier–Stokes equations is based on their weak form, which is obtained by weighting the stress-divergence form of the momentum equations with the global test functions , and integrating by parts to obtain the discrete residuals Weighting the dynamic condition (7) by the same global test functions and integrating over the domain boundary gives In a two-dimensional problem, such as the one considered in this tutorial, the domain boundary reduces to a one-dimensional curve, . A further integration by parts of (11) therefore gives where , is the -th component of a unit vector tangent to and pointing in the direction of increasing , and and are the two endpoints of . In the problem considered in this tutorial, the domain boundary can be written as , where represents the portion of the domain boundary corresponding to a rigid wall and represents the portion corresponding to the free surface. The velocity along is prescribed by Dirichlet boundary conditions, and we recall that the global test functions vanish in this case. On non-Dirichlet boundaries we must either specify the external pressure , or deliberately neglect this term to obtain the `natural' condition . In this two-dimensional case, the contact `line' actually reduces to two contact points, and , which are located at either side of the portion of the domain boundary corresponding to the free surface . The two point contributions are added by specifying the the tangent to the surface at each of the contact points, which is equivalent to prescribing the contact angle that the free surface makes with the neighbouring domain boundary. We note that in the problem considered here we do not explicitly apply any boundary conditions at either end of the free surface. Neglecting these contributions corresponds to the `natural' condition of prescribing a contact angle, which happens to be the appropriate condition in this case. Contact angles of arbitrary size can be enforced using FluidInterfaceBoundingElements, which are discussed in a later tutorial. Specifying the contact angle is not the only condition that can be applied at the edges of an interface. The alternative boundary condition is to pin the contact line so that its position is fixed for all time. Since this is a Dirichlet condition it causes the integral over the contact line to vanish. A pdf version of this document is available.
http://oomph-lib.maths.man.ac.uk/doc/navier_stokes/single_layer_free_surface/html/index.html
CC-MAIN-2021-39
en
refinedweb
Created on 2019-07-19 15:28 by Ákos Tompos, last changed 2019-07-19 18:37 by serhiy.storchaka. This issue is now closed. The following code does work on python 2.7 but fails on python 3.7. The code seems correct. class A: class B: def __init__(self, param): self.param = param l = [B(i) for i in range(10)] The result on: 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] Traceback (most recent call last): File "test.py", line 6, in <module> class A: File "test.py", line 11, in A l = [B(i) for i in range(10)] File "test.py", line 11, in <listcomp> l = [B(i) for i in range(10)] NameError: name 'B' is not defined B can be accessed if not inside a generator expression I think it's about a class being defined inside another class and not about subclass. This seems to be similar to that discusses about class attribute scope for comprehension. This is a duplicate of issue3692.
https://bugs.python.org/issue37632
CC-MAIN-2021-39
en
refinedweb
SYNOPSIS #include <unistd.h> int rcmd(char **ahost, int inport, const char *locuser, const char *remuser, const char *cmd, int *fd2p); int rresvport(int *port); int ruserok(const char *rhost, int superuser, const char *ruser, const char *luser); int iruserok(in_addr_t raddr, int superuser, const char *ruser, const char *luser); DESCRIPTION The The If the connection succeeds, a socket in the Internet domain of type SOCK_STREAM is returned to the caller, and given to the remote command as stdin and stdout. If fd2p is non-null, then an auxiliary channel to a control process will be set up, and a descriptor for it will be placed in that location to which it refers. The control process will return diagnostic output (stderr) from the command on this channel, and also accepts bytes on this channel as being UNIX signal numbers, to be forwarded to the process group of the command. The diagnostic information returned does not include remote authorization failure, as the secondary connection is set up after authorization has been verified. If fd2p is null, then the stderr of the remote command is made the same as the stdout and no provision is made for sending arbitrary signals to the remote process, although you may be able to get its attention by using out-of-band data. The The If this file does not exist, is not a regular file, is owned by anyone other than the user or the super-user, or is writable by anyone other than the owner, the check automatically fails. The PARAMETERS - ahost Points to the name of the host to which the connection is made. If the connection is successful, this name is updated with the standard name for the host. - inport Is the Internet port number on which the connection should be attempted. - locuser Is the user name on the local system. - remuser Is the user name to use for authentication on the remote system. - cmd Is the command to be executed on the remote host. - fd2p If non-null, a second connection is made to stderr of the remote command, and the file descriptor is returned through this pointer. If null, stderr of the remote command is connected to its stdout. - port Points to a port number to which an attempt is made to bind. This port number is updated to specify the last port number attempted. - rhost Is the name of the remote host for which authentication is requested. - raddr Is the address of remote host for which authentication is requested. - superuser Is a boolean flag indicating whether the local user is to be considered the super-user. - ruser Is the name of the remote user. - luser Is the name of the local user. RETURN VALUES On success, On success, On success, CONFORMANCE 4.4BSD MULTITHREAD SAFETY LEVEL Unsafe.: bind(), gethostbyname(), gethostname(), rexec(), socket() PTC MKS Toolkit 10.3 Documentation Build 39.
https://www.mkssoftware.com/docs/man3/rcmd.3.asp
CC-MAIN-2021-39
en
refinedweb
Today, we are going to learn about Generators, what they are, how to use them, and their advantages. Before going further, make sure that you know iterators. If you don’t, learn about them here. Python Generator Function A generator function is a function that returns a generator object, which is iterable, i.e., we can get an iterator from it. Unlike the usual way of creating an iterator, i.e., through classes, this way is much simpler. Moreover, regular functions in Python execute in one go. In other words, they cannot be stopped midway and rerun from that point. The lines of code after the return statement never get executed. In a generator function, however, we use yield expression instead of return, which allows us to maintain the local state of the function. When we invoke a generator function, it just returns an iterator. Note that it does not start to execute at this point. Let’s understand how a generator function works through an example. def test_generator(): i = 0 print("First execution point") yield i i += 1 print("Second execution point") yield i i += 1 print("Third execution point") yield i obj = test_generator() print(obj) Output <generator object test_generator at 0x7fad8b858a98> The above test_generator() function contains a variable i that gets incremented after each yield statement. When we call test_generator(), it returns a generator object, which is an iterator. Python next() To start its execution, we can use the next() method that takes the generator object as an argument. In doing so, the function runs until it encounters a yield statement. After that, the function returns the next value in the iterator and hands over the transfer to the caller, but its state is maintained. When we call the next() method again, the function begins its execution after the last encountered yield statement. Let’s see. print(f"The value of i is {next(obj)}") print(f"The value of i is {next(obj)}") print(f"The value of i is {next(obj)}") Output First execution point The value of i is 0 Second execution point The value of i is 1 Third execution point The value of i is 2 As you can see, the variable i does not get destroyed, i.e., the value from the previous call is maintained. Python StopIteration Exception What happens if we try to call the next() method one more time? As the function does not contain any more lines, so we will get a StopIteration exception, i.e., print(f"The value of i is {next(obj)}") Output StopIteration Traceback (most recent call last) <ipython-input-13-f06cc408a533> in <module>() ----> 1 print(f"The value of i is {next(obj)}") StopIteration: for loop Instead of calling next() each time we want to get the next item, we can use the for loop that will implicitly use next() until the generator exhausts. It is simple, short, and eliminates the chances of raising a StopIteration exception (as mentioned above). Let’s see. obj = test_generator() for val in obj: print(f"The value of i is {val}") Output First execution point The value of i is 0 Second execution point The value of i is 1 Third execution point The value of i is 2 To reiterate, we need to call the generator function again. Python Generator Expressions Generator Expressions are an even shorter way of creating iterators, and they are anonymous generator functions. They are similar to list comprehensions and defined in the same way, except it requires parenthesis instead of square brackets. They provide the same functionality as list comprehensions do but are more memory efficient and provide high performance. Let’s take an example to understand them. obj1 = [x * x for x in range(0, 9)] # list comprehension print(obj1) obj2 = (x * x for x in range(0, 9)) # generator expression print(obj2) for item in obj2: print(item) Output [0, 1, 4, 9, 16, 25, 36, 49, 64] <generator object <genexpr> at 0x7fad83a7e620> 0 1 4 9 16 25 36 49 64 Memory Efficient and High Performance List comprehensions store the complete list in memory. However, the generator expression only holds the generator object in memory. Therefore, they are more memory efficient and provide high performance. Consider the same example as above, except we are calculating the squares of numbers from 1 to 1 million here. import time import sys start = time.time() obj1 = [x * x for x in range(0, 1000000)] # list comprehension end = time.time() print(f"Time Taken: {end-start}seconds") print(f"Memory: {sys.getsizeof(obj1)} bytes\n") start = time.time() obj2 = (x * x for x in range(0, 1000000)) # generator expression end = time.time() print(f"Time Taken: {end-start} seconds") print(f"Memory: {sys.getsizeof(obj2)} bytes") Output Time Taken: 0.10663628578186035seconds Memory: 8697464 bytes Time Taken: 8.130073547363281e-05 seconds Memory: 88 bytes See the difference Infinite Sequence As we have a limited amount of memory, we cannot generate an infinite sequence using usual methods. However, we can produce it using generators since they do not need to store complete data in memory. Consider the following example that generates the square number series. def infinite_square_number(): i = 0 while True: yield i * i i += 1 sequence = infinite_square_number() for num in sequence: print(num, end=", ") Output Python send() The send() method sends a value to a generator function. When we call the send() method, the execution of the function resumes, and the value passed in the argument becomes the result of the yield expression from the previous execution point. If you use the send() method to call the generator function for the first time, then pass None as the argument as no yield expression is executed yet. import random def test_generator(n, recv=0): for i in range(n): recv = yield i * recv n = 5 obj = test_generator(n) print(obj.send(None), end=" ") for i in range(1, n): print(obj.send(random.randint(1, 10)), end=" ") Output 0 8 18 15 20 The test_generator() function runs the loop for n number of times. It yields the product of the current iteration number and the random integer sent through the send() method. Note that we pass None in send() in the first call to the test_generator() function. The close() method stops the generator. It closes the generator by raising the GeneratorExit exception. If the generator has already exited, either by exhaustion (normal exit) or due to some exception, it does nothing. Consider the following example, in which the test_generator() function takes squares of numbers from 0 to n. However, we stop the generator when the yielded value is 25. import random def test_generator(n): j = 0 for i in range(n): yield j ** 2 j += 1 n = 1000 obj = test_generator(1000) for val in obj: print(val) if val == 25: obj.close() Output 0 1 4 9 16 25 throw() It is used to throw a specified exception. It takes three arguments. The first argument is the type of exception. The second optional argument represents the value of the error, and a third optional argument is a traceback object. Consider the same example as above, except it throws ValueError when the yielded value is greater than or equal to 1000. import random def test_generator(n): j = 0 for i in range(n): yield j ** 2 j += 1 n = 1000 obj = test_generator(1000) for val in obj: if val >= 1000: obj.throw(ValueError, "Too Large") print(val, end=" ") Output Creating a Generator Pipeline Generators can be chained together to create a pipeline, in which the output of one generator goes as an input to another generator. This will make your code and pipeline more readable. Consider the following example, where one generator reads a file. The file contains a sample list of Australian cricket players and their career periods. The names of the players are all in lowercase. We want to capitalize their first and last names. Let’s do it. lines = (line for line in open("sample.txt")) # read each line from the file words_list = ( words.capitalize() + " " for l in lines for words in l.split(" ") ) # split each line and capitalize line = " " for w in words_list: line += w print(line) Output James Pattinson 2011–2015 Pat Cummins 2011– Mitchell Marsh 2011– Daniel Christian 2012–2014 Matthew Wade 2012– Peter Forrest 2012 Nathan Lyon 2012– George Bailey 2012–2016 Glenn Maxwell 2012– Aaron Finch 2013– The first generator expression yields each line of the file. The second generator expression splits each line into a list of words, and then each word is capitalized.
https://www.codesdope.com/blog/article/python-generators/
CC-MAIN-2021-39
en
refinedweb
One of the things I failed to do at the end of last year was put together a spellchecking pipeline to try to pick up typos across several dozen Jupyter notebooks used as course materials. I’d bookmarked pyspelling as a possible solution, but didn’t have the drive to do anything with it. So with a need to try to correct typos for the next presentation (some students on the last presentation posted about typos but didn’t actually point out where they thought were so we could fix them) I thought I’d have a look at whether pyspelling could actual help having spotted a Github spellcheck action — rojopolis/spellcheck-github-actions — that reminded me of it (and that also happens to use pyspelling). The pyspelling package uses a matrix and pipeline ideas. The matrix lets you define and run separate pipelines, the pipelines let you sequence a series of filter steps. Available filters include markdown, html and python filters that preprocess files and pass text elements for spellchecking to the spellchecker. The Python filter allows you to extract things like comments and docstrings and run spell checks over those; the markdown and HTML filters can work together so you can transform markdown to HTML, then ignore the content of code, pre and tt tags, for example, and spell check the rest of the content. A url filter lets you remove URLs before spellchecking. By default, there is no Jupyter notebook / ipynb filter, so I started off by running the spellchecker against Jupytext markdown files generated from my notebooks. A filter to strip out the YAML header at the start of the jupytext-md file was there to help minimise false positive typos from the spell checker report. In passing, I often use a Jupytext -pre-commit filter to commit a markdown version of Git committed notebooks to a hidden .md directory. For example, in .git/hooks/pre-commit, add the line: jupytext –from ipynb –to .md//markdown –pre-commit [docs]. Whenever you commit a notebook, a Jupytext markdown version of the notebook (ex- of the code cell output content) will also be added and commited into a .md hidden directory in the same directory as the notebook. Here’s the first attempt a pyspelling config file: # -- .pyspelling.yml -- matrix: - name: Markdown aspell: lang: en dictionary: wordlists: - .wordlist.txt encoding: utf-8 pipeline: - pyspelling.filters.context: # Cribbed from pyspelling docs context_visible_first: true # Ignore YAML at the top of juptext-md file # (but may also exclude other content?) delimiters: - open: '(?s)^(?P<open> *-{3,})$' close: '^(?P=open)$' - pyspelling.filters.url: - pyspelling.filters.markdown: markdown_extensions: - pymdownx.superfences: - pyspelling.filters.html: comments: false ignores: - code - pre - tt sources: - '**/.md/*.md' default_encoding: utf-8 Note that the config also includes a reference to a custom wrodlist in .wordlist.txt that includes additional whitelist terms over the default dictionary. Running pyspelling using the above confguration runs the spell checker over the desired files in the desired way: pyspelling > typos.txt The output typos.txt file then has the form: Misspelled words: <htmlcontent> content/02. Getting started with robot and Python programming/02.1 Robot programming constructs.ipynb: html>body>p -------------------------------------------------------------------------------- accidently -------------------------------------------------------------------------------- Misspelled words: <htmlcontent> content/02. Getting started with robot and Python programming/02.1 Robot programming constructs.ipynb: html>body>p -------------------------------------------------------------------------------- autorunning -------------------------------------------------------------------------------- We can create a simple pandas script to parse the result and generate a report that counts the prevalence of particular typos. For example, something of the form: datalog 37 dataset 32 pre 31 convolutional 19 RGB 17 .. pathologies 1 Microsfot 1 One possible way of using that information is to identify terms that maybe aren’t in the dictionary but should be added to the whitelist. Another way of using that infomation might be to identify jargon or potential glossary terms. Reverse ordering the list is more likely to give you occasional typos; middling prevalence items might be common typos; and so on. That recipe works okay, and could be used to support spell checking over a wide range of literate programming file formats (Jupyter notebooks, Rmd, various structured Python and markdown formats, for example). Basing the process around a format Jupytext exports into allows us to then have a Jupytext step at the front a small pieces lightly joined text file pipeline that takes a literate programming document, converts it to eg Jupytext-md, and then passes it to the pyspelling pipeline. But a problem with that approach is that we are throwing away perfectly good structure in the orginal document. One of the nice things about the ipynb JSON format is that it separates code and markdown in a very clean way (and by so doing makes things like my innovationOUtside/nb_quality_profile notebook quality profiler relatively easy to put together). So can we create our own ipynb filter for pyspelling? Cribbing the markdown filter definition, it was quite straightforward to hack a first pass attempt at an ipynb filter that lets you extract the content of code or markdown cells into the spell checking pipeline: # -- ipynb.py -- """Jupyter ipynb document format filter.""" from .. import filters import codecs import markdown import nbformat class IpynbFilter(filters.Filter): """Spellchecking Jupyter notebook ipynb cells.""" def __init__(self, options, default_encoding='utf-8'): """Initialization.""" super().__init__(options, default_encoding) def get_default_config(self): """Get default configuration.""" return { 'cell_type': 'markdown', # Cell type to filter 'language': '', # This is the code language for the notebook # Optionally specify whether code cell outputs should be spell checked 'output': False, # TO DO # Allow tagged cells to be excluded 'tags-exclude': ['code-fails'] } def setup(self): """Setup.""" self.cell_type = self.config['cell_type'] if self.config['cell_type'] in ['markdown', 'code'] else 'markdown' self.language = self.config['language'].upper() self.tags_exclude = set(self.config['tags-exclude']) def filter(self, source_file, encoding): # noqa A001 """Parse ipynb file.""" nb = nbformat.read(source_file, as_version=4) self.lang = nb.metadata['language_info']['name'].upper() if 'language_info' in nb.metadata else None # Allow possibility to ignore code cells if language is set and # does not match parameter specified language? E.g. in extreme case: #if self.cell_type=='code' and self.config['language'] and self.config['language']!=self.lang: # nb=nbformat.v4.new_notebook() # Or maybe better to just exclude code cells and retain other cells? encoding = 'utf-8' return [filters.SourceText(self._filter(nb), source_file, encoding, 'ipynb')] def _filter(self, nb): """Filter ipynb.""" text_list = [] for cell in nb.cells: if 'tags' in cell['metadata'] and \ set(cell['metadata']['tags']).intersection(self.tags_exclude): continue if cell['cell_type']==self.cell_type: text_list.append(cell['source']) return '\n'.join(text_list) def sfilter(self, source): """Filter.""" return [filters.SourceText(self._filter(source.text), source.context, source.encoding, 'ipynb')] def get_plugin(): """Return the filter.""" return IpynbFilter We can then create a config file to run a couple of matrix pipelines: one over ntoebook markdown cells, one over code cells: # -- ipyspell.yml -- matrix: - name: Markdown aspell: lang: en dictionary: wordlists: - .wordlist.txt encoding: utf-8 pipeline: - pyspelling.filters.ipynb: cell_type: markdown - pyspelling.filters.url: - pyspelling.filters.markdown: markdown_extensions: - pymdownx.superfences: - pyspelling.filters.html: comments: false # #captures: # - '*|*:not(script,style,code)' #ignores: # - 'code > *:not(.c1)' ignores: - code - pre - tt sources: - 'content/*/*.ipynb' #- '**/.md/*.md' default_encoding: utf-8 - name: Python aspell: lang: en dictionary: wordlists: - .wordlist.txt encoding: utf-8 pipeline: - pyspelling.filters.ipynb: cell_type: code - pyspelling.filters.url: - pyspelling.filters.python: sources: - 'content/*/*.ipynb' #- '**/.md/*.md' default_encoding: utf-8 We can then run that config as: pyspelling -c ipyspell.yml > typos.txt The following Python code then generates a crude dataframe of the reseults: import pandas as pd fn = 'typos.txt' with open(fn,'r') as f: txt = f.readlines() # aspell df = pd.DataFrame(columns=['filename', 'cell_type', 'typo']) currfile = '' cell_type = '' for t in txt: t = t.strip('\n').strip() if not t or t in ['Misspelled words:', '!!!Spelling check failed!!!'] or t.startswith('-----'): continue if t.startswith('<htmlcontent>') or t.startswith('<py-'): if t.startswith('<html'): cell_type = 'md' elif t.startswith('<py-'): cell_type = 'code' else: cell_type='' currfile = t.split('/')[-1].split('.ipynb')[0]#+'.ipynb' continue df = df.append({'filename': currfile, 'cell_type': cell_type, 'typo': t}, ignore_index=True) The resulting dataframe lets us filter by code or markdown cell: We can also generate reports over the typos found in markdown cells, grouped by notebook: df_group = df[(df['filename'].str.startswith('0')) & (df['cell_type']=='md')][['filename','typo']].groupby(['filename']) for key, item in df_group: print(df_group.get_group(key).value_counts(), "\n\n") Thsi gives basic results of the form: Something that might be worth exploring is a tool that present a user with form that lets them enter (or select from a list of options?) a corrected version and that will then automatically fix the typo in the original file. To reduce the chance of false positives, it might also be worth showing the typo in it’s original context using the sort of display that is typical in a search engine results snippet, for example (eg ouseful-testing/nbsearch).
https://blog.ouseful.info/2021/03/17/spellchecking-jupyter-notebooks-with-pyspelling/
CC-MAIN-2021-39
en
refinedweb
JDK Flight Recorder, or JFR, is an event-based production environment profiler available from OpenJDK 8u272 forward. Being a HotSpot-native feature, JDK Flight Recorder performs with extremely low overhead in terms of how it uses both space and time. While JDK Flight Recorder collects basic Java runtime information by default, it is also possible to use JFR's Event API to collect custom events. Developers who want to collect application-level events must actively define and instantiate them in their application source code. In this article, we'll show you how to use JMC Agent and the JMC Agent Plugin to instrument your application classes with event-emitting code. When you use JMC Agent with the JDK Flight Recorder Event API, you do not need to shut down the JVM and recompile the application code. Note: We include an overview of the JDK Flight Recorder toolchain in this article, but we'll focus on introducing JMC Agent and the JMC Agent Plugin. To learn more about JDK Flight Recorder, see our previous article, Get started with JDK Flight Recorder in OpenJDK 8u. Overview of the JDK Flight Recorder toolchain JMC Agent is a subcomponent of the JDK Mission Control (JMC) project. JDK Mission Control focuses on interacting with JDK Flight Recorder and analyzing the recordings that it dumps. Although we mainly cover JMC Agent and the JMC Agent Plugin, an overview of the toolchain will be helpful. JDK Flight Recorder JDK Flight Recorder was originally a JRockit JVM feature. It captures key JVM statistics events and records them in a flight recording file for offline analysis. In 2018, Oracle open-sourced this feature under the name JDK Flight Recorder and integrated it into OpenJDK 11. JFR was also backported to OpenJDK 8. Developers use JDK Flight Recorder to profile JVMs in production environments. JFR records events in compact binary forms. At a glance, it stores these events first in an in-memory buffer. Periodically, it flushes the buffer to the file system or another store. JFR is meant to be an "alway on" production time profiler and has an overhead of less than 2% for most use cases. JDK Mission Control Having a flight recording in a binary format is not useful by itself. OpenJDK provides tooling to access these recordings and decode their content. However, JDK Mission Control is the most powerful and flexible way to study flight recordings. JDK Mission Control is a GUI tool specifically designed to analyze JFR recordings. Together with JDK Flight Recorder, JMC gives developers an in-depth view of the application's runtime characteristics. You can use this view to identify performance bottlenecks and fine-tune the JVM. JMC also has the ability to connect to a locally running JVM, to take new recordings, and to control ongoing recordings. JMC is an Eclipse Rich Client Platform application. It can be extended with various plugins. It also offers a powerful standalone API for reading and analyzing JFR recordings independently from the GUI application. Note: JDK Mission Control is available in Fedora and Red Hat Enterprise Linux (RHEL) 7 via Red Hat Software Collections (RHSCL), in RHEL 8 via the modules, and for Windows users from the OpenJDK developer portal. You can also obtain JDK Mission Control via a downstream distribution like AdoptOpenJDK. JMC Agent JMC Agent is a subproject of JMC. You can use this bytecode transformer to add JFR instrumentation declaratively to running applications. When you use JMC Agent, you do not need to program the JFR instrumentation in the source code. Because the agent operates in the same address space as the JVM, it is extremely versatile. You can load it at the start of the application or sideload it dynamically at any time. A running JMC agent exposes an MBean controller for further configuration via Remote Java Management Extensions (JMX). The JMC Agent Plugin The JMC Agent Plugin is an ongoing effort that integrates JMC Agent features into JDK Mission Control. It is currently being developed as an external plugin in a separate project. Eventually, it will be rehomed as a submodule of JMC. Developers can use the JMC Agent Plugin to manage the JMC Agent lifecycle and control an agent's behaviors. While the JMC Agent Plugin is in an early development stage, essential features are already usable. In the following sections, you will learn more about JMC Agent and the JMC Agent Plugin, including instructions for building an agent plugin that is usable in JDK Mission Control. Introduction to JMC Agent The most common way to produce events and commit them to JDK Flight Recorder is to use the standard jdk.jfr.* API, which was introduced in JDK 9. Developers who wish to use the jdk.jfr.* API to create events and operate on their instances must manually extend from a jdk.jfr.Event. An alternative, available from JMC Agent, is to use declarative and hot-swappable configurations. JDK Flight Recorder treats all events the same way, regardless of whether JMC Agent or the standard API produces them. Creating and operating on event instances with JMC Agent JMC Agent uses the Java Instrumentation API to register a ClassFileTransformer immediately after starting. When a class loader initiates class loading, the agent ClassFileTransformer transforms the class bytecode by injecting event-committing bytecode, which is generated according to the configuration supplied. It's also possible to revert or update instrumentation by retransforming and reloading the class, as long as the agent can obtain a reference to target classes. We prioritized the following requirements when we designed JMC Agent: - Declarative: You can use XML configuration to define inject events. - Unobtrusive: You do not need to change the source code to implement JMC Agent. - Minimal footprint: You do not need to use reflection; you only issue event-related function calls. - Painless: You never have to shut down the JVM. (see below). Together, these features help to ensure that JMC Agent is safe to use and free of side-effects. It is perfect for production use when the source is not available, or it is not possible to shut down services or maintenance immediately. JMC Agent is especially applicable for situations that require creating custom instrumentation for the application. Next, we'll look at how to use JMC Agent and the JMC Agent Plugin. Configuring the information to be recorded in events JMC Agent instrumentation applies to one or more functions. You can enable or disable the following information in the XML configuration: - Function runtime characteristics: Start time, end time, and duration. - Function input and output: Parameters, return values, and exceptions (if any). - Event metadata: Label, description, thread ID, and call stack. For expression evaluation, you can also use JMC Agent to enable or disable a limited subset of primary expressions. JMC Agent accepts all Java primary expressions except those containing method invocations, array accesses, or array or instance creation. This design is intended to enforce evaluation safety by static checking and to guarantee a constant-time overhead. The agent configuration file An agent configuration file is an XML representation controlling how a JMC Agent instruments application bytecode: - The document root is a <jfragent>element. As of current implementation, JMC Agent requires no namespace. A <jfragent>element has no inner text and optionally encloses the <config>and <events>elements. - The <config>element contains global options to be applied across all events. Currently, the options are <classprefix>, <allowconverter>, and <allowtostring>. - The <events>elements enclose any number of <event>elements, often called probes. Each <event>element contributes to a specific instrumentation point identified by <class>, <method>, and the method <descriptor>. - The <parameter>and <field>elements record the values of the given parameters and expression accordingly. Note: See the JMC Agent repository for an example that demonstrates common usages of the Java Fight Recorder Template. Limitations of JMC Agent JMC Agent is in an early stage of development. At the time of this writing, we are seeking to resolve the following constraints: - JMC Agent is unable to work with synthetic classes. - It is also unable to access nestmates' private fields. - Newly uploaded configurations only work with classes defined with SystemClassLoader. - JMC Agent currently uses jdk.internal.misc.Unsafe,so you must open the module via --add-opens (see below). - JMC Agent is currently not integrated with JDK Mission Control. Note: Instrumenting synthetic classes is arguably a non-goal. It is often hard to determine the exact names of the generated classes, making them hard to work with. In most cases, it does not make sense to instrument generated code. Introduction to the JMC Agent Plugin Thankfully, the JMC team developed JMC on the extensible and modular Eclipse Rich Client Platform. Therefore, instead of creating new client software, the JMC Agent Plugin adds agent-related functionality to JDK Mission Control. In a nutshell, the JMC Agent Plugin is to JMC Agent what JDK Mission Control is to JDK Flight Recorder. That is, it controls JMC agents. While still under active development, the JMC Agent Plugin already helps navigate the JMC Agent lifecycle. You can use the plugin to start JMC Agent in a local JVM and then connect to it via the JMX API. Once connected, you can apply new or modified configurations. The JMC Agent Plugin also displays live information about the resulting transformations. You can also manage predefined configurations with the preset manager and create or edit them with a set of wizards. Live configurations The Live Configuration page was one of the first features that we added to the JMC Agent Plugin. You can use it to see the configuration currently applied to a JMC agent in a tabular format. As shown in Figure 1, the Live Config screen's left side lists all of the events instrumented by your JMC Agent instance. The right side contains each event's definition. Note: We will eventually support saving live configurations directly into the preset manager so that you can use them later. Editing wizards and the preset manager Editing an XML configuration file is difficult for beginners and tedious for experienced developers, as well as being error-prone. JMC Agent Plugin introduces editing wizards to save you the hassle. Together with the preset manager, editing wizards streamline creating, modifying, and managing local configuration templates, also known as presets. Presets are especially useful when you don't need all of the configuration or event options that creating a full XML configuration would entail. Figure 2 shows the JMC Agent Plugin's preset editing wizards in the preset manager screen. As an alternative to editing presets with wizards, you can use the built-in XML source editor to edit raw configuration files manually. While we don't have them yet, we'll eventually add inline error and warning indications to the XML source editor. You've been introduced to JMC Agent and the JMC Agent Plugin. We'll conclude with quick instructions for building and running these tools in your applications. Be sure to check out the demonstration video at the end of the article, as well. Build and run JMC Agent To build and run JMC Agent, you will need JDK 7 or later. To start, clone the JMC source tree from its GitHub repository: $ git clone Then, use Maven in the agent folder: $ mvn clean package After the build succeeds, you will find the agent JAR under the target directory: $ ls target/org.openjdk.jmc.agent-*.jar To run your application with the agent statically attached, use the -javaagent option to specify the agent's JAR path and optional configuration path: $ java -XX:+FlightRecorde -javaagent:<path-to-agent-jar>[=<path-to-agent-config>] <rest-of-your-app-cmd> Export the Unsafe class in JDK 9 and above When using JDK 9 and above, remember to export the Unsafe class with the --add-opens option for the agent to use: --add-opens java.base/jdk.internal.misc=ALL-UNNAMED For instance, to run the sample program that is included with JMC Agent, you would enter: $ java --add-opens java.base/jdk.internal.misc=ALL-UNNAMED Build JMC with the JMC Agent Plugin enabled Until the JMC Agent Plugin is packaged with JDK Mission Control, you'll have to build it yourself. Before you attempt to follow these instructions, make sure that you have JDK 8 and Maven installed on your system. First, clone the JMC source tree, if you haven't already done so: $ git clone Then, clone the JMC Agent Plugin source tree: $ git clone Copy the agent plugin and feature folds from the JMC Agent Plugin source tree to JMC: $ cp -r jmc-agent-plugin/org.openjdk.jmc* jmc/application Apply the patch to JMC's root directory: $ cd jmc $ patch -p0 < ../jmc-agent-plugin/scripts/diff.patch Get third-party dependencies into a local p2 repository and make it available on localhost: $ cd jmc/third-party && mvn p2:site && mvn jetty:run Finally, in another terminal, compile and package JMC: $ cd jmc/core && mvn install && cd .. && mvn package Do more with JMC Agent: Video presentation and demo This article is based on an internal presentation that we made to the Red Hat JDK Mission Control team, now available for public viewing. The demonstration starts at 8:50 minutes and was recently updated to reflect the latest development progress. You will find the demonstration code on the GitHub repository for the Dining philosophers demo. Conclusion JDK Flight Recorder is meant to be a production-time profiler. In this context, JMC Agent is a powerful addition to the JFR toolchain. As a developer, JMC Agent lets you instrument your runtime applications without needing to shut down the JVM. You do not need to refactor and recompile your code to redeploy the application. There are, of course, alternatives to using JMC Agent. For example, Byteman is a powerful tool that you can configure to inject similar instrumentation into a running application. However, JMC Agent's dedication to JFR event instrumentation makes it more suitable and easier to use for problems that require custom JFR events. Although it is a work in progress, adding the JMC Agent Plugin to JDK Mission Control further elevates the ease-of-use factor in this toolchain. Both JMC Agent and the JMC Agent Plugin are currently under development, with new features being planned and implemented constantly. If you would like to contribute to this project or have ideas, suggestions, or feedback, you can join the discussion on the JMC-dev mailing list.Last updated: December 4, 2020
https://developers.redhat.com/blog/2020/10/29/collect-jdk-flight-recorder-events-at-runtime-with-jmc-agent
CC-MAIN-2021-39
en
refinedweb
Ternary Operator deal with three operands.It is also called conditional assignment statement because the value assigned to a variable depends upon a logical expression. a=5,b=3; max=(a>b)?a:b; Here,the value 5 is stored in max as a>b is true // Program using ternary operator public class TernaryOperator { public static void main(String args[]){ int num1 , num2; num1 = 10; num2 = (num1 == 1) ? 20: 30; System.out.println( "Value of num2 is : " + num2 ); num2 = (num1 == 10) ? 20: 30; System.out.println( "Value of num2 is : " + num2 ); } } Value of num2 is : 30 Value of num2 is : 20 These operator are used to show the relationship among the operands.Relational Operators compare the values of the variable and result in terms of 'True' or 'False'(i.e 0 or 1). Java uses logical operators AND(&&),OR(||) or NOT(!).These operators yield 1 or 0 depending upon the outcome of different expressions. In java programming,you can use some special types of operators,which perform operations on bit level of the operands.These operators use byte,short int and long type operands. // Program to perform bitwise operation public class bitwiseoperation{ public static void main(String args[]) { int a,b; a=12;b=10;int n = 35,m; m=~n; System.out.println("complement is ="+m); System.out.println("(a&b)="+(a&b)); System.out.println("(a|b)="+(a|b)); System.out.println("(a^b)="+(a^b)); System.out.println("(a<<b)="+(a<<b)); System.out.println("(12>>2)="+(12>>2)); System.out.println("(14>>>2)="+(14>>>2)); } } complement is =-36 (a&b)=8 (a|b)=14 (a^b)=6 (a<<b)=48 (a>>b)=3 (a>>>b)=3 Assignment operators are used in Java to assign values to variables.
https://www.cseworldonline.com/javatutorial/java_basicoperator.php
CC-MAIN-2021-39
en
refinedweb
Node.js Tools for Visual Studio It would be awesome if we were able to launch using nodemon.js as a node.exe option when using "Start Without Debugging" but alternately launch without nodemon when using "Start Debugging". Nodemon appears to be incompatible with the VS debugger. However, it's is extremely useful for "normal" development, where I typically don't attach the debugger unless I'm trying to track down a bug. Any thoughts on how this could be achieved? Or ways to make the debugger play nice with nodemon? ------ Discover test started ------ Processing: J:\dev\antlr4ts\target\test\TestMocha.js Test discovery error: [SyntaxError: J:\dev\antlr4ts\target\test\TestMocha.js:4 Processing finished for framework of Mocha Discovered 0 testcases. ========== Discover test finished: 0 found (0:00:00.7930225) ========== The line in question contains the following: const MurmurHash_1 = require('../src/misc/MurmurHash'); which was presumably produced by the following line in TestMocha.ts, the original TypeScript source file for the test in question. import {MurmurHash} from '../src/misc/MurmurHash'; <entry> <record>606</record> <time>2016/10/05 19:09:34.451</time> <type>Error</type> <source>Editor or Editor Extension</source> <description>System.InvalidOperationException: Operation is not valid due to the current state of the object. at Microsoft.VisualStudioTools.Project.Automation.OAProjectItem.get_Collection() at Microsoft.VisualStudio.Web.Editor.Package.Lint.WebLinter.LinterUtilities.IsFileSupported(String fileName) at Microsoft.VisualStudio.Web.Editor.Package.Lint.ErrorTagger.LintErrorTaggerProvider.CreateTagger[T](ITextBuffer textBuffer) at Microsoft.VisualStudio.Text.Tagging.Implementation.TagAggregator`1.GatherTaggers(ITextBuffer textBuffer)</description> </entry> NTVS 1.2 VS 2015.msialso seems like a windows kind of file .msifile is not a VSIX file it seems
https://gitter.im/Microsoft/nodejstools?at=576975df0ede04dc49035d18
CC-MAIN-2019-43
en
refinedweb
4 Job Doesn't Get Scheduled With Delay() @bobbybouwmann Yep. It was cached. It's picking up the connection from the .env now. Thank you ? Replied to Laravel Job Doesn't Get Scheduled With Delay() @BOBBYBOUWMANN - I guess it was. I'll try again. Replied to Laravel Job Doesn't Get Scheduled With Delay() Specifying a connection on dispatch seems to work perfectly. Thanks @bobbybouwmann ? For reference, changed my dispatch to this: RemoveTorrent::dispatch($torrent) ->onQueue('RemoveTorrent') ->delay(now()->addMinutes(15)) ->onConnection('database'); note the onConnection() Replied to Laravel Job Doesn't Get Scheduled With Delay() @BOBBYBOUWMANN - Changing it to database didn't work ? Replied to Laravel Job Doesn't Get Scheduled With Delay() @BOBBYBOUWMANN - Queue driver in the .env says QUEUE_DRIVER=sync Should I change it to database? I've already created the table in the database (as said in the documentation)! Started a new conversation Laravel Job Doesn't Get Scheduled With Delay() I am trying to schedule a job in the queue as described in the example here but it's getting processed immediately. Here's my code dispatching new job: RemoveTorrent::dispatch($torrent) ->onQueue('RemoveTorrent') ->delay(now()->addMinutes(15)); Here's the job: <?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Services\MyService; class RemoveTorrent implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @return void */ protected $torrent; public function __construct(Modal $modal) { $this->torrent = $modal; } /** * Execute the job. * * @return void */ public function handle(MyService $myService) { // } } Replied to Creating Drag And Drop Between Two Lists In React(Like A Trello Board) User react-dnd. It's might be a bit hard to setup at first, but examples and documentation is awesome. Check the repo here: Example: Replied to Homestead.yaml Is Not As Same As In The Docs And Laracst? Replied to Best Domain Registrar (Best Place To Buy Domain) I'd recommend namecheap.com Cheap and better than others. You can buy a .io domain from google for $60/year or buy the same domain from namecheap.com for only $32.88/year. Started a new conversation Homestead.yaml Is Not As Same As In The Docs And Laracst? I just created a public key with my email in my homestead.yaml file on windows inside my xampp/htdocs/code. But it only shows my private key in the homestead.yaml file. It's not as same as mentioned in the docs and in the videos on laracast. Do I need to re clone the homestead in my directory or what? I am following instruction line by line as in the laracst beginner videos i watched on this website.
https://laracasts.com/@arximughal
CC-MAIN-2019-43
en
refinedweb
$ cnpm install foldify Fold your folders, any way you like. Import / require folders of any filetypes; evaluate / curry the results. var foldify = require("foldify"); var routes = foldify(__dirname + "/lib/routes", {tree: true}); // routes.errors.500: function(app){ app.get(...) } // routes.errors.501: function(app){ app.get(...) } // routes.index: function(app){ app.get(...) } // routes.user.login: function(app){ app.get(...) } // routes.user.logout: function(app){ app.get(...) } routes(app, {whitelist: "errors/**"}); //just errors are now attached! routes(app); /: require("./filename.js"), filename2: fs.readFileSync("./filename.html") } = require("foldify"); var errorControllers = foldify(__dirname + "/lib/controllers/errors"); Even just this object can be useful: //with a folder structure like: // ~/lib/controllers/errors/ // .../500.js // .../403.js // .../402.js app.get( '/500', errorControllers.500 ); app.get( '/403', errorControllers.403 ); app.get( '/402', errorControllers.402 ); also for...in compatible: for(var controllerName in errorControllers){ app.get( '/' + controllerName, errorControllers[controllerName] ); } = require("foldify"); var stylesAndHtml = foldify(__dirname + "/client", {whitelist: ["*.less, *.html"], recursive: true}); //will grab all .less and .html files into hash, as strings Accepts string or array. Uses minimatch upon filepaths using supplied blacklist patterns. Supplied rules are prefixed by the curried directory. Reference minimatch documentation for matching behavior. var foldify = require("foldify"); var templates = foldify(__dirname + "/templates", {blacklist: ".json", recursive: true}); /.exports = function(app){ app.get('/', function(req, res){ res.end("hello world"); }); } = express(); var foldify = require("foldify"); var routes = foldify(__dirname + "/routes"); routes(app); //all routes are attached! Accepts string or array. Uses minimatch upon property names using supplied whitelist patterns. Reference minimatch documentation for matching behavior. var foldify = require("foldify"); var routes = foldify(__dirname + "/routes"); routes(app, {whitelist: "a*"} ); / = require("foldify"); var routes = foldify(__dirname + "/routes"); routes(app, {blacklist: "a*"} ); /.exports = sum; function sum(){ var sum = [].slice.call(arguments, 0) .reduce(function(prev, current){ return (+prev || 0) + (+current || 0); }); console.log("sum = " + sum); } var foldify = require("foldify"); var mathFuncs = foldify(__dirname + "/lib/mathFuncs"); //To curry only, set 'evaluate' to false: var curried = mathFuncs(1, {evaluate: false}); var curried2 = curried([2,3], {evaluate: false}); curried() //sum = 1 curried2() / var curried3 = curried2(10); //sum = 16 typeof curried3.mathFunc // function curried3() //sum = 16 var curried4 = curried3(20) //sum = 36 curried4() //sum = 46 But if allowUndefined is true, functions may return undefined into the hash instead of a curried version of itself: var curried3 = curried2(10, {allowUndefined: true}); //sum = 16 typeof curried3.mathFunc // undefined curried3() //folding further will continue to produce `undefined` ###completed: ###yet to be completed: Run npm install then npm test to test server code. To test in browser please install browserify globally and testling globally, and then run testling -u in the root dir of this module.
https://npm.taobao.org/package/foldify
CC-MAIN-2019-43
en
refinedweb
Template parameters The body of a code template may contain: Plain text that represents source code constructs and comments. It is inserted as is when you apply the template. Template parameters that are replaced dynamically when you apply the template. A template parameter has the following format: $PARAM_NAME$- where PARAM_NAMEis an arbitrary identifier. When the format is correct, Templates Explorer window highlights predefined parameters in dark blue and other parameters in dark red: Predefined parameters The following template parameters are predefined in ReSharper: $END$— the caret position after the template is applied. $SELECTION$— the text selected by the user before invoking the template. This parameter is only used in surround templates. $SELSTART$— the starting position of the text block that will be selected after the template is applied. $SELEND$— the ending position of the text block that will be selected after the template is applied. User-defined parameters All other parameters can be defined with arbitrary identifiers when you create or edit a template. Normally you will need to supply your parameters with macros for calculating their values when the template is applied. Also, you can make each parameter editable so that the user can change its value when the template is applied. Editable parameters If a code template has no editable parameters, it is applied instantly without user interactions; all non-editable parameters, if any, are calculated automatically with macros (e.g. by inserting a fixed value, the current namespace, type name, or even the clipboard content). After the template code is inserted into your source code, you resume typing at the position specified by template developer with the $END$ or $SELEND$ parameters, but if you need to change some parts of the inserted code, you will be able to do so only by going back and editing it. In contrast, editable parameters will expose the fields that may need to be changed and, often, reasonable choices will be suggested for them by the underlying macros. As you are getting acquainted with ReSharper, you will see that many of its predefined templates have editable parameters. You can also study Creating and Editing Templates section to learn how to create and edit custom templates with editable parameters. For example, a well-designed template for iteration over all elements of a container will use editable parameters to allow you choosing: with editable parameters is applied, ReSharper deploys a Hot Spot Session in the editor. This session lets you specify or choose values for all parameters, step by step. You can either replace the parameters with your input or accept one of the suggested values. Examples of applying templates with editable parameters are given in the Creating Source Code With Live Templates and Surrounding Code Fragments With Templates sections.
https://www.jetbrains.com/help/resharper/Templates__Template_Basics__Template_Variables.html
CC-MAIN-2019-43
en
refinedweb
Spring Tip: Check for existence of Bean during startup Sometimes we are working on an application where we have no control over specific Spring bean implementations. Nevertheless we want to check for the existence (or duplication) of these bean implementations during start-up of the application server. Since Spring version 3.0 it is possible to use Spring's ApplicationListener. This interface is based on the EventListener and uses the standard Observer design pattern. In 3 steps we can easily check for the existence of a specific Spring bean. We create an ApplicationListener<ContextRefreshedEvent> implementation. The method onApplicationEvent will be called when a refresh of the ApplicationContext occurs. package com.jdriven.blog.applicationlistener; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; public class BeanContextStartupListener implements ApplicationListener<ContextRefreshedEvent> { public void onApplicationEvent( ContextRefreshedEvent event ) { ... } } We need to register the BeanContextStartupListener as a Spring Component. In this sample we just simply enable component scanning in the spring xml configuration as follows. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns: <context:component-scan </beans> We also add the @Componentto the class definition: import org.springframework.stereotype.Component; @Component public class BeanContextStartupListener implements ApplicationListener<ContextRefreshedEvent> We implement the onApplicationEvent method of the BeanContextStartupListener and throw an Exception when no bean exists within the current ApplicationContext. public void onApplicationEvent( ContextRefreshedEvent event ) { Map serviceImplementations = event.getApplicationContext().getBeansOfType( JDrivenService.class ); if ( serviceImplementations.isEmpty() ) { throw new IllegalStateException("JDrivenService was not instantiated during startup."); } } As mentioned before we can also check for the occurance of Beans with a certain interface. For example: We need to check if there is only one implementation of the JDrivenEmailService and throw a specific Exception when there isn't.
https://blog.jdriven.com/2012/10/spring-tip-check-for-existence-of-bean-during-startup/
CC-MAIN-2019-43
en
refinedweb
1,505 Mix IE11 Babel Issues I'm currently trying to install Laravel Mix inside a WordPress project to handle my asset compilation. I have my webpack.mix.js file set up as follows: let mix = require("laravel-mix"); mix.babel("src/js/app.js", "dist/js/app.js") .sass("src/scss/style.scss", "dist/css/style.css") .sourceMaps() .setPublicPath("dist"); I also have a .babelrc set up as follows: { "presets": [ [ "@babel/preset-env", { "targets": { "ie": "11" } } ] ] } The only code I'm currently using inside app.js is this: import Vue from "vue"; However, when I go to the page I get the following error: Uncaught ReferenceError: require is not defined at app.js:3 And file compiled looks like this (the issue apparently lies on the var _vue line): "use strict"; var _vue = _interopRequireDefault(require("vue")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } I'm really stuck on this issue as I'm unsure what to do. Any ideas appreciated! Replied to Install Wordpress From Git Repo? @nathangross I achieved this using the Bedrock Wordpress installation, it's up and running nice and easy :) Replied to Wordpress, Forge & Version Controlled WP Themes Thanks @sutherland this'll be tonights project :) Replied to Wordpress, Forge & Version Controlled WP Themes @sutherland good shout dude, I totally forgot about Bedrock. What would be the process for setting up the Forge account with it? Do I create a site as a standard PHP/Laravel site or still set up as Wordpress? Thanks for the reminder :) Started a new conversation Wordpress, Forge & Version Controlled WP Themes Hey friends, I'm currently developing a Wordpress site for my photography and I'm using Git to control the theme files. I know that I can set Wordpress up on Forge which is awesome, but how can I go about setting my server up to read from the theme's repo? Do I need to do anything specific with the deploy script or will it work fine out of the box so to speak if I reuse a deploy script from one of my Laravel sites? I've not installed WP on Forge before. Thanks in advance for any guidance :) Andy Replied to Install Wordpress From Git Repo? @nathangross I haven't yet I'm afraid, I need to take another look into it. Let me know if you find anything :) Replied to Install Wordpress From Git Repo? @alenabdula I know this question is old but what's the best way to set up automated pull when listening to the master branch when working with git controlled themes in Wordpress? I'm about to set my Forge up the same way you suggested above Replied to Tightening Up Security For An Upcoming App Idea Replied to Tightening Up Security For An Upcoming App Idea @36864 If they're stored in a table, with a foreign key, does that not then make an obvious correlation with what user it belongs to? If only the database is compromised, they can decrypt everything right? But if one key was stored in the .env, and they didn't get access to that (just the DB) the data would be useless - right? I know it's a lot of what if's though haha. Yeah I use Spatie's Laravel-Permission in a couple of projects already, works really well :) No worries on the JWT, new ground for me too haha Replied to Tightening Up Security For An Upcoming App Idea @bashy haha thanks dude, much appreciated :) @36864 Aye, I definitely don't assume it's safe from any attack because it's encrypted; but it's saf_er_ with the encryptions. I have thought about trying to work out how to use unique keys for each user, but is there a simple way to pass each user's key on the request etc rather than using the global? I was originally going to use a trait to encrypt/decrypt. It's hard to share anymore than I already have at this point in time: I'd like the details of users, those user's clients and any associated jobs/files to be encrypted so that they aren't plain text - one box ticked when it comes to security. I'll also want to roll JWT or similar into it so the API can be consumed by an app. Just want to get a little bit of a clear picture on a good place to start so I don't need to rewrite the app a couple of times - though sometimes that's required Replied to Tightening Up Security For An Upcoming App Idea @bashy haha ah yeah, that was my reptile genetics calculator :P I saw your laptop skin on Twitter a while back, was meant to tweet you to see where you got it as I'd forgotten. This is true, this particular project needs a lot of thought overall. I'm going to look into how to really lock down a server and keep that key as safe as possible - If any of you guys have recommendations on securing linux or similar I'm all ears. Thanks for the suggestions so far, really don't want to go down one path with this and then have to totally rewrite it haha Replied to Tightening Up Security For An Upcoming App Idea @bashy Ah dude I wondered if you'd ever see me post on here, blows my mind we're in the same building haha. I'll take a look at the suggestions and see what we can do. Can any of you see any immediate issues with what I'm proposing at all? Is encrypting multiple columns going to cause me some speed issues or will it be negligible? Easy to get an idea and run before you walk so doing my best to do this properly :P Started a new conversation Tightening Up Security For An Upcoming App Idea Hey guys, I've got a little system that I plan to work on soon (which when its ready will be released worldwide), but I want to try and make the data that's stored in the server as secure as possible. We will be capturing user details (name, email, password etc.), details of their clients (name, address, email etc.) and then details of jobs for those clients (job number, description etc.). There will also be PDF contracts created that have a digital version of the user & client signatures We will be using Stripe for payments to us, and perhaps offer it as a platform for user's to be paid via Stripe from their clients - so not too much of a worry there as we can leverage Stripes API. I know that I can use Crypt::encrypt and Crypt::decrypt which utilises the key stored in the .env - is this enough security inside the application itself, or are there other things that I should look into? Also, what steps should I take when setting up a server for this kind of application - would something like AWS be a good option? I usually just use linux servers with mysql but looking to use a better stack as I feel like I'm using an archaic setup. Thanks in advance for any advice on this, Andy Started a new conversation Will The "How To Accept Payments" Series Be Updated To Reflect Stripe's Changes? Hey @JeffreyWay , I was browsing twitter this morning and saw that Adam Wathan tweeted about the changes to Stripe.js. Will this be reflected in upcoming episodes of the series? Thanks for all you do on Laracasts :) Andy Replied to Laracasts Refresh omfg this design is so good Replied to Modify Authenticated() Method Inside AuthenticatesUsers.php Class Replied to Modify Authenticated() Method Inside AuthenticatesUsers.php Class Started a new conversation Modify Authenticated() Method Inside AuthenticatesUsers.php Class Hi guys. I'm looking for the correct way to modify the authenticated() method inside the \Illuminate\Foundation\Auth\AuthenticatesUsers.php file. I don't want to just modify this file as the changes won't reflect on the server, as it's inside the vendor folder which is git ignored. I've not had to modify a core method before so don't know the best way to do this? Any advice is appreciated :) Andy Replied to Stripe New Tutorial For 5.2 @darrynsmith Looks like you don't need to wait any longer ;) Started a new conversation Laravel Passport Questions Hey friends, I've set up a central app (let's call this maindomain.com), where I've setup Passport. This site will be where users register to gain access to all other apps I create. To test it out, I've followed Matt Stauffer's blog post to create a client app that will use the user data stored on maindomain.com, let's call this app1.com. I can confirm that my callback and whatnot work fine. When you go to app1.com/login (as per my route) it redirects to maindomain.com and allows you to authorise app1.com to use your login details - beautiful. As per Matt's post, right now it prints the token to the screen. I need to change this so that it saves to the database - I assume I should just create a column on my user's table and store it there? I've tested the token and can access the API routes using PostMan. However, because at the moment I'm creating web apps that all need to use this centralised user system, I'm not sure how I can use a login form to authorise users and allow them access to their dashboard. If user's are logging into app1.com do I send a POST request to maindomain.com? Isn't that going to be a problem with CSRF? I've read the documentation but as this is my first venture into oauth2 I am pretty confused. If you guys can help me out at all I'd seriously appreciate it :) Andy Replied to Is There Any Way To Run `php Artisan` On Forge? Wow holy crap I totally forgot to run composer install. Thanks for that @tykus_ikus, now I feel stupid ;) Replied to Is There Any Way To Run `php Artisan` On Forge? Started a new conversation Is There Any Way To Run `php Artisan` On Forge? I'm spinning up some new servers and on one of the sites I want to put it in maintenance mode - I planned on using php artisan down but forge doesn't allow it saying Could not open input file: artisan. How on earth do I go about doing this? Replied to One Login For Multiple Sites Replied to One Login For Multiple Sites But if you go to another one of the sites (where no login session exists), how would you login? Started a new conversation One Login For Multiple Sites Hey friends, I've got a couple of apps I'm building on Laravel. They are all going to be separate systems, likely on separate servers but part of one "ecosystem". I have a goal of allowing people to sign up on any of the sites that I create, and that login can then be used on any of the other sites. Is this the sort of thing Passport is used for? If so, what's the best way to implement it? Should I pick just one site and make that the "main" user database, or spin up a single app just for holding all the user data? Thanks in advance for your feedback/ideas, Andy Replied to 'Minimize Redirects' When Using SSL On Forge Started a new conversation 'Minimize Redirects' When Using SSL On Forge Hey guys, I've got a couple of sites on Forge that have LetsEncrypt enabled, neither of them are Laravel at the minute. When I run them through they always come back with this warning: Remove the following redirect chain if possible: Is it possible to fix this or is it just not worth worrying about? Andy Replied to What Is The Correct Approach To Adding Extra Fields To Spark's Registration Form? @zaffarsaffee Yes unfortunately, this is based off of experimentation due to lack of documentation in the beginning. Taylor has now added this as a cookbook tutorial on the Spark documentation with the proper implementation Replied to Integrating Socialite With Spark @zanematthew Could well be a better way of doing it than my way. I just tied it into the already existing LoginController but honestly didn't think about the impact of updates. The rest of what I did is incredibly similar to your own except I just put the token for Facebook and Twitter into a column on my Users table. Did you just make your Socialite routes point to your new SocialAuthController and handle all the Socialite stuff there? Seems like a much cleaner way of doing it ;) A lot of my spark work is experimentation at the moment as I couldn't find any good docs on integrating Socialite properly or creating additional registration fields, but Taylor has created a little cookbook for that bit now ;) haha. Replied to Integrating Socialite With Spark Sorry all, have been on holiday in Portugal. I'll go through my files tonight but not a lot is actually different to how you would usually implement Socialite to a Laravel app. I can confirm that Socialite works with Spark, quite nicely too. Andy Replied to What Is The Correct Approach To Adding Extra Fields To Spark's Registration Form?', ]; } Replied to Cannot Find A Way To Make Spark Register Fields Show Errors?', ]; } Started a new conversation Cannot Find A Way To Make Spark Register Fields Show Errors? I've added a new field to my form. But I can't find where to set the errors so that my new username input must be unique. I've spent hours trying to work this out and I'm really quite stuck :( Andy Started a new conversation What Is The Correct Approach To Adding Extra Fields To Spark's Registration Form? Hi all, I'd like to add some extra fields to my Spark registration form but can't find anything in the docs explaining how to do this. Can anyone point me in the right direction on what I need to alter in order for the new fields to work? For example I'd like to add a username field so that users can log in with either their username and password or email and password after signing up. Update Okay so I've worked out that I literally just need to update the view for the form in order to add the field, and then handle the field in the UserRepository, that's done. What I can't quite get my head around is why when the field is empty and I try and submit the form, there are no errors returned for the username field? <!-- Username --> <div class="form-group" : <label class="col-md-4 control-label">Username</label> <div class="col-md-6"> <input type="username" class="form-control" name="username" v- @{{ registerForm.errors.get('username') }} </span> </div> </div> Replied to Integrating Socialite With Spark The answer is no, not really lol. I just used LoginController to control all the Socialite stuff, updated my routes, job done. Started a new conversation Integrating Socialite With Spark Hi all, I've got Socialite working on my "standard" Laravel App. I'm just wondering if the way to integrate Socialite into a Spark based App is exactly the same process? I've noticed that Spark uses a different AuthController file which I think is called LoginController. Apart from that, is there much different? Cheers, Andy Started a new conversation "Sign In" Link Gets Lost In Header When Previously Visited Hey Jeffrey, Just noticed that the contrast seems a little off for the previously visited "Sign In" link in the header. I almost missed it ;) Andy Replied to Reviewing My Routes, Do They Make Sense? @frezno Thanks for that info, I think I'll restructure my routes file today as I wasn't aware that was available haha. @Snapey The logic behind naming is all sorted don't worry. My system is working well, I'm just crap with knowing the best way to do the API. I think your suggestion of /gecko/images/{gecko_name}/upload is good, would you also do something like /gecko/images/{gecko_name} in order to view a gallery? Thanks for your feedback guys, trying to think of a logical route is difficult at times haha. Replied to Reviewing My Routes, Do They Make Sense? Started a new conversation Reviewing My Routes, Do They Make Sense? Hi everyone, I'm still working on my first Laravel app - it's a reptile tracker app. Anyways I'm still trying to understand the best way of doing RESTful routes, below are my current routes: // Weight routes... Route::resource('weights', 'WeightController'); Route::get('weights/{gecko_name}/create', 'WeightController@create'); // Gecko routes... Route::get('geckos', 'GeckoController@index'); Route::resource('gecko', 'GeckoController'); Route::get('gecko/{gecko_name}/view', 'GeckoController@show'); Route::get('gecko/{gecko_name}/edit', 'GeckoController@edit'); So to give you an idea, a couple of the routes could be: app.dev/gecko/Zilly/view app.dev/gecko/Zilly/update app.dev/weights/Zilly/create And I want to implement some image uploads, so I'm thinking the following routes: app.dev/gecko/Zilly/images app.dev/gecko/Zilly/images/upload app.dev/gecko/Zilly/images/delete Have I got my endpoints correct? Does the way I'm doing things make sense or could I make them better/more understandable? I appreciate any help with this stuff, Andy Started a new conversation Submitting Array In Laravel Gives Error - Preg_replace(): Parameter Mismatch, Pattern Is A String While Replacement Is An Array I'm trying to use the following in my application: <div class="form-group"> <label for="genetics">Bell Albino</label> <select name="genetics[]" class="form-control"> <option>N/A</option> <option value="BA">Visual</option> <option value="ba">Recessive</option> </select> </div> <div class="form-group"> <label for="genetics">Tremper Albino</label> <select name="genetics[]" class="form-control"> <option>N/A</option> <option value="TA">Visual</option> <option value="ta">Recessive</option> </select> </div> Which you would assume works okay, however when I try submitting my form, I get the error: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array This is my model, not sure if it will help: <?php namespace App; use Illuminate\Database\Eloquent\Model; class Gecko extends Model { /** * Fillable fields for a gecko * @var array */ protected $fillable = [ 'name', 'aquisition_date', 'morph', 'sex', 'genetics', 'bio', 'bred', 'hatchling', 'clutch', 'user_id' ]; /** * A gecko has many photos * @return \Illuminate\Database\Eloquent\Relations\HasMany; */ public function photos() { return $this->hasMany('App\GeckoPhoto'); } /** * A gecko has many weights * @return \Illuminate\Database\Eloquent\Relations\HasMany; */ public function weights() { return $this->hasMany('App\Weight'); } } The store method: public function store(GeckoRequest $request) { Gecko::create($request->all()); flash()->success('Success!', 'Your gecko has been added to the system'); return redirect()->action('GeckoController@show', [$request['name']]); } The GeckoRequest file: <?php namespace App\Http\Requests; use Auth; use App\Http\Requests\Request; class GeckoRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'morph' => 'required', 'sex' => 'required', 'genetics' => 'required', 'name' => "required|unique:geckos,name,NULL,id,user_id," . \Auth::user()->id ]; } } All it saves into the database is the word Array. I'm sure it's super simple, but I'm unsure on how to fix it Replied to Laravel 5.1 Don't Allow Duplicate Gecko Name For Current User Wonderful, thank you! Started a new conversation Laravel 5.1 Don't Allow Duplicate Gecko Name For Current User I have a situation with my app and I shall do my best to explain what it is i'm trying to do. In my migration, I made my gecko name column unique ( $table->string('name')->unique()). This obviously means that gecko names must be unique across the board for all users - this isn't what I want to do, I want to make sure that the current user cannot use the same name for another gecko. For example: If user 1 makes a gecko called Bob and user 2 made a gecko called Bob that would be fine. If user 1 made a gecko called Bob, and then made another gecko called Bob - This wouldn't be fine. What is the best way/practice to make this work?
https://laracasts.com/@andyjh07
CC-MAIN-2019-43
en
refinedweb
comes with multiple options to format log files created by framework. It can create simple log files, html log files or xml log files also. This this post, I am showing the example code for configuring log4j to produce logs in html format. Step 1) Create a maven java project and update log4j dependencies Follow the steps given in this post related to configuring log4j with maven. Step 2) Configure HTMLLayout in log4j.properties file The HTMLLayout class extends the abstract org.apache.log4j.Layout class and overrides the format() method from its base class to provide HTML-style formatting. This provided the following information to be displayed: - The time elapsed from the start of the application before a particular logging event was generated. - The name of the thread that invoked the logging request. - The level associated with this logging request. - The name of the logger and logging message. - The optional location information for the program file and the line number from which this logging was invoked. # Define the root logger with file appender log4j.rootLogger = DEBUG, HTML # Define the file appender log4j.appender.HTML=org.apache.log4j.FileAppender log4j.appender.HTML.File=application.html # Define the html layout for file appender log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout log4j.appender.HTML.layout.Title=Application logs log4j.appender.HTML.layout.LocationInfo=true log4j.appender.HTML.Threshold=DEBUG Step 3) Configure log4j.properties and test the application package com.howtodoinjava; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class Log4jHTMLLayoutExample { static Logger log = Logger.getLogger(Log4jHTMLLayoutExample.class); public static void main(String[] args) { PropertyConfigurator.configure("log4j.properties"); log.debug("Sample debug message"); log.info("Sample info message"); log.error("Sample error message"); log.fatal("Sample fatal message"); } } Output will be logged in application.html in project root folder: Let me know if any question. Happy Learning !! Feedback, Discussion and Comments Somanath K. Hi Lokesh, How can I customize HTML output file? I want to add the timestamp column in the file, please let me know how can I achieve this? Tulasi Hello Lokesh, I have a questing on the same. Can we change the log4j output format ? like attached Html code with the comment ? Html Code : Application log Log session start time Thu Nov 17 17:45:01 IST 2016 Time Thread Level Category File:Line Expected Result Actual Result 29819 main INFO Testing Cases MyAccountModuleTC.java:52 WS_TC_30: Actual Result WS_TC_30: Expected Result Lokesh Gupta I am not aware of such feature. Gianluca Rosa What I see is that if a I use newline (\n) or any html tag they are skipped or printed out as they are (ex. for html tag) Is there a way to print out the messages with formatted text ? Lokesh As far I see, org.apache.log4j.HTMLLayout class is responsible for removing the formatting and uses org.apache.log4j.helpers.Transform.escapeTags() method for removing the formatting from log messages. It does not check any configuration option, so I believe that using configuration it’s not possible. A valid work around is to rewrite “org.apache.log4j.HTMLLayout” class again as per your need (basically comment the lines where escapeTags() has been called), generate the .class file, and put this .class file in your class path. Class loader will pickup the .class file from class-path and will use it for writing the logs. Milind Hello Lokesh, Following is my log4j property file & I am getting : ERROR: invalid console appender config detected, console stream is looping=D:\applicationLog Can you please suggest that what I need anymore to output in CONSOLE as well as in LOG FILE. Milind Hello Lokesh, I have a questing on the same. Can we change the log4j output format ? I need to add some parameter while calling ‘log.error()’ method like userdefined error code. & its description. Is it possible ? Lokesh Gupta Sure you can. It’s code after all. Explore the sourcecode and identify the classes which you need to override.
https://howtodoinjava.com/log4j/how-to-create-logs-in-html-format-using-log4j/
CC-MAIN-2019-43
en
refinedweb
Using GrabCut with OpenCv 3.1.0 I'm using opencv3 grabcut function with initial mask guessing ( cv2.GC_INIT_WITH_MASK), but for some reason I'm always getting the same output as the original mask. I'm running with python 3.5 and opencv 3.1.0. I've attached some sample code below. The results are attached as image. Instead of getting the full shape as grabcut output, I'm getting just the original mask, no matter which number of iterations or if I'm using real images instead of synthetic ones. What can be the cause for those strange results? import cv2 import numpy as np import matplotlib.pyplot as plt img = np.zeros((200,200, 3), 'uint8') mask = np.zeros((200,200), 'uint8') cv2.circle(img, (100,100), 50, (255,255,255), -1); cv2.circle(mask, (100,100), 5, 1, -1) bgdModel = np.zeros((1,65),np.float64) fgdModel = np.zeros((1,65),np.float64) out_mask, out_bgdModel, out_fgdModel = cv2.grabCut(img, mask, None, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_MASK) print('opencv', cv2.__version__) # opencv 3.1.0 fig,ax = plt.subplots(1,3) ax[0].imshow(img) ax[1].imshow(mask) ax[2].imshow(out_mask) ax[0].set_title('original') ax[1].set_title('mask') ax[2].set_title('output') plt.show() Use grabcut constant. What does it mean 1 in cv2.circle(mask, (100,100), 5, 1, -1)? I I think 1 is cv.GC_FGD. You must fill mask withcv. GC_PR_BGD or cv.GC_PR_FGD for unknown pixels and cv.GC_BGD for pixels belong to background (it is not necessary but it helps) .Algorithm will process all pixels with GC_PR. You can find an example here Please update your code to master or opencv 3.4.1 Thanks, LBerger. The problem was indeed with the inititation of the mask. The code below fix that.
https://answers.opencv.org/question/194130/using-grabcut-with-opencv-310/
CC-MAIN-2019-43
en
refinedweb
436 of file Progress.h. #include <Progress.h> Prepare existing progress object for subtask. Definition at line 442 of file Progress.h. References Rose::Progress::Report::completion. Create progress object for subtask. Definition at line 452 of file Progress.h. References Rose::Progress::Report::completion. Clean up subtask progress. Definition at line 460 of file Progress.h. Progress object being used. This returns one of the following values: Definition at line 472 of file Progress.h. Cancel all cleanup operations. If called, then the destructor will do nothing other than possibly releasing a reference to the progress object supplied to or created by the constructor. Definition at line 480 of file Progress.h.
http://rosecompiler.org/ROSE_HTML_Reference/classRose_1_1ProgressTask.html
CC-MAIN-2019-43
en
refinedweb
This document is for Kombu's development version, which can be significantly different from previous releases. Get the stable docs here: 4.5. Getting Started¶ - Version 4.6.5 - Web - Download - Source - Keywords messaging, amqp, rabbitmq, redis, mongodb, python, queue About¶ Kombu is a messaging library for Python. protocol for message orientation, queuing, routing, reliability and security, for which the RabbitMQ messaging server is the most popular implementation. Features¶ Allows application authors to support several message server solutions by using pluggable transports. AMQP transport using the py-amqp, librabbitmq, or qpid-python, Amazon SQS, Azure Storage Queues, Azure Service Bus, ZooKeeper, SoftLayer MQ and Pyro.¶ - 1(1,2,3,4. - 4 AMQP Message/Queue TTL support depends on broker implementation. Documentation¶ Kombu is using Sphinx, and the latest documentation can be found here: Quick overview¶ from kombu import Connection, Exchange, Queue media_exchange = Exchange('media', 'direct', durable=True) video_queue = Queue('video', exchange=media_exchange, routing_key='video') def process_media(body, message): print body message.ack() # connections with Connection('amqp://guest:[email protected]//'). Terminology¶”. Installation¶ Getting Help¶ Mailing list¶ Join the carrot-users mailing list. Bug tracker¶ If you have any suggestions, bug reports or annoyances please report them to our issue tracker at Contributing¶ Development of Kombu happens at Github: You are highly encouraged to participate in the development. If you don’t like Github (for some reason) you’re welcome to send regular patches.
https://docs.celeryproject.org/projects/kombu/en/stable/introduction.html
CC-MAIN-2019-43
en
refinedweb
§Handling form submission Before you start with Play forms, read the documentation on the Play enhancer. The Play enhancer generates accessors for fields in Java classes for you, so that you don’t have to generate them yourself. You may decide to use this as a convenience. All the examples below show manually writing accessors for your classes. §Enabling/Disabling the forms module By default, Play includes the Java forms module ( play-java-forms) when enabling the PlayJava SBT plugin, so there is nothing to enable if you already have enablePlugins(PlayJava) on your project. The forms module is also available in PlayImport as javaForms, which can be used with libraryDependencies += javaForms in your build.sbt. Note: If you are not using forms, you can remove the forms dependency by using the PlayMinimalJavaSBT plugin instead of PlayJava. This also allows you to remove several transitive dependencies only used by the forms module, including several Spring modules and the Hibernate validator. §Defining a form The play.data package contains several helpers to handle HTTP form data submission and validation. The easiest way to handle a form submission is to define a play.data.Form that wraps an existing class: import play.libs.Files.TemporaryFile; import play.mvc.Http.MultipartFormData.FilePart; public class User { protected String email; protected String password; protected FilePart<TemporaryFile> profilePicture; public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public FilePart<TemporaryFile> getProfilePicture() { return profilePicture; } public void setProfilePicture(FilePart<TemporaryFile> pic) { this.profilePicture = pic; } } The above form defines an password text field and a profilePicture file input field, meaning the corresponding HTML form has to be defined with the multipart/form-data encoding to be able to upload the file. As you can see, by default, you have to define getter and setter methods so Play is able to access the Form fields. You can however also enable “direct field access” (for all forms) by setting play.forms.binding.directFieldAccess = true in conf/application.conf. In this mode Play will ignore the getter and setter methods and will try to directly access the fields: import play.libs.Files.TemporaryFile; import play.mvc.Http.MultipartFormData.FilePart; public class User { public String email; public String password; public FilePart<TemporaryFile> profilePicture; } Note: When using “direct field access” and a field is not accessible to Play during form binding (e.g. if a field or the class containing the field is not defined as public) Play will try to make a field accessible via reflection by calling field.setAccessible(true)internally. Depending on the Java version (8+), JVM and the Security Manager settings that could cause warnings about illegal reflective access or, in the worst case, throw a SecurityException To wrap a class you have to inject a play.data.FormFactory into your Controller which then allows you to create the form: Form<User> userForm = formFactory.form(User.class); Instead of enabling “direct field access” for all forms, you can enable it only for specific ones: Form<User> userForm = formFactory.form(User.class).withDirectFieldAccess(true); Note: The underlying binding is done using Spring data binder. This form can generate a User result value from a HashMap<String,String> for the text data and from a Map<String, FilePart<?>> for the file data: Map<String,String> textData = new HashMap<>(); textData.put("email", "[email protected]"); textData.put("password", "secret"); Map<String, FilePart<?>> files = new HashMap<>(); files.put("profilePicture", myProfilePicture); User user = userForm.bind(lang, attrs, textData, files).get(); If you have a request available in the scope, you can bind directly from the request content: User user = userForm.bindFromRequest(request).get(); §Defining constraints You can define additional constraints that will be checked during the binding phase using JSR-380 (Bean Validation 2.0) annotations: public class User { @Required protected String email; protected String password; public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } Tip: The play.data.validation.Constraintsclass contains several built-in validation annotations. All of these constraint annotations are defined as @Repeatable. This lets you, for example, reuse the same annotation on the same element several times but each time with different groups. For some constraints however it makes sense to let them repeat itself anyway, like @ValidateWith/ @ValidatePayloadWithfor example. In the Advanced validation section further below you will learn how to handle concerns like cross field validation, partial form validation or how to make use of injected components (e.g. to access a database) during validation. §Handling binding failure Of course if you can define constraints, then you need to be able to handle the binding errors. if (userForm.hasErrors()) { return badRequest(views.html.form.render(userForm)); } else { User user = userForm.get(); return ok("Got user " + user); } Typically, as shown above, the form simply gets passed to a template. Global errors can be rendered in the following way: @if(form.hasGlobalErrors) { <p class="error"> @for(error <- form.globalErrors) { <p>@error.format(messages)</p> } </p> } Errors for a particular field can be rendered in the following manner with error.format: @for(error <- form("email").errors) { <p>@error.format(messages)</p> } Note that error.format takes messages() as an argument – this is an play.18n.Messages instance defined in JavaI18N.Handling a form with dynamic fields You can use a DynamicForm if you need to retrieve data from an html form with dynamic fields: public Result hello(Http.Request request) { DynamicForm requestData = formFactory.form().bindFromRequest(request); String firstname = requestData.get("firstname"); String lastname = requestData.get("lastname"); return ok("Hello " + firstname + " " + lastname); } §Register a custom DataBinder In case you want to define a mapping from a custom object to a form field string and vice versa you need to register a new Formatter for this object. You can achieve this by registering a provider for Formatters which will do the proper initialization. For an object like JavaTime’s LocalTime it could look like this: import java.text.ParseException; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import java.time.LocalTime; import play.data.format.Formatters; import play.data.format.Formatters.SimpleFormatter; import play.i18n.MessagesApi; @Singleton public class FormattersProvider implements Provider<Formatters> { private final MessagesApi messagesApi; @Inject public FormattersProvider(MessagesApi messagesApi) { this.messagesApi = messagesApi; } @Override public Formatters get() { Formatters formatters = new Formatters(messagesApi); LocalTime.of(hour, min); } @Override public String print(LocalTime localTime, Locale l) { return localTime.format(DateTimeFormatter.ofPattern("HH:mm")); } }); return formatters; } } After defining the provider you have to bind it: import com.google.inject.AbstractModule; import play.data.format.Formatters; public class FormattersModule extends AbstractModule { @Override protected void configure() { bind(Formatters.class).toProvider(FormattersProvider.class); } } Finally you have to disable Play’s default FormattersModule and instead enable your module in application.conf: play.modules.enabled += "com.example.FormattersModule" play.modules.disabled += "play.data.format.FormattersModule" When the binding fails an array of errors keys is created, the first one defined in the messages file will be used. This array will generally contain: ["error.invalid.<fieldName>", "error.invalid.<type>", "error.invalid"] The errors keys are created by Spring DefaultMessageCodesResolver, the root “typeMismatch” is replaced by “error.invalid”. §Advanced validation Play’s built-in validation module is using Hibernate Validator under the hood. This means we can take advantage of features defined in the JSR-380 (Bean Validation 2.0). The Hibernate Validator documentation can be found here. §Cross field validation To validate the state of an entire object we can make use of class-level constraints. To free you from the burden of implementing your own class-level constraint(s), Play out-of-the-box already provides a generic implementation of such constraint which should cover at least the most common use cases. Now let’s see how this works: To define an ad-hoc validation, all you need to do is annotate your form class with Play’s provided class-level constraint ( @Validate) and implement the corresponding interface (in this case Validatable<String>) - which forces you to override a validate method: import play.data.validation.Constraints; import play.data.validation.Constraints.Validate; import play.data.validation.Constraints.Validatable; @Validate public class User implements Validatable<String> { @Constraints.Required protected String email; protected String password; @Override public String validate() { if (authenticate(email, password) == null) { // You could also return a key defined in conf/messages return "Invalid email or password"; } return null; } // getters and setters } The message returned in the above example will become a global error. Errors are defined as play.data.validation.ValidationError. Also be aware that in this example the validate method and the @Constraints.Required constraint will be called simultaneously - so the validate method will be called no matter if @Constraints.Required was successful or not (and vice versa). You will learn how to introduce an order later on. As you can see the Validatable<T> interface takes a type parameter which determines the return type of the validate() method. So depending if you want to be able to add a single global error, one error (which could be global as well) or multiple (maybe global) errors to a form via validate(), you have to use either a String, a ValidationError or a List<ValidationError> as type argument. Any other return types of the validate method will be ignored by Play. If validation passes inside a validate() method you must return null or an empty List. Returning any other non- null value (including empty string) is treated as failed validation. Returning a ValidationError object may be useful when you have additional validations for a specific field: import play.data.validation.Constraints.Validate; import play.data.validation.Constraints.Validatable; import play.data.validation.ValidationError; @Validate public static class LoginForm implements Validatable<ValidationError> { // fields, getters, setters, etc. @Override public ValidationError validate() { if (authenticate(email, password) == null) { // Error will be displayed for the email field: return new ValidationError("email", "Invalid credentials"); } return null; } } You can add multiple validation errors by returning List<ValidationError>. This can be used to add validation errors for a specific field, global errors or even a mix of these options: import play.data.validation.Constraints.Validate; import play.data.validation.Constraints.Validatable; import play.data.validation.ValidationError; import java.util.List; @Validate public static class SignUpForm implements Validatable<List<ValidationError>> { // fields, getters, setters, etc. @Override public List<ValidationError> validate() { final List<ValidationError> errors = new ArrayList<>(); if (authenticate(email, password) == null) { // Add an error which will be displayed for the email field: errors.add(new ValidationError("email", "Access denied")); // Also add a global error: errors.add(new ValidationError("", "Form could not be submitted")); } return errors; } } As you can see, when using an empty string as the key of a ValidationError it becomes a global error. One more thing: Instead of writing out error messages you can use message keys defined in conf/messages and pass arguments to them. When displaying the validation errors in a template the message keys and it’s arguments will be automatically resolved by Play: // Global error without internationalization: new ValidationError("", "Errors occurred. Please check your input!"); // Global error; "validationFailed" should be defined in `conf/messages` - taking two arguments: new ValidationError("", "validationFailed", Arrays.asList(arg1, arg2)); // Error for the email field; "emailUsedAlready" should be defined in `conf/messages` - taking the email as argument: new ValidationError("email", "emailUsedAlready", Arrays.asList(email)); §Partial form validation via groups When a user submits a form there can be use cases where you don’t want to validate all constraints at once but just some of them. For example think about a UI wizard where in each step only a specified subset of constraints should get validated. Or think about the sign-up and the login process of a web application. Usually for both processes you want the user to enter an email address and a password. So these processes would require almost the same forms, except for the sign-up process the user also has to enter a password confirmation. To make things more interesting let’s assume a user can also change his user data on a settings page when he is logged in already - which would need a third form. Using three different forms for such a case isn’t really a good idea because you would use the same constraint annotations for most of the form fields anyway. What if you have defined a max-length constraint of 255 for a name field and then want to change it to a limit of just 100? You would have to change this for each form. As you can imagine this would be error prone in case you forget to update one of the forms. Luckily we can simply group constraints: import play.data.validation.Constraints; import play.data.validation.Constraints.Validate; import play.data.validation.Constraints.Validatable; import play.data.validation.ValidationError; import javax.validation.groups.Default; @Validate(groups = {SignUpCheck.class}) public class PartialUserForm implements Validatable<ValidationError> { @Constraints.Required(groups = {Default.class, SignUpCheck.class, LoginCheck.class}) @Constraints.Email(groups = {Default.class, SignUpCheck.class}) private String email; @Constraints.Required private String firstName; @Constraints.Required private String lastName; @Constraints.Required(groups = {SignUpCheck.class, LoginCheck.class}) private String password; @Constraints.Required(groups = {SignUpCheck.class}) private String repeatPassword; @Override public ValidationError validate() { if (!checkPasswords(password, repeatPassword)) { return new ValidationError("repeatPassword", "Passwords do not match"); } return null; } // getters and setters } The LoginCheck group are defined as two interfaces: public interface SignUpCheck { } public interface LoginCheck { } For the sign-up process we simply pass the form(...) method: Form<PartialUserForm> form = formFactory().form(PartialUserForm.class, SignUpCheck.class).bindFromRequest(request); In this case the email address is required and has to be a valid email address, both the password and the password confirmation are required and the two passwords have to be equal (because of the @Validate annotation which calls the validate method). But we don’t care about the first name and last name - they can be empty or we could even exclude these input fields in the sign up page. For the login process we just pass the LoginCheck group instead: Form<PartialUserForm> form = formFactory().form(PartialUserForm.class, LoginCheck.class).bindFromRequest(request); Now we only require the email address and the password to be entered - nothing more. We don’t even care about if the email is valid. You probably wouldn’t display any of the other form fields to the user because we don’t validate them anyway. Imagine we also have a page where the user can change the user data (but not the password): Form<PartialUserForm> form = formFactory().form(PartialUserForm.class, Default.class).bindFromRequest(request); Which is exactly the same as: Form<PartialUserForm> form = formFactory().form(PartialUserForm.class).bindFromRequest(request); In this case following constraints will be validated: The email address is required and has to be valid plus the first name and last name are required as well - that is because if a constraint annotation doesn’t explicitly define a group then the Default group is used. Be aware we don’t check any of the password constraints: Because they explicitly define a group attribute but don’t include the Default group they won’t be taken into account here. As you can see in the last example, when only passing the group javax.validation.groups.Default you can omit it - because it’s the default anyway. But as soon you pass any other group(s) you would also have to pass the Default group explicitly if you want any of it’s fields taken into account during the validation process. Tip: You can pass as many groups as you like to the form(...)method (not just one). Just to be clear: These groups will then be validated all at once - not one after the other. For advanced usage a group of constraints can include another group. You can do that using group inheritance. §Defining the order of constraint groups You can validate groups in sequences. This means groups will be validated one after another - but the next group will only be validated if the previous group was validated successfully before. (However right now it’s not possible to determine the order of how constraints will be validated within a group itself - this will be part of a future version of Bean Validation) Based on the example above let’s define a group sequence: import javax.validation.GroupSequence; import javax.validation.groups.Default; @GroupSequence({ Default.class, SignUpCheck.class, LoginCheck.class }) public interface OrderedChecks { } Now we can use it: Form<PartialUserForm> form = formFactory().form(PartialUserForm.class, OrderedChecks.class).bindFromRequest(request); Using this group sequence will first validate all fields belonging to the Default group (which again also includes fields that haven’t defined a group at all). Only when all the fields belonging to the Default group pass validation successfully, the fields belonging to the Using a group sequence is especially a good practice when you have a validate method which queries a database or performs any other blocking action: It’s not really useful to execute the method at all if the validation fails at it’s basic level (email is not valid, number is a string, etc). In such a case you probably want the validate be called only after checking all other annotation-based constraints before and only if they pass. A user, for example, who signs up should enter a valid email address and only if it is valid a database lookup for the email address should be done afterwards. §Passing payloads to validators If needed, you can also pass a ValidationPayload object - which contains useful information sometimes needed for a validation process - to a validate method. To pass such a payload.ValidationError; import play.data.validation.ValidationPayload; import play.i18n.Lang; import play.i18n.Messages; @ValidateWithPayload public class ChangePasswordForm implements ValidatableWithPayload<ValidationError> { // fields, getters, setters, etc. @Override public ValidationError validate(ValidationPayload payload) { Lang lang = payload.getLang(); Messages messages = payload.getMessages(); Map<String, Object> ctxArgs = payload.getArgs(); TypedMap attrs = payload.getAttrs(); Config config = payload.getConfig(); // ... } } §Custom class-level constraints with DI support Sometimes you need more sophisticated validation processes. E.g. when a user signs up you want to check if his email address already exists in the database and if so validation should fail. Because constraints support both runtime Dependency Injection and , we can easily create our own custom (class-level) constraint which gets a Database object injected - which we can use later in the validation process. Of course you can also inject other components like MessagesApi, JPAApi, etc. Note: You only need to create one class-level constraint for each cross concern. For example, the constraint we will create in this section is reusable and can be used for all validation processes where you need to access the database. The reason why Play doesn’t provide any generic class-level constraints with dependency injected components is because Play doesn’t know which components you might have enabled in your project. First let’s set up the interface with the validate method we will implement in our form later. You can see the method gets passed a Database object (Checkout the database docs): - Without Payload import play.db.Database; public interface ValidatableWithDB<T> { public T validate(final Database db); } - With Payload import play.db.Database; import play.data.validation.Constraints.ValidationPayload; public interface ValidatableWithDB<T> { public T validate(final Database db, final ValidationPayload payload); } We also need the class-level annotation we put on our form class: import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Repeatable; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target({TYPE, ANNOTATION_TYPE}) @Retention(RUNTIME) @Repeatable(ValidateWithDB.List.class) @Constraint(validatedBy = ValidateWithDBValidator.class) public @interface ValidateWithDB { String message() default "error.invalid"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; /** * Defines several {@code @ValidateWithDB} annotations on the same element. */ @Target({TYPE, ANNOTATION_TYPE}) @Retention(RUNTIME) public @interface List { ValidateWithDB[] value(); } } Finally this is how our constraint implementation looks like: - Without Payload import javax.inject.Inject; import javax.validation.ConstraintValidatorContext; import play.data.validation.Constraints.PlayConstraintValidator; import play.db.Database; public class ValidateWithDBValidator implements PlayConstraintValidator<ValidateWithDB, ValidatableWithDB<?>> { private final Database db; @Inject public ValidateWithDBValidator(final Database db) { this.db = db; } @Override public void initialize(final ValidateWithDB constraintAnnotation) { } @Override public boolean isValid(final ValidatableWithDB<?> value, final ConstraintValidatorContext constraintValidatorContext) { return reportValidationStatus(value.validate(this.db), constraintValidatorContext); } } - With Payload import javax.inject.Inject; import javax.validation.ConstraintValidatorContext; import play.data.validation.Constraints.PlayConstraintValidator; import play.data.validation.Constraints.PlayConstraintValidatorWithPayload; import play.data.validation.Constraints.ValidationPayload; import play.db.Database; public class ValidateWithDBValidator implements PlayConstraintValidatorWithPayload<ValidateWithDB, ValidatableWithDB<?>> { private final Database db; @Inject public ValidateWithDBValidator(final Database db) { this.db = db; } @Override public void initialize(final ValidateWithDB constraintAnnotation) { } @Override public boolean isValid(final ValidatableWithDB<?> value, final ValidationPayload payload, final ConstraintValidatorContext constraintValidatorContext) { return reportValidationStatus(value.validate(this.db,, where you only need to pass it on to the reportValidationStatusmethod however anyway. As you can see we inject the Database object into the constraint’s constructor and use it later when calling validate. When using runtime Dependency Injection, Guice will automatically inject the Database object, but for compile-time Dependency Injection you need to do that by yourself: import play.ApplicationLoader; import play.BuiltInComponentsFromContext; import play.data.FormFactoryComponents; import play.data.validation.MappedConstraintValidatorFactory; import play.db.DBComponents; import play.db.HikariCPComponents; import play.filters.components.NoHttpFiltersComponents; import play.routing.Router; public class ValidateWithDBComponents extends BuiltInComponentsFromContext implements FormFactoryComponents, DBComponents, HikariCPComponents, NoHttpFiltersComponents { public ValidateWithDBComponents(ApplicationLoader.Context context) { super(context); } @Override public Router router() { return Router.empty(); } @Override public MappedConstraintValidatorFactory constraintValidatorFactory() { return new MappedConstraintValidatorFactory() .addConstraintValidator( ValidateWithDBValidator.class, new ValidateWithDBValidator(database("default")) ); } } Note: you don’t need to create the databaseinstance by yourself, it is already defined in the implemented interfaces. This way, your validator will be available when necessary. When writing your own class-level constraints you can pass following objects to the reportValidationStatus method: A ValidationError, a List<ValidationError> or a String (handled as global error). Any other objects will be ignored by Play. Finally we can use our custom class-level constraint to validate a form: - Without Payload import play.data.validation.Constraints; import play.data.validation.ValidationError;) { // Access the database to check if the email already exists if (User.byEmail(email, db) != null) { return new ValidationError("email", "This e-mail is already registered."); } return null; } // getters and setters } - With Payload import play.data.validation.Constraints; import play.data.validation.ValidationError; import play.data.validation.Constraints.ValidationPayload;, final ValidationPayload payload) { // Access the database to check if the email already exists if (User.byEmail(email, db) != null) { return new ValidationError("email", "This e-mail is already registered."); } return null; } // getters and setters } Tip: You might have recognized that you could even implement multiple interfaces and therefore add multiple class-level constraint annotations on your form class. Via validation groups you could then just call the desired validate method(s) (or even multiple at once during one validation process). Next: Using the form template helpers
https://www.playframework.com/documentation/2.7.1/JavaForms
CC-MAIN-2019-43
en
refinedweb
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <rtl.h> void os_dly_wait ( U16 delay_time ); /* Length of time to pause */ The os_dly_wait function pauses the calling task. The argument delay_time specifies the length of the pause and is measured in number of system_ticks. You can set the delay_time to any value between 1 and 0xFFFE. The os_dly_wait function is in the RL-RTX library. The prototype is defined in rtl.h. Note The os_dly_wait function does not return any value. os_itv_set, os_itv_wait, os_time_get #include <rtl.h> __task void task1 (void) { .. os_dly_wait .
http://www.keil.com/support/man/docs/rlarm/rlarm_os_dly_wait.htm
CC-MAIN-2019-43
en
refinedweb
How To: Add a Payment Method Prerequisite ReadingPrerequisite Reading OverviewOverview In general, to add a payment method you must do the following: - Create a plugin or modify an existing one - Extend the GraphQL API with mutations, queries, and types specific to your payment method - Create and provide functions for supported payment actions - Add routes for callback URLs if necessary - Create a React component for collecting any necessary payment data - Create a React component for operators to enter and edit necessary settings for your payment method - Register the method definition, its functions, the routes, and the React components using your plugin's registerPlugincall There are two included plugins (in /imports/plugins/included) that provide payment methods, which you can look at for inspiration: - payments-example - payments-stripe Extend the GraphQL APIExtend the GraphQL API There are generally two things you need to define in a GraphQL schema: - The payment method name - The payment data type Define the payment method nameDefine the payment method name Add this in your plugin's schema.graphql file: extend enum PaymentMethodName { myMethod } Define the payment data inputDefine the payment data input Define what the data collected and stored by your method looks like. Add this in your plugin's schema.graphql file: "Data for my custom payment. This can be anything you want." type MyPaymentMethodPaymentData { "Some info I need to process the payment" cardNumber: String! } # This is the important part. Add your type to the PaymentData union extend union PaymentData = MyPaymentMethodPaymentData Payment React ComponentPayment React Component This is shown during checkout. It can be whatever you want, so long as it ends up providing the information you need to request an authorization from the payment provider. It could also just be a collection of information necessary to later create and send an invoice. This component is then used as the InputComponent property of your payment method in the paymentMethods array that you pass to the PaymentsCheckoutAction component. You may want to start with a provided InputComponent, such as ExampleIOUPaymentForm and modify it to meet your needs. Action FunctionsAction Functions Your plugin must define functions for the following actions: - authorize - capture Your plugin must define functions for the following actions only if it supports refunding: - refund - list refunds authorize functionauthorize function This function must authorize the proposed payment for the proposed amount and then return a payment. It can be an async function. The signature of this function is (context, input), where input has the following structure: { amount, billingAddress, shopId, paymentData // This is whatever data your checkout UI component collects } You are expected to return a valid payment object similar to this: { _id: Random.id(), address: billingAddress, amount, createdAt: new Date(), data: { fullName, gqlType: "ExampleIOUPaymentData" // GraphQL union resolver uses this }, displayName: `IOU from ${fullName}`, method: METHOD, mode: "authorize", name: PAYMENT_METHOD_NAME, paymentPluginName: PACKAGE_NAME, processor: PROCESSOR, riskLevel: "normal", shopId, status: "created", transactionId: Random.id(), transactions: [] } Be sure that: - the modeis "authorize" - the statusis "created" - the namematches the method name you specified in registerPluginand in the GraphQL PaymentMethodNameenum amountmatches what was passed in - All required properties are present If you are unable to authorize the payment, the function should throw an error with a helpful message that is shown to the shopper in the checkout UI. capture functioncapture function This function must capture an authorized payment if it hasn't been captured yet. It receives a PaymentMethod object as its only argument. For some payment methods, this might do nothing. The signature of this function is (context, payment), where payment is what your authorize function returned. The function is expected to return an object with result property, and optional response property. It can be an async function. - If you successfully capture the payment, return { saved: true, response }, where responseis optional but can contain a full third-party API response or anything else you want to be saved in the payment transactionsarray. - If there is an error capturing the payment, return { saved: false, errorCode, errorMessage }, where errorCodeis a unique string your UI or reporting might understand and errorMessageis a helpful message to be shown in the operator UI. - If the payment has already been captured, return { saved: false, isAlreadyCaptured: true } - Try to avoid your function throwing any uncaught errors refund functionrefund function This function must create a refund in your external payment system. It can be an async function. If your payment method can't be refunded, you do not need to provide this function. The function signature is (context, payment, amount), where amount is the requested refund amount and payment is what your authorize function returned. - If you successfully refund the requested amount from the payment, return { saved: true, response }, where responseis optional but can contain a full third-party API response or anything else you want to be saved in the payment transactionsarray. - If there is an error refunding the payment, return { saved: false, error }, where erroris a helpful message to be shown in the operator UI. - Try to avoid your function throwing any uncaught errors list refunds functionlist refunds function This function must query your external payment system and return an array of refund objects for a single payment. It can be an async function. If your payment method can't be refunded, you do not need to provide this function. The function signature is (context, payment), where payment is what your authorize function returned. - If you successfully query for the refund list, return it in an array. Each object in the array must have type, amount, created, currency, and rawproperties. - If there is an error listing refunds, log it and return an empty array. - Try to avoid your function throwing any uncaught errors RoutingRouting If your payment plugin needs to register additional client-side routes (for example where you go to a provider and get a token that gets saved) you can look at the PayPal express implementation which adds additional routes to register.js for storing the token. RegistrationRegistration Everything needs to be registered to be seen by Reaction core. GraphQLGraphQL If you followed How To: Create a new GraphQL mutation, your GraphQL should already be registered. Payment methodsPayment methods Here's an example of how to register the payment methods your plugin provides: import stripeCapturePayment from "./util/stripeCapturePayment"; import stripeCreateAuthorizedPayment from "./util/stripeCreateAuthorizedPayment"; import stripeCreateRefund from "./util/stripeCreateRefund"; import stripeListRefunds from "./util/stripeListRefunds"; export default async function register(app) { await app.registerPlugin({ label: "Stripe", name: "reaction-stripe", icon: "fa fa-cc-stripe", paymentMethods: [{ name: "stripe_card", displayName: "Stripe Card", canRefund: true, functions: { capturePayment: stripeCapturePayment, createAuthorizedPayment: stripeCreateAuthorizedPayment, createRefund: stripeCreateRefund, listRefunds: stripeListRefunds } }], // other props }); } Each object in paymentMethods must have a name and displayName. The displayName is used in the operator UI, in the Payment panel, where each registered method is shown and can be toggled on or off. It is also sent to storefront clients with the availablePaymentMethods GraphQL query response, so it should be what you want shown in the checkout UI (although storefront client UI code could choose to display some other name). The name is the key used to identify a payment as being of this method. The name property of the payment object returned from your authorize function must exactly match this. The canRefund option is true by default, but if your method does not support refunds, you must set canRefund: false in its config. Settings UISettings UI If your plugin needs any settings that it will not get from environment variables, register the React component in the registry array: export default async function register(app) { await app.registerPlugin({ registry: [ { label: "Acme Payments", provides: ["paymentSettings"], container: "dashboard", template: "AcmePaymentsPluginSettings" } ] // other props }); } The label is shown in the operator UI to group the settings for each payment plugin. The provides property must be an array containing "paymentSettings". Set template to the name of your React component, which you must register with registerComponent in client code. With the 2.0 release, we now recommend customizing a storefront starter kit to build your storefront. In src/custom/paymentMethods.js, you will see a paymentMethods array. Modify this to add your payment method and remove any others you do not need.
https://docs.reactioncommerce.com/docs/how-to-create-a-payment-provider
CC-MAIN-2019-43
en
refinedweb
USBSerial Table of Contents Mbed OS 2 and Mbed OS 5 This is the handbook for Mbed OS 2. If you’re working with Mbed OS 5, please see the Mbed OS 5 documentation. For the latest information about Serial, please see The Windows Serial Driver. The USBSerial interface is used to emulate a serial port over USB. You can use this serial port as an extra serial port or as a debug solution. It's also a great solution to easily communicate between your mbed and a computer. The USB connector should be attached to - p31 (D+), p32 (D-) and GND for the LPC1768 and the LPC11U24 - The on-board USB connector of the FRDM-KL25Z Driver required on Windows! On Windows, you need a configuration file. You can download this archive containing a .inf file. Extract it. When you plug your USBSerial serial device, Windows will try to find an existing driver for it without success. After this step, go into the device manager to find the unknown device: - Right click on the device - Update driver software - Click on "Browse my computer for driver software" - Indicate the path of serial.inf extracted previously and click next. - Accept the warning and you should have a virtual port (called Mbed Virtual Serial Port in device manager) over USB! As product_id and vendor_id are hardcoded in the .inf file, if you don't want to use default values, you will have to change them in your program AND in the .inf file. Hello World¶ Import program API¶ More example¶ In this example, the program waits a line on the virtual serial port. When it receives a line, it sends it to the usual mbed serial port (the one used to flash a new program) and to the virtual one. USBSerial echo #include "mbed.h" #include "USBSerial.h" //Virtual serial port over USB USBSerial serial; Serial pc(USBTX, USBRX); int main(void) { uint8_t buf[128]; while(1) { serial.scanf("%s", buf); serial.printf("recv: %s", buf); pc.printf("recv: %s\r\n", buf); } }
https://os.mbed.com/handbook/USBSerial
CC-MAIN-2019-43
en
refinedweb
Invoking a business rule from a processJohn Santoro Dec 27, 2013 1:25 PM I have a simple process with a simple rule, but I cannot get it to trigger. The process does this: Start -> Human Task -> Rule -> Gateway ... How can I get the process data to the rule? I know via a script activity that my process data (e.g., ProcessDataType) has values. For the rule task, I mapped my process data to an input and output variable of type ProcessDataType, but in my rule my when does not get triggered even as: when $data : ProcessDataType() then System.out.println("this rule has been triggered"); I can invoke the rule only if my when is "eval(true)", so I know that the rule is there. What step am I missing? 1. Re: Invoking a business rule from a processZahid Ahmed Prs Dec 30, 2013 2:05 AM (in response to John Santoro) Hi Santoro, You need to follow these steps if u want process data in rules. IN - Code Apporach 1 U need to put process instance in working memory so that the rule can evaluate the conditions in when part. a. Do this In a script task just after start node kcontext.getKnowledgeRuntime().insert(kcontext.getProcessInstance()) Approach 2 Or Register a Process event listener, and in afterProcessStarted() event add this line session.insert(event.getProcessInstance()) IN - RULES Sample Rule 1 : import org.drools.runtime.process.WorkflowProcessInstance; $process: WorkflowProcessInstance() eval(Integer.parseInt((String)$process.getVariable("piAgeVariable")) > 30) then ......... Notes : 1. I am not sure about JBPM-6, but in JBPM 5.4 if u don't fire the rule when u enter the node, then rule is not fired. Resolution to this is Be sure that u have placed this line just before u enter the rules node. ksession.fireAllRules(); . 2. Keep one thing in mind to retract the process instaces properly after rule node is executed using the kcontext.getKnowledgeRuntime().retract() or the eventListener approach. Else this process instance will remain in working memory and will be part of rules evaluation when anyother JBPM process instance triggers fireAllRules(). 2. Re: Invoking a business rule from a processMaciej Swiderski Jan 2, 2014 4:16 AM (in response to Zahid Ahmed Prs) 3. Re: Invoking a business rule from a processJohn Santoro Jan 3, 2014 2:01 PM (in response to Maciej Swiderski) Maciej, Thank you for the blog. I was able to reproduce your process and make my own. My problem was that I named a project with mixed case, but the forms and process did not behave properly unless I used all lower case (e.g., my package was "MixedCase" but I had to refer to it as "org.jbpm.mixedcase".
https://developer.jboss.org/thread/235751
CC-MAIN-2018-17
en
refinedweb
RuntimeException subclass annotated with @ApplicationException(rollback=false) still rolls back ifJohn Francis Mar 25, 2014 9:23 AM I am using Jboss As 7.1.1.Final with Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode) under Windows 7 I have a vanilla Message Driven Bean; @MessageDriven(name = "QTestAppExceptionMDB", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/streamedAppErrorQ"), @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") }) @TransactionAttribute(TransactionAttributeType.REQUIRED) public class QTestAppExceptionMDB implements MessageListener { private static int beans = 0; private int count = 0; private String id; { DateTime now = DateTime.now(); DateTimeFormatter fmt = DateTimeFormat.forPattern("k:m:s.SSS"); id = "MDB (AppExceptioning) ID=" + ++beans + ", " + now.toString(fmt); } public QTestAppExceptionMDB() throws JAXBException { } public void onMessage(Message message) { ++count; System.err.println(id + ": count is " + count); System.err.flush(); forwardMessage(message); throw new MyNonRollbackRuntimeException("This is a BL error: "); } private void forwardMessage(Message message) { String destinationName = "queue/streamed"; Context ic = null; ConnectionFactory cf = null; Connection connection = null; try { ic = new InitialContext(); cf = (ConnectionFactory) ic.lookup("/JmsXA"); Queue queue = (Queue) ic.lookup(destinationName); connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer publisher = session.createProducer(queue); connection.start(); publisher.send(message); } catch (Exception exc) { exc.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } } } MyNonRollbackRuntimeException is a RuntimeException which is marked as an Application Exception, with rollback=false; @SuppressWarnings("serial") @ApplicationException(rollback=false) public class MyNonRollbackRuntimeException extends RuntimeException { public MyNonRollbackRuntimeException(String arg0) { super(arg0); } } When I run the example the message forwarded by forwardMessage is not seen by the 'downstream' message listener. If I comment out the throw of MyNonRollbackRuntimeException, it is. So I assume despite the fact that my RuntimeException is marked as rollback=false, the transaction is being rolledback. HornetMQ goes into its normal resubmission protocol, and I see the message being resubmitted as if it had been rolledback. There is a difference between the behaviour of MyNonRollbackRuntimeException and a normal RuntimeException which is that the MDB instance is not discarded if the MyNonRollbackRuntimeException is thrown. Looking at; p 213 Table 12 in the section 9.3.4 Exceptions from Message-Driven Bean Message Listener Methods, it might appear that I should expect the transaction to commit, but it is not clear. Do the Application Server maintainers think this is a bug, or is it just badly defined by the specs (or is there another spec I missed) and therefore up to the implementers? (I was told to resubmit here having initially submitted to the HornetMQ forum) Thanks 1. Re: RuntimeException subclass annotated with @ApplicationException(rollback=false) still rolls back ifJustin Bertram Mar 25, 2014 10:06 AM (in response to John Francis)1 of 1 people found this helpful IMO this is a bug. However, both the JMS 1.1 (in section 4.5.2) and 2.0 (in section 8.7) specifications state: It is possible for a listener to throw a RuntimeException; however, this is considered a client programming error. Well-behaved listeners should catch such exceptions and attempt to divert messages causing them to some form of application-specific 'unprocessable message' destination. An MDB is fundamentally a MessageListener so I believe this would apply to both standalone MessageListener implementations and MDBs. I recommend you simply inject a MessageDrivenContext and control the transaction rollback with that rather than throwing an exception from onMessage(). 2. Re: RuntimeException subclass annotated with @ApplicationException(rollback=false) still rolls back ifJohn Francis Mar 25, 2014 10:31 AM (in response to Justin Bertram) Thanks. Nothing like consistent specifications!
https://developer.jboss.org/thread/238424
CC-MAIN-2018-17
en
refinedweb
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 On 2011-01-23 16:05, michael wrote: > [...] Hey, Sorry for the late reply. I am taking the liberty of answering this one first. >. Regarding the next step: well, >> > >> > I would also like you to clean up d/rules. At least remove/merge >> > uninterested targets and comments. Please also either fix the "noopt" >> > build option or remove the code for it (fixing it probably requires >> > patching upstreams Makefile, since it does not react to CFLAGS). >> > Personally I prefer things like the debhelper "tiny rules"[2] with >> > override targets (or cdbs, but I have less practice with it). These >> > styles have the advance of hiding the "standard stuff", making the >> > "non-standard" parts more visible. > I'm not sure if it's worth changing to cdbs and/or quilt right now for > only 4 small changes (I use it for an other adopted package - snacc - > right now, so it's not a question of skill). > I removed that dh_desktop line - that's o.k. for I added the #, but I > can't see the necessity of changing the other things or removing > comments. It was o.k. all the time so far and is doing no harm. I also > like to have some comments, even if they remain from the initial > conversion to a debian package. >. Finally there is this part, which I asked you to look at: ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS))) CFLAGS += -O0 else CFLAGS += -O2 endif I do not see any changes to it, nor to the upstream Makefile. Does this work as intended? That is, will DEB_BUILD_OPTIONS=noopt dpkg-buildpackage produce an unoptimized package? As I recall I came to the conclusion that it probably did not work, but feel free to correct me if I am wrong. >> > >> > When you clean up the rules file, please bump debhelper to at least 7. >> > if you go with "tiny rules" with overrides, you will need a >> > Build-Depends on debhelper (>= 7.0.50~) - but the compat is still 7 in >> > this case. >> > > Why that? Even lintian was only requesting (on that mentioned snacc > package W: snacc source: > package-lacks-versioned-build-depends-on-debhelper 5) to change from >>4 > to >>5. On the other hand actualised lenny is using 8.0.0~bpo50+2, so > why not change to 8, for I haven't checked against older versions and I > do NOT intend to do so? > Just to be complete : this change has to be made in the control file, > not in rules. So, starting with Lintian here. The Lintian warning you saw is about the package having a Build-Depends on debhelper 4, when the package said it used debhelper 5 features (in debian/compat). Since compat 5 is not strictly deprecated, Lintian will not warn about its usage. As for debhelper in lenny; lenny has 7.0.15 - the version you are seeing is debhelper in lenny-backports. There is a difference between the two. I am willing to believe that snake4 is an unlikely candidate for security or (old-)stable uploads. I see no reason why you cannot use debhelper 8 instead of 7 for snake4 actually. I have just been accustomed to using compat 7, so the new 8 compat went past me. :) > [...] > > Kind regards > Michael > > If you have any questions to the above, feel free to write back on list. If I do not reply within four days (like I failed to do this time), feel free to ping me in private as well. Else I would recommend you send an RFS to the Games Team. :) ~Niels -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - iQIcBAEBCAAGBQJNSeqtAAoJEAVLu599gGRC47IQAJuMLVmr0GRkz3Cxb14mcO3c QPIO/dJx0smtZ0J6vX1wteHfH0Fo3Z9avzE2ryu7QgGOtDGwPVLhD9fWq0+Ad3F/ vus3IrSDmNRbmpRhRR/Ja8URswHt1pF4sA42343DcmUgscNP8I3JSpB4yCPeeQut Kfgva7UZmeOgri4gnAuCJL9Kp8XGSKsPWWSaHjI6JdlANAv4/gJuLpHYD8/8DPiA lYUBDe+GXB72YU9VrRai8t5MZkoOx0deJaHeJSaM/5mpfBbrraMBT2Kv1qxZ02F8 ydUELFx/odDmQS8Nv/7zD8qvSjNIG/m1kscOwKvwounf8UBhoE33JdQAOEo1ihAB MPBt2YUQSQhTcGxSDWLw2WP/UFkppAvSTil3cB14qkF525wNi261RUGNmG9yPyms aRXErM6yGKfNKDSzJvivjeeA40WST3/tUfwoMMIy7UpgyRXwlEZlf+PCoz7mYzIx lqQps+gNWDvHIepFAHwx1/FJVPsRiNFV/gmitRpYHF4CTSbljeiGiGkWN5HYXVkA mStw6vfxRLpsDMYnKX/cBCE26gIwBV0cvFukkKOD9GeR0daPT7XhId+cIrrRVd1q Cae1sw5U16HhrGOudVJHnbly4V38DPKtLy0OUqC1Cpr4fetdreBEYx7atRg08p2x zwh2YoYd9QnFIwrFhLb3 =hWF9 -----END PGP SIGNATURE-----
https://lists.debian.org/debian-mentors/2011/02/msg00017.html
CC-MAIN-2018-17
en
refinedweb
patch for drivers/net/irda/irport.c IRDA driver removes one call to check_region using request_region instead. The patch also moves the call to request_region to before the allocation of the driver instance. I don't have this hardware so patch is not tested. This patch removes all references to check_region in this driver. Patch also available at the following URL: This is patch number 38 in a series of check_region patches I am doing as part of the kernel janitors project. Removal of check_region is one of the items on the kernel janitors TODO list () - "get rid of check_region, use just request_region checking its return (2.2 request_region returned void) and now the driver init sequence is not to be serialized anymore, so races are possible (look at cardbus/pcihotplug code)" Best regards William Stinson --- linux-2.5.59/drivers/net/irda/irport.c 2003-01-31 22:17:39.000000000 +0100 +++ linux-local/drivers/net/irda/irport.c 2003-01-31 23:44:45.000000000 +0100 @@ -102,9 +102,6 @@ int i; for (i=0; (io[i] < 2000) && (i < 4); i++) { - int ioaddr = io[i]; - if (check_region(ioaddr, IO_EXTENT)) - continue; if (irport_open(i, io[i], irq[i]) != NULL) return 0; } @@ -142,6 +139,14 @@ IRDA_DEBUG(1, "%s()\n", __FUNCTION__); + /* Lock the port that we need */ + ret = request_region(iobase, IO_EXTENT, driver_name); + if (!ret) { + IRDA_DEBUG(0, "%s(), can't get iobase of 0x%03x\n", + __FUNCTION__, iobase); + return NULL; + } + /* * Allocate new instance of the driver */ @@ -149,6 +154,7 @@ if (!self) { ERROR("%s(), can't allocate memory for " "control block!\n", __FUNCTION__); + release_region(iobase, IO_EXTENT); return NULL; } memset(self, 0, sizeof(struct irport_cb)); @@ -165,14 +171,6 @@ self->io.irq = irq; self->io.fifo_size = 16; - /* Lock the port that we need */ - ret = request_region(self->io.sir_base, self->io.sir_ext, driver_name); - if (!ret) { - IRDA_DEBUG(0, "%s(), can't get iobase of 0x%03x\n", - __FUNCTION__, self->io.sir_base); - return NULL; - } - /* Initialize QoS for this device */ irda_init_max_qos_capabilies(&self->qos); -------------------------------------------------------
https://sourceforge.net/p/irda/mailman/irda-users/?viewmonth=200302&viewday=2
CC-MAIN-2018-17
en
refinedweb
US5408598A - Method for fast generation of parametric curves employing a pre-calculated number of line segments in accordance with a determined error threshold - Google PatentsMethod for fast generation of parametric curves employing a pre-calculated number of line segments in accordance with a determined error threshold Download PDF Info - Publication number - US5408598AUS5408598A US08202678 US20267894A US5408598A US 5408598 A US5408598 A US 5408598A US 08202678 US08202678 US 08202678 US 20267894 A US20267894 A US 20267894A US 5408598 A US5408598 A US 5408598A - Authority - US - Grant status - Grant - Patent type - - Prior art keywords - sub - curve - δt - error - Abstract Description This is a continuation of application Ser. No. 07/705,041, filed on May 23, 1991, now abandoned. This invention relates to computer graphics, and more precisely, to a method and apparatus for rapidly generating curves on a computer display. Computer graphics employ a number of techniques to reproduce curved lines and surfaces. One commonly used technique involves producing a set of points and connecting those points with straight lines to approximate the curve. The curve is successively divided into smaller pieces and then checked to see if each piece can be approximated by a straight line to within a given error threshold. It turns out that the check of the accuracy of the approximation is the dominant part of the cost of executing the curve approximation algorithm. In a two-dimensional space, a curve is often expressed as a function of orthogonal components x and y, i.e., y is equal to f(x). In a three-dimensional coordinate system, the x, y and z coordinates may also be represented as functions of one or two of the orthogonal components. However, these representations may cause difficulty in generating the coordinate values. One alternative technique is to use a parametric representation of the curve or a representation where each coordinate value on a curve is represented as a function of some common variable, that is, a variable common to all coordinate components. For a three dimensional system, such a variable may be described as t resulting in the following: x=f(t); y=g(t); and z=h(t); for 0<t<1. A further representation is a parametric cubic curve that is represented by third order polynomials. x=f(t)=a.sub.x t.sup.3 +b.sub.x t.sup.2 +c.sub.x t+d.sub.x y=g(t)=a.sub.y t.sup.3 +b.sub.y t.sup.2 +c.sub.y t+d.sub.y z=h(t)=a.sub.x t.sup.3 +b.sub.y t.sup.2 +c.sub.z t+d.sub.z Cubic curves are important because no lower-order representation of curve segments can provide either continuity of position and slope or continuity of slope and curvature at the point where the curve segments meet. Cubic curves are also the lowest order curves that can render non-planar curves in three dimensions. A popular prior art method for subdividing parametric cubic curves is termed "Bezier subdivision". The Bezier subdivision method will be briefly described, but no explanation or proof of its correctness will be given. Such proofs may be found in various texts on graphics, i.e., see "Fundamentals of Interactive Computer Graphic, Foley et al., Addison-Wesley Publishing Co., pp. 514-523; "Algorithms for Graphics and Image Processing", Pavlidis, Computer Science Press, pp. 220-231; and "Computational Geometry For Design and Manufacture", Faux et al., Wiley and Sons, pp. 126-145. Given a curve and an error threshold ΔE, the Bezier algorithm produces a list of line segments which approximate the curve with errors no larger than ΔE. The curve itself is described by a control polygon consisting of 4 points, p1, p2, p3, p4. Such a control polygon is shown in FIG. 1 and which also includes cubic curve 10 is being approximated. The dimension E is the error and defines the distance between the chord p1-p4 and the apogee of curve 10. If E is greater than ΔE two more polygons are constructed from the original polygon, with the property that curve 10 lies within each new polygon, and that each new polygon is the control polygon for the part of the curve which it contains. This subdivision proceeds recursively. An iteration of this subdivision process has three stages. The first stage is indicated in FIG. 2 wherein the following values are found: ##EQU1## The second stage of the calculation is shown in FIG. 3 and shows the derivation of points 13 and r2 as follows: ##EQU2## The third stage involves the derivation of points l4 and r1 as follows: ##EQU3## At the end of the above iterations, the derived values are: ##EQU4## As can be seen from FIG. 4, the Bezier control polygons l1-l4 and r1-r4 now better approximate curve 10. For any given resolution ΔE, the subdivision process ends when, any curve within a polygon is at most a distance ΔE from the base line of that polygon. (The base line of the polygon is the line connecting P1 to P4). The calculation may be simplified by calculating the value for d instead of ΔE (see FIG. 1). In essence, Bezier subdivision generates a binary tree where each node of the tree corresponds to a subdivision step, and each edge of the tree descending from a node corresponds to a right or left control polygon that is the result of a subdivision at that node. In a simple implementation, the calculation cost for each node includes approximately 12 additions and 12 shifts (24 cycles). However, the error check for ΔE requires at least 350 additional cycles. Thus, most of the computational work (88%) is in computing the error condition ΔE at the end of each iteration. Similar disparities in calculation work exist for more complex equations, i.e., parametric quadratics, conics, etc. Bezier subdivision algorithms such as the one presented for Bezier cubics exist for Bezier curves of all orders. In particular, subdivision of parametric quadratics will now be described. A parametric quadratic is a parametric curve whose coordinate functions are second order polynomials in the parameter t. The parametric curve is described by a triangular control polygon (see FIG. 5) consisting of three points, p0, p1, p2. These points define the curve as follows: (x(t),y(t))=p.sub.0 (1-t).sup.2 +2.sub.p 1t(1-t)+p.sub.2 t.sup.2 0<t<1 From this polygon, two more polygons are constructed with the property that half of the curve lies within each new polygon and that each new polygon is the control polygon for the part of the curve which it contains. Thus the subdivision may proceed recursively. An iteration of this subdivision process has two stages as follows: ##EQU5## The second stage: ##EQU6## At the end of such an iteration, the values are: ##EQU7## The notation r(p)(t) will be used to denote the curve determined by ri and l(p)(t) to denote the curve determined by li. The algorithm continues recursively with each of the two output polygons being subdivided. Just as with subdivision for cubics, the subdivision process ends when the curve within the polygon is sufficiently close to the polygon, e.g., a distance less than some threshold T away. Again, if d is the function which gives the distance from a point to a line, and l(p,q) represents the line which connects p to q, d(p1,l(p0,p2))≦T where, ##EQU8## where • is the 2-D dot product and the hat of a vector is a vector of the same length as that vector but perpendicular to it. In this section, a prior art algorithm for drawing rational quadratics is described. It is based on using the subdivision algorithm described above to subdivide both the numerator and denominator of a rational quadratic. The control points of the subdivided numerator and denominator are divided to give the endpoints of a linear approximation to the curve. Assume the following rational quadratic curve (x(t),y(t)) in a plane. The forms of the coordinate functions are given by: ##EQU9## Note that the numerator is expressed in the quadratic Bezier basis, as is the denominator. Henceforth, wi is required to be positive since this can be done without losing the ability to represent all rational quadratics. Geometrically, (xi, yi) are control points and wi is the weight attached to these control points. The following quantities are defined, Xi =xi wi and Yi =yi wi. These are the coordinates in the Bezier basis of the numerator, (X(t), Y(t)). In order to draw such a curve, Bezier subdivision is applied to both the Xi,Yi and the wi to generate l(X), l(Y), l(w) and r(X), r(Y) and r(w) as in the previous section. Let s(a) denote r(a) or l(a) (i.e., "a" subdivided once). By evaluating the resultant fraction (s(X)i,s(Y)i /s(w)i, the control points of the resultant curves are obtained. The weights of the resultant curves are the s(w)i. This is equivalent to the application of Bezier subdivision to the 3-d, second order curve (Z(t),Y(t),w(t)) followed by a perspective projection onto the x,y plane (see FIG. 6). The ending condition of the previous subsection is then applied to the curve in the x,y plane. If the subdivision is not finished, the 3-d curve is further subdivided and again projected. This continues recursively. An Incremental Algorithms For Cubics There are several incremental schemes for evaluating cubics. Assume a cubic curve that is specified by its two coordinate functions, x(t)=x.sub.0 +x.sub.1 t+x.sub.2 t.sup.2 +x.sub.3 t.sup.3 y(t)=y.sub.0 +y.sub.1 t+y.sub.2 t.sup.2 +y.sub.3 t.sup.3 Suppose the values of the coordinate functions are known for some t0 and it is desired to know them for some other value t0 +Δt. Define x.sub.t (t.sub.0)=x(t.sub.0 +Δt)-x(t.sub.0) x.sub.tt (t.sub.0)=x.sub.t (t.sub.0 +Δt)-x.sub.t (t.sub.0) x.sub.ttt (t.sub.0)=x.sub.tt (t.sub.0 +Δt)-x.sub.tt (t.sub.0) y.sub.t (t.sub.0)=y(t.sub.0 +Δt)-y(t.sub.0) y.sub.tt (t.sub.0)=y.sub.t (t.sub.0 +Δt)-y.sub.t (t.sub.0) y.sub.ttt (t+.sub.0)=y.sub.tt (t.sub.0 +Δt)-y.sub.tt (t.sub.0) By rewriting the above quantities in terms of the derivatives of x and y, it can be seen that xttt and yttt are constant with respect to t. Now, to get x(t+Δt) add x(t)+xt (t). To continue in this fashion, compute xt (t+Δt) in order to make the next step forward by Δt. Similarly, xtt must be updated. This leads to the following algorithm for generating points of the curve. ##EQU10## An Incremental Algorithm for Conics Assume a parametric quadratic coordinate function y(t)=y.sub.0 +y.sub.1 t+y.sub.2 t.sub.2 Suppose the values of the coordinate function for some t0 are known and it is desired to know them for some other value t0 +Δt. y.sub.t (t.sub.0)=y(t.sub.0 +Δt)-y(t.sub.0) y.sub.tt (t.sub.0)=yt(t.sub.0 +Δt)-y.sub.t (t.sub.0) By rewriting the above quantities in terms of the derivatives of y it can be seen that ytt is constant with respect to t. Now, to get y(t+Δt) simply add y(t)+y1 (t), continue in this fashion and compute yt (t+Δt) in order to make the next step forward by Δt. This leads to the following algorithm for generating coordinates. ##EQU11## This may be extended to an algorithm for rational quadratics in the same way the subdivision algorithm was. Namely, the above algorithm which works for a coordinate function is applied to the numerator, (X(t), Y(t)) and the denominator, w(t), and then divide to get the result. Both prior art incremental algorithms suffer from similar problems which will be explained using cubics as an example. The incremental algorithm is more efficient than subdivision, but is also numerically ill-conditioned in the sense that errors in yttt grow cubically with the number of steps taken. That problem can be skirted, to some extent, by calculating yttt to high precision, however, precision grows cubically with the number of steps. The proper choice of value for Δt is a more difficult problem. One approach to solving this problem is adaptive subdivision which varies the size of Δt based upon the distance moved in the last step. This makes the function more expensive and more complicated. While the Bezier subdivision technique has been described above, other derivations employ the Hermite form and the B-spline form, which forms are also considered in the above cited texts. In U.S. Pat. Nos. 4,760,548 to Baker et al, 4,912,659 to Liang 4,949,281 to Hilenbrand et al. and 4,907,282 to Daly, various aspects of B-spline curve approximation techniques are described. In U.S. Pat. Nos. 4,674,058 to Lindbloom et al. and 4,943,935 to Sato, Bezier calculations are described for curve approximation. All of the aforedescribed patents either precalculate the curve approximations and then store the results for subsequent display or calculate error values as the curves are being constructed. In U.S. Pat. 4,855,935 to Lein, the problems inherent in recursive subdivision methods are recognized and it is suggested that a technique called "forward differencing" (advancing along a parametric curve or surface in constant parameter increments) be utilized to more efficiently generate the curve. This adaptation is performed by transforming the equation of the curve to an identical curve with different parameterization, such that the step sizes increase or decrease so that the curve proceeds in substantially uniform increments. In U.S. Pat. No. 4,648,024 to Kato et al., curved lines (circles) instead of straight lines are employed at the lowest level of approximation for the algorithm. Other prior art concerns itself with the construction of curves that can be parameterized by arc length, i.e., a curve whose points, at equally stepped times t, are separated by a constant function or distance along the curve, (e.g. a circle). Such a system is shown in U.S. Pat. No. 4,654,805 to Shoup, II. In U.S. Pat. No. 3,806,713 to Ryberg, a curve approximation system is described for curves having a rotational axis. Ryberg's system is based on an error in approximation of a circle by a line. Ryberg does not attempt to overcome the error calculation problem mentioned above by determining, in advance, the number of straight line segments that will be required to approximate the curve. The length of each straight line approximation is expressed by Ryberg in terms of the number of steps along the rotational axis of the curve, for each straight line approximation. That value is determined by multiplying the total number of steps to be taken along the rotational axis times a function that results from dividing a predetermined maximum error in the number of steps to be taken along a radial axis, by the total number of steps to be taken along the radial axis for a given curve. While Ryberg's procedure is useful for curves that can be parameterized by arc length, he does not teach any method for more complex curves that do not lend themselves to such parameterization. Recently, it has been proved by Dahmen that subdivision algorithms used to reproduce curves converge in a quadratic fashion. In specific Dahmen found that the class of subdivision algorithms that includes Bezier subdivision, converges quadratically. This is equivalent to the statement that at some indeterminate point in the subdivision algorithm, the error E began to reduce in size by a factor of approximately 4 at each division step. See "Subdivision Algorithms Converge Quadratically", Dahmen, Journal of Computational and Applied Mathematics, Vol. 16, 1986, pp. 145-158. While Dahmen's results indicate that widely used subdivision algorithms do have a convergency, he does not indicate at which stage that convergency occurs and at which point in the subdivision process the error begins to be divided by a factor of 4. Accordingly, it is an object of this invention to provide an improved method for approximating a curve through the use of straight lines, and to reduce the number of error calculations. It is another object of this invention to provide an improved curve approximation algorithm which is particularly applicable to cubics, conics, quadratics, and other high order curvilinear equations. A method is described which enables the prediction of the number of subdivisions of a curve that will be required by control polygons to assure that a resulting straight line representation of the curve will not exceed a preset error threshold. The method is applicable to cubics and parametric quadratics including parabolas, ellipses and hyperbolas. In each case, the prediction of the number of subdivisions eliminates the need for a detailed error calculation at each subdivision step, thereby enabling an error calculation to be carried out only once in the process. FIGS. 1-4 illustrate the prior art Bezier subdivision of a curve to enable representation of a curve by straight line segments. FIG. 5 illustrates a prior art Bezier subdivision of a second order curve (parabola). FIG. 6 illustrates a perspective projection of a 3-d parabola onto a viewplane to obtain a 2-d conic. FIG. 7 is a high level block diagram of a data processing system for carrying out the invention. FIG. 8 is a high level flow diagram of the method of the invention as applied to a cubic curve. FIG. 9 is a high level flow diagram of an alternate method of the invention as applied to a cubic curve. FIG. 10 is a high level flow diagram showing the application of the invention to a conic curve. FIG. 11 is a high level flow diagram showing a modification to the method of FIG. 10. FIG. 12 is a high level flow diagram showing an application of the method of the invention to an incremental algorithm for approximating a cubic curve. FIG. 13 is a high level flow diagram showing the application of the method to an incremental algorithm for the approximating a conic curve. As indicated in the Background of the Invention, in the process of subdividing a curve into smaller segments and checking to see if each segment can be approximated by a line to within a given threshold, substantial computation time is taken up at each subdivision by the calculation of an error function. When it is realized that each subdivision creates a tree wherein the next level of subdivision doubles the number of control polygons, it can be seen that error calculations greatly hinder the curve approximation procedure. As further indicated in the Background, Dahmen has determined, theoretically, that at some point in the subdivision procedure the error decreases by a factor of four at each subsequent subdivision. It has been found, for a curve which can be expressed as a cubic, that the reduction in error by four occurs generally after the second subdivision. Also, the largest contribution to the error function occurs as a result of attempting to simulate a complex curve with a straight line, and arises from the fact that a straight line cannot approximate the second derivative of the curve. It has been further determined that the number of subdivisions of control polygons to simulate a curve within a certain error tolerance can be predicted by carrying out an initial error computation and then dividing the found error by a factor (e.g. the value 4) an integer number of times until the resultant error is less than a predetermined value. The number of times the error function is divided is then equal to the number of subdivisions that need to be accomplished. As a result, the required number of subdivisions is then known. This allows the required number of control polygons to be constructed, and thus gives the starting and end points of the straight lines to simulate the curve. No further error function calculations are required. The method of this invention can be carried out on a personal computer-sized data processing system, such as is shown in FIG. 7. The firmware for carrying out the method is stored in electrically programmable read only memory (EPROM) 11. The operation of the system is controlled by microprocessor 12 which communicates with the various elements of the system via bus 13. A curve's coordinate points are stored, for instance, on disk drive 14 and are transferred into random access memory (RAM) 15 when the curve approximation and display method is to be performed. Once the required number of control polygons has been determined, the coordinates of the beginning and end of each control polygon are employed by display control 16 to construct a curve approximation that is then shown on display 17. The procedure has been found applicable to not only curves described by a cubic function, but also to rational quadratics (i.e. conics, ellipses, parabolas, and hyperbolas) and further to incremental algorithms for simulating curves. Hereafter, the algorithms for both Bezier subdivision and incremental subdivision will be described, followed by a proof section which substantiates the illustrated relationships. The algorithm takes as its input, a cubic curve specified by its control polygon (as indicated in the background of the invention and with respect to FIGS. 1-4). An error tolerance ΔE is specified and is the maximum error which the user is willing to tolerate in the curve approximation. Referring to FIG. 8, a flow diagram illustrating the algorithm is shown. Initially, the Bezier control polygon is provided for the curve (box 20) and the maximum error ΔE is selected (box 22). A modified error m is then calculated by the equation shown in box 24. It will be noted that the numerator of that equation is the maximum of the second derivatives of the x and y coordinate functions at the beginning and end points of the curve. It turns out that the maximum second derivative value will always occur at either the beginning or end point of the curve, so by testing for the maximum second derivative at those points, one is able to derive the maximum second derivative coordinate function for the curve. The numerator result is divided by the maximum error ΔE and the quotient multiplied by a constant 7√2 to derive the modified error m. The constant 7√2 assures that the modified error m does not affect the calculation, substantially, until after approximately the second subdivision. The modified error m is then tested (decision box 26) to see whether its value is less than or equal to one (i.e. if the real error is less than or equal to ΔE), and if it is, a line is drawn from one end of the control polygon to the other since the error limit has been reached. If not, the polygon is subdivided (or if this is a subsequent step, the polygons are subdivided) leaving, for each subdivided polygon a left polygon and right polygon (box 30). The value of m is then divided by four and tested to determine if its new value is less than or equal to one. If not, the process repeats until the condition set in decision box 26 is met. It can thus be seen that the modified error calculation need only be made once, after which, the value of m is divided subsequent to a next subdivision and the effort repeated until the error condition is met. As a result, sufficient polygons are generated to meet the error condition without requiring additional calculations of the error function. In effect the number of control polygons to be used is equal to 2n, where n=the number of modified error values calculated. The following is a pseudocode listing for the procedure shown in FIG. 8. Input is a Bezier cubic with its control points, and an error tolerance, ΔE Derive the second derivatives of the coordinate functions at the end of points of the cubic. Compute the Modified Error, ##EQU12## where the primes denote differentiation. Call the subdivision routine subdivision (cubic, m) End procedure processcubic Begin procedure subdivision (cubic, m) If m≦1, draw a line from one endpoint of the polygon to the other. Otherwise, subdivide the polygon as in the prior art, yielding two polygons, Left Polygon and Right Polygon. call subdivision (Left Polygon, m/4) call subdivision (Right Polygon, m/4) end procedure subdivision An alternative procedure (see. FIG. 9) for accomplishing the same result as above described is as follows: Input is a Bezier cubic with its control points, and an error tolerance, ΔE Derive the second derivatives of the coordinate functions at the end of points of the cubic. Compute a value ##EQU13## where the primes denote differentiation. Call the subdivision routine subdivision (cubic, L) End procedure processcubic Begin procedure subdivision (cubic, L) If L≦1, draw a line from one endpoint of the polygon to the other. Otherwise, subdivide the polygon as in the prior art, yielding two polygons, Left Polygon and Right Polygon. call subdivision (Left Polygon, L-1) call subdivision (Right Polygon, L-1) end procedure subdivision The value of log4 (x) can be easily calculated by shifting. When L=log4 (m) is computed, where m is the modified error, what is desired is that L=the smallest positive integer which is not greater than log4 (m). It is also known that m>1. So, m may be computed as follows: if m<4, then L=1; otherwise: L=1 while (m≧4) m=m/4; L=L+1 return (L) This computes L by successive shifting since division by 4 is equivalent to right shifting by 2. As will be remembered from the Background section, the coordinate functions for a rational quadratic are expressed as a fraction having quadratics in the both denominator and the numerator. If x(t), y(t) are the coordinate functions of the conic, it will be recalled (for ease of expression) that the x(t) function in the numerator and denominator, is defined as X(t)/w(t). Similarly, the expression for y(t) is simplified by letting its numerator and denominator respectively equal Y(t)/w(t). The value of ΔE is then chosen as the maximum error to be tolerated in the approximation. In the following equations, "a" can represent either x or y, as the case may be. Two quantitites are defined in terms of X, Y, w. The modified error m for an ellipse and a hyperbola (parabola) are as follows: ##EQU14## To determine if a particular curve is an ellipse or a hyperbola, the values of w0 and w1 are compared. It will be recalled that a rational quadratic has, for its beginning and end coordinates, three coordinate functions X, Y, and w, with w being a "weight" or third dimensional value which determines in which direction the curve is "pulled" and vice versa. If w0 and w1 are the beginning and end coordinate point weights, whether a curve is a hyperbola, ellipse or parabola can be determined from the following (The hyperbola modified error function is used for parabolas). w.sub.1 >w.sub.0 =hyperbola w.sub.1 <w.sub.0 =ellipse w.sub.1 =w.sub.0 =parabola. The above noted procedures are shown in boxes 40, 42, and 44 in FIG. 10. Once the type of curve has been identified, then one or the other of the modified error equations (box 46) is solved. It will be recalled from the Background, that the Bezier polygon for a conic is an open sided triangle having points p0, p1 and p2. An equation in box 46 is thus solved by initially substituting for each "a" value the appropriate value of x. The equation is then solved. Then the appropriate values of y are inserted and the equation solved. The maximum value obtained from the solution is then equal to the modified error m for the curve. The procedure completes by following the procedure shown in boxes 26, 28, 30, and 32 in FIG. 8. Here again, it can be seen that the number of polygonal subdivisions required to achieve the desired error is determined by the number of divisions by 4 required to reduce the value of m to less than or equal to 1. The following is a pseudocode listing for the procedure shown in FIG. 10: begin procedure processconic (conic, Δe) input is a conic specified as a rational quadratic, m and an error tolerance, Δe if the conic is an ellipse, compute m=mellipse if the conic is an hyperbola, compute m=mhyperbola call the conicsubdivision routine conicsubdivision (conic, m) end procedure processconic begin procedure conicsubdivision (conic, m) if m≦1, draw a line from one endpoint of the conic to the other. otherwise, subdivide the conic as in the prior art section, yielding two polygons, LeftConic and RightConic. call conicsubdivision (LeftConic, m/4) call conicsubdivision (RightConic, m/4) end procedure conicsubdivision An alternative procedure (see FIG. 11) that accomplishes the same result as above is as follows: begin procedure processconic (conic, Δe) input is a conic specified as a rational quadratic, m and an error tolerance, Δe if the conic is an ellipse, compute L=Log4 mellipse if the conic is an hyperbola, compute L=Log4 mhyperbola call the conicsubdivision routine conicsubdivision (conic, L) end procedure processconic begin procedure conicsubdivision (conic, m) if L≦1, draw a line from one endpoint of the conic to the other. otherwise, subdivide the conic as in the prior art section, yielding two polygons, LeftConic and RightConic. call conicsubdivision (LeftConic, L-1) call conicsubdivision (RightConic, L-1) end procedure conicsubdivision As indicated in the Background, incremental algorithms are also used to approximate curves. Such algorithms start at one end of the curve and successively step along the curve by a predetermined amount and at each interval, determine whether the interval is small enough to give a good approximation of the curve by an inserted straight line. This invention enables the best time step along the curve to be precalculated and then simply utilized without intervening error calculations. Furthermore, rather than requiring a modified error calculation, a direct calculation is made of the optimum number of time steps to enable a given error to be achieved. It has been determined that the best number of time steps is 2L with L being dependent upon the maximum second derivative of either the x or y coordinate functions at the beginning and end points of the curve. As shown in FIG. 12, the algorithm starts by having as its inputs, a Bezier cubic polygon specified by its coordinate functions and a specified tolerance error ΔE (box 50). The procedure then computes the value of L using the expression shown in box 52. Here again, the value of L is directly related to the maximum second derivative of one of the coordinate functions of the curve (L being the optimum number of step sizes required to achieve the error tolerance ΔE). The algorithm then proceeds along the prior art incremental subdivision route shown in boxes 54, 56 and 58. In essence, the step size is chosen as being the reciprocal of 2L. Next, finite differences xt, xtt, xttt, yt, ytt, yttt, as defined in the Background of the invention are calculated for the x and y coordinate functions at the beginning coordinate, to a precision determined by the error tolerance and the step size. Then, the functions shown in box 58 are calculated using Δt increments to determine the succeeding coordinate points. Here again, it is to be noted that subsequent to the calculation shown in box 52, there is no further error calculation. The requisite straight lines are then drawn. A pseudo code description for this procedure follows: compute ##EQU15## choose step size Δt=2-L compute x(0), xt (0), xtt (0), xttt (0) to a precision ΔE 2-L compute y(0), yt (0), ytt (0), yttt (0) to a precision ΔE 2-L for (t=Δt to 1, by Δt increments)) draw line from x(t-Δt), y(t-Δ) to x(t), y(t). end procedure processcubic In lieu of using the Bezier subdivision for conics, an incremental subdivision technique can be employed. In this instance, the modified error expressions for both ellipses and hyperbolas are utilized, as above described. With reference to FIG. 13, a rational quadratic and error tolerance ΔE are input (box 60). Then, if the conic is determined to be an ellipse, L is computed as shown in box 62 using the modified error equation shown in box 46, FIG. 6. If, on the other hand, the conic is determined to be a hyperbola, then L is computed, as shown in box 62, using the equation shown in box 46, FIG. 6. At this point, the number of increments required to achieve an error tolerance ΔE is known. Thus, knowing the value of L, the number of steps chosen are 2L and the step size Δt is chosen as 2-L (box 64). At this point, the procedure continues, as in prior art incremental algorithms, and computes the values shown in box 66. Subsequently, the specific increments and their weights are derived as shown in box 68, and the requisite lines drawn. A pseudocode description for this procedure follows: begin procedure processconic(conic, ΔE) input is a conic specified as a rational quadratic, and an error tolerance, ΔE if the conic is an ellipse, compute L=log4 (mellipse) if the conic is an hyperbola, compute L=log4 (mhyperbola) choose step size Δt=2-L compute X(0), Xt (0), Xtt (0) to a precision ΔE 2-L compute Y(0), Yt (0), Ytt (0) to a precision ΔE 2-L compute w(0), wt (0), wtt (0) to a precision ΔE 2-L for(t=Δt to 1 by Δt) X(t)=X(t-Δt)+X.sub.t) draw line from x(t-Δt), y(t-Δ) to x(t), y(t) end procedure processconic (1) Proof of correctness of the bound for cubics This section gives a proof of the correctness of the bound on the depth of the cursion which is necessary to make the algorithm work. Dahmen proved [Journal of Computational and Applied Mathematics 16(1986) 145-158 "Subdivision algorithms converge quadratically"] that a class of subdivision algorithms which includes Bezier Subdivision converges quadratically and that this bound is tight in the sense that no cubic bound is possible. Using this result, along with several computations, a formula has been found for an upper bound on the depth of the tree necessary to subdivide to a given error threshold. Furthermore, this formula is readily computed (requiring 13 additions, 6 shifts, 3 compares and a variable number of shifts which is less than half the word size.) and needs to be computed only once, using quantities available before the subdivision starts. Dahmen's result, is an estimate for the distance of the control points from the curve in terms of a constant, the granularity of the partition of the time variable, and the second derivative. The general form of his Theorem 2.1 gives an estimate of the form |S.sub.δ -P(t.sub.δ)|<C.sub.k *δ.sup.2 *||P"||∞ Where |Sd-P(td)| is the distance between the control points and the curve, evaluated at a point which is the average of neighboring partition points. δ is a measure of the granuality of the partition, and P" is the second derivative of the curve. ||f||∞ is the L∞ norm of the function, f. k is the order of the curve. Ck is a constant which depends only on k. A special case of this result is needed where δ is a (negative) power of 2, since the subdivision can be thought of as evaluation of points on the curve for t equal to multiples of some power of 2. Due to the fact that cubics are considered, the LHS can be thought of simply as the distance from the control points to the curve. This special case result is assumed with this interpretation. If Ck is known, then it can be found exactly how far the iteration will need to go. Dahmen's proof does not, however generate a value for Ck. The proof relies on the fact that the basis for the subdivision is uniformly stable and uses the uniform stability inequality as the starting point. In fact, a careful reading of the proof reveals that Ck is exactly the reciprocal of the constant which appears in the uniform stability inequality. So, an upper bound on Ck =m-1 is computed where ##EQU16## [Note that uniform stability of a basis is the same as m being finite and for the purposes of the proof, will be taken as the definition.] The control vector r has k+1 components and the norm on the space of control vectors is given by, ||r||=max|r.sub.i | Bi are some basis functions for the polynomial space. So, the Σri Bi is an element of the polynomial space with control vector r. [Note that control points are simply coefficients in a basis. They are called control points because they also have some geometric significance]. That element is called Pr. In this case, the Bi are the Bernstein-Bezier (hence called B-B) Basis functions for polynomials of degree 3. B.sub.0 (t)=(1-t).sup.3 B.sub.1 (t)=3t(2-t) B.sub.2 (t)=3t.sup.2 (1-t) B.sub.3 (t)=t.sup.3 So, m measures how small the sup norm of the function can get when the control points are made small. deBoor calculates the value of m for the power basis. The calculation of m for the B-B basis will follow his closely, but will have some differences which exploit features of the B-B basis. deBoor shows that an equivalent formula for m is ##EQU17## The following quantitites may be defined ##EQU18## So that m-1 =maxi mi -1 Now consider the B-B basis under the reparameterization as t goes to 1-t. This exchanges r0 with r3 and r1 with r2 but leaves the image of the curve (and hence its sup norm) unchanged. From this it can be concluded that m.sub.0.sup.-1 =m.sub.3.sup.-1 m.sub.1.sup.-1 =m.sub.2.sup.-1 To estimate m0 -1 and m1 -1 the following fact is used together with the exact form of the transformation between the B-B basis and the power basis and the relation of the coordinates of the power basis to the derivatives. For 0≦a<b ##EQU19## where Tn-1.sup.(i) is the ith derivative of the n-1th Chebyshev polynomial, and pn is the n dimensional vector space of all polynomials of degree less than n-1. In this special case, this formula becomes ##EQU20## Suppose a third degree polynomial, P(t). Call its coordinates in the B-B ri and its coordinates in the power basis ai, then, r.sub.0 =a.sub.0 r.sub.1 =1/3a.sub.1 +a.sub.0 a.sub.0 =P(.sub.0) a.sub.1 =P'(0) It can be seen, now that m0 -1 =1 ##EQU21## The argument for m1 -1 is more involved. Pick some cubic polynomial, P, with coordinates r in the B-B basis and a in the power basis. ##EQU22## Since this inequality is valid for every polynomial in the space, it must be valid for the maximum over all polynomials in the space. ##EQU23## At the end of this calculation, the desired result is, C.sub.3 ≦7 This may or may not be the best bound. However another calculation yields C3 ≧3.5. The difference in the upper and lower bounds is a factor of 2. Since a factor of 4 in C3 is required to double the average execution time for the algorithm there is little to gain from tightening the bound. Now that an upper bound on C3 has been found, a calculation is needed to get the precomputable ending condition. If Dahmen's result is rewritten using the upper bound, |S.sub.δ -P(t.sub.δ)|≦7*δ.sup.2 *||P"||∞ So, if it is required |S.sub.δ -P(t.sub.δ)≦Δ This can be accomplished by requiring 7*δ.sup.2 *||P"||√≦Δ then the following is needed ##EQU24## Also, restrict d to be a power of two, say, 2-1 ##EQU25## This reveals the error in each coordinate function, but if Euclidean error is desired another calculation is required. ##EQU26## If the Euclidean error is bounded by ΔE, Δx and Δy must be bounded by ##EQU27## This gives a formula 1 in terms of the Euclidean error which is acceptable in the rasterized curve. ##EQU28## Since P is assumed to be a cubic, P" is a linear function and hence must take its maximum and minimum values at the endpoints of its interval of definition. This gives ##EQU29## which is the precomputable ending condition. In the most often used special case, of ΔE =1/2, the following results l≧log.sub.4 (max(|x"(0)|, |x"(1)|, |y"(0)|, |y"(1)|))+2.154 (2) Derivations of the ending conditions for rational quadratics (conics etc.) This section is devoted to calculating formulae for ending conditions for conic subdivision. In para 2.2 a simple test at each iteration is shown to be an ending condition. In para 2.5 a uniform bound on the depth of subdivision necessary for a given ellipse is derived. This bound is a worst case estimate for the ending condition in 2.2. In para 2.6 a similar bound is derived for hyperbolae. In the next subsection, a bound is generated on the error in a straight line approximation to a parametric quadratic after Bezier subdivision is carried out to a depth of n. This will be used in later paragraphs to derive an ending condition and a bound on the maximum possible depth of the tree for the subdivision of rational parametric quadratics. (2.1) Prerequisite Calculations Consider the Bezier quadratic coordinate function c(t)=c.sub.0 (1-t).sup.2 +2c.sub.1 t(1-t)+c.sub.2 t.sup.2 Now, consider the error made in approximating this curve for 0<t<1/2 by the line which joins c0 to c1.Also approximate c(t) by the line from c1 to c2 for 1/2<t<1. This approximation will be called approximation by the legs of the control triangle to distinguish it from approximation by the base of the control triangle which will be introduced later. The arguments for each side of 1/2 are similar and only the argument for 0<t<1/2 will be presented. In the following we will assume 0<t<1/2. The error is then, E(c,t)=(c.sub.0 +2(c.sub.1 -c.sub.0)t)-c(t) Take the Taylor expansion of c(t) about t=0 and calculate E(c,t)=(2c.sub.1 -c.sub.0 c.sub.2)t.sup.2 Now, let l(c) and r(c) be the curves produced by subdividing c. The arguments for right and left side are identical, so only the left side will be shown. So, ##EQU30## Hence, with each subdivision, pointwise error is reduced by a factor of four. This is also true of the worst case error. So, for a Curve, c(t), let sn (c)(t) denote n applications of either r or l to c(t). Hence sn (c)(t) is short hand for any of the curves which appear at depth n in the tree. In order to simplify the notation, let sn (c) denote the particular segment at depth n which is being tested for termination. This corresponds to letting sn take on specific value. For example, s2 takes the values rl, rr, lr, and ll. The pointwise error after n subdivisions is E(s.sup.n (c), t)=(1/4).sup.n (2c.sub.1 -c.sub.0 -c.sub.2)t.sup.2 The largest absolute value of the error occurs when t=1/2 so, max(|E(s.sup.n (c), t)|)=(1/4).sup.n+1 |2c.sub.1 -c.sub.0 -c.sub.2 | If the curve for 0<t<1 is approximated by the line from c(0) to c(2), this is called approximation by the base of the control triangle. By looking at a plot of c(t) and the ci in the c-t plane, it can be seen that the maximum error for approximation by the legs occur at the same point, t=1/2. This is because c(1/2) is the midpoint of the line connecting c1 with the midpoint of the line connecting c0 to c2. So, the maximum error for the two approximations is the same, occurs at the same point and the two errors are of opposite sign. From this special case, the general result can be generated. (2.2) General Ending Condition (2.3) Errors in the Numerator and Denominator Recall that for the subdivision of conics, (X,Y, w) are weighted points where Xi =xi wi, Yi =yi wt which then project down under perspective projection to the correct answer. Each of these coordinate functions behaves like c of the previous paragraph. Let A denote X or Y and let a denote x or y respectively so the argument need be given only once. The curve may be reparametrized in order to get w0 =w2. So using equation 2 it can be concluded that for approximation by the legs of the triangle, E(s.sup.n (A), t)=(1/4).sup.n (2a.sub.1 w.sub.1 -w.sub.0 a.sub.0 -w.sub.0 a.sub.2)t.sup.2 E(s.sup.n (w), t)=(1/4).sup.n 2(w.sub.1 -w.sub.0)t.sup.2 Now, translate so that a1 lands at 0. In this new coordinate system, a0 becomes a0 -a1, a1 becomes zero, a2 becomes a2 -a1, so the error bound for sn (A)(t) becomes E(s.sup.n (A), t)=(1/4).sup.n w.sub.0 (2a.sub.1 -a.sub.0 -a.sub.2)t.sup.2 For approximation of an ellipse by the base, |E(s.sup.n (A), t)|≦(1/4).sup.n+1 w.sub.0 |2a.sub.1 -a.sub.0 -a.sub.2 | 0≦E(s.sup.n (w), t)≦(1/4).sup.n+1 2(w.sub.0 -w.sub.1) recall that for an ellipse, w0 ≧w1, (2.4) Error in a fraction Suppose the two quantities, x+Δx and y+Δy. x and y are the true values while Δx and Δy are errors in the quantities. What is then the error in the quotient of the two quantitites. Algebra gives. ##EQU31## Applying this formula to the problem, i.e. letting x=sn (A)(t) and y=sn (w)(t), the following results ##EQU32## Dividing top and bottom by sn (w)(t) ##EQU33## By choosing approximation by the base line for ellipses and approximation by the legs for hyperbolas, it can be insured that E(sn (w),t) is non-negative. This allows the following to be written ##EQU34## By plugging in the maximum errors and taking absolute values in the numerator as well as worst case estimates for other quantities in the denominator, the following results. ##EQU35## In order to make this more computationally tractable, the fact that maxt (sn (a)(t))≦maxt (a(t)) is used and results in ##EQU36## and is precomputable before any subdivision begins. Since the control points of sn (w)(t) are known at each iteration, and are a weighted average of two quantitites, an estimate is derivable for mint (sn (w)(t)) at each iteration by using the smallest control point. Suppose that it is wanted to ensure that E(sn (a),t)≦b. This can be done by ensuring that the right hand side of equation 4 is less than b. With rearrangement, the check for termination becomes ##EQU37## which takes one shift and one comparison at each node to compute. Up to this point, ellipses and hyperbolas have been treated together. However, in order to prove that this is a good bound and to derive a formula to precompute the sufficient depth of a uniform tree, each case must be analyzed separately. (2.5) Precomputable Bound for Ellipses For ellipses, it can be shown that such an estimate generates a formula for the sufficient depth of a uniform tree. This is done using the fact that for ellipses, w0 >w1 and ##EQU38## Beginning with formula 3, plugging in the bounds for ellipses, and applying the above facts, along with the fact that sn (a)(t)≦maxt (a(t)) the following results ##EQU39## If it is required that E(sn (a),t)≦b, any n satisfying ##EQU40## will do. So, for an ellipse, the ending condition will never generate a tree deeper than the bound given in the previous equation. Hence subdividing uniformly to that depth will also generate an accurate curve. (2.6) Precomputable Bound for Hyperbolas In this section a precomputable bound for hyperbolas is found. Starting with equation 3 and plugging in the errors for approximation by the legs, results in ##EQU41## For a hyperbola, w0 ≦w(t)≦w1 for every t. Hence, the first term in the error poses no problems, since ##EQU42## The second term, however, requires more analysis. Suppose that n is fixed and allow the meaning of s to vary. Recall that sn (w) denotes the function given by n subdivisions of w and at each subdivision, either the right or the left resultant curve may be chosen. For a hyperbola, it is clear that the choice which minimizes the absolute values of sn (w) is to choose the segment which contains one of the endpoints. Suppose the endpoint corresponding to t=0 is chosen. (The argument for t=1 is similar) Look at the quantity ##EQU43## for this segment. In particular its maximum value is to be found. A calculation shows that this quantity has nonnegative first derivatives at all points. Hence it will attain its maximum value for the maximum allowable value of t, namely 1/2. This value is ##EQU44## So with rearrangement, ##EQU45## Requiring E(sn (a),t)<b, it can be required ##EQU46## which is a precomputable depth given the curve and the error bound. Also, this is a bound on the depth to which the original error check will go since it represents a worst case for that check. (14) w(1)>w(0)=hyperbola w(1)<w(0)=ellipse.), and x(0)=x coordinate function at t=0, x.sub.t (0)=x.sub.t (t.sub.0 -Δt)-x(t.sub.0), x.sub.tt (0)=x.sub.t (t.sub.0 +Δt)-x.sub.t (t.sub.0), x.sub.ttt (0)=x.sub.tt (t.sub.0 +Δt) -x.sub.tt (t.sub.0), y(0)=y coordinate function at t=0, y.sub.t (0)=y.sub.t (t.sub.0 -Δt)-y(t.sub.0), y.sub.tt (0)=y.sub.t (t.sub.0 +Δt)-y.sub.t (t.sub.0), y.sub.ttt (0)=y.sub.tt (t.sub.0 +Δt) -y.sub.tt 0)(t.sub.0 +Δt)-X(0)(t.sub.0); X.sub.tt (0)=X.sub.t (0)(t.sub.0 +Δt)-X.sub.t (0)(t.sub.0); X.sub.tt (0)=X.sub.tt (0)(t.sub.0 +Δt)-X.sub.t (0)(t+Δt)-X(0)(t.sub.0); X.sub.tt (0)=x.sub.t (0)(t.sub.0 +Δt)-X.sub.t (0)(t.sub.0); X.sub.ttt (0)=X.sub.tt (0)(t.sub.0 +Δt)-X.sub.tt
https://patents.google.com/patent/US5408598A/en
CC-MAIN-2018-17
en
refinedweb
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Hi, I am trying to access a radio button and/or a check box to then set value for other custom fields on our form using the Behaviours plugin, but can seem to get the right syntax ... this is the one scenario with a radio button FormField Solution = getFieldByName("Solution") FormField Security = getFieldByName("Security Required?") String SolutionVal = (String) Solution.getValue() if (SolutionVal == "Solution 1" || SolutionVal == "Solution 2") { Security.setFormValue("Yes") } else { Security.setFormValue("Do Not Know") } Hi William, You should attach the following script to your "APS Solution" field with behaviours: import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.issue.customfields.option.Option import com.onresolve.jira.groovy.user.FormField def solutionField = getFieldById(getFieldChanged()) // this is APS Solution def securityField = getFieldByName("MSM Security Required?") // radio button def solutionValue = solutionField?.value if (solutionValue == "Retail" || solutionValue == "Loyalty") { securityField.setFormValue(optionFor(securityField, "Yes").optionId) } else { securityField.setFormValue(optionFor(securityField, "Do Not Know").optionId) } private Option optionFor(FormField securityField, String value) { def optionsManager = ComponentAccessor.getOptionsManager() def customFieldManager = ComponentAccessor.getCustomFieldManager() def customField = customFieldManager.getCustomFieldObject(securityField.getFieldId()) def config = customField.getRelevantConfig(getIssueContext()) def options = optionsManager.getOptions(config) def optionToSelect = options.find { it.value == value } optionToSelect } There is also some examples in the documentation that can help you piece this together. First setting the values: Also setting value based on another field changing: Hope this helps,.
https://community.atlassian.com/t5/Marketplace-Apps-questions/How-to-set-value-for-radio-button-or-check-boxes-in-Behaviours/qaq-p/292148
CC-MAIN-2018-17
en
refinedweb
Jersey Client Dependencies for JAX-RS 2.1 Jersey Client Dependencies for JAX-RS 2.1 If you're looking to make use of a JAX-RS client outside of an enterprise container, you'll need to know the necessary dependencies. Join the DZone community and get the full member experience.Join For Free Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now! Jersey. The> If JSON objects should be mapped using JSON-P, the following dependency is required as well: <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-processing</artifactId> <version>2.26</version> </dependency> This already adds an implementation for JSON-P 1.1, namely Glassfish javax.json. If JSON objects should be mapped using JSON-B, the following dependency is added instead of or additionally to the previous one: <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-binding</artifactId> <version>2.26</version> </dependency> This transitively adds the Yasson dependency, the reference implementation of JSON-B. These dependencies enable the project to use the JAX-RS 2.1 client together with JSON-P or JSON-B binding: Client client = ClientBuilder.newClient(); WebTarget target = client .target(""); Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get(); JsonArray customers = response.readEntity(JsonArray.class); response = target.path("123").request(MediaType.APPLICATION_JSON_TYPE).get(); Customer customer = response.readEntity(Customer.class); ... public class Customer { @JsonbTransient private long id; private String name; // getters & setters } And for our Gradle users, here is the equivalent of the Maven declarations: compile 'org.glassfish.jersey.core:jersey-client:2.26' compile 'org.glassfish.jersey.inject:jersey-hk2:2.26' compile 'org.glassfish.jersey.media:jersey-media-json-processing:2.26' compile 'org.glassfish.jersey.media:jersey-media-json-binding:2 }}
https://dzone.com/articles/jersey-client-dependencies-for-jax-rs-21
CC-MAIN-2018-17
en
refinedweb
#include <application.h> Inherits Wt::Object, and Wt::Singleton< DERIVED >< Wt::Application >. List of all members. Extend this class to create your application. Constructor. Default destructor. event handling Reimplemented from Wt::Object. process all events so far until the end of the application Halt execution and close window with a return code. process on event event if we have to wait for it process all events while the var is true process all the events in the queue for a maximum period of time process all events until the condition is met Halt execution and close window. Reimplemented from Wt::Singleton< DERIVED >. process the already posted events -- empties the queue This document is licensed under the terms of the GNU Free Documentation License and may be freely distributed under the conditions given by this license.
http://libwt.sourceforge.net/uguide/html/class_wt_1_1_application.html
CC-MAIN-2018-17
en
refinedweb
(source:) How often do you encounter #TODO: Fix this ? Too many times? Do you even notice it anymore, or does your sight slides through without noticing? If the answer for this question is positive, then this post is for you! People generally tend to procrastinate the work that is not necessary at the moment - and this is a good way of doing things. Too many time people over-implement a feature that turns out to be unnecessary for anyone – only wasting time and giving no value. Sometimes, while developing, one can spot a place for possible improvement, refactoring or much needed fix. But the worst that can be done here is to place a #TODO only. Why? Read on to find out. #TODO is present only in the source code. This means that no one besides developers will be aware of it. Not even each developer will know about it unless he works on this particular piece of code. Neither project managers nor the system architects usually access the source code of application and they are almost always oblivious aware of the idea of improvement. As a consequence they will not take it into consideration during their development plans - and as such they will not give programmers time to develop such fix, even when it's much needed. Other developers also won't benefit from this information - they encounter it while doing different task, they don't have to know what author of #TODO had exactly in mind. And it also goes other way around – if you’re assigned to task that is actually mentioned in one of #TODOs you’ll still spent time to examine the flow and eventually find this #TODO – instead of knowing this place right away from task description. Better situation is if we have both #TODO and a task reported somewhere in the system that the company uses. In case of such linked #TODO-task situation we get rid of both problems – the managers know that there is an issue pending, and the developer can always check what this #TODO refers to. But also this approach has its drawbacks - it's much easier to bury a task in the system, and it's way more difficult to coordinate removing actual annotation in the source code. You may ask if my point is actually valid - as many of IDEs support #TODOs by default and helps us dealing with them? Even frameworks itself have those features (for ex. Rails have rake notes:todo). Well, in theory you’re right, you can usually find all #TODOs in a convenient way. But it comes down to one simple question: Do you even use it? IDEs and frameworks tend to have many features that are barely used and this one seems to be one of them. Developers and project managers tend to have a big scope of duties and unless someone is directly forced to do this, they’re really not likely to do it. Especially when the number of things to check regularly is always increasing as the project grows more complex with time. And last, but not least, what would you do with the results even if you do actually use this feature? Go to the client and tell him “Next two weeks we’ll be making multiple #TODOs, ok"? Not gonna happen. Clients tend to care what they pay money for and don’t want to improve features unless they directly know that it will either benefit them or fix an already existing error. If it’s the first case – then we should have it reported in a system beforehand, if the second – it shouldn’t be a #TODO in a first place. #TODO tend to stay, very often they last in code long after the author of this comment has already forgotten he worked in the company. They tend to stay even if the idea behind is already gone, and the code changed so much that the intended change is no longer viable. Nobody deletes them, as it's not included in the scope of their task and sometimes they even believe some day this #TODO will fulfil its destiny. It won't. So what can we do, when we have an urge to add #TODO to our code? Do it immediately. Job will be done, nothing has to be remembered. This will probably mean that the task will take longer, so this factor should be taken into consideration if we plan to do it that way. But on the other hand you already are in a proper environment and you know exactly what you want to do. Report it in the system. Jira (or any other tool) is a great way for storing such tasks - it won't disappear, managers will be able to see it and if it's important to the project. Assign it to yourself, your superior or your manager - this way it will be remembered. Maybe it will never be done, but this is no longer your responsibility. The good practice here is to describe it as good as possible – event with small implementation details – as it would much help if another developer will cover this in future. In this situation adding a #TODOin the code with the reference to the task is available option Forget it. Sometimes even when you notice a place for improvement, you don't have resources for making them or the effort is too big for the potential gains. Projects are never complete. If somebody tells you that he finished his project, he’s simply lying. Improvement are always possible, updating libraries can always be done. That’s why managers create MVPs – because a developer will always find something to work on. Usually things don’t have to be perfect, they have to be good enough. As always, there has to be exception to the rules. There are situation where you can safely use #TODO marker. When you’re developing a major task that requires several days or even weeks of work, you may treat #TODO as sticky notes for this task. But only put it where you’re actually planning to develop in following days, not for a hypothetical developer who will work on in unforeseeable future. And remember to check that all #TODOs are gone when you submit your code for review. I think that #TODOs are also acceptable if you develop an application only by yourself and share the positions of developer, manager and even a client. In such case reporting tasks to external services may be a little overkill. Examples of #TODO Good example def index @projects = Project.all #TODO Filter the project listed by default. Task: PRO-1 end Bad example def index @projects = Project.all #TODO Filter the project listed by default. end Very bad example def index @projects = Project.all #TODO Fix that end How does it look like in real life? (state of 01.09.2017) (Source: My own research) As we can see – the well known ruby projects didn’t eliminate the “TODOs” entirely, but the number of them is relatively small (1 TODO on 1-5k LOC). And this is understandable, as sometimes you slightly can bend the rules. The problem is that when you have few TODOs on 100 LOC file. There is almost no chance that you will do them and either you will eventually delete them or they’ll stay there till the bitter end. Because, as always, the temporary solutions are usually staying in the project for a long, long time.
http://www.visuality.pl/posts/todo-not-do-or-do-not
CC-MAIN-2018-17
en
refinedweb
A supersonic micro-framework for building cloud APIs. Project Description Overview Come hang out with us in #falconframework on freenode. Falcon is a high-performance Python framework for building cloud APIs. It encourages the REST architectural style, and tries to do as little as possible while remaining highly effective. Perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away. - Antoine de Saint-Exupéry Design Goals Fast. Cloud APIs need to turn around requests quickly, and make efficient use of hardware. This is particularly important when serving many concurrent requests. Falcon processes requests several times faster than other popular web frameworks. Light. Only the essentials are included, with six and mimeparse being the only dependencies outside the standard library. We work to keep the code lean, making Falcon easier to test, optimize, and deploy. Flexible. Falcon can be deployed in a variety of ways, depending on your needs. The framework speaks WSGI, and works great with = api = falcon.API() # Resources are represented by long-lived class instances things = ThingsResource() # things will handle all requests to the '/things' URL path api.add_route('/things', things) You can run the above example using any WSGI server, such as uWSGI or Gunicorn. For example: $ pip install gunicorn $ gunicorn things:app Then, in another terminal: $ curl localhost:8000/things More Cowbell Here is a more involved example that demonstrates reading headers and query parameters, handling errors, and working with request and response bodies. import json import logging from wsgiref import simple_server) app = application = api # Useful for debugging problems in your API; works with pdb.set_trace() if __name__ == '__main__': httpd = simple_server.make_server('127.0.0.1', 8000, app) httpd.serve_forever() Contributing Kurt Griffiths (kgriffs) is the creator and current maintainer of the Falcon framework. Pull requests are always welcome. (one-liners are OK for now but body and footer may be required as the project matures). Legal Falcon image courtesy of John O’Ne Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/falcon/0.1.7/
CC-MAIN-2018-17
en
refinedweb
The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified! using System; using System.Text.RegularExpressions; public string getBrowser() { string functionReturnValue = null string searchforthis="Netscape"; Match q = Regex.Match(user_agent,searchforthis); if (q.Success) { functionReturnValue = "ns4"; } Dim source As String = "Luke, come to the dark side!" Dim found As Boolean = source.Contains("dark") Are you are experiencing a similar issue? Get a personalized answer when you ask a related question. Have a better answer? Share it in a comment. Join the community of 500,000 technology professionals and ask your questions.
https://www.experts-exchange.com/questions/26912457/Is-my-Regex-Syntax-correct-in-C.html
CC-MAIN-2018-17
en
refinedweb
The basis to define an integer attribute. More... #include <TDataStd_Integer.hxx> The basis to define an integer attribute. Dumps the minimum information about <me> on <aStream>. Reimplemented from TDF_Attribute. Returns the integer value contained in the attribute. Returns the ID of the attribute. Implements TDF_Attribute. Returns True if there is a reference on the same label. Returns an new empty attribute from the good end type. It is used by the copy algorithm. Implements TDF_Attribute. This method is different from the "Copy" one, because it is used when copying an attribute from a source structure into a target structure. This method may paste the contents of <me> into <intoAttribute>. The given pasted attribute can be full or empty of its contents. But don't make a NEW! Just set the contents! It is possible to use <aRelocationTable> to get/set the relocation value of a source attribute. Implements TDF_Attribute. Restores the backuped contents from <anAttribute> into this one. It is used when aborting a transaction. Implements TDF_Attribute. Finds, or creates, an Integer attribute and sets the Integer attribute is returned. Finds, or creates, an Integer attribute with explicit user defined <guid> and sets . The Integer attribute is returned. Sets the explicit GUID (user defined) for the attribute. Reimplemented from TDF_Attribute. Sets default GUID for the attribute. Reimplemented from TDF_Attribute.
https://www.opencascade.com/doc/occt-7.2.0/refman/html/class_t_data_std___integer.html
CC-MAIN-2018-17
en
refinedweb
Russell Butek wrote: > > So we've agreed to: > 1. remove --package > 2. add some sort of command line argument for the namespace-to-package > mappings > 3. look for a mapping properties file > 4. 2 takes precedence over 3 Yep. +1 > So now we have to decide > 2. What does the command line argument look like? How about > --NStoPkg <ns0> <pkg0> -N <ns1> <pkg1> ... -N <nsN> <pkgN> I'm thinking along the lines of what is easy to implement. The CLI util that we are already using supports 2 argurment parameters in the form of <arg1>=<arg2>. I suggest we use that. I would be +1 to "--NStoPkg" being the long form and "-N" being the short form. > 3. What's the name of this file? wsdl2java.mapping.properties? Are the > pairs in the file <namespace>=<package>? What happens if the namespace > string contains "=" or whitespace? Does java.util.Properties handle it? > Maybe the pairs should be <package>=<namespace>? Yes, java.util.Properties does handle that. Basically the information needs to be escaped by a backslash ('\='). If you generate the mapping from a Properties file, you will see what I mean. I believe whitespace requires you to enclose the property name in quotes. The Javadocs has all the information. I believe it is easier for the user if the namespace is first. Logically, we are mapping the namespace to the package, not the other way around. (not to mention the problems with using the Properties object). As to the name, it should probably match the WSDL file name with the "properties" extension in lieu of the "wsdl" extension: example: --------------- test.wsdl test.properties > About your last point, Berin, I disagree with you. I believe, via imports, > you can have multiple WSDL definitions and, therefore, multiple namespaces > for the WSDL things in the definitions. Here's an example from section > 2.1.2 of the WSDL spec. The namespace for the service and the binding is > "" and the namespace for the portType > is "". WSDL4J supports this. My last point is regarding XInclude processing--meaning it should be done before we process the WSDL document. If the resulting WSDL is bad, the author has given us an invalid document. I am relatively new to WSDL in detail, so if I say something rediculous let me know (as you are doing now ;P). In the example you presented, you are _not_ using XInclude semantics. Therefore my comments regarding XInclude don't apply here. The confusion surrounded comments (either in source or on the list) that alluded to us using XInclude for the processing. To use XInclude, the result would have to be altered like this: <?xml version="1.0"?> <definitions name="StockQuote" targetNamespace="" xmlns:tns="" xmlns:xsd1="" xmlns:soap="" xmlns: <xi:include > </definitions> The wsdl:import has different semantics around it--and in fact, I am surprised that WSDL4J doesn't automagically handle it for us. Since it is officially part of the spec, I would think that this is something WSDL4J needs to do. Otherwise, the utility of it is reduced.
http://mail-archives.apache.org/mod_mbox/axis-java-dev/200110.mbox/%3C3BC4756F.E97F3F07@apache.org%3E
CC-MAIN-2018-17
en
refinedweb
SADI - Perl extension for the automatic generation of SADI web services This new version of SADI contains some modifications to the entry CGI scripts for each service. In order to stay up to date with the SADI methodology, you should re-generate the cgi scripts for all of your services. The easiest way to update your services is to do the following (assuming for a second that your home directory is /home/ubuntu/ and that you are using a *NIX machine): To update your entry scripts, do something like: # C<for i in `find /home/ubuntu/Perl-SADI/cgi -type f -print`; do sadi-generate-services.pl $i; done> # C<for i in `find /home/ubuntu/Perl-SADI/cgi -type f -print`; do sadi-generate-services.pl -A $i; done> Of course, you will have to remove the scripts located /home/ubuntu/Perl-SADI/cgi. If you are on windows, try the following (assuming that your home directory is C:\Users\ubuntu\): # C<for /R %i in ("C:\Users\ubuntu\Perl-SADI\cgi\*") do sadi-generate-services %i> # C<for /R %i in ("C:\Users\ubuntu\Perl-SADI\cgi\*") do sadi-generate-services -A %i> Additionally, for those of you that pre-generate your service base files (not default operation), you will need to re-generate your service bases. For each service that is affected, do # C<sadi-generate-service -B your_service_name> for asynchronous services and a# C<sadi-generate-service -b your_service_name> for synchronous ones. If you have any problems whatsoever, please contact me or any other SADI developer for help! This new version of SADI uses an updated OWL2Perl module that adds many new items to generated OWL classes, as well as, makes them more memory and cpu efficient. In order to use these features to the fullest, you will need to regenerate all of your OWL2Perl generated OWL classes again, using sadi-generate-datatypes. This new version of SADI uses an updated OWL2Perl module that adds property restrictions to generated OWL classes. In order to use these features to the fullest, you will need to regenerate all of your OWL2Perl generated OWL classes again, using sadi-generate-datatypes. Version 0.99.5 contains some neat new features and bug fixes! One of the added features is the ability to add unit test for your service. All that is needed to upgrade to 0.99.5 is for you to re-run the sadi-install.pl script. For those of you upgrading a previous SADISeS installation and using OWL2Perl modules, you will need to regenerate your datatypes. After careful consideration, it was determined that we could clean up the package names for generated owl entities. The easiest way to update your services is to do the following (assuming for a second that your home directory is /home/ubuntu/ and that you are using a *NIX machine): To update your implementation files, do something like: for i in `find /home/ubuntu/Perl-SADI/services/Service -type f -print`; do perl -pi -e 's|::owl::|::|g' $i; done If you are on windows, try the following (assuming that your home directory is C:\Users\ubuntu\): for /R %i in ("C:\Users\ubuntu\Perl-SADI\cgi\*") do perl -pi -e 's|::owl::|::|g' %i Additionally, for those of you that pre-generate your asynchronous service base file (not default operation), you will need to re-generate your service basis. For each service that is affected, do a sadi-generate-service -B your_service_name. For those of you upgrading a previous SADISeS installation, you will need to decide if you want to remove the CGI entry scripts for your services and re-generate them. The reason for this is that the mime type header for SADI services has been changed to "application/rdf+xml", as per the W3C RDF spec. While this change makes your services more correct, it doesnt change how your services behave. The easiest way to update your services is to do the following (assuming for a second that your home directory is /home/ubuntu/ and that you are using a *NIX machine): To update your entry scripts, do something like: for i in `find /home/ubuntu/Perl-SADI/cgi -type f -print`; do perl -pi -e 's|text/xml|application/rdf\+xml|g' $i; done If you are on windows, try the following (assuming that your home directory is C:\Users\ubuntu\): for /R %i in ("C:\Users\ubuntu\Perl-SADI\cgi\*") do perl -pi -e 's|text/xml|application/rdf\+xml|g' %i # to get started, run the install script sadi-install.pl # for those of you using MS Windows (commands are issued without the ".pl") sadi-install # generate a service definition file, for example HelloSadiWorld sadi-generate-services.pl -D HelloSadiWorld # now you have to go and edit the definition file # in Perl-SADI/definitions/HelloSadiWorld # to point it to the various ontologies that your service uses # once you have done that, then... # generate a service implementation, based on this edited # definitions file. In this example, you would simply type: sadi-generate-services.pl HelloSadiWorld # now add your business logic to the module that was created in # Perl-SADI/services/Service/HelloSadiWorld.pm # finally, make a symbolic link from Perl-SADI/cgi/HelloSadiWorld to # your cgi-bin/ directory to deploy your service. # assuming that you deployed it, test the service (-g gets the service interface # while -e allows you to send input data to the service) sadi-testing-service.pl -g # read the POD for more details! This is the documentation for Perl SADISeS (SADI Services Support). If you are reading this from the perldoc utility, you may notice that some words are missing or that some phrases are incomplete. In order to view this documentation in the manner intended, please view the html version of this documentation that was installed duing make install or the version on CPAN. First of all, it is assumed that you are familiar with SADI. If this assumption is false, please go to the SADI homepage (). Hopefully, you have chosen to install this package so that you can create SADI web services. SADI is a novel Web Services framework that dynamically generates RDF graphs by accessing Web Services. Web Service discovery is achieved by registering the type of relationship (i.e. the predicate) that the Web Service creates between its input data and its output data. Installation of this helpful perl package is straightforward! On *nix machines, install as follows: perl Makefile.PL make test make install On Window machines, install as follows: perl Makefile.PL nmake test nmake install Assuming that you have already installed this package, the very first thing that you should do is run the script sadi-install.pl. This script will do the following: Once the installation process is complete, you can create your first service! Perl SADISeS, is a project aiming to help SADI service providers develop their code in Perl. The basic design principles are the same: to provide libraries that allow a full object-oriented approach to SADI services(data types and service instances) and shielding service developers from all the nitty gritty required to develop SADI services. Some of the new features included in this release are: Perl SADI is a generator of Perl code - but this code does not need to be always stored in files, it can be generated on-the-fly every time a service is called. Also, there are up to four things to be generated: objects representing SADI data types, classes establishing bases for services, empty (but working) service implementation modules, and cgi-bin scripts, the entry points to our SADI services. However, before going into the gory details, let's install Perl SADI, create and call the first service. From the command prompt, enter: sadi-install or, sadi-install.pl This works, because part of the installation for the SADISeS module entails the installation of scripts that make SADISeS tasks more simple. You can pick any name for your service: sadi-generate-services -D HelloSadiWorld or, sadi-generate-services.pl -D HelloSadiWorld This will create a definition for your SADI service (in the <your-home-directory>/Perl-SADI/definitions/ directory). Next create the implementation for the SADI service by doing: sadi-generate-services HelloSadiWorld or, sadi-generate-services.pl HelloSadiWorld It creates a Perl module Service::HelloSadiWorld (in <your-home-directory>/Perl-SADI/services/), representing your first SADI Web Service . The service is empty - but is already able to accept SADI input requests and recognize its own data type, and it produces fake output data (of the correct type). The only thing you need to do is to tell your Web Server where there is a starting cgi-bin script. The script was already created during the service generation phase in <your-home-directory>/Perl-SADI/cgi directory. Make a symbolic link from a cgi-bin directory of your Web Server (e.g on some Linux distributions, using Apache Web server, the cgi-bin directory is /usr/lib/cgi-bin). For example: cd /usr/lib/cgi-bin sudo ln -s /home/kawas/Perl-SADI/cgi/HelloSadiWorld . on windows, you can mimic the above If you cannot create Symbolic links, or apache is not allowed to follow them, try this workaround There is a testing client that sends only empty data (so it can be used by any service): sadi-testing-service.pl -e Of course, you can also send real data, from a local file (for example, from data/my-input.xml): sadi-testing-service.pl -e \ data/my-input.xml The output (the same with any input data) is not really that exciting: HTTP/1.1 200 OK Connection: close Date: Tue, 25 Aug 2009 20:45:08 GMT Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.3 with Suhosin-Patch Vary: Accept-Encoding Content-Type: text/xml; charset=ISO-8859-1 Client-Date: Tue, 25 Aug 2009 20:45:09 GMT Client-Peer: 127.0.0.1:80 Client-Response-Num: 1 Client-Transfer-Encoding: chunked <rdf:RDF xmlns:a="" xmlns: <rdf:Description rdf: <a:somePredicate0>0</a:somePredicate0> <a:somePredicate1>1</a:somePredicate1> <a:somePredicate2>2</a:somePredicate2> </rdf:Description> </rdf:RDF> You immediately notice that the returned value does not have an expected "hello" greeting. Well, a fake output is just fake output. You would need to add your own business logic into your service to do something meaningful (such as saying warmly "Hello, SADI world"). Also, the service provider can see few log entries: 2009/08/26 08:35:28 (254) INFO> [5554] (eval 34):38 - *** REQUEST START *** REMOTE_ADDR: 127.0.1.1, HTTP_USER_AGENT: libwww-perl/5.829, CONTENT_LENGTH: 228, CONTENT_TYPE: application/x-www-form-urlencoded 2009/08/26 08:35:28 (278) INFO> [5554] (eval 34):84 - *** RESPONSE READY *** The number in square brackets is a process ID - it helps to find which response belongs to which request when a site gets more to many requests in the same time. And in parenthesis, there is the number of milliseconds since the program has started. More about the log format in logging. SADISeS in Perl was created to allow people to enter the SADI world with little to no barriers. Web services are complicated enough without SADI! Why should SADI add to the complications? based on objects created on-the-fly (or pre-generated) from service definition files and OWL classes. (and therefore easier changeable if/when needed) support for service configuration, for request logging, and even for protocol binding (for example, in your service implementation code there are no visible links to any HTTP protocol). In other words, the services written with the Perl SADI as their back-end are more unified and less prone to be changed when their environment changes. They should differ really only in their business logic (what they do, and not how they communicate with the rest of the world). The other modules needed are (all available from the CPAN): The installation script is (as well as the other Perl SADI scripts) installed at module install time and is available from any command prompt. You should run it the first time, and you can run it anytime later again. The files that are already created are not overwritten - unless you want it to be (using the -F option). sadi-install.pl or sadi-install on the MS Windows platform This is an example of a typical conversation and output of the first installation: ubuntu@ubuntu:~/Perl-SADI$ sadi-install.pl Welcome, SADIiers. Preparing stage for Perl SADI ... ------------------------------------------------------ OK. Module Carp is installed. OK. Module CGI is installed. OK. Module File::Spec is installed. OK. Module Config::Simple is installed. OK. Module File::HomeDir is installed. OK. Module File::ShareDir is installed. OK. Module Log::Log4perl is installed. OK. Module HTTP::Date is installed. OK. Module Template is installed. OK. Module Params::Util is installed. OK. Module Class::Inspector is installed. OK. Module Unicode::String is installed. OK. Module IO::String is installed. OK. Module RDF::Core is installed. OK. Module IO::Prompt is installed. Installing in /home/ubuntu/Perl-SADI Created install directory '/home/ubuntu/Perl-SADI'. Created install directory '/home/ubuntu/Perl-SADI/cgi'. Created sample-resources directory '/home/ubuntu/Perl-SADI/sample-resources'. Created service defintions directory '/home/ubuntu/Perl-SADI/definitions'. Created service defintions directory '/home/ubuntu/Perl-SADI/unittest'. Created service defintions directory '/home/ubuntu/Perl-SADI/xml'. Log properties file created: '/home/ubuntu/Perl-SADI/log4perl.properties'. Configuration file created: '/home/ubuntu/Perl-SADI/sadi-services.cfg'. Done. All these things can be done manually, at any time. Installation script just makes it easier for the first comers. Here is what the installation does: * It checks if all needed third-party Perl modules are available. Since you got this far, they most likely are! It does not help with installing them, however. Perl has a CPAN mechanism in place to do that. The required modules are listed in requirements. Installation stops if some module is not available. * It creates a directory called 'Perl-SADI' in your user directory. Perl SADI will stop working if you move this directory because it contains vital configuration information inside it. * It creates sub directories in the 'Perl-SADI' directory for places to store your service definitions, generated code, example service input, etc. * It creates two empty log files Perl-SADI/services.log and Perl-SADI/parser.log - unless they already exist. In any case, it changes their permissions to allow everybody to write to them. This helps later, when the same log files are written to by a Web Server. The purpose of these two files is described in logging. * It creates a Perl-SADI/log4perl.properties file from a distributed template, and updates their locations to reflect your local installation. Again, more about this file in logging. * Finally, it creates a configuration file Perl-SADI/sadi-services.cfg (unless it already exists). See more about how to further configure Perl SADI in configuration. If you wish to install from scratch (the same way it was done the first time), start it by using a force option: sadi-install.pl -F In this mode, it overwrites the files sadi-services.cfg, services.log, parser.log and log4perl.properties. There is a little extra functionality going on behind the scenes: If the configuration file sadi-services.cfg exists when you start the installation script, its values are used instead of default ones. It may be useful in cases when you plan to put all Perl SADI directories somewhere else (typically and for example, if your Web Server does not support symbolic links that can point to the current directories). In such cases, edit your sadi-services.cfg, put the new locations inside it, and run sadi-install.pl again. Perl Moses generates Perl code. Actually, up to four pieces of the code: SADISeS allows for easier implementation of SADI services by allowing you to use automatically generated PERL modules representing OWL classes in your service implementation. The Generated perl modules that represent OWL classes have their own constructors, contain getter and setters for their datatype properties, and even have range checking for object properties. While the generator isn't perfect, it will do the job in most cases; making your service provision much more simple. Each Perl SADI service implementation can benefit by inheriting some basic functionality from its base. These bases contain the code specific for the given service. The service base takes care about: * Logging request/response. * Allowing to run a service locally, outside of the HTTP environment (good for early testing). * Catching and reporting exceptions if the input is wrong or incomplete. You can see its code by running (for example): sadi-generate-services.pl -sb HelloSadiWorld Again, the services bases can be generated and loaded on-the-fly, or pre-generated in the files. This is your playground! What is generated is only an empty service implementation - and you are supposed to add the meat - whatever your service is expected to do. Well, it is not that empty, after all. First, because it inherits from its base, it already knows how to do all the features listed in the paragraph above: #----------------------------------------------------------------- # Service name: HelloSadiWorld # Authority: helloworld.com # Created: 26-Aug-2009 07:52:01 PDT # Contact: myaddress@organization.org # Description: # the usual hello world service #----------------------------------------------------------------- package Service::HelloSadiWorld; use FindBin qw( $Bin ); use lib $Bin; #----------------------------------------------------------------- #; # (this to stay here with any of the options above) use vars qw( @ISA ); @ISA = qw( com::helloworld::HelloSadiWorldBase ); use strict; Second, it has the code that reads the input, using methods specific for this service. It does not do anything with the input, but the code shows you what methods you can use and how:) } And finally, it produces a fake output (not related to the input at all). Which is good because you can call the service immediately, without writing a single line of code, and because you see what methods can be used to create the real output: # fill in the output nodes - this is what you need to do! foreach my $output (0..2) { # for example ... $core->addOutputData( node => $core->Signature->OutputClass, value => "$output", predicate => "" ); } The service implementations are definitely not generated on-the-fly. They must be pre-generated into a file (because you have to edit them, don't you?). Again, the sadi-generate-services.pl script will do it. More in scripts. The files generated into the Perl-SADI/cgi directory are the gateway for the world to use your SADI services. These scripts are the ones that you will be deploying to the apache cgi-bin directory and usually do not need changing! Scripts The scripts are small programs that generate pieces and that let you test things. They share some basic features: * They are automatically installed with the perl module. * They can be started from anywhere. * They all are Perl programs, expecting Perl executable in /usr/bin/perl. If your perl is elsewhere, start them as: perl -w <script-name> * They all recognize an option -h, giving a short help. They also have options -v (verbose) and -d (debug) for setting the level of logging. Here they are in the alphabetic order: This script does not do much but gives you overview of your configuration and installation. You can run it to find how Perl SADI will behave when used. For example: Perl-SADI VERSION: 0.96 Configuration ------------- Default configuration file: sadi-services.cfg Environment variable SADI_CFG_DIR is not set Successfully read configuration files: sadi-services.cfg All configuration parameters: generators.impl.definitions => /home/ubuntu/Perl-SADI/definitions generators.impl.home => /home/ubuntu/Perl-SADI generators.impl.outdir => /home/ubuntu/Perl-SADI/services generators.impl.package.prefix => Service generators.outdir => /home/ubuntu/Perl-SADI/generated log.config => /home/ubuntu/Perl-SADI/log4perl.properties All imported names (equivalent to parameters above): Logging ------- Logger name (use it in the configuration file): services Available appenders (log destinations): Log: /home/ubuntu/Perl-SADI/services.log Screen: stderr Logging level FATAL: true Logging level ERROR: true Logging level WARN: true Logging level INFO: true Logging level DEBUG: false Logging configuration file Name: /home/ubuntu/Perl-SADI/log4perl.properties Contents: log4perl.logger.services = INFO, Screen, Log #log4perl.logger.services = DEBUG, # for parser debugging log4perl.logger.parser = INFO, ParserLog #log4perl.logger.parser = DEBUG, ParserLog log4perl.appender.ParserLog = Log::Log4perl::Appender::File log4perl.appender.ParserLog.filename = /home/ubuntu/Perl-SADI/parser.log log4perl.appender.ParserLog.mode = append log4perl.appender.ParserLog.layout = Log::Log4perl::Layout::PatternLayout log4perl.appender.ParserLog.layout.ConversionPattern = %d (%r) %p> [%x] %F{1}:%L - %m%n Testing log messages (some may go only to a logfile): 2009/08/26 08:38:37 (50) FATAL> [[undef]] sadi-config-status.pl:106 - Missing Dunkin' Donuts This script is really important for those of you wishing to use PERL modules representing your OWL classes. Basically, this script reads your OWL file and processes all of the OWL classes and properties specified in that file. Once the processing is complete, PERL modules representing those classes and properties are either written to disk or displayed on screen. One obvious question is "where are these perl objects generated"? You can always determine this after generation by looking in the log file - the message has the INFO level which means it is almost always logged. But, if you want to know in advance here are the rules: You can use option -s to get the generated result directly on the screen (in that case no file is created). To generate OWL classes and properties from a remote url, you would use the -u option. This option sets the base URI for the OWL file to be the URL to the OWL file (if one didn't already exist). If the file you would like to generate classes and properties from resides on your disk, then you would use not specify any option. If the local file doesn't specify a base URI for the ontology, you can do this with the -b flag. When the script executes, it will prompt you for a URI. More often than not, your ontology will contain import statements. If you wish to follow them, you need to set the -i flag. This flag tells the script to process import statements, so make sure that you have an internet connection if the referenced files are located somewhere remote. Like the other SADI scripts included in this distribution, you can access the script help page by running the script with the -h flag. For more information on the perl OWL modules that were generated, read the perldoc for the class or property of interest! This is the most important script. You may use only the sadi-install.pl and this one - and you will get all what you need. It generates services - all pieces belonging to services (except data types). Usually, you generate code for one or only several services. Before you can generate an implementation for your service, you need to generate and edit a definition file for it. sadi-generate-services.pl -D HelloSadiWorld will generate a definition file for the service and will place it into Perl-SADI/definitions. Once created, all you need to do is modify the various values as you see fit. An example of a definition file is listed below# make sure to escape the chars: # #,= with a \, for instance \# # new lines in a property value are not supported yet! # dont change the service name! # if you find that you need to modify # the service name, regenerate a new file # and remove this one! ServiceName = HelloSadiWorld # modify the values below as you see fit. ServiceType = InputClass =\#Input1 OutputClass =\#Output1 Description = An implementation of the 'HelloSadiWorld' service UniqueIdentifier = urn:lsid:myservices:HelloSadiWorld Authority = authority.for.HelloSadiWorld Authoritative = 1 Provider = myaddress@organization.org ServiceURI = URL = SignatureURL = Follow up the generation of the Service definition with a call to sadi-generate-services.pl to generate your skeleton files! sadi-generate-services.pl HelloSadiWorld There are several configurables options to influence the result: generators.impl.outdir dictates where the code is to be generated. generators.impl.package.prefix tells what package name should be used (the package name always ends with the service name as was used during definition generation). Default is Service. With options, you can generated other Perl SADI pieces: Option -D generate a definition file for the service that you can fill in. This is the first thing that you need to generate before generating a service implementation! Option -b generates service bases, Option -S generates both service bases and service implementations. This also influences how the service base will be used at run-time: if it is already generated (with the -S option) there is no need to do it again in the run-time - therefore, the service implementation is generated slightly differently - with an option "use the base, rather than load the base" enabled. Option -A generates both a service implementation as well as an asynchronous module. This is not supported yet! You can use option -s to get the generated result directly on the screen (in that case no file is created). This script is used for installation. A script for the testing of your SADI web service. It does not give you the comfort that you can get from other SADI clients - but it is well suited for immediate testing. It calls a SADI service in one of the two modes (actually the two modes are completely separated to the point that this script could be two scripts): In both modes, the script can send an input RDF/XML file to the service - but if the input file is not given, an empty input is created and sent to the service. Which is not particularly useful, but still it can help with some preliminary testing. When calling the service locally, you may use the following options/parameters: * A mandatory package name - a full package name of the called service. * Option -l location can be used to specify a directory where is the called service stored. Default is Perl-SADI/services. * Options -v and -d make also sense in this mode (but not in the other one). * An optional input file name. sadi-testing-service.pl -d Service::HelloSadiWorld The output of this call was already shown in this documentation. Therefore, just look what debug messages were logged (notice the -d option used): 2009/08/26 09:17:32 (218) INFO> [6283] (eval 45):38 - *** REQUEST START *** 2009/08/26 09:17:32 (218) DEBUG> [6283] (eval 45):46 - Input raw data: <?xml version="1.0"?> <rdf:RDF xmlns: </rdf:RDF> 2009/08/26 09:17:32 (227) INFO> [6283] (eval 45):85 - *** RESPONSE READY *** The full mode has the following options/parameters: One of: * An optional input file name. This method only makes sense with the -e option. As the -g option is used to get the service interface. sadi-testing-service.pl \ -e Configuration means to avoid hard-coding local-specific things (such as file paths) into the code itself but hard-coding them in a separate file, a file that is not shared with other (CVS) users. Perl SADI stores configuration in a file named moby-services.cfg. The file name is hard-coded (and cannot be changed without changing the SADI::Config module), but its location can be set using an environment variable SADI_CFG_DIR. Perl SADI looks for its configuration place in the following places, in this order: 1. In the "current" directory (which is not that well defined when used from a Web Server). 2. In the directory given by SADI_CFG_DIR environment variable. 3. In the directory <your-user-dir>/Perl-SADI/. 4. In one of the @INC directories (directories where Perl looks for its modules). Therefore, the best place is to keep the configuration file together where the installation script puts it anyway. The Perl SADI internally uses Config::Simple CPAN module, but wraps it into its own SADI::Config. This allows expansion later, or even changing the underlying configuration system. The Config::Simple is simple (thus the name, and thus we selected it) but has few drawbacks that may be worth to work on later. The file format is as defined by the Config::Simple. It can be actually of several formats. The most common is the one distributed in the sadi-services.cfg.template. This is an example of a configuration file: [generators] outdir = /home/ubuntu/Perl-SADI/generated impl.outdir = /home/ubuntu/Perl-SADI/services impl.package.prefix = Service impl.definitions = /home/ubuntu/Perl-SADI/definitions impl.home = /home/ubuntu/Perl-SADI [log] config = /home/ubuntu/Perl-SADI/log4perl.properties #file = /home/ubuntu/Perl-SADI/services.log #level = info #pattern = "%d (%r) %p> [%x] %F{1}:%L - %m%n" The names of the configuration parameters are created by concatenating the "section" name (the one in the square brackets) and the name itself. For example, the logger configuration is specified by the parameter log.config. Parameters that are outside of any section has just their name, or they can be referred to as from the default section. For example, these two names are equivalent: default.cachedir and cachedir. Blank lines are ignored, comments lines start with a hash (#), and boolean properties must have a value ('true' or 'false'). Obviously, important is to know what can be configured, and how. This document on various places already mentioned several configuration options. Here is their list (for more explanations about their purpose you may visit an appropriate section of this document): generators.outdir - Directory where to generate data types and service bases. The default value for data types is 'generated', for service bases is 'services'. generators.impl.outdir - Directory where to generate service implementations. Default is 'Perl-SADI/services'. generators.impl.package.prefix - A beginning of the package name of the generated service implementations. Default is 'Service'. For example, a service Mabuhay will be represented by a Perl module Service::Mabuhay. generators.impl.definitions - Directory where SADI web service definition files are kept. generators.impl.home - The users Perl-SADI directory. Default is 'Perl-SADI'. log.config - A full file name with the Log4perl properties. No default. If this parameter is given but the file is not existing or not readable, Perl SADI complains on STDERR (which may end up in the Web Server error.log file). log.file - A full file name of a log file (where the log messages will be written to). No default. If the value is 'stderr' (case-insensitive) the messages will go to the STDERR. It is not clear what happens when it is used together with the above log.config. log.level - A log level. Default is ERROR. log.pattern - A format of the log messages. Default is '%d (%r) %p> [%x] %F{1}:%L - %m%n'. The parameters just described are used by Perl SADI modules - but the configuration system is here also for your own services. You can invent any not-yet-taken name, and add your own parameter. In order not to clash with the future Perl Moses parameters, it is recommended to prefix your configuration properties with the service name. For example, the HelloSadiWorld service needs to read a file with "hellos" in many languages, so it defines: [HelloSadiWorld] resource.file = /home/ubuntu/Perl-SADI/samples-resources/HelloSadiWorld.file All configuration parameters are imported to a Perl namespace SADICFG. The imported names are changed to all-uppercase and dots are replaces by underscores. You can see this change if you run the config-status.cfg: $SADICFG::HELLOSADIWORLD_RESOURCE_FILE In your program, you can use the imported names. For example, here is how the HelloSadiWorld service opens its resource file: open HELLO, $SADICFG::HELLOSADIWORLD_RESOURCE_FILE or $self->throw ('HelloSadiWorld resource file not found.'); You can also change or add parameters during the run-time. For example, to overwrite existing parameters because you want to create everything in a separate place, in a temporary directory, and within the 'Testing' package. Because the generators read from the configuration files: my $outdir = File::Spec->catfile ($tmpdir, 'generated-services'); SADI::Config->param ('generators.impl.outdir', $outdir); SADI::Config->param ('generators.impl.package.prefix', 'Testing'); unshift (@INC, $SADICFG::GENERATORS_IMPL_OUTDIR); my $generator = new SADI::Generators::GenServices; More about how to communicate pragmatically with the configuration can be (hopefully) find in the Perl Modules Documentation. The logging system is based on a splendid Perl module Log::Log4perl, a Perl port of the widely popular log4j logging package. The Log4perl is well documented (here is its POD documentation). How does it work in Perl SADI? The logging is available from the moment when Perl SADI knows about the SADI::Base module. All generated service implementations inherit from this class, so all of them have immediate access to the logging system. By default, the SADI::Base creates a logger in a variable $LOG. Which means that in your service implementation you can log events in five different log levels: $LOG->debug ("Deep in my mind, I have an idea..."); $LOG->info ("What a nice day by a keyboard."); $LOG->warn ("However, the level of sugar is decreasing!"); $LOG->error ("Tim Hortons'' Donuts"); $LOG->fatal ('...and we are out of their splendid coffee!'); The logger name is "services". (The name is used in the logging configuration file - see below). You can create your own logger. Which may be good if you wish to have, for example, a different logging level for a particular service, or for a part of it! Here is what you need to do: use Log::Log4perl qw(get_logger :levels); my $mylog = get_logger ('my_log_name'); Then use the name "my_log_name" in the configuration to set its own properties. Which brings also us to the logging configuration. The logging configuration can be done in three ways: If Perl SADI cannot find a log4perl.properties file, and if there are no logging options in sadi-services.cfg, it assumes some defaults (check them in SADI::Base, in its BEGIN section, if you need-to-know). The better way is to use log4perl.properties file. The file name can be actually different - it is specified by an option log.config in the sadi-services.cfg configuration file. This is what Perl SADI installation creates there (of course, using your own path): [log] config = /home/ubuntu/Perl-SADI/log4perl.properties The log4perl.properties is created (in the installation time) from the log4perl.properties.template, by putting there your specific paths to log files. The log4perl (or log4j) documentation explains all details - here is just a brief example what is in the file and what it means: log4perl.logger.services = INFO, It says: Log only INFO (and above) levels (so no DEBUG messages are logged) on the screen (meaning on the STDERR) and to a file. But because of the "screen appender" has defined a Threshold FATAL - the screen (STDERR) will get only FATAL messages. There is no threshold in the "file appender" so the file gets all the INFO, WARN, ERROR and FATAL messages. In both cases the format of the messages is defined by the "ConversionPattern". Note that printing to STDERR means that the message will go to the error.log file of your Web Server. To change the log level to DEBUG, replace INFO by DEBUG in the first line. The message format (unless you change the Perl SADI default way) means: %d (%r ) %p > [%x ] %F{1} :%L - %m %n 2009/08/28 11:38:07 (504) FATAL> [26849] HelloSadiWorld:63 - Go away! 1 2 3 4 5 6 7 8 Where: The last option how to specify logging properties is to set few configuration options in the sadi-service.cfg file. It was already mentioned that there is an option log.config that points to a full log property file. If this option exists, no other logging configuration options are considered. But if you comment it out, you can set the basics in the following options: [log] #config = /home/ubuntu/Perl-SADI/log4perl.properties file = /home/ubuntu/Perl-SADI/services.log level = info pattern = "%d (%r) %p> [%x] %F{1}:%L - %m%n" Where log.file defines a log file, log.level specifies what events will be logged (the one mentioned here and above), and the log.pattern creates the format of the log events. This is meant for a fast change in the logging system (perhaps during the testing phase). There are definitely more features in the Log4perl system to be explored: For example, in the mod_perl mode it would be interesting to use the "Automatic reloading of changed configuration files". In this mode, Log::Log4perl will examine the configuration file every defined number of seconds for changes via the file's last modification time-stamp. If the file has been updated, it will be reloaded and replace the current logging configuration. Or, one can explore additional log appenders (you will need to install additional Perl modules for that) allowing, for example, to rotate automatically log files when they reach a given size. See the Log4perl documentation for details. Deploying means to make your SADI web service visible via your Web Server. By contrast to the deployment of the Java-based services, Perl services are invoked by a cgi-bin script directly from a Web Server - there is no other container, such as Tomcat in the Java world. Which makes life a whole bunch easier. Well, only slightly, because soon you will start to think about using mod_perl module, and it may make things complicated. TO BE DONE The Perl SADI was not tested in the mod_perl environment, at all. But it should be. I wonder if anybody can explore this a bit. In order to deploy a Perl SADI service, you need: #!/usr/bin/perl -w # This is a CGI-BIN script, invoked by a web server when an HTTP # POST comes in, dispatching requests to the appropriate module # (SADI web service). # # It includes some hard-coded paths - they were added during the # generate service call. # # $Id: SADI.pm,v 1.36 2010-03-09 18:04:43 ubuntu Exp $ # Contact: Edward Kawas <edward.kawas@gmail.com> # --------------------------------------------------------------- #----------------------------------------------------------------- # Authority: helloworld.com # Service name: HelloSadiWorld # Generated: 26-Aug-2009 10:15:16 PDT # Contact: Edward Kawas <edward.kawas@gmail.com> #----------------------------------------------------------------- use strict; # --- during service generation --- # leave at the top! use lib '/home/ubuntu/Perl-SADI/generated'; use lib '/home/ubuntu/Perl-SADI/services'; use lib '/home/ubuntu/Perl-SADI'; use CGI; use CGI::Carp qw(fatalsToBrowser); use SADI::Service::Instance; use SADI::RDF::Core; use SADI::Generators::GenServices; # limit the max size of a post - change it as you see fit $CGI::POST_MAX=1024 * 1024 * 10; # max 10MB posts # here we require the service module and add it to ISA hierarchy use base 'Service::HelloSadiWorld'; # get the cgi variable my $q = new CGI; # if this is a GET, send the service interface if ($ENV{REQUEST_METHOD} eq 'GET') { # send the signature for this service # instantiate a new SADI::RDF::Core object my $core = SADI::RDF::Core->new; # set the Instance for $core $core->Signature(__PACKAGE__->get_service_signature('HelloSadiWorld')); print $q->header(-type=>'text/xml'); print $core->getServiceInterface(); } else { # call the service # get the data from the 'data' parameter my $data = $q->param('data') || $q->param('POSTDATA') || ""; # call the service my $x = __PACKAGE__->HelloSadiWorld($data); # print the results print $q->header(-type=>'text/xml'); print $x; } __END__ These 2 things (a Web Server knowing about your cgi-bin scripts and a cgi-bin script knowing about Perl SADI code) are all you need to have your service deployed. After reading so far you may still wonder: Okay, but what should I do in my implementation to gain all the benefits generated for me by Perl SADI? This section will try to answer it - but notice that some particular activities were already explained in corresponding sections about logging and configuration. First of all, you need to have a service implementation, at least its starting (empty) phase. Generate it, using the sadi-generated-services script. Depending on how you generate it (without any option, or using an -S option) generator enables one of the following options (not that it matters to your business logic code): #----------------------------------------------------------------- #; Secondly, you need to understand when and how your implementation code is called: Your service implementation has to implement method process_it that is called for every incoming SADI web service request. The SADI::Service::ServiceBase has details about this method (what parameters it gets, how to deal with exceptions, etc.). In the beginning of the generated process_it method is the code that tells you what methods are available for reading inputs, and at the end of the same method is the code showing how to fill the response. Feel free to remove the code, extend it, fill it, turn it upside-down, whatever. This is, after all, your implementation. And Perl SADI generator is clever enough not to overwrite the code once is generated. (It is not clever enough, however, to notice that it could be overwritten because you have not touched it yet.) Perhaps the best way how to close this section is to show a full implementation of (so often mentioned) service HelloSadiWorld: #----------------------------------------------------------------- # process_it # This method is called for every client request. # Input data are in $values. # You will need to add output via $core->addOutputData() # this method adds nodes to the final output. # param keys: node, value, predicate #----------------------------------------------------------------- sub process_it { my ($self, $values, $core) = @_; # empty data, then return return unless $values;) } # fill in the output nodes - this is what you need to do! foreach my $output (0..2) { # for example ... $core->addOutputData( node => $core->Signature->OutputClass, value => "$output", predicate => "" ); } } When you go through the code above you notice how to do basic things that almost every service has to do. Which are: Reading input data: The possible methods were already pre-generated for you so you know what methods to use. But you should always check if the data are really there (the clients can send you rubbish, of course). The question is what to do if input (or anything else) is not complete or valid. This brings us to... Reporting exceptions: One option is to throw an exception: open HELLO, $SADICFG::HELLOSADIWORLD_RESOURCE_FILE or $self->throw ('HELLO SADI WORLD resource file not found.'); This immediately stops the processing of the input request. Another, less drastic, option is to record an exception (and, usually, return): TO BE DONE - not sure of how to report errors in SADI Creating output data:Again, methods for creating response were pre-generated, so you have hints how to use them. foreach my $output (0..2) { # for example ... $core->addOutputData( node => $core->Signature->OutputClass, value => "$output", predicate => "" ); } For more information on how to use the $core variable, refer to SADI::RDF::Core! This can be done using the following steps (Please make sure to back up the file first!): <Directory "C:/Documents/Eddie/Perl-SADI"> AllowOverride None Options +ExecCGI Order allow,deny Allow from all </Directory> Add the following to the end of your httpd.conf file: <Directory "/path/to/cgi-bin" > Options +FollowSymLinks </Directory> Make sure to change /path/to/cgi-bin to be the real path to your cgi-bin directory! If you cannot create symbolic links, another tested alternative would be to copy your file HelloSadiWorld to the cgi-bin directory of your web server. Once the file has been copied, change the ownership of the file to the web servers' user/group. Also, make sure that the path (and its parents) to all of the directories in the 'use lib ...' are readable by your web server. That's all there is to it! Now when you test your services, remember that your file may no longer be called HelloSadiWorld, but something else that you named it! doesnt seem to work too well and produces numerous warnings in our module. Other versions have yet to be tested. There will be always bugs waiting to be fixed. Please let us know about them. And there are features (and known) bugs that should or could be implemented (or fixed). Here are those I am aware of (B = bug, N = not yet implemented, F = potential future feature): * (N) Parsing the input and output owl classes and creating perl module stubs for them so that you can use them in your code and not have to manipulate RDF by yourself. * (N) Documentation of the Perl Modules is unfinished, and links to it are not yet included in this document. This is an important part of the documentation because it expands hints how to write your own service implementation. * (N) The generated service implementation could have a better Perl documentation, listing all available methods for inputs and outputs (the methods are already shown in the code, but having them also in the POD would help). An up-to-date list of the recent changes is in the Changes file included with the distribution. The main perl developers (whom please direct your suggestions and reports to) are Edward Kawas and Mark Wilkinson. However, there would be no SADISes without CardioSHARE - CardioSHARE is generously supported by the Heart and Stroke Foundation of B.C. and Yukon, the Canadian Institutes of Health Research, and Microsoft Research. Lots of code was written by Martin Senger for the Perl MoSeS module and used in this module. None by default. For information on SADI, please see Please visit the SADI website British Columb.
http://search.cpan.org/~ekawas/SADI-1.10/lib/SADI.pm
CC-MAIN-2015-40
en
refinedweb
Patrick de Kruijf wrote:Hello, I'm staring at a code I copied from a reader I got from my school, I understand most of it but I can't figure out what the usage is of this. . What does this. do? public class Stock { private String name; private int amount; private double value; public (String name, int amount, int value) { this.name = name; this.amount = amount; this.value = value; } public String getname() { return this.name; } public void setname(String name) { this.name = naam; } public int getsamounts(){ return this.amount; } public void setstocks(int amount){ this.amount = amount; } public double getvalue(){ return this.value; } public void setvalue(double value) { this.value = waarde; } } Thanks in advance for your time and effort! Seetharaman Wrote, typically, this represents currently executing object. Patrick de Kruijf wrote: I will pay more attention to my question in the future. Patrick de Kruijf wrote: You say I have to follow the JavaBean convention on methods, you mean I had to type? public String getName(){} instead of public String getname(){} Patrick de Kruijf wrote:I have started writing the code below for a assingment for my school, I think I almost understand what the use of this.is. Is it true that this.age refers to the parameter put in the setAge(int age) method in the class Goose? Am I right when I say that this.age refers to the argument send from gilbert.setAge in the class GooseTestDrive? (if the Object made from the Goose class is Gilbert ofcourse.) Patrick de Kruijf wrote:So when I write gilbert.setAge(4); in the GooseTestDrive class, then this.age in the Goose class is 4 for the object gilbert of class Goose. And then when I say this.age = age in the class Goose; The instance variable age gets a value of 4, but only for the object gilbert of the class Goose? Patrick de Kruijf wrote:Thank you very much for this 'AHA' moment! Abimaran Kugathasan wrote: Patrick de Kruijf wrote:Thank you very much for this 'AHA' moment! What's that?
http://www.coderanch.com/t/508942/java/java/usage
CC-MAIN-2015-40
en
refinedweb
JDK - GetAbsolutePath doesn't By ByronNevins on Mar 21, 2008 I just finished fixing a bug and I decided to share it so you can avoid the misery of finding it yourself. JDK's java.io.File is not that smart about Files vs. String Paths. You may use getAbsolutePath and getAbsoluteFile because you think it will really give you an absolute path. Not true at all. It merely fills in the beginning of the path for you. It does nothing about trailing dots. Say your current directory is /foo. Let's say you have a file named x in the current directory. String s = new File("x").getAbsolutePath(); this returns "/foo/x". Perfect! Now say you do something crazy like String s = new File("../foo/./x").getAbsolutePath(); this returns "/foo/./x" -- doesn't look absolute to me! What the JDK means by absolute is only that the absolute path will unambiguously point at a file -- without needing the location of the current directory. Period. It does most definitely not imply that that you are getting a path with no relative elements in it. getCanonicalFile and getCanonicalPath are highly under-used methods in my experience. These methods guarantee to return a 1:1 mapping with the file. I.e. there is one and only one unique Canonical path for every file on disk. There are an infinite number of Absolute paths for a given file. String s = new File("../foo/./x").getCanonicalPath(); this returns "/foo/x" -- just what you wanted. Now here is where I got into trouble. I'm given a ABSOLUTE path to a jar file. I need to get the parent directory of the directory that contains the jar file. So I innocently did the following: given: File f which internally has this path "/foo/lib/./x.jar" File grandparent = f.getParentFile().getParentFile(); String s = grandparent.getPath(); I expected the String to be "/foo" It wasn't though, it was "/foo/lib"! JDK says the parent is "/foo/lib/.", and the parent of the parent is "/foo/lib" JDK is not treating "." specially but, rather, like it's a regular file in this context! My code was working perfectly until the caller decided to drop a dot in the middle of the path and then suddenly my code broke. SOLUTION: Use CanonicalPath and CanonicalFile. But wait -- they might throw an IOException. What a hassle!! That's no big deal. I've been using them for years and I have never seen an Exception get thrown. JDK is paranoid because these methods call into native code to get the right path. I've written this following snippet of code way, way too many times. I highly recommend it -- but add it into your utility code, write it once and call it a gazillion times. public static File sanitize(File f) { if(f == null) { return null; } try { return f.getCanonicalFile(); } catch(Exception e) { return f.getAbsoluteFile(); } } Here is some sample code you can try, along with the output: public class Main { public static void main(String[] args) { File f = new File(System.getProperty("java.io.tmpdir") + "/foo"); f.mkdirs(); String foo = f.getPath(); foo += "/./././././."; f = new File(foo); // f is now "c:/tmp/foo/./././././." while((f = f.getParentFile()) != null) { System.out.println("PARENT: " + f); } } } Output: PARENT: c:\\tmp\\foo\\.\\.\\.\\.\\. PARENT: c:\\tmp\\foo\\.\\.\\.\\. PARENT: c:\\tmp\\foo\\.\\.\\. PARENT: c:\\tmp\\foo\\.\\. PARENT: c:\\tmp\\foo\\. PARENT: c:\\tmp\\foo PARENT: c:\\tmp PARENT: c:\\ Great eye-opener. Thanks. Posted by Kedar Mhaswade on March 21, 2008 at 03:57 PM PDT # Great work, Byron.Very interesting Posted by Siraj Ghaffar on March 22, 2008 at 01:45 AM PDT #
https://blogs.oracle.com/foo/entry/jdk_getabsolutepath_doesn_t
CC-MAIN-2015-40
en
refinedweb
0 Hi! i'm a bit new in c++ so i'v got some question wish you to answer me...! first of all i want my program to show the specific group of line of my file so i use this code for it: using namespace std; int main() { ifstream myfile; myfile.open("test.txt"); cout<<"which line to start showing?"; string showline; cin>>showline; string line; while(getline(myfile,line)) { if(line==showline) { do { cout<<line<<endl; }while(line!="javad"); } } myfile.close(); } what is the problem of this code? can anyone give the correct one of this or another one for my question? 2.after that i want my program to delete specific lines of my file... i don't have any idea what to do... can anyone give the code? thanks so much!
https://www.daniweb.com/programming/software-development/threads/443602/need-some-help-in-files
CC-MAIN-2015-40
en
refinedweb
In this section, you will learn about handling the situation where view name is not provided, through RequestToViewNameTranslator interface. Where no view name is provided, the RequestToViewNameTranslator interface determines the view name automatically. For this you need to configure DefaultRequestToViewNameTranslator class in Spring MVC configuration file. To understand it completely, lets take an example : Consider the below controller code : public class WritingController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) { // request processing ModelAndView model= new ModelAndView(); // note that no view name is provided // addition of data as to the model return model; } } Note that no view name is provided in the above code. For auto generation of the view name, you need to configure the DefaultRequestToViewNameTranslator class in Spring MVC configuration file as shown below : <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns: <!-- this bean with the well known name generates view names for us --> <bean id="viewNameTranslator" class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator"/> <bean class="x.y.Writing> In the above controller code, you can see that no view name is provided. The DefaultRequestToViewNameTranslator class, configured in conjunction with ControllerClassNameHandlerMapping , is responsible for auto generating view name. In the above case, if the requested URL is : the resultant generated logical view name would be writing .According to above configuration and returned view name the resultant view name would be reside in " /WEB-INF/jsp/ " as writing.jsp. Advertisements Posted on: January: Autogenerated logical view name through RequestToViewNameTranslator Post your Comment
http://roseindia.net/spring/spring3.2/Autogenerated_logical_view_name_through_RequestToViewNameTranslator.shtml
CC-MAIN-2015-40
en
refinedweb
C++ Callback Demo This article was contributed by Elmue. Environment: Pure C++. Runs on Windows, Mac, Linux, and so on. Introduction This fully functional example shows how in C++ callbacks can be done in an absolutely flexible way! Callbacks in C++ are not as simple as in C. Pure C functions are from the type __cdecl. C++ functions are from the type __thiscall. (They differ in the way how they pass arguments on the stack.) In C++, you have classes and, additionally, instances of classes. Every instance uses its own memory area for storing class variables. The pointer to this area of variables is the "this" pointer. It represents the instance. Every time you call any C++ function, the "this" pointer is passed to the function as an invisible parameter! (M$ Visual Studio 6 uses the processor register ECX to pass the "this" pointer.) So, in C++ it is not enough to store the address of the function, which you want to call back. You also have to store the "this" pointer! Using the Callback Class You can include "Callback.h" into your project. The usage it is very simple because the cCallback class has only two member functions: SetCallback() and Execute(). You can understand the following examples without knowing what is happening inside cCallback. cMyProject.h: #include "callback.h" private: // the functions of your project void CallbackFox (int Param); void CallbackRabbit(int Param); void TestTheCallback(cCallback *pCallbackFunction, int Param); // Some instances of the Callback class TCallback<cMyProject> i_Callback_1; TCallback<cMyProject> i_Callback_2; cMyProject.cpp: void cMyProject::CallbackRabbit(int Param) { char Buf[50]; sprintf(Buf, "Now I'm in Rabbit with Param %d !\n", Param); printf(Buf); } void cMyProject::CallbackFox(int Param) { char Buf[50]; sprintf(Buf, "Now I'm in Fox with Param %d !\n", Param); printf(Buf); } void); } If you call cMyProject::CallbackDemo(), the output will be: Now I'm in Rabbit with Param 16 ! Now I'm in Fox with Param 25 ! Callback Re-Definitions It is also possible to re-define the callback with SetCallback() as often as you like: void cMyProject::CallbackDemo() { i_Callback_1.SetCallback(this, &cMyProject::CallbackRabbit); TestTheCallback(&i_Callback_1, 4); i_Callback_1.SetCallback(this, &cMyProject::CallbackFox); TestTheCallback(&i_Callback_1, 5); } The output would be the same, but i_Callback_2 is not needed anymore. Callback Arrays It is also possible to use arrays of callbacks: cMyProject.h: private: TCallback<cMyProject> i_Callback[10]; cMyProject.cpp: void TestTheCallback(int Index, int Param) { i_Callback[Index].Execute(Param * Param); } void cMyProject::CallbackDemo() { i_Callback[0].SetCallback(this, &cMyProject::CallbackRabbit); i_Callback[1].SetCallback(this, &cMyProject::CallbackFox); i_Callback[2].SetCallback(.....); TestTheCallback(0, 4); TestTheCallback(1, 5); } Callback Arrays, Part 2 In the above example, all callbacks are from cMyProject. In i_Callback you can ONLY store callbacks to the cMyProject class because it is defined as TCallback<cMyProject>. If you want to store callbacks to different classes in a callback array, you have to create the array from cCallback instead of TCallback: cMyProject.h: private: cCallback *p_Callback[10]; cMyProject.cpp: void cMyProject::StoreCallback(cCallback *p_CallbackFunction, int Index) { p_Callback[Index] = p_CallbackFunction; } StoreCallback() then can be called by ANY class to set a callback to itself. For example: cDemo.h: private: TCallback<cDemo> i_MyCallback; cDemo.cpp: #include "cMyProject.h" extern cMyProject i_MyProject; ...... i_MyCallback.SetCallback(this, &cDemo::MyCallbackFunction); i_MyProject.StoreCallback(&i_MyCallback, Index); ...... You can even later modify i_MyCallback with SetCallback() without having to call StoreCallback() again!! In the source code (see the download link at the end of this article) you find a different example, and additionally a demonstration of a global callback, which you need, if you want to be called back by the operating system. (Windows API callbacks always go into the global namespace.) The Callback Class Finally, here comes the great cCallback class itself. It consits of only a header file without a corresponding cpp file. Callback.h: class cCallback { public: virtual void Execute(int Param) const =0; }; template <class cInstance>; }; This class defines an Execute() function that takes one integer parameter and returns no parameter (void). You can simply adapt it to your needs; for example, a callback that takes five paramaters and returns a bool. (Then, you have to modify three lines: the two lines beginning with "virtual void Execute" and the typedef.) To completely understand this class, you need advanced C++ knowledge. I will not explain all the details here because this would be too much. Instead I recommend the very good book: Author: André Willms Title: C++ Programming (German title: "C++ Programmierung") Publisher: Addison Wesley ISBN 3-8273-1495-X And from my homepage, you can download free C++ books in the compiled HTML format. ã¸ãã¼ãã¥ã¦ ããã°= by MefeTillQuise on 07/12/2013 05:12am ããããã®ææï¼ç¬ï¼ã¯ç¹ã«ããã対çãã ãããç«ã¡ã¾ãEO対çã¦ãSEOæãhoo!æ¤ä¸ãããã®å¤§èª²é¡50åã¯ãã ãã©ãå¤æåºã [url=]ãã¼ã¯ãã¤ãã¼ã¯ã¸ã§ã¤ã³ãã¹ ã¢ã¦ãã¬ãã[/url] ã°ãã ãã¼ã±ã¼ã¹= [url=]ã¸ãã¼ãã¥ã¦ ã»ã¼ã«[/url] ã§ããã®ããé£ãã«ã«æ¿ãæ¿å®ã«ã¯åæãã°è¯ãã ãã§å¤±ãå¤ãï¼ï¼ï¼ã¨ãã£ãã¨ããå¤ãã£ã¦ãã®ãããªæããåç´ã®äººãªã©ã«ãå¹æçãªãã¼ã ãã¼ã¸ã§ã¯ãªããYahoã£ã¦ãï¼ [url=]ã¸ãã¼ãã¥ã¦ é´[/url] ãã¼ã¯ãã¤ãã¼ã¯ã¸ã§ã¤ã³ãã¹ ããã°= [url=]ã³ã¼ã[/url] ãã¼ã¯ãã¤ãã¼ã¯ã¸ã§ã¤ã³ãã¹ æè¨= [url=]GUCCI ããã°æãæã[/url] [url=]ãã¼ã¯ãã¤ãã¼ã¯ã¸ã§ã¤ã³ãã¹ åºè[/url] ã¸ãã¼ãã¥ã¦ åºè= [url=]ã°ãã ãã¼ãããã°[/url] ã¸ãã¼ãã¥ã¦ ã¢ã¦ãã¬ãã= ã¸ãã¼ãã¥ã¦ ã¡ã³ãº= [url=]ã¸ãã¼ãã¥ã¦ é´[/url] [url=]ã¸ãã¼ãã¥ã¦ é´[/url] ã°ããããã°ã¢ã¦ãã¬ãã= ã³ã¼ã 財å¸= [url=]ã¸ãã¼ãã¥ã¦ 財å¸[/url] 対çãã¼ã¸ãçºä¿¡ã®ã¦ããããªã§ãã¦ã®æ ã¼ã¸ã®å¶ã§æ¸ã¾ããã®ãæãªããã§æ¿ããã¼ãªãè²´éã ã¨èãã¦ã¾ããããããè¼ã£ã¦ã¾ããã御å覧ããã°ããã«ãã¨ã«ããå å®åº¦ã¯ç¨æãªãã®ã¨ãã«ã®ãã¦ããã¾ã£ãï¼ ã¸ãã¼ãã¥ã¦ ããã°ã¸ãã¼ãã¥ã¦ åºè= ã¸ãã¼ãã¥ã¦ é´= Wholesale Oakley Big Taco no tax worldwidePosted by tgijsiutj on 07/07/2013 04:29am FakE OaklEyS ,Oakley can be a unique group of scientific, artistic, unyielding challenge in the traditional contemplating the cultural heritage, but also very persistent. The main products include women's Oakley sunglasses, ski goggles, motocross goggles, golf series, leisure series, special series of five major categories, besides hats, T-shirts, handbags along with peripheral products. When you pick a set of two designer sunglasses, it's guaranteed to become the Oakley sunglasses to elegant and classy colors will really affect the way you look. Cheap Oakley Frogskins ,Oakley sunglasses tend to be the dedicated efforts and expensive high-tech outcomes of the survey. Sunglasses in the past two years has increasingly turned into a real fashion designers than ever before. These Oakley sunglasses are available in the market for all age groups, the main range of colors, styles and designs. Glasses may make up his face disadvantage, people seem more temperament, specifically in sun glasses, to ensure the face is always to choose sunglasses. Experience of your skin, nose pad special high-energy minerals thetemperature reached 32 degrees, you aren't doing the special energy and negative ions, in order to achieve the antioxidant, and gradually the role of cell activity, and promote head blood circulation, thus effectively relieve eye fatigue . Fake Oakleys ,Various Internet Providers for the comfort of the customer's request, select on the list of men and women probably be accurate and appropriate glasses and identity. The outer layer of skin and eyes has reached the risk of solar energy, solar radiation (UV). It had been founded through the rays of the sun and ultraviolet illumination In point of fact, exposure might cause burning in the sun, scaring the organization. Fake Ray Ban ,While using merciless sun beating right, it's not a strong of sunglasses perched on his nose to strengthen outdoor. In year retro massive construction projects, Oakley glasses as essential clothing accessories, and sometimes keep to the outfits go, sometimes they lead the trend. SacS Longchamp ,Cheap male OAKLEY sunglasses more(a) 99% in the film is enhanced polarized glasses shape at the molecular level. Oakley lenses don't simply stop there simply because employ a hydrophobic coating re-execution, preventing moisture build up lenses. Find the ideal company know of high quality and solid guarantee scheme, can not simply mention how much interest and welcome jealous eyes.Reply ã³ã¼ã 財å¸= by LesNaltestake on 06/26/2013 06:14pm COACH ã¡ã³ãº= æãã¦ããã ãä¸å¯§ã«è§£ãã¦ãè¾¼ãï¼ï¼ãããããã¦ããï¼ï¼ããã³ããããã[url=]ã³ã¼ã æããã[/url]èªåãã©ãå ¥ã ï¼ï¼æªãï¼ ã³ã¼ã ã¢ã¦ãã¬ãã= ã¾ãããåå¿è ãå¹æããªã ããå®ç§ãª[url=]ã³ã¼ã ã¢ã¦ãã¬ãã[/url]SEOãã§ãªSEOãªã©åå¨ããªå¤§ããå¹ã®ãäºãã¨ãã ã³ã¼ã æããã= ç¾å½¹ã¦æ¬æ°äº¤è¤ãä¼¼åãæã®é³¶ã©ã¤ããããªã§ããã¶ã§ã¯ãªãã«ä»ç«ã¦ã¦[url=] COACH ããã°[/url]ãããã³ã«ç¡¬ããªããèã®ç¡ããããã³ã¯ã®ãReply Michael Kors PursesPosted by gogofkn on 05/14/2013 06:13pm I'm looking at your site through Google Chrome and not each of the pictures is displaying right. Did you know about this? toms shoes sale toms shoes ray banReply bxmaobPosted by Mandyyad on 03/30/2013 12:07pm oakley sunglasses,Younger brother is the sworn brother to sworn to Your brother the Monkey King Torr World ah! Cattle devil looked at the familiar face goes, several hundred years later, finally appeared in front of him, think carefully, after he identified. To know Princess Iron Fan's affair in mind so that his head green cap is still green, that is a huge shame his life! His disgrace in the demon world face the pain of the man than this! Is the little brother ray ban wayfarer ah! Monkey King saw the astonished face cow devil I know Me, then quickly respond cattle devil face with a happy, his Deyizhiyu also did not care about his side the Jingjing Hechun 30th Niang face of surprising and strange, or else he will not respond so readily and excitement. ray ban wayfarer sizes kill you hook her sister-in-law of anti-bone Aberdeen!oakley sunglasses discount,raybansunglassesouty.com/" title="ray ban clubmaster"ray ban clubmaster, Cattle devil confirmed after the fact, immediately toward Monkey King swallowed their anger, waving his big fork, want killed and outlet.Reply cheap ugg boots vEsr mMghPosted by Suttonjge on 03/09/2013 05:19am michael kors bags nfaswndu michael kors handbags zgtumsfn michael kors outlet mmxqxuvd michael kors purse ehvtikeg michael kors purses aeevevwh michael kors sale zagkrigz michael kors pccdklkxReply ghd australia jbraodPosted by Mandyglh on 02/03/2013 05:41pm 7uXdj ugg pas cher vDlh ¥åê©`¥é`¥à ¥Ã¥å° fLsq nike sko 7nQez cheap toms 3aFkr cheap hollister 1tDmb bottes ugg 1oHau longchamp pliage 1mSfv cheap louis vuitton 7aBci michael kors bags 7xTls christian louboutin norge 9cThe 49ers jerseys 2cCko 1nKet GHD Australia 1zHbl Lisseur GHD 9gJwt ugg boots saleReply ugg boots alwpoy by Mandyqep on 01/26/2013 11:00pm 2gJpu nike outlet mMji Michael Kors outlet wJsu ugg boots 7nKrj monster beats 6dZnx Cheap nfl jerseys 7eXes ugg norge 8tWdk burberry outlet 9vAfu longchamp 8nWyg nike air max 7kEuf cheap ugg boots 0eOvx monster beats 7wSib ugg 1gBsw GHD Australia 4lMjo 5xWuxReply wfhkjt vrzkiuPosted by rootlyJerie on 11/15/2012 03:49am C++ Callback Demo pfdkxs ptjlclk adgkly doudoune moncler bqeqosd lvusbcgu doudoune moncler femme gozerck ymxmz moncler france cigseoee moncler france cufjsdxb abercrombie vbzjzhbgReply lydwry olymbfPosted by PambInabe on 11/10/2012 11:51pm C++ Callback Demo mhzdmu smbojfx sefypk polo ralph lauren uk przmcoe chplrgbb ã¢ãã£ã¼ãf50 rxmmgif sgufr air ã¸ã§ã¼ãã³ qtdlfauq ããã·ã£ã ltzrkrqe ã´ã£ãã³ ã¢ãã°ã©ã jcywkkqdReply
http://www.codeguru.com/cpp/cpp/cpp_mfc/callbacks/article.php/c4129/C-Callback-Demo.htm
CC-MAIN-2015-40
en
refinedweb
File I/O with Streams - Part 1 - An Excerpt from Inside C#, Second Edition The StreamReader and StreamWriter ClassesAs you can see, FileStream is OK for reading and writing raw byte (binary) data. If you want to work with character data, classes such as StreamReader and StreamWriter are more suitable. These classes will use a FileStream object in the background, effectively interposing a character-interpolation layer on top of the raw byte processing. Closing the StreamReader/StreamWriter also closes the underlying FileStream: public class ReadWriteApp { public static void Main(string[] args) { FileStream s = new FileStream("Bar.txt", FileMode.Create); StreamWriter w = new StreamWriter(s); w.Write("Hello World"); w.Close(); s = new FileStream("Bar.txt", FileMode.Open); StreamReader r = new StreamReader(s); string t; while ((t = r.ReadLine()) != null) { Console.WriteLine(t); } w.Close(); } } The output follows: Hello World Recall from Table 1 that the StreamReader and StreamWriter classes can use Encoding to convert characters to bytes and vice versa. To write our data to the file with some encoding other than the default, we need to construct the StreamWriter and StreamReader with an Encoding parameter, as shown here: //StreamWriter w = new StreamWriter(s); StreamWriter w = new StreamWriter(s, System.Text.Encoding.BigEndianUnicode); If you want to open a file that's been set to read-only, you need to pass an additional parameter to the FileStream constructor to specify that you only want to read from the file: s = new FileStream("../../TextFile1.txt", FileMode.Open, FileAccess.Read); Paths in C#Because C# treats the backslash the same way as C and C++ do, if you want to specify a path for a file, you have three choices. You can either use double backslashes, as in: s = new FileStream("C:\\temp\\Goo.txt", FileMode.Create);...or use forward (Unix-style) slashes: s = new FileStream("C:/temp/Goo.txt", FileMode.Create);...or use the "@" character, which is a control-character suppressor: s = new FileStream(@"C:\temp\Goo.txt", FileMode.Create); Memory and Buffered StreamsThe classes MemoryStream and BufferedStream are both derived from the abstract Stream class, just as FileStream is. Therefore, MemoryStream and BufferedStream share many of the same characteristics and functionality. Both are designed for streaming data into and out of memory rather than persistent storage. Both can be associated with a stream of another kind.such as a file.if required, and thus both can be used to act as a buffer between memory and persistent storage. The MemoryStream class offers methods such as WriteTo, which will write to another stream. Similarly, a BufferedStream object is normally associated with another stream on construction, and when you close the BufferedStream, its contents are flushed to the associated stream. In the following example, we first create a MemoryStream object with an initial capacity of 64 bytes and print some arbitrary property values. Then we write out 64 bytes and report the same properties. We then use MemoryStream.GetBuffer to get a byte array of the entire contents of the stream and print the values, before finally closing the stream: class MemStreamApp { static void Main(string[] args) { MemoryStream m = new MemoryStream(64); Console.WriteLine("Length: {0}\tPosition: {1}\tCapacity: {2}", m.Length, m.Position, m.Capacity); for (int i = 0; i < 64; i++) { m.WriteByte((byte)i); } Console.WriteLine("Length: {0}\tPosition: {1}\tCapacity: {2}", m.Length, m.Position, m.Capacity); Console.WriteLine("\nContents:"); byte[] ba = m.GetBuffer(); foreach (byte b in ba) { Console.Write("{0,-3}", b); } m.Close(); } } Here's the output: Length: 0 Position: 0 Capacity: 64 Length: 64 Position: 64 Capacity: Given that the stream is already up to capacity, let's see what happens if we write some more data to it. Will it generate a runtime exception? Will it overrun into unallocated memory? Or will it just dynamically resize the buffer? The last scenario is, of course, the correct one.which you.ll realize if you've examined the previous output closely. Although we set an initial capacity of 64, this wasn.t the initial size of the memory buffer because the buffer was initialized to 0. So, clearly, the buffer is dynamically resized automatically. string s = "Foo"; for (int i = 0; i < 3; i++) { m.WriteByte((byte)s[i]); } Console.WriteLine("\nLength: {0}\tPosition: {1}\tCapacity: {2}", m.Length, m.Position, m.Capacity); Here's the output: Length: 67 Position: 67 Capacity: 256 As you can see, the minimum block size is 256 bytes. Finally, let.s associate this MemoryStream with a FileStream before closing it: FileStream fs = new FileStream("Goo.txt", FileMode.Create, FileAccess.Write); m.WriteTo(fs); m.Close(); Now let.s do the same thing with a BufferedStream object. Although generally similar, there are some subtle differences between MemoryStream and BufferedStream. First, we can construct a BufferedStream only by initializing it to some other existing Stream.in this example, a file. The buffer in a BufferedStream is managed differently than that in the MemoryStream: if we don.t specify an initial size when we construct the object, it defaults to 4096 bytes. Also, if we've written some data to the BufferedStream and want to read it back, we must use the Read method.because there is no GetBuffer method. Using the Read method means making sure the internal stream pointer is positioned correctly.in this case, at the beginning of the stream.before attempting the read: class BufStreamApp { static void Main(string[] args) { // Create a FileStream for the BufferedStream. FileStream fs = new FileStream("Hoo.txt", FileMode.Create, FileAccess.ReadWrite); BufferedStream bs = new BufferedStream(fs); Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); for (int i = 0; i < 64; i++) { bs.WriteByte((byte)i); } Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); // Reset to the beginning and read the data. Console.WriteLine("\nContents:"); byte[] ba = new byte[bs.Length]; bs.Position = 0; bs.Read(ba, 0, (int)bs.Length); foreach (byte b in ba) { Console.Write("{0,-3}", b); } // Write some more, exceeding capacity. string s = "Foo"; for (int i = 0; i < 3; i++) { bs.WriteByte((byte)s[i]); } Console.WriteLine("\nLength: {0}\tPosition: {1}\t", bs.Length, bs.Position); for (int i = 0; i < (256-67)+1; i++) { bs.WriteByte((byte)i); } Console.WriteLine("\nLength: {0}\tPosition: {1}\t", bs.Length, bs.Position); bs.Close(); } } The console output is listed here: Length: 0 Position: 0 Length: 64 Position: Length: 67 Position: 67 Note that the Hoo.txt file will have the same contents as those in the MemoryStream example. We didn.t have to explicitly write from the BufferedStream to the FileStream as we did for MemoryStream because the BufferedStream must be associated with another stream in the first place. All writes to the BufferedStream will be buffered for writing to the associated stream, and merely closing the BufferedStream object is enough to flush any pending writes to the file. Page 3 of 6
http://www.developer.com/net/csharp/article.php/10918_2106771_3/File-IO-with-Streams---Part-1---An-Excerpt-from-Inside-C-Second-Edition.htm
CC-MAIN-2015-40
en
refinedweb
I'm not sure that me managing to produce a map with only 4 colours would have "proved" anything :-) As the help dialog explains, the light blue areas contain all the tiny namespaces that don't "make the cut". In reply to Re^2: CPAN - As Seen From Space! by grantm in thread CPAN - As Seen From Space! by grantm Yes No Other opinion (please explain) Results (99 votes), past polls
http://www.perlmonks.org/index.pl?parent=943919;node_id=3333
CC-MAIN-2015-40
en
refinedweb
Difference between default arguments and keyword arguments Discussion in 'Python' started by Edward Diener, Apr 4, difference between a namespace and class with just default constructorYoussef Mesri, Jan 17, 2006, in forum: C++ - Replies: - 15 - Views: - 704 - Earl Purple - Jan 19, 2006 keyword checker - keyword.kwlist, May 10, 2007, in forum: Python - Replies: - 6 - Views: - 620 - Peter Otten - May 10, 2007 RE: keyword checker - keyword.kwlistHamilton, William, May 10, 2007, in forum: Python - Replies: - 4 - Views: - 462 Keyword arguments in a block, possible with zero arguments?Peter Motzfeldt, Mar 13, 2007, in forum: Ruby - Replies: - 1 - Views: - 223
http://www.thecodingforums.com/threads/difference-between-default-arguments-and-keyword-arguments.329539/
CC-MAIN-2015-40
en
refinedweb
Manages all the rendering at the level of the observer's surroundings. More... #include <LandscapeMgr.hpp> Manages all the rendering at the level of the observer's surroundings. This includes landscape textures, fog, atmosphere and cardinal points. I decided to put all these elements together in a single class because they are inherently linked, especially when we start moving the observer in altitude. Create a new landscape from the files which describe it. Reads a landscape.ini file which is passed as the first parameter, determines the landscape type, and creates a new object for the landscape of the proper type. The load member is then called, passing both parameters. Draw the landscape graphics, cardinal points and atmosphere. Reimplemented from StelModule.. Get the light pollution following the Bortle Scale. Get atmosphere fade duration in s. Get the order in which this module will draw it's objects relative to other modules. Reimplemented from StelModule. Get Cardinals Points color. Return a pseudo HTML formated string with all informations on the current landscape. Get the current landscape ID. Get the current landscape name. Get the default landscape ID. Return a pseudo HTML formated string with information from description or ini file. Get flag for displaying Atmosphere. Get flag for displaying Cardinals Points. Get flag for displaying Fog. Return the value of the flag determining if a change of landscape will update the observer location. Return the global landscape luminance, for being used e.g for setting eye adaptation.. This function searches for a file named "landscape.ini" in the root directory of the archive. If it is not found there, the function searches inside the topmost sub-directories (if any), but no deeper. If a landscape configuration file is found: The landscape identifier is either: The landscape identifier must be unique.. Set the light pollution following the Bortle Scale. Set atmosphere fade duration in s. Set Cardinals Points color. Change the current landscape to the landscape with the ID specified. Change the current landscape to the landscape with the name specified. Change the default landscape to the landscape with the ID specified. Set flag for displaying Atmosphere. Set flag for displaying Cardinals Points. Set flag for displaying Fog. Set the value of the flag determining if a change of landscape will update the observer location. Set the rotation of the landscape about the z-axis. This is intended for special uses such as when the landscape consists of a vehicle which might change orientation over time (e.g. a ship). Update time-dependent state. Includes: Implements StelModule.
http://stellarium.org/doc/0.11.4/classLandscapeMgr.html
CC-MAIN-2015-40
en
refinedweb
iTerrainFactoryState Struct ReferenceAllows the setting of a set of generic terrain parameters outside any specific algorithm. More... [Mesh plugins] #include <imesh/terrain.h> Detailed DescriptionAllows the setting of a set of generic terrain parameters outside any specific algorithm. It is up to the algorithm to determine the best use of the information provided in the interface. Definition at line 176 of file terrain.h. Member Function Documentation Save/Restore preprocessing information, the algorithm will do some preprocessing based on the material and height information this allows the process to be saved out to a file and cached for later reuse (maybe this should be the caching system) In some cases it may actually memorymap this file. This specifies the max region the renderer will sample from. This is more of a hint to the renderer as it may try to optimally sample only from regions near the camera. The terraformer defines the height, scale and other properties related to the formation and structure of the terrain. The terrain rendering plugin will sample from this data model based on its algorithm. The terraformer can be shared between plugins, especially plugins which use the information for vegatation rendering. The documentation for this struct was generated from the following file: Generated for Crystal Space 1.2.1 by doxygen 1.5.3
http://www.crystalspace3d.org/docs/online/api-1.2/structiTerrainFactoryState.html
CC-MAIN-2015-40
en
refinedweb
I have five classes all together: Instructor, Student, Course, Section, and Testing. In the section class, I have this: In the main method, I want to create a Section object by accessing this constructor from the Section class:In the main method, I want to create a Section object by accessing this constructor from the Section class:public class Section { private Course course; private Instructor instructor; private ArrayList<Student> students; public Section() { super(); } public Section(Course course) { } public Section(Course course, Instructor instructor) { } public Section(Course course, Instructor instructor, ArrayList<Student> students) { } // getters and setters public void setCourse(Course course) { this.course = course; } public Course getCourse() { return course; } public void setInstructor(Instructor instructor) { this.instructor = instructor; } public Instructor getInstructor() { return instructor; } public void setStudents(ArrayList<Student> students) { this.students = students; } public ArrayList<Student> getStudents() { return students; } public void addStudent(Student student) { students.add(student); // add a student to the section roster } } public Section(Course course, Instructor instructor, ArrayList<Student> students) { } So I started with: public class Testing01 { public static void main (String [] args) throws IOException { Section sec = new Section("Java Programming", "George Jones", /* ArrayList variable here*/); { } } } I would like the constructor to create the ArrayList, but I can not figure out how to code the parameter. It's not in my reading and I have scoured the Internet for the answer with no results. I really want to comprehend this, so can anyone walk me through this? I would be most appreciative.
http://www.javaprogrammingforums.com/whats-wrong-my-code/18112-arraylist-parameter.html
CC-MAIN-2015-40
en
refinedweb
/* * _Noncopyable_h #define WTF_Noncopyable_h // We don't want argument-dependent lookup to pull in everything from the WTF // namespace when you use Noncopyable, so put it in its own namespace. #include "FastAllocBase.h" namespace WTFNoncopyable { class Noncopyable : public FastAllocBase { Noncopyable(const Noncopyable&); Noncopyable& operator=(const Noncopyable&); protected: Noncopyable() { } ~Noncopyable() { } }; class NoncopyableCustomAllocated { NoncopyableCustomAllocated(const NoncopyableCustomAllocated&); NoncopyableCustomAllocated& operator=(const NoncopyableCustomAllocated&); protected: NoncopyableCustomAllocated() { } ~NoncopyableCustomAllocated() { } }; } // namespace WTFNoncopyable using WTFNoncopyable::Noncopyable; using WTFNoncopyable::NoncopyableCustomAllocated; #endif // WTF_Noncopyable_h
http://opensource.apple.com/source/JavaScriptCore/JavaScriptCore-7533.18.1/wtf/Noncopyable.h
CC-MAIN-2015-40
en
refinedweb
Visual Studio 2008’s release has come and gone, and I can confidently say that I am fully overwhelmed. As of this writing, I've had almost no time to dive into new language features LINQ, let alone such major paradigm shifts like WPF. I'm approaching this article as a platform to learn WPF myself, but I hope you find it instructional as well. I decided to use the mathematical concept of an epicycloid as the subject for my first attempt at WPF. Most people will remember epicycloids from their youth as Spirographs. I had an endless fascination drawing Spirograph artwork as a kid, so it seems fitting to resurrect the memory for a graphics-related article. For those not already familiar with what Windows Presentation Foundation is, WPF is Microsoft’s next generation platform for building Windows user interfaces. The beauty of WPF is that, for the first time, the presentation and layout that defines a Windows UI is decoupled from the code. The UI is rendered using XAML, the native WPF, XML-based mark up, while code remains in *.cs files. Most importantly, WPF should make most UI tasks exponentially easier. We'll explore that claim throughout this article.The separation of XAML and code is essentially the same as the separation between HTML markup and an ASP.NET code behind file. This is a far cry from the visually limiting, drag and drop interface left over even from the VB 5 days. The clear benefit is that, with tools like Expressions, an application’s UI can be designed by a graphics team while a development team remains focused on development. This is especially important for someone like me considering some of the terrible UIs I've designed in my career. Despite my lack of design talent, WPF should provide a hefty UI advantage. Let’s take a crack at a putting together a decent interface. The first stop along the path is adding a nice background. In years past, developers had to subscribe to or override a forms paint event, do some not-so-fun clipping calculations, and then manually paint their image to get what WPF offers in just a couple lines of XAML. Here’s the XAML for the tiled background: <grid> <grid.background> <imagebrush viewport="0,0,0.3,0.3" viewbox="0,0,1,1" stretch="None" tilemode="FlipXY" imagesource="background.jpg" /> </grid.background> </grid> Isn't it nice how the XAML almost speaks for itself? The main (parent) element on my form is a grid. I've added an ImageBrush to the grid’s background. The image is set to tile by flipping every other tile horizontally (have fun coding that without WPF). The Viewbox property simply represents the area of the original image to be displayed. The Viewbox property is the target area where the Viewbox will be displayed. In other words, the XAML above tells the WPF Framework which portion of the image should be tiled. Notice that as you change the Viewport values in the XAML, the UI representation within Visual Studio 2008 dynamically updates! ImageBrush Viewbox Viewport Ok, the background was easy in just a couple lines of mark up. What we need now is a general window layout. I'm aiming for two columns with controls on the left and the Spirograph’s drawing surface on the right; something like this: To pull this off, I'm using a combination of Grid, StackPanel, and DockPanel objects. The dock panel is the primary container. That’s simple enough, to me, I want to dock the controls to the left and have the drawing surface fill the rest of the window. One hangup I found is that there’s no “Fill” property in WPF, where I've come to rely on that up through the 2.0 Framework. I did find, however, that the DockPanel control has a handy property called LastChildFill which does exactly what I need. Here’s the abbreviated XAML: Grid StackPanel DockPanel DockPanel LastChildFill <dockpanel lastchildfill="True" margin="20,20,5,5 " name="dockPanel1" > <stackpanel name="stackPanel1" width="200" dockpanel. ... </stackpanel> <dockpanel lastchildfill="True" margin="20,0,15,15" name="stackPanel2" dockpanel. ... </dockpanel> </dockpanel> Once again, terribly simple. We now have a left-docked panel and a filled right area. I thought it would look nice for the controls to sit on top of a semi-transparent. Once again, without using WPF this would be a time consuming task. And once again, WPF makes short work of designing the UI. Take a look at the following XAML that renders a semi-transparent rectangle with rounded corners: <rectangle width="200" opacity="0.5" stroke="Silver" fill="White" radiusy="10" radiusx="10" height="260" /> That’s it. One line. It’s still sinking in how easily this is coming together. Note that in the source code, you'll see this Rectangle object inside a Canvas element. The quick explanation is that the Canvas element allows for controls to overlap one another. Rectangle Canvas Next I thought I'd try customizing a standard button. I wanted a button with a PNG image on the left edge. This is one task that isn't difficult in previous versions of .NET and Visual Studio, so let’s put the XAML to the test and see if it’s either easier or more customizable in WPF. Here’s the XAML for an image button. <button name="drawButton" margin="10,10,0,10" width="80" height="23" horizontalalignment="Right"> <stackpanel width="Auto" height="Auto" horizontalalignment="Left" orientation="Horizontal"> <img height="16" width="16" stretch="Fill" source="draw.png" /> <textblock margin="10,0,50,0" text="Draw" fontsize="12" verticalalignment="Center" /> </stackpanel> </button> Did you notice that the button is acting as a host for child controls? The implications are endless! Unlike a standard WinForms button, this WPF button is as feature rich as any other drawn element in the WPF Framework. Ever wanted a button with an integrated drop down list? Me neither, but it’s possible. Hopefully by now you're seeing how much power is in so little markup. Now for the fun part. This is where we get to build a custom control for drawing the Spirograph. As it turns out, the Canvas element has all the drawing methods and context needed to draw or animate a Spirograph. Let’s take a look at how a Canvas object can be extended for custom drawing. public class GraphContext : Canvas { protected override void OnRender(DrawingContext drawingContext){…} protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo){…} } Nothing fancy here except that overriding the OnRender method gives us access to the DrawingContext object. You can liken this to the Graphics object in previous versions of .NET. We'll use the DrawingContext to add custom shapes to the canvas for custom rendering and animation. OnRender DrawingContext Graphics I won't belabor how to extend a control; that’s just standard OOP practices. Instead, let’s look at how we can get this custom control on to our window. Once again, it’s just a little bit of XAML. This time, however, we need to add a little definition about the control using standard XML namespacing. <window xmlns:codeprojectexample="clr-namespace:WpfApplication1" x: <graphcontext background="Black" x:</graphcontext> This xmlns declaration tells WPF to include the WpfApplication1 namespace using a CodeProjectExample prefix. This is a bit like the section of an ASP.NET page if you're not as familiar with XML. xmlns WpfApplication1 namespace CodeProjectExample The XAML to reference the custom element couldn't be easier. It is a simple combination of the prefix we defined and the class name of the element. Any additional properties can be defined inline. In this case, I'm setting the drawing area to black. Drawing shapes in WPF isn't necessarily easier than in previous versions of .NET, but there are some nice amenities in the WPF Framework, namely Shape UI elements. Since an epicycloid (like any mathematical graph) is essentially a series of connected X and Y points, we can draw a collection of lines to visually represent the graph. Here’s how the line segments are generated: Shape X Y private void DrawStaticGraph(DrawingContext drawingContext) { // PathGeometry is a nice alternative to drawingContext.DrawLine(...) as it // allows the points to be rendered as an image that can be further manipulated PathGeometry geometry = new PathGeometry(); // Add all points to the geometry foreach (Points pointXY in _points) { PathFigure figure = new PathFigure(); figure.StartPoint = pointXY.FromPoint; figure.Segments.Add(new LineSegment(pointXY.ToPoint, true)); geometry.Figures.Add(figure); } // Add the first point to close the gap from the graph's end point // to graph's start point PathFigure lastFigure = new PathFigure(); lastFigure.StartPoint = _points[_points.Count - 1].FromPoint; lastFigure.Segments.Add(new LineSegment(_firstPoint, true)); geometry.Figures.Add(lastFigure); // Create a new drawing and drawing group in order to apply // a custom drawing effect GeometryDrawing drawing = new GeometryDrawing(this.Pen.Brush, this.Pen, geometry); DrawingGroup drawingGroup = new DrawingGroup(); drawingGroup.Children.Add(drawing); ... } Let me take a minute to explain that there are a couple ways of drawing lines (specifically the DrawLine method on the DrawingContext object), but there’s a purpose to this code. We'll get to that point shortly. For now, let’s take note of a couple important points. Notice that we have a PathGeometry object to which we're adding a collection of PathFigure objects. Finally, the geometry object is added to a DrawingGroup. Read between the lines and you'll see that WPF is capable of rendering any number of shapes or figures in one fell swoop. I find that impressive. DrawLine DrawingContext PathGeometry PathFigure geometry DrawingGroup Like I said, there’s a point to the verbose code above. I didn't just want to draw an epicycloid, I wanted to draw it and make it look really smooth. That’s where WPF REALLY starts to shine. I don't even want to begin to imagine how to add a blur effect to individual line segments in .NET 2.0. It would take plenty of custom code. The theme of this article is how simply WPF can achieve stunning visual effects. Here’s the three lines of code needed to soften the entire Spirograph. BlurBitmapEffect blurEffect = new BlurBitmapEffect(); blurEffect.Radius = Softness; drawingGroup.BitmapEffect = blurEffect; I wish I had more code to show for this snippet, but that’s it. Splendid, if you ask me! There are dozens of effects in the WPF Framework, all of which are customizable both in XAML and in code. In most cases, it only takes a few lines of code like this to apply an effect to part or all of an image. All that’s left to render the graph is to call the Add() method to add the drawing to our custom canvas. That's it! Add() WPF has a bunch of build in features to support animation. Unfortunately, I haven't found any yet that can paint a series of lines in succession. Until I find a way to do that, the animation in this sample is facilitated by a standard timer. I will say, however, that the ability to add and remove rendering elements from the canvas at run time makes animating the Spirograph extremely simple, and there are less overall pieces that have to be buffered and redrawn. I didn't find the animation solution I was looking for, but I'm still impressed! I really love how simple a custom UI can be with WPF. It’s a very powerful framework, and we've just scratched the.
http://www.codeproject.com/Articles/22003/WPF-and-NET-3-5-Drawing-Customized-Controls-and-Cu?PageFlow=FixedWidth
CC-MAIN-2015-40
en
refinedweb
by March 2012 This article presents three recipes specially selected from among the 80 recipes included in the Oracle Service Bus 11g Development Cookbook (Packt 2012), collectively illustrating how to efficiently develop service- and message-oriented (integration) solutions on Oracle Service Bus 11g. The three recipes presented here focus on: To develop and test these recipes you need to have Oracle Service Bus 11g (OSB) Patch Set 3 (11.1.1.4 or higher) and Oracle Database 11g (XE or Enterprise edition) installed on your system. To use the web-based consoles, either Internet Explorer or Firefox is necessary. All of the recipes were developed on the so-called "developers" installation of Oracle Service Bus 11g and Oracle SOA Suite 11g. This means that all the software is running on a single Admin Server – no additional Managed Servers are needed. At the beginning of writing the book, Oracle Service Bus Patch Set 3 (11.1.1.4) was the current release and we have implemented all the recipes using this version. Keep that in mind when interpreting the screenshots (though in most cases this is transparent). However, the differences will be relevant when entering the URI of the OSB server (i.e. to open the Service Bus Console). In our installation, having only an Admin Server, the port we use throughout these recipes is always 7001. Make sure to change that in case of a different installation. To guide you through the installation of the various components, we have written an extra document, OsbCookbookInstallationGuide.pdf, included in this zip file: osb-cookbook-1540083.zip. The environment for the recipes included in this article is comprised of set of artifacts, including a JMS queue and connection factory to be set up on Oracle WebLogic Server. These artifacts are installed through a WLST script, which is called from an ANT script. That script is also included in the aforementioned zip file (osb-cookbook-1540083.zip). Once extracted, the file can be installed by running setup\wlst\install.cmd. In this recipe we will create a Business Service which sends a message to either a JMS queue or to a JMS topic. Because writing to a queue and topic is very similar from the business service perspective, we decided to combine it into a single recipe. We will use and configure the JMS transport provided by Oracle Service Bus. For this recipe we will use the DestinationQueue or the DestinationTopic from the OSB Cookbook standard environment and implement a business service to send messages to the queue/topic. We will not implement the proxy service in this recipe. Instead, we will test the business service directly on the OSB console. First let's create the JMSProducer business service which sends the messages to the DestinationQueue. In the There's more section we will show the necessary changes to send a message to the JMS topic. In Eclipse OEPE, perform the following steps: Configuring a business service with the JMS transport is enough to send a message from OSB to a JMS queue or topic. The queue or topic can reside on: We have only configured the business service and tested it through the OSB console. In real-life the business service would be called from a proxy service either by a Routing or Publish action. If there is no need to transform the message, a simple pass through proxy-service is enough. This section will discuss some of the advanced settings on the JMS Transport tab, and the necessary changes to the recipe in order to send to a JMS topic instead of a JMS queue. There are some advanced settings which can be set on the JMS Transport tab on the business service configuration, as illustrated in the image below. The option Enable Message Persistence is enabled by default, which guarantees message delivery because the messages are persisted and will survive server shutdowns and failures. To improve throughput, deselect this option (assuming the occasional lost message is tolerable). Set a time interval in milliseconds in the Expiration field to specify the message time-to-live. After the time-to-live is passed, the message will automatically be treated according to the Expiration Policy defined on the JMS destination (i. The same steps as shown in the How to do it ... section apply for sending to a JMS topic, too. To change from the queue to the JMS topic DestinationTopic, make sure to enter jms://localhost:7001/weblogic.jms.XAConnectionFactory/jms.DestinationTopic into the EndpointURI in step 10, below, and to set the Destination Type option to Topic in step 12. Redeploy the project to the OSB server. With that the business service will now write to the JMS topic. This can be tested through the OSB console by performing the following steps: Let's check if the message is in the DestinationTopic by performing the following steps in the WebLogic Console: Because we don't have any subscribers on the topic, the message is not persisted. So let's add a subscriber to the topic: In this recipe we will write a file to the local file system (local to the OSB server). We will implement a business service which uses the File transport to do that. Additionally, we will create a proxy service and control the file name of the file being written by using a Transport Header action. We begin with a business service writing a file to a local folder. In Eclipse OEPE perform the following steps: The business service to write a file is now configured and we can test it through the Test Console. In the Service Bus Console perform the following steps: We now have a business service through which we can write to a local file. The file name is generated. We can only control the prefix and suffix being used through the configuration of the File transport. To specify the complete file name, a Transport Header action can be used in the Routing action of the proxy service which is invoking the business service. Simply using a business service configured with the File transport is enough to be able to write a file to a local folder. The Endpoint URI configured on the File transport defines where that target local folder resides. If the folder does not yet exist, then it is created by the File transport upon writing the first file. The File transport allows some control over the file name by the prefix and suffix option. However the middle part of the file name is by default generated based on a UUID-like string. By that we it's guaranteed that the file names are always unique. If this is not the behaviour we want, then we can overwrite the file name by using a Transport Header action, as shown in the next section, Specifying a file name at runtime. If a file already exists, "_N" will be appended, where N is a number starting from 0. The string will be added before the suffix, so an original filename targetFile.txt would be extended to targetFile_0.txt, if targetFile.xml already exists in the destination folder. In this section we discuss how to specify the file name dynamically at runtime and how to use the FTP transport to write a file to a remote folder through FTP. If we want to overwrite the file name generated by the File transport, then we have set some transport headers using a Transport Header action when invoking the business service from a proxy service. So let's create a proxy service which invokes the business service created above. To simplify things, we just use the Generate Service functionality to create a proxy service based on the existing business service and change the protocol to Http transport. In Eclipse OEPE perform the following steps: We can now test the proxy service through the Test Console. In the Service Bus Console perform the following steps: We can replace the File transport with FTP transport to write to a remote file system through FTP. To write the file to an FTP server, perform the following steps in Eclipse OEPE: The business service can now be invoked from the proxy service, and the file is written to the FTP server. In this recipe we will show how to implement custom XPath functions, which extend the collection of XPath functions available with the OSB platform. You can import the OSB project containing the base setup for this recipe into Eclipse OEPE from \chapter-9\getting-ready\using-custom-xpath-function, included in osb-cookbook-1540083.zip. First we have to create the Java functionality we like to expose as a custom XPath function. We will reuse the same Java class as we have used in the recipe Using the Java Callout action to invoke Java code, as shown below: which is shown here: package osbcookbook.util.checksum; import java.util.zip.CRC32; import java.util.zip.Checksum; public class ChecksumUtil { public static long calculateChecksum(String data) { Checksum checksum = new CRC32(); checksum.update(data.getBytes(), 0, data.getBytes().length); return checksum.getValue(); } } A JAR with this class is available in \chapter-9\getting-ready\misc\osb-checksum-util.jar, included in osb-cookbook-1540083.zip. Next we need to configure the XPath function on the OSB server and map it to the calculateChecksum method of the ChecksumUtil class. The configuration for the XPath functions is held in [WL_HOME]/Oracle_OSB1/config/xpath-functions. Perform the following steps in an Explorer window. Copy the osb-built-in.xml file and paste it as a new file called osb-cookbook.xml, which will hold the definition of the custom XPath function. Now we have to make the JAR available to the OSB Server: Now let's use our new XPath function. In Eclipse OEPE perform the following steps: Now let's test the proxy service by performing the following steps in the Service Bus Console: We have seen how we can extend the set of XPath functions available on the OSB platform by custom XPath function. A custom XPath function is implemented by some Java code. In order to map the Java functionality to the custom XPath function, the Java code needs to be exposed as a public static method in a public Java class. The Java method should not produce side-effects, for example it should not update any databases or participate in a global transaction. Such code should be invoked by a Java Callout action. A custom function will only appear in Eclipse OEPE if the OSB can find the Java class. Such a custom XPath function can be used both in inline XQuery expression, such as shown with the Replace and in XQuery resources, just as any other functions provided by the Oracle Service Bus. The isDeterministic property in the configuration specifies whether the function is deterministic or non-deterministic. Deterministic functions always provide the same results where as Non-Deterministic functions return the unique results. The XQuery standard recommends that functions should be deterministic, so that the XQuery engine is able to perform optimizations. A custom XPath function can also be invoked in a XQuery resource, as shown in the image below. Just drag the XPath function from the Expression Functions tree into the Expression window, as you would with any other built-in XPath function. Guido Schmutz is an Oracle ACE director specializing in Oracle Fusion Middleware and SOA. He works for Trivadis, an Oracle Platinum Partner. Edwin Biemond is an Oracle ACE and solution architect at Amis. Jan van Zoggel is a principal Oracle Fusion Middleware consultant with Rubix, an Oracle Gold Partner. Mischa Kölliker is a principal consultant with Trivadis. Eric Elzinga is an Oracle ACE specializing in Oracle Fusion Middleware and SOA. He works for Xenta Consultancy and Randstad / I-bridge.
http://www.oracle.com/technetwork/articles/soa/schmutz-osb-cookbook-1543518.html
CC-MAIN-2015-40
en
refinedweb
IRC log of tagmem on 2003-12-15 Timestamps are in UTC. 14:51:51 [RRSAgent] RRSAgent has joined #tagmem 16:03:26 [Norm] Norm has joined #tagmem 16:06:36 [Ian] Norm, status update on XML Core review of arch doc? 16:07:08 [Norm] Uhm. None that I know of. It only went to last call on Tuesday! :-) 16:07:34 [Ian] I mean just a confirmatino that they will review... 16:07:45 [Norm] Yes 16:08:43 [Ian] I assume that was PG. 16:09:02 [Norm] PG? 16:09:08 [Ian] Paul 16:09:24 [Norm] Paul Grosso and I are co-chairs of Core, if that's what you're asking 16:09:27 [Ian] Aha! 16:09:28 [Ian] Okey 16:09:43 [Ian] I forgot the "co-" part 16:09:53 [Norm] no worries 16:10:06 [Ian] think we're ready to close on qnames finding today? 16:10:19 [Ian] 16:10:44 [Norm] Sigh. No, probably not. I told David I'd tweak it again, but I haven't had time. I might this week, but not (likely) for today's call. 16:11:23 [Ian] ok 19:58:34 [RRSAgent] RRSAgent has joined #tagmem 19:58:41 [Zakim] Zakim has joined #tagmem 20:00:36 [Norm] Zakim, this is tag 20:00:36 [Zakim] ok, Norm 20:01:13 [Norm] Zakim, who's on the phone? 20:01:13 [Zakim] On the phone I see Roy, Norm 20:01:42 [Zakim] +??P1 20:01:49 [Norm] Zakim, ??P1 is Stuart 20:01:49 [Zakim] +Stuart; got it 20:02:48 [Roy] Roy has joined #tagmem 20:03:37 [Zakim] +[Microsoft] 20:04:00 [Zakim] +DanC 20:04:27 [Ian] zakim, call Ian-BOS 20:04:27 [Zakim] ok, Ian; the call is being made 20:04:28 [Zakim] +Ian 20:04:52 [Stuart] zakim, who is here? 20:04:52 [Zakim] On the phone I see Roy, Norm, Stuart, [Microsoft], DanC, Ian 20:04:53 [Zakim] On IRC I see Roy, Zakim, RRSAgent, Stuart, DanC, Norm, Ian 20:05:34 [TBray] TBray has joined #tagmem 20:05:47 [TBray] Will call in in a second; finishing up a hot email 20:06:57 [Zakim] +David_Orchard 20:07:18 [Zakim] +Tim_Bray 20:07:57 [Ian] SW, DO, PC, TB, IJ, DC, NW, RF 20:08:04 [Stuart] zakim, who is here? 20:08:04 [Zakim] On the phone I see Roy, Norm, Stuart, [Microsoft], DanC, Ian, David_Orchard, Tim_Bray 20:08:05 [Ian] Missing: TBL, CL 20:08:06 [Zakim] On IRC I see TBray, Roy, Zakim, RRSAgent, Stuart, DanC, Norm, Ian 20:08:40 [Ian] Proposed to accept 1 Dec minutes 20:08:45 [Ian] So .Resolved 20:08:48 [Ian] Proposed to accept 4 Dec minutes 20:09:01 [Ian] 20:09:03 [tim-mit] tim-mit has joined #tagmem 20:09:05 [Ian] PC, RF: looked fine 20:09:11 [Ian] Resolved to accept 4 Dec minutes 20:09:17 [Zakim] +TimBL 20:09:38 [Ian] Proposed to accept monthly summary: 20:09:50 [Ian] 20:09:53 [Ian] Regrets: CL 20:09:56 [Ian] So accepted. 20:10:04 [Ian] (Proposal re: summary accepted) 20:10:20 [DanC] (regrets from CL per , prolly team-only) 20:10:26 [Roy] future regrets for 12/29 and 1/5 20:10:35 [Ian] Janet apologizes for the couple of errors in the press release. 20:10:39 [DanC] i.e. 29 Dec and 5 Jan, right Roy? 20:10:49 [Roy] /me right 20:11:42 [Ian] DO: XMLP WG request for revision of uriMediaType-9 issue and related finding 20:11:50 [Ian] 20:11:59 [Ian] SW: We'll look at this as part of findings review. 20:12:05 [Ian] 20:12:08 [Ian] Next meeting: 20:12:26 [Ian] PC: Propose 5 Jan 2004 20:12:35 [Ian] IJ: Seconded 20:12:57 [Ian] Resolved: Next teleconf 5 Jan 2004. 20:13:09 [Ian] 1.1 Feedback from XML 2003 Town Hall? 20:13:29 [Ian] TBray: I was satisfied with some of the commentary from the floor to improve the document. 20:14:11 [Ian] DC: There may be confusion between Web arch and Web Services arch 20:14:22 [DanC] in fact, there was 20:14:50 [Ian] TBray: I think XML 2003 not our natural constituency; thinly attended town hall. 20:14:54 [Ian] DC: Also evening... 20:14:58 [Ian] ==== 20:15:10 [Ian] 1.2 Last Call Update 20:15:19 [Ian] SW: I18N WG has ack'd request but not committed to review. 20:15:44 [Ian] SW: I have emailed Voice; I've had a holding reply with Scott M. 20:16:24 [Ian] IJ: I also think the Voice WG will be doing a review (based on my conversations with SM). 20:16:39 [Ian] SW: Jim Hendler has committed for Webont 20:16:56 [Ian] SW: Brian McBride will seek commitment from RDF Core WG 20:17:20 [Ian] [19 Jan 2004 teleconf will be with I18N] 20:17:43 [TBray] For the record, I'll be on vacation in Australia for a large part of February. 20:18:26 [Ian] DO: The WSDL WG has agreed to review the document. 20:19:21 [Ian] Action DO: Secure review commitment from the XMLP WG. 20:19:41 [Ian] --- 20:19:52 [Ian] 1.3 Patent Policy 20:20:48 [tim-mit] For the record, I will NOT be travelling to France for the Technical Plenary meeting. 20:21:25 [Ian] IJ: We are implementing new patent policy; likely to modify TAG charter. 20:22:50 [tim-mit] q+ 20:23:08 [Ian] q+ 20:23:21 [Ian] [Discussion of patent policy] 20:25:31 [TBray] q+ to say yes, we need to be 100% clear on this 20:26:03 [tim-mit] q+ 20:26:24 [tim-mit] q+ to note\ I will NOT be travelling to France for the Technical Plenary meeting. 20:26:36 [tim-mit] q- 20:26:39 [tim-mit] q+ to note\ I will NOT be travelling to France for the Technical Plenary meeting. 20:26:49 [Stuart] q- Ian 20:27:51 [DanC] ack TBray 20:27:51 [Zakim] TBray, you wanted to say yes, we need to be 100% clear on this 20:28:08 [Stuart] q? 20:28:40 [DanC] (I gather we've moved on to "1.4 Video meeting in Feb 2003") 20:28:41 [tim-mit] Paul: an all-day videolink meeting with several video location 20:29:03 [Ian] 1.4 Video meeting in Feb 2003 20:29:17 [tim-mit] point of order 20:29:22 [tim-mit] Zakim, point of order 20:29:22 [Zakim] I don't understand 'point of order', tim-mit 20:31:10 [Ian] q+ 20:31:19 [Ian] q- 20:31:20 [Stuart] q? 20:31:23 [Ian] ack tim-mit 20:31:23 [Zakim] tim-mit, you wanted to note\ I will NOT be travelling to France for the Technical Plenary meeting. 20:32:33 [Ian] [Discussion of extent to which TAG participants represents the organization they work for] 20:32:45 [Ian] q+ 20:33:28 [Ian] q- 20:34:17 [Ian] SW: Will we have result of TAG election by 1 Feb 2004? 20:34:19 [Ian] IJ: Yes. 20:34:34 [Norm] Monday 2 Feb is problematic for me, FWIW 20:35:02 [Ian] I am expecting to announce election results no later than 30 Jan. 20:35:03 [Roy] I have a tentative conference panel in Switzerland on Feb 2 or 3 20:35:14 [Ian] [Scheduling of video meeting] 20:35:41 [Ian] Proposal: 9 Feb 2004 videoconf 20:35:45 [Ian] TBray: Likely regrets. 20:35:51 [Ian] [No resolution] 20:37:35 [Ian] Action SW/PC: Proposed more concrete meeting around 9 Feb 2004. 20:37:46 [Ian] --- 20:37:52 [Ian] 1.5 Technical Plenary 20:38:00 [TBray] q+ 20:38:22 [Ian] SW: Should we invite observers to the TAG's ftf meeting 2 Mar 2004? 20:38:48 [Stuart] q+ PC 20:39:07 [DanC] ack danc 20:39:11 [Ian] DC: If we don't ask for prior agreement from Chair, I can almost guarantee some people will wander in. 20:39:21 [Ian] TBray: I'm ok with observers. 20:39:30 [Ian] PC: I'm against observers. 20:39:51 [Ian] PC: We do our technical discussion in public; why do we have to have our ftf discussions in public? 20:39:52 [DanC] I prefer "yes, with prior arrangement" 20:39:53 [Stuart] q? 20:39:58 [DanC] (but I said that in email) 20:40:05 [Stuart] q- TBray 20:40:10 [Stuart] q- PC 20:40:25 [Ian] 1+ 20:40:31 [Ian] s/1+/q+ 20:40:34 [Ian] q+ 20:41:20 [Ian] TBL: Not thrilled with the idea of a televised private meeting; people need to realize we are not meeting for them. There is also a risk that people take away partial/incorrect answers based on our discussion. 20:41:36 [TBray] Not passionate about this one, could go either way 20:41:51 [Ian] ack DanC 20:42:13 [Ian] DC: I think people can attend if they ask the chair in advance and have a good reason to be there. 20:42:26 [TBray] q+ 20:42:28 [tim-mit] +1 for prior arrangement only 20:42:29 [Ian] ack Ian 20:43:09 [Ian] IJ: Past messages make clear that "observer <> short-term participant" 20:43:46 [Ian] SW Proposes to revise his answer to "No observers" 20:43:51 [Ian] DO: I think I would object. 20:43:54 [Ian] TBray: I think I would too. 20:44:08 [Ian] SW Proposes to revise his answer to "Observers ok with prior arrangemetn with the Chair." 20:44:29 [Ian] So RESOLVED: SW will revise answer to tech plenary committee as proposed : "observers ok with prior arrangement of the CHair" 20:44:37 [Ian] ---- 20:44:56 [Ian] Review of "Using Qualified Names (QNames) as Identifiers in Content 20:44:56 [Ian] " 20:45:04 [Ian] 20:45:15 [Ian] NW: I have not been able to make changes desired by DO in time for this meeting. 20:45:36 [Ian] NW: I propose to do those revisions by our 5 Jan 2004 teleconf. 20:45:53 [Ian] DC: Do you expect to talk about canonicalization? 20:45:54 [Ian] NW: Yes. 20:46:10 [Ian] NW: Also, I think 3 Nov draft is the latest draft to date. 20:46:15 [Ian] ------ 20:46:31 [Ian] Client handling of authoritative metadata 20:46:38 [Ian] 20:46:50 [Ian] [IJ reviews] 20:47:22 [Ian] Announcemetn: 20:47:22 [Ian] \ 20:47:30 [Ian] 20:47:36 [Ian] Diff: 20:47:42 [Ian] 20:48:24 [Ian] 20:48:45 [Ian] 20:49:24 [Ian] SW: Diff between resource provider and resource owner? 20:49:44 [Ian] SW: I think leads to confusion about resource v. representation. 20:49:59 [Ian] IJ: "Resource provider" is from RF; I'd like to hear from him. 20:50:50 [DanC] in webarch we call it the "owner" of the resource, no? 20:50:55 [Ian] yes 20:51:09 [Ian] RF: I was referring by "resource provider" to people, not mechanism. 20:51:15 [tim-mit] q+ to ask whether we can use 'owner" 20:51:51 [TBray] ack TBray 20:52:03 [Ian] IJ: I recognize as a bug in finding if person and origin server confused. 20:52:10 [Stuart] ack tim 20:52:10 [Zakim] tim-mit, you wanted to ask whether we can use 'owner" 20:52:27 [Ian] TBray: "Ownership" is defined in arch doc. 20:52:32 [Ian] TBL: Then let's use that in the finding. 20:52:33 [DanC] hear hear 20:52:37 [Ian] RF: Sure. 20:52:41 [Stuart] +1 20:52:45 [DanC] cf 20:53:24 [Ian] q? 20:54:01 [Ian] SW: I propose that we discuss at 5 Jan meeting. 20:54:06 [Ian] DC: I'd rather have two advocates. 20:54:34 [Ian] Action TB, SW: Review finding by 5 Jan 2004 teleconference, and work with IJ. 20:54:59 [Ian] --------------- 20:55:11 [Ian] 20:55:16 [Ian] XMLP WG request for revision of uriMediaType-9 issue and related finding 20:55:36 [Ian] DO: XLMP WG talking about encoding media type information in XML. 20:56:05 [Ian] DO: The finding is a bit out of date (8 Apr 2003) and IANA has made some changes since then. 20:56:12 [Ian] 20:56:18 [Ian] From DO email: 20:56:33 [Ian] [[" ]]]-- XMLP WG request for revision of uriMediaType-9 issue and related finding from David Orchard on 2003-12-12 (tag@w3.org from December 2003) 20:56:33 [Ian] sts.w3.org/Archives/Member/tag/2003Dec/0062.htmlMon, 15 Dec 2003 15:00:52 GMT 20:56:43 [Ian] ==== 20:57:12 [TBray] URN URIs, ie xsi:mediaType="urn:ietf:param:contentType:image:jpeg 20:57:42 [Ian] DO: Problem with HTTP URIs was that not available for all media types. 20:57:49 [Ian] q+ 20:57:51 [TBray] e.g. is not available 20:58:30 [Ian] DO: I think the finding needs to be updated. 20:58:42 [Stuart] q? 20:58:46 [Ian] See CL's action item for this issue: 20:58:47 [Stuart] ack DanC 20:58:47 [Zakim] DanC, you wanted to clarify: IANA has provided http URIs for a while; but they don't promise not to 404 them at a moment's notice 20:58:50 [Ian] 20:58:51 [TBray] q+ 20:59:09 [Ian] DC: I have been trying to extract promise of persistence from relevant folks. 20:59:22 [Ian] 20:59:29 [Stuart] 20:59:38 [DanC] ah... found Revised 27 May 2002 20:59:57 [Ian] ack Ian 21:00:06 [Stuart] q+ DO 21:00:09 [Ian] IJ: I recall CL talking about missing URIs for media types. 21:00:17 [Ian] IJ: Missing HTTP URIs. 21:00:47 [Stuart] ack Tbray 21:00:50 [Stuart] ack DO 21:00:50 [DanC] CL's action is still outstanding, per 21:01:09 [tim-mit] q+ To agree with Tim Bray's analysis 21:01:20 [Ian] DO: I'd like for the TAG to address this before arch doc 1.0 21:01:31 [Ian] DC: What is your suggestion? 21:01:40 [Ian] DO: Revise finding, making trade-offs clear. 21:01:50 [Ian] DO: Feb 2004 seems ok as time frame. 21:02:07 [Ian] DO: I'd like the finding to say: 21:02:19 [Ian] "Use HTTP URIs as provided by IANA." Or something as simple. 21:02:49 [Ian] DC: Note that IANA answers with 200 ok, but doesn't commit to doing so forever. 21:03:07 [Ian] RF: I suggest that DO respond to the WG that they use the media type and nothing but the media type. 21:03:15 [Ian] q? 21:03:16 [Stuart] q? 21:03:45 [DanC] next IETF/W3C telcon is scheduled for 6 Feb 2004 21:04:00 [TBray] +1 to Roy 21:04:09 [Ian] DO: Validation may be simpler if there is one, not two way to specify media type. 21:04:29 [Ian] RF: No software that I am aware of uses a URI; they all use the short string. 21:04:33 [Stuart] ack tim 21:04:33 [Zakim] tim-mit, you wanted to agree with Tim Bray's analysis 21:04:55 [DanC] " Tim Bray's analysis" seems to be ambiguous 21:04:56 [Roy] /me uses a URI to define the media type 21:05:03 [Ian] TBL: I agree with TB's initial analysis. I think that the finding can say what *ought* to happen (use HTTP URIs) and then there's the question of what to do in practice. 21:06:22 [Ian] TBL: I suggest that the finding suggest what ought to happen. And we continue discussions with the IANA folks. And that we find a solution in the short term for the WG. 21:06:33 [Ian] TBL: We can build a registry in W3C space for mime types. 21:06:42 [Ian] TBL: We've had a list of mime types before. 21:06:44 [Stuart] q+ 21:06:45 [TBray] Per Web Architecture, it would be ideal to refer to Internet Media Types as Web Resources, i.e. using URIs. If however the organization that logically owns these resources is not interested in publishing URIs for them, the choices are to use the Internet Media Types they publish, or cook up our own URI-addrssable registry 21:07:16 [Ian] TBL: We can note that these URIs will not be persistent beyond, say 1 year, and we will maintain the URIs for that duration. 21:07:24 [TBray] q+ to blanch at the idea of an interim semi-authoritative registry 21:07:42 [DanC] fyi, Martin built a list of MIME types that sorta come from W3C recently. 21:08:02 [DanC] (my list was URI schemes) 21:08:11 [Ian] TBL summarizing: 21:08:16 [Ian] 1) Tell WG what to do right now 21:08:30 [Ian] 2) NEgotiate with IANA ; propose W3C manages. 21:08:42 [Ian] the mime registry and that IANA can clone. 21:08:43 [Stuart] ack Stuart 21:08:47 [Ian] 3) Put principles behind this in finding. 21:09:16 [Ian] SW: I agree that finding should say that, in the absence of URIs, to use content type short strings as is. 21:09:18 [Ian] DC: No things. 21:09:21 [Ian] s/things/thanks 21:09:38 [Ian] TBray: The idea of a semi-authoritative registry doesn't strike me as a good idea. 21:09:42 [Ian] TBray: RDDL has this problem, too. 21:09:49 [DanC] people can figure out to use names like "text/plain" on their own; there's no value in the TAG endorsing that practice. 21:10:34 [Stuart] q? 21:10:40 [Stuart] ack TBray 21:10:40 [Zakim] TBray, you wanted to blanch at the idea of an interim semi-authoritative registry 21:10:40 [Ian] TBL: Will be important to have a URI for these things if there is to be RDDL mapping to RDF. 21:10:46 [Ian] s/TBL/TB 21:10:53 [DanC] well, RDF can deal with "text/plain" strings just fine. 21:11:24 [tim-mit] But that does not allow any old person to invent a personalmedia type. 21:11:25 [Ian] DO: Two issues if W3C provides registry: (1) dereferencable or not? (2) or just URI space not used for any other resource types. 21:11:39 [Roy]:11:58 [TBray] Yes, but I want to say that with respect to, that has a nature of <insert namespace name for XML Schema> 21:12:13 [Ian] RF: E.g. of algorithm: List the parameters in lexical/alphabetical order. 21:12:18 [TBray] but, if I want to provide a related resource that's a CSS stylesheet, how do I identify its nature? 21:12:38 [Ian] RF: Point out to the WGs that there's a relative URI into a registry, wherever the registry is. That way you get both - media types and URIs at the same time. 21:12:47 [Ian] RF: I suggest we update the finding to say this. 21:12:56 [Stuart] q? 21:13:10 [Ian] RF: To get IANA attention, write RDF... 21:13:13 [Ian] s/RDF/RFC 21:13:18 [Ian] DC: Been there /done that. 21:13:25 [Ian] RF: When the RFC is published, IANA will follow it. 21:13:34 [Ian] RF: There mandate is to follow the instructions of the IETF... 21:13:41 [Ian] DC:...except when the instructions conflict. 21:13:54 [Ian] DC: Mark Baker and I are to ask for last call of our Internet Draft 21:14:34 [Stuart] 21:17:29 [Stuart]:41 [Stuart] that was from Roy above. 21:17:44 [Ian] ack DanC 21:17:44 [Zakim] DanC, you wanted to ask DaveO to come to the IETF/W3C telcon 21:17:47 [TBray]:54 [Ian] DC to DO: Do you want to attend the W3C/IETF meeting? 21:18:02 [Ian] [6 Feb 2004] 21:18:12 [Ian] DO: If I'm available; sure. 21:18:40 [Ian] Action DC: Invite DO to IETF/W3C for 6 Feb 2004. 21:18:50 [DanC] ... noting varous risks 21:19:02 [Ian] SW: Any finding updates expected? 21:19:25 [Ian] DO: I am hearing "If you need to make a decision right now; use media type strings. We are negotiating the use of URIs for the IANA registry." 21:19:39 [Ian] DO: We'd like authoritative URIs, but we're not there yet. 21:20:01 [Ian] TBray: I heard RF suggest that we start minting URIs for the IANA... 21:20:39 [Ian] RF: The media type is structured like a URI; if you start out using the media type alone, but add an ordering mechanism for the parameters (which are rarely used), the name that you use is a URI. It's just relative. 21:20:41 [Ian] q+ 21:20:54 [Stuart] ack Dan 21:20:54 [Zakim] DanC, you wanted to say if you need a decision right now, TAG isn't finished with the issue, so go ahead and make your own decision 21:20:56 [Ian] DC: I haven't heard any suggested changes to finding that i consider an improvement. 21:21:16 [Ian] TBray: I hear RF saying that we take proactive action. 21:21:22 [Ian] DC: We are doing that; those negotiations are not yet done. 21:21:50 [Ian] DC: I'm against some short-term action by the TAG; people can do what they want, but not with the TAG's blessing. 21:22:09 [Ian] SW: I think we have already decided this issue, and the answer is in the finding. 21:22:44 [DanC] tim's question is too long 21:22:45 [Ian] TBL: I hear people saying "These media type strings are relative URIs w.r.t. the IANA registry....we need to do some things to make this happen in practice..." 21:23:05 [Ian] TBL: But I don't think what we need to do with IANA has to be our first action. 21:23:17 [Ian] TBL: In fact, IANA may respond to the community if there is consensus there. 21:23:27 [Stuart] ack Ian 21:23:37 [Ian] q? 21:24:00 [Ian] DO: Is there any connection between DC/MB's internet draft and RF's algorithm? 21:24:34 [Ian] RF: My suggestion for the WG is to just use the media types today. 21:24:54 [Ian] TBL: Can we say: If you want to look ahead, treat as a relative URI reference. But we can't tell you the base URI today. 21:26:26 [Ian] TBL: I think the answer to the WG should be: 21:26:33 [Ian] a) Identify media types with URIs (of course) 21:26:40 [Ian] b) But we can't tell you yet the base of the URI 21:26:43 [Roy] agrees with TBL 21:26:54 [Ian] c) We can't make guarantees about persistence/dereferenceability today. 21:27:03 [Ian] DC: That's not the answer I want to give today. 21:27:22 [Ian] TBL: Why does the WG need to make any changes to its spec? 21:27:53 [tim-mit] DO: What si the base changes? 21:27:56 [tim-mit] if 21:28:56 [Ian] DC: I expect the TAG to resolve the issue in good course; I don't want to endorse anything until we resolve the issue. 21:29:22 [Ian] DC: I am waiting for the IANA negotiations to finish first. 21:29:44 [tim-mit] q+ 21:29:46 [DanC] "The TAG would prefer that dereferencable http: scheme URIs be assigned under the authority of the body that maintains the Internet media type registry." 21:29:54 [Ian] q+ DO 21:30:03 [Stuart] ack DO 21:30:24 [Ian] DO: I think I can wait a few weeks before I next talk to XMLP WG about this. 21:30:31 [Ian] ack tim-mit 21:30:54 [Ian] TBL: I'm concerned about the idea of trying to convince IANA before we implement this on our site. 21:31:20 [Ian] TBL: The picture that RF painted was that, if you write up an RFC, and you have some community behind you, then IANA will go ahead and do it. 21:31:36 [Ian] TBL: I've not seen the IANA agree "in principle" 21:32:31 [Ian] SW: I request that people review the current finding and suggest concrete revisions. 21:32:32 [Ian] ADJOURN 21:32:33 [Zakim] -David_Orchard 21:32:37 [Zakim] -[Microsoft] 21:32:37 [Ian] RRSAgent, stop
http://www.w3.org/2003/12/15-tagmem-irc.html
CC-MAIN-2015-40
en
refinedweb
. If you were paying close attention to our last tutorial, Android Fundamentals: Working With Content Providers, you may have noticed that we took a shortcut. We used the managedQuery() method of the Activity class, which is a newly deprecated method. This method represents the "old" way of letting an activity manage a cursor. Now we'll switch it to the new way, using a CursorLoader, as suggested in the latest SDK documentation. We can do this safely because although the CursorLoader class was included in Android 3.0, it is also part of the new compatibility library we discussed in Android Compatibility: Working with Fragments, and therefore can be used on devices as far back as Android 1.6. Step 0: Getting Started This tutorial assumes you will start where our tutorial called Android Fundamentals: Working With Content Providers left off. You can download that code and work from there, though you will have some tasks you'll have to do unassisted, or you can simply download the code for this tutorial and follow along. The choice is yours. Step 1: Using the Right Class Versions Normally, we can get away with just using the default import statement that Eclipse gives us. However, for loaders to work, we must ensure that we are using the correct versions of the classes. Here are the relevant import statements: import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; These imports replace the existing CursorAdapter import statements found in previous tutorial’s TutListFragmet class. This is the only class we'll need to modify. We don't normally talk about import statements, but when building this sample, Eclipse kept referencing the wrong CursorLoader package and we had to make the change manually, so we're calling it out here in our first step. Step 2: Implementing Callbacks Next, modify the TutListFragment class so that it now implements LoaderManager.LoaderCallbacks. The resulting TutListFragment class will now have three new methods to override: public class TutListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { // ... existing code // LoaderManager.LoaderCallbacks<Cursor> methods: @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // TBD } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // TBD } @Override public void onLoaderReset(Loader<Cursor> loader) { // TBD } } Step 3: Initializing the Loader You need to make several changes to the onCreate() method of the TutListFragment class. First, the Cursor will no longer be created here. Second, the loader must be initialized. And third, since the Cursor is no longer available immediately (as it will be loaded up in a separate thread instead), the initialization of the adapter must be modified. The changes to the onCreate() method are encapsulated here: // TutListFragment class member variables private static final int TUTORIAL_LIST_LOADER = 0x01; private SimpleCursorAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] uiBindFrom = { TutListDatabase.COL_TITLE }; int[] uiBindTo = { R.id.title }; getLoaderManager().initLoader(TUTORIAL_LIST_LOADER, null, this); adapter = new SimpleCursorAdapter( getActivity().getApplicationContext(), R.layout.list_item, null, uiBindFrom, uiBindTo, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); setListAdapter(adapter); } As you can see, we've made the three changes. The Cursor object and the resulting query() call have been removed. In it’s place, we call the initLoader() method of the LoaderManager class. Although this method returns the loader object, there is no need for us to keep it around. Instead, the LoaderManager takes care of the details for us. All loaders are uniquely identified so the system knows if one must be newly created or not. We use the TUTORIAL_LIST_LOADER constant to identify the single loader now in use. Finally, we changed the adapter to a class member variable and no cursor is passed to it yet by using a null value. Step 4: Creating the Loader The loader is not automatically created. That's a job for the LoaderManager.LoaderCallbacks class. The CursorLoader we'll need to create and return from the onCreateLoader() method takes similar parameters to the managedQuery() method we used previously. Here is the entire implementation of the onCreateLoader() method: @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String[] projection = { TutListDatabase.ID, TutListDatabase.COL_TITLE }; CursorLoader cursorLoader = new CursorLoader(getActivity(), TutListProvider.CONTENT_URI, projection, null, null, null); return cursorLoader; } As you can see, it's fairly straightforward and really does look like the call to managedQuery(), but instead of a Cursor, we get a CursorLoader. And speaking of Cursors... Step 5: Using the Cursor You might be wondering what happened to the Cursor object? When the system finishes retrieving the Cursor, a call to the onLoadFinished() method takes place. Handling this callback method is quite simple: @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { adapter.swapCursor(cursor); } The new swapCursor() method, introduced in API Level 11 and provided in the compatibility package, assigns the new Cursor but does not close the previous one. This allows the system to keep track of the Cursor and manage it for us, optimizing where appropriate.: @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } Step 7: Testing the Results At this point, you're finished transitioning the TutListFragment to a loader-based implementation. When you run the application now, you'll probably notice that it basically behaves the same. So, how do you know this change is doing something? We leave this task as an exercise to the reader. How would you test the effectiveness of this solution? HINT: It can be achieved with a single functional line of code that will require a try-catch block. Conclusion By moving the loading of data off the main UI thread of the application and into a CursorLoader, you've improved the responsiveness of the application, especially during orientation changes. If the content provider took 10 seconds per query, the user interface would not be negatively affected whereas in its previous implementation, it would have likely caused the dreaded "Force Close" dialog to appear.<< Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this postPowered by
http://code.tutsplus.com/tutorials/android-sdk_loading-data_cursorloader--mobile-5673
CC-MAIN-2015-40
en
refinedweb
Name of scheme: Royal & Sun Alliance 2006 Long-Term Incentive Plan Period of return: From: 1 July To: 31 December 2013 2013 Balance of unallotted securities under 1,246,212 shares of 27.5p each scheme(s) from previous return: Plus: The amount by which the block scheme(s) has been increased since the Nil date of the last return (if any increase has been applied for): Less: Number of securities issued/allotted under scheme(s) during 594,226 shares of 27.5p each period (see LR3.5.7G): Equals: Balance under scheme(s) not yet 651,986 shares of 27.5p each issued/allotted at end of.
http://www.bloomberg.com/article/2014-01-02/asbWj4cY.RLs.html
CC-MAIN-2015-40
en
refinedweb
in reply to How to share a group of functions with multiple main processes? How do you run your two perl scripts? If it was indeed impossible for multiple scripts to use (well, require in your case) the same module at the same time, that issue would have been raised long ago. I recommend you read Perl Modules. To make it short, if PrintVar.pm (something that is not a standalone Perl script but should be included, ie a module should have the .pm extension) is in the same folder as your script, to include it you just have to write: use PrintVar. And if it is in Something, use Something::Printvar;. This would allow you to move all your files at once without having to change every include path. You should still read Perl Modules if you want to make "good" Perl modules, to learn about packages (namespaces) and exporting. Yes No Other opinion (please explain) Results (99 votes), past polls
http://www.perlmonks.org/index.pl?node_id=1063365
CC-MAIN-2015-40
en
refinedweb
twython 3.1.2 Actively maintained, pure Python wrapper for the Twitter API. Supports both normal and streaming Twitter APIs ======= .. image:: :target: .. image:: :target: .. image:: :target: .. image:: :target: ``Twython`` is the premier Python library providing an easy (and up-to-date) way to access Twitter data. Actively maintained and featuring support for Python 2.6+ and Python 3. It's been battle tested by companies, educational institutions and individuals alike. Try it today! Features -------- - Query data for: - User information - Twitter lists - Timelines - Direct Messages - and anything found in `the docs <https: dev.twitter.`_ - Image Uploading: - Update user status with an image - Change user avatar - Change user background image - Change user banner image - OAuth 2 Application Only (read-only) Support - Support for Twitter's Streaming API - Seamless Python 3 support! Installation ------------ Install Twython via `pip <http:""/>`_ .. code-block:: bash $ pip install twython or, with `easy_install <http: pypi.python.`_ .. code-block:: bash $ easy_install twython But, hey... `that's up to you <http:"" en="" latest="" other-tools.html#`_. Or, if you want the code that is currently on GitHub .. code-block:: bash git clone git://github.com/ryanmcgrath/twython.git cd twython python setup.py install Documentation ------------- Documentation is available at Starting Out ------------ First, you'll want to head over to and register an application! After you register, grab your applications ``Consumer Key`` and ``Consumer Secret`` from the application details tab. The most common type of authentication is Twitter user authentication using OAuth 1. If you're a web app planning to have users sign up with their Twitter account and interact with their timelines, updating their status, and stuff like that this **is** the authentication for you! First, you'll want to import Twython .. code-block:: python from twython import Twython Authentication ~~~~~~~~~~~~~~ Obtain Authorization URL ^^^^^^^^^^^^^^^^^^^^^^^^ Now, you'll want to create a Twython instance with your ``Consumer Key`` and ``Consumer Secret`` Only pass *callback_url* to *get_authentication_tokens* if your application is a Web Application Desktop and Mobile Applications **do not** require a callback_url .. code-block:: python APP_KEY = 'YOUR_APP_KEY' APP_SECRET = 'YOUR_APP_SECRET' twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens(callback_url='') From the ``auth`` variable, save the ``oauth_token`` and ``oauth_token_secret`` for later use (these are not the final auth tokens). In Django or other web frameworks, you might want to store it to a session variable .. code-block:: python OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] Send the user to the authentication url, you can obtain it by accessing .. code-block:: python auth['auth_url'] Handling the Callback ^^^^^^^^^^^^^^^^^^^^^ If your application is a Desktop or Mobile Application *oauth_verifier* will be the PIN code After they authorize your application to access some of their account details, they'll be redirected to the callback url you specified in ``get_autentication_tokens`` You'll want to extract the ``oauth_verifier`` from the url. Django example: .. code-block:: python oauth_verifier = request.GET['oauth_verifier'] Now that you have the ``oauth_verifier`` stored to a variable, you'll want to create a new instance of Twython and grab the final user tokens .. code-block:: python twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(oauth_verifier) Once you have the final user tokens, store them in a database for later use!:: OAUTH_TOKEN = final_step['oauth_token'] OAUTH_TOKEN_SECERT = final_step['oauth_token_secret'] For OAuth 2 (Application Only, read-only) authentication, see `our documentation <https: twython.readthedocs.`_ Dynamic Function Arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~ Keyword arguments to functions are mapped to the functions available for each endpoint in the Twitter API docs. Doing this allows us to be incredibly flexible in querying the Twitter API, so changes to the API aren't held up from you using them by this library. Basic Usage ----------- **Function definitions (i.e. get_home_timeline()) can be found by reading over twython/endpoints.py** Create a Twython instance with your application keys and the users OAuth tokens .. code-block:: python from twython import Twython twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) Authenticated Users Home Timeline ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Documentation: .. code-block:: python twitter.get_home_timeline() Updating Status ~~~~~~~~~~~~~~~ This method makes use of dynamic arguments, `read more about them <https: twython.readthedocs.`_ Documentation: .. code-block:: python twitter.update_status(status='See how easy using Twython is!') Searching ~~~~~~~~~ says it takes "q" and "result_type" amongst other arguments .. code-block:: python twitter.search(q='twitter') twitter.search(q='twitter', result_type='popular') Advanced Usage -------------- - `Advanced Twython Usage <https: twython.readthedocs.`_ - `Streaming with Twython <https: twython.readthedocs.`_ Notes ----- - Twython 3.0.0 has been injected with 1000mgs of pure awesomeness! OAuth 2 application authentication is now supported. And a *whole lot* more! See the `CHANGELOG <https: github.`_ for more details! Questions, Comments, etc? ------------------------- My hope is that Twython is so simple that you'd never *have* to ask any questions, but if you feel the need to contact me for this (or other) reasons, you can hit me up at ryan@venodesigns.net. Or if I'm to busy to answer, feel free to ping mikeh@ydekproductions.com as well. - `@ryanmcgrath <https: twitter.`_ - `@mikehelmick <https: twitter.`_ Want to help? ------------- Twython is useful, but ultimately only as useful as the people using it (say that ten times fast!). If you'd like to help, write example code, contribute patches, document things on the wiki, tweet about it. Your help is always appreciated! .. :changelog: History ------- 3.1.2 (2013-12-05) ++++++++++++++++++ - Fixed Changelog (HISTORY.rst) 3.1.1 (2013-12-05) ++++++++++++++++++ - Update `requests` version to 2.1.0. - Fixed: Streaming issue where `Exceptions` in handlers or `on_success` which subclass `ValueError` would previously be caught and reported as a JSON decoding problem, and `on_error()` would be called (with status_code=200) - Fixed issue where XML was returned when bad tokens were passed to `get_authorized_tokens` - Fixed import for `setup` causing installation to fail on some devices (eg. Nokia N9/MeeGo) 3.1.0 (2013-09-25) ++++++++++++++++++ - Added ``html_for_tweet`` static method. This method accepts a tweet object returned from a Twitter API call and will return a string with urls, mentions and hashtags in the tweet replaced with HTML. - Pass ``client_args`` to the streaming ``__init__``, much like in core Twython (you can pass headers, timeout, hooks, proxies, etc.). - Streamer has new parameter ``handlers`` which accepts a list of strings related to functions that are apart of the Streaming class and start with "on\_". i.e. ['delete'] is passed, when 'delete' is received from a stream response; ``on_delete`` will be called. - When an actual request error happens and a ``RequestException`` is raised, it is caught and a ``TwythonError`` is raised instead for convenience. - Added "cursor"-like functionality. Endpoints with the attribute ``iter_mode`` will be able to be passed to ``Twython.cursor`` and returned as a generator. - ``Twython.search_gen`` has been deprecated. Please use ``twitter.cursor(twitter.search, q='your_query')`` instead, where ``twitter`` is your ``Twython`` instance. - Added methods ``get_list_memberships``, ``get_twitter_configuration``, ``get_supported_languages``, ``get_privacy_policy``, ``get_tos`` - Added ``auth_endpoint`` parameter to ``Twython.__init__`` for cases when the right parameters weren't being shown during the authentication step. - Fixed streaming issue where results wouldn't be returned for streams that weren't so active (See) - Streaming API now uses ``_transparent_params`` so when passed ``True`` or ``False`` or an array, etc. Twython formats it to meet Twitter parameter standards (i.e. ['ryanmcgrath', 'mikehelmick', 'twitterapi'] would convert to string 'ryanmcgrath,mikehelmick,twitterapi') 3.0.0 (2013-06-18) ++++++++++++++++++ - Changed ``twython/twython.py`` to ``twython/api.py`` in attempt to make structure look a little neater - Removed all camelCase function access (anything like ``getHomeTimeline`` is now ``get_home_timeline``) - Removed ``shorten_url``. With the ``requests`` library, shortening a URL on your own is simple enough - ``twitter_token``, ``twitter_secret`` and ``callback_url`` are no longer passed to ``Twython.__init__`` - ``twitter_token`` and ``twitter_secret`` have been replaced with ``app_key`` and ``app_secret`` respectively - ``callback_url`` is now passed through ``Twython.get_authentication_tokens`` - Update ``test_twython.py`` docstrings per - Removed ``get_list_memberships``, method is Twitter API 1.0 deprecated - Developers can now pass an array as a parameter to Twitter API methods and they will be automatically joined by a comma and converted to a string - ``endpoints.py`` now contains ``EndpointsMixin`` (rather than the previous ``api_table`` dict) for Twython, which enables Twython to use functions declared in the Mixin. - Added OAuth 2 authentication (Application Only) for when you want to make read-only calls to Twitter without having to go through the whole user authentication ritual (see docs for usage) - Added ``obtain_access_token`` to obtain an OAuth 2 Application Only read-only access token - ``construct_api_url`` now accepts keyword arguments like other Twython methods (e.g. instead of passing ``{'q': 'twitter', 'result_type': 'recent'}``, pass ``q='twitter', result_type='recent'``) - Pass ``client_args`` to the Twython ``__init__`` to manipulate request variables. ``client_args`` accepts a dictionary of keywords and values that accepted by ``requests`` (`Session API <http: docs.python-requests.`_) [ex. headers, proxies, verify(SSL verification)] and the "request" section directly below it. - Added ``get_application_rate_limit_status`` API method for returning the current rate limits for the specified source - Added ``invalidate_token`` API method which allows registed apps to revoke an access token presenting its client credentials - ``get_lastfunction_header`` now accepts a ``default_return_value`` parameter. This means that if you pass a second value (ex. ``Twython.get_lastfunction_header('x-rate-limit-remaining', 0)``) and the value is not found, it returns your default value 2.10.1 (2013-05-29) ++++++++++++++++++ - More test coverage! - Fix ``search_gen`` - Fixed ``get_lastfunction_header`` to actually do what its docstring says, returns ``None`` if header is not found - Updated some internal API code, ``__init__`` didn't need to have ``self.auth`` and ``self.headers`` because they were never used anywhere else but the ``__init__`` - Added ``disconnect`` method to ``TwythonStreamer``, allowing users to disconnect as they desire - Updated ``TwythonStreamError`` docstring, also allow importing it from ``twython`` - No longer raise ``TwythonStreamError`` when stream line can't be decoded. Instead, sends signal to ``TwythonStreamer.on_error`` - Allow for (int, long, float) params to be passed to Twython Twitter API functions in Python 2, and (int, float) in Python 3 2.10.0 (2013-05-21) ++++++++++++++++++ - Added ``get_retweeters_ids`` method - Fixed ``TwythonDeprecationWarning`` on camelCase functions if the camelCase was the same as the PEP8 function (i.e. ``Twython.retweet`` did not change) - Fixed error message bubbling when error message returned from Twitter was not an array (i.e. if you try to retweet something twice, the error is not found at index 0) - Added "transparent" parameters for making requests, meaning users can pass bool values (True, False) to Twython methods and we convert your params in the background to satisfy the Twitter API. Also, file objects can now be passed seamlessly (see examples in README and in /examples dir for details) - Callback URL is optional in ``get_authentication_tokens`` to accomedate those using OOB authorization (non web clients) - Not part of the python package, but tests are now available along with Travis CI hooks - Added ``__repr__`` definition for Twython, when calling only returning <twython: - Cleaned up ``Twython.construct_api_url``, uses "transparent" parameters (see 4th bullet in this version for explaination) - Update ``requests`` and ``requests-oauthlib`` requirements, fixing posting files AND post data together, making authenticated requests in general in Python 3.3 2.9.1 (2013-05-04) ++++++++++++++++++ - "PEP8" all the functions. Switch functions from camelCase() to underscore_funcs(). (i.e. ``updateStatus()`` is now ``update_status()``) 2.9.0 (2013-05-04) ++++++++++++++++++ - Fixed streaming issue #144, added ``TwythonStreamer`` to aid users in a friendly streaming experience (streaming examples in ``examples`` and README's have been updated as well) - ``Twython`` now requires ``requests-oauthlib`` 0.3.1, fixes #154 (unable to upload media when sending POST data with the file) 2.8.0 (2013-04-29) ++++++++++++++++++ - Added a ``HISTORY.rst`` to start tracking history of changes - Updated ``twitter_endpoints.py`` to ``endpoints.py`` for cleanliness - Removed twython3k directory, no longer needed - Added ``compat.py`` for compatability with Python 2.6 and greater - Added some ascii art, moved description of Twython and ``__author__`` to ``__init__.py`` - Added ``version.py`` to store the current Twython version, instead of repeating it twice -- it also had to go into it's own file because of dependencies of ``requests`` and ``requests-oauthlib``, install would fail because those libraries weren't installed yet (on fresh install of Twython) - Removed ``find_packages()`` from ``setup.py``, only one package (we can just define it) - added quick publish method for Ryan and I: ``python setup.py publish`` is faster to type and easier to remember than ``python setup.py sdist upload`` - Removed ``base_url`` from ``endpoints.py`` because we're just repeating it in ``Twython.__init__`` - ``Twython.get_authentication_tokens()`` now takes ``callback_url`` argument rather than passing the ``callback_url`` through ``Twython.__init__``, ``callback_url`` is only used in the ``get_authentication_tokens`` method and nowhere else (kept in init though for backwards compatability) - Updated README to better reflect current Twython codebase - Added ``warnings.simplefilter('default')`` line in ``twython.py`` for Python 2.7 and greater to display Deprecation Warnings in console - Added Deprecation Warnings for usage of ``twitter_token``, ``twitter_secret`` and ``callback_url`` in ``Twython.__init__`` - Headers now always include the User-Agent as Twython vXX unless User-Agent is overwritten - Removed senseless TwythonError thrown if method is not GET or POST, who cares -- if the user passes something other than GET or POST just let Twitter return the error that they messed up - Removed conversion to unicode of (int, bool) params passed to a requests. ``requests`` isn't greedy about variables that can't be converted to unicode anymore - Removed `bulkUserLookup` (please use `lookupUser` instead), removed `getProfileImageUrl` (will be completely removed from Twitter API on May 7th, 2013) - Updated shortenUrl to actually work for those using it, but it is being deprecated since `requests` makes it easy for developers to implement their own url shortening in their app (see) - Twython Deprecation Warnings will now be seen in shell when using Python 2.7 and greater - Twython now takes ``ssl_verify`` parameter, defaults True. Set False if you're having development server issues - Removed internal ``_media_update`` function, we could have always just used ``self.post`` 2.7.3 (2013-04-12) ++++++++++++++++++ - Fixed issue where Twython Exceptions were not being logged correctly 2.7.2 (2013-04-08) ++++++++++++++++++ - Fixed ``AttributeError`` when trying to decode the JSON response via ``Response.json()`` 2.7.1 (2013-04-08) ++++++++++++++++++ - Removed ``simplejson`` dependency - Fixed ``destroyDirectMessage``, ``createBlock``, ``destroyBlock`` endpoints in ``twitter_endpoints.py`` - Added ``getProfileBannerSizes`` method to ``twitter_endpoints.py`` - Made oauth_verifier argument required in ``get_authorized_tokens`` - Update ``updateProfileBannerImage`` to use v1.1 endpoint 2.7.0 (2013-04-04) ++++++++++++++++++ - New ``showOwnedLists`` method 2.7.0 (2013-03-31) ++++++++++++++++++ - Added missing slash to ``getMentionsTimeline`` in ``twitter_endpoints.py`` 2.6.0 (2013-03-29) ++++++++++++++++++ - Updated ``twitter_endpoints.py`` to better reflect order of API endpoints on the Twitter API v1.1 docs site - Downloads (All Versions): - 190 downloads in the last day - 2790 downloads in the last week - 11757 downloads in the last month - Author: Ryan McGrath - Keywords: twitter search api tweet twython stream - License: The MIT License Copyright (c) 2013 Ryan McGr: mikehelmick, ryanmcgrath - Package Index Maintainer: mikehelmick - DOAP record: twython-3.1.2.xml
https://pypi.python.org/pypi/twython/3.1.2
CC-MAIN-2015-40
en
refinedweb
April 2015 Volume 30 Number 4 Microsoft Azure - Azure Notification Hubs: Best Practices for Managing Devices By Sara Silva The mobile applications market is growing faster and faster, and improving the UX of any application is crucial because it increases user loyalty. One of the most important features of modern applications is that they can be kept alive, which means keeping the user informed about the latest events that have occurred in the application, even when it’s not being used. This is possible through push notifications. Each mobile platform has its own push notification service (PNS) responsible for pushing the notifications—short messages—to the device. Windows applications allow apps to receive different push notification types that represent different ways to display the message: toast, tile, raw and badge. For Android applications, on the other hand, only a key/value message is sent to the device and the layout is defined in the application by the class responsible for managing push notifications. In Apple iOS applications, the process is a mix of these approaches. The PNS delivers the notifications, though each application needs a back end or a Web or desktop application to define the message and to connect to the push notification provider to send it. Azure Notification Hubs is a Microsoft Azure service that provides an easy-to-use infrastructure for sending push notifications from any back end to any mobile platform. Actually, there are two main patterns and two models for managing devices in Notification Hubs. In this article I’ll show how each pattern should be used; discuss the advantages, disadvantages and possible scenarios for each; and describe the different models that can be used. I’ll focus on best practices for sending cross-platform and customized push notifications using Notification Hubs, and also show how Notification Hubs is integrated into Azure Mobile Services. The Push Notification Lifecycle The push notification lifecycle consists of three main steps: - The application makes a request for the push notification service handle, which can be a token, channel URI or a registrationId, depending on the mobile platform. - The application sends the PNS handle to the back end to store it. - The back end sends a request to the PNS, which then delivers the push notification. Conceptually this process is very simple, but in practice it’s not so easy because the infrastructure required to implement this flow is complex. If an application is provided for different client platforms, it requires an implementation for each one (in reality, it will represent an implementation for each interface provided by each platform). Moreover, the format for each push notification has its own platform specifications and, in the end, these can be hard to maintain. And that’s not all: The back end needs to be able to scale some push notification services that don’t support broadcasting to multiple devices; to target push notifications to different interest groups; and monitor the push notifications for delivery status. These issues must be handled in the back end and, consequently, this requires a complex infrastructure. Using Notification Hubs As I noted, Azure Notification Hubs makes it easy to send mobile push notifications from any back end to any mobile platform, and it supports sending push notifications for different interest groups and providing monitoring, telemetry and scheduling of push notifications. In this way, Notification Hubs is a third-party service that helps send cross-platform and personalized push notifications to applications and implements all the needs of a push notification infrastructure. To integrate Notification Hubs in an application requires configuration in the Azure Portal; the connection between Notification Hubs and the PNS should be configured in the Configuration separator of the respective Notification Hub. Without these configurations, push notifications can’t be sent and an error will occur. (If you’re ever in doubt about which push notification services are supported by Notification Hubs, the Configuration separator is the best place to check.) To use Notification Hubs, you’ll need to understand tags, templates and the different ways Notification Hubs can be used. In general, a tag represents an interest group, which allows you to send push notifications to specific targets. For example, a sports news application could define tags for each sport: cycling, football, tennis and so forth, allowing the user to select what he wants to receive based on his interests. For cases where authentication is required and the focus is the user, the user id can be used as the tag. In practice, a tag is no more than a simple string value (like “cycling,” “football” or “tennis”), and it’s also useful for localization (for different languages there’s a pattern like “en_cycling” or “pt_cycling,” which represents tags in English or Portuguese, respectively). Templates aren’t a new concept, but Notification Hubs creates an abstraction that allows you to define either platform-specific templates or generic templates, which means you can specify key/value pairs for each push notification defined when the device is registered. The registration will then provide a native notification (toast, payload or message) that contains expressions (such as $(message)) with a value the back end or application will define when the push notification is sent. Figure 1 shows examples of the generic template (for Windows, iOS and Android) using expressions. Figure 1 Generic Templates var toast = new XElement("toast", new XElement("visual", new XElement("binding", new XAttribute("template", "ToastText01"), new XElement("text", new XAttribute("id", "1"), "$(message)")))).ToString(SaveOptions.DisableFormatting); var alert = new JObject( new JProperty("aps", new JObject(new JProperty("alert", "$(message)"))), new JProperty("inAppMessage", notificationText)) .ToString(Newtonsoft.Json.Formatting.None); var payload = new JObject( new JProperty("data", new JObject(new JProperty("message", "$(message)")))) .ToString(Newtonsoft.Json.Formatting.None); The back end or application will fill the value when it sends the key/value (Figure 2 illustrates the process): {"message", "Message here!"} Figure 2 Sending a Platform-Independent Message .png) Registering Devices In mobile development using Notification Hubs, there are two patterns for managing devices and sending push notifications, which can use two different models. In general, the patterns can be described as follows: Case 1: Devices connect directly to Notification Hubs - The client application connects directly to Notification Hubs to register the device. - The back end or a Web or desktop application connects to Notification Hubs to send the push notification. - The PNS will deliver the mobile push notification. Case 2: The back end manages devices in Notification Hubs - The client application connects to the back end. - The back end connects with Notification Hubs to register the devices. - The back end defines the push notification, which will be sent by Notification Hubs. - The PNS will distribute the mobile push notification. Both patterns allow you to use either the Registration model or the Installation model; these models describe the way a device sends the required information to the notification hub. The Installation model was introduced recently and is recommended for new applications or even for current applications. This new model doesn’t make the Registration model obsolete. Here’s a general description of each model: Registration model: In this model, the application sends a registration request to the Notification Hub, providing the PNS handler and tags, and the hub returns a registration id. For each registration you can choose a native template or a generic template, which will define the message. Installation model: In this model, the application sends an installation request to the Notification Hub, providing all information required for the process: InstallationId (for example, a GUID), tags, PNS handler, templates and secondary templates (for Windows apps). Although both models are currently available for use, the Installation model was introduced for certain technical reasons, including: - The installation model is easier to implement and maintain. - The installation model allows partial updates to modify, add or remove tags, PNS handlers, templates, and so forth, without sending the Installation object; in contrast, the registration model requires the entire registration object. - The registration model introduces the possibility of duplicate registrations in the back end for the same device. - The registration model creates complexities in maintaining the list of registrations. - No matter which pattern you use, the flow will be the same. The Installation model can be used in any .NET or Java back end with the Notification Hubs .NET and Java SDKs. For client applications, you can use the REST API with this model, until the new NuGet package that will support the installation model is released. You’ll find the current NuGet package with support for the registration model, WindowsAzure.Messaging.Managed, available at bit.ly/1ArIiIK. Now, let’s take a look at the two patterns. Case 1: Devices Connect Directly to Notification Hubs I’m going to discuss what happens when devices connect directly to Notification Hubs as this is the pattern most frequently used by developers. To describe this, I’ll use the registration model. Registering and unregistering a device in Notification Hubs: The device requests a PNS handle from the PNS, then it connects to a Notification Hub to register, using the PNS handle. The Notification Hub uses this value in the PNS connection. In practice, for example with Universal Applications, the application starts by requesting the channel from the Windows push notification service (WNS) with the following code: // Get the channel from the application var pushNotificationChannel = await PushNotificationChannelManager. CreatePushNotificationChannelForApplicationAsync(); For Android, Google Cloud Messaging provides a registrationId, and for iOS, the Apple Push Notification Service provides a token. A Notification Hub object should be created using the hub name, defined in the Azure Portal, and the connection string (more specifically, the DefaultListenSharedAccessSignature key): // Create the notification hub object var hub = new NotificationHub(HubName, ConnectionString); Note that the NotificationHub class is provided by the WindowsAzure.Messaging.Managed NuGet package (bit.ly/1ArIiIK). Now the application can be registered with the Notification Hub: // Register the device in Notification Hubs var result = await hub.RegisterNativeAsync(pushNotificationChannel.Uri, Tags); When you register a device in Notification Hubs, you don’t have to provide a list of tags, but if the application needs to define interest groups, those tags should be stored in the device to use them in a registration update. Note that the result.RegistrationId received is the id of the registration in Notification Hubs and should not be confused with the registrationId used in Android applications (the id from Google Cloud Messaging). Sending the push notification: The back end (or an application) connects to the Notification Hub to send the push notification, which can be sent to specific tags (or not) using a specific or generic template. In this case, it’s not important who will connect to the Notification Hub, the back end or a Web or desktop application to send the notification. In practice, a NotificationHubClient object should be created and it will require the hub name, defined in the Azure Portal, and the connection string (more specifically, the DefaultFullSharedAccessSignature key): // Create the Notification Hub client object var hub = NotificationHubClient.CreateClientFromConnectionString( HubName, ConnectionString); Next, the native push notification must be defined, for example, as shown in Figure 3. Figure 3 Defining the Native Push Notification // Define template for Windows var toast = new XElement("toast", new XElement("visual", new XElement("binding", new XAttribute("template", "ToastText01"), new XElement("text", new XAttribute("id", "1"), notificationText)))).ToString(SaveOptions.DisableFormatting); // Define template for iOS var alert = new JObject( new JProperty("aps", new JObject(new JProperty("alert", notificationText))), new JProperty("inAppMessage", notificationText)) .ToString(Newtonsoft.Json.Formatting.None); // Define template for Android var payload = new JObject( new JProperty("data", new JObject(new JProperty("message", notificationText))) .ToString(Newtonsoft.Json.Formatting.None); And then the push notification can be sent: var googleResult = await hub.SendGcmNativeNotificationAsync(payload, tags); var windowsResult = await hub.SendWindowsNativeNotificationAsync(toast, tags; var appleResult = await hub.SendAppleNativeNotificationAsync(alert, tags); Whenever a mobile push notification is sent, a list of tags can be provided, but this is optional (it depends on the application requirements). Distributing the push notification: To finish the process, the PNS delivers the notification to devices. The service will try to push the notification during a limited period of time, which varies for each service. One of the advantages of this scenario is that it doesn’t require a back end, but there’s a disadvantage when a user uses more than one device: The tags aren’t shared among devices and the user needs to redefine the tags for each one. The mobile application depends on the Notification Hub, and it’s needed each time to update the tags in the application, which can be a problem if the user doesn’t update to the latest version (a common problem with mobile applications). Possible scenarios for this case can include: - The mobile application doesn’t require a back end, such as when push notifications are sent by a desktop application with this capacity or by the back office (the admin Web site). For example, consider an application based on an online tech event’s news feed that has a settings page where users can subscribe to their interests, such as Developer Events, IT Pro Events and so on. Once the interests are selected, the user will receive push notifications for those interests. Instead of requiring a back end to trigger push notifications, a desktop application or back office can talk directly to the Notification Hub whenever a new event is created to trigger push notifications to all devices that have subscribed to the specific interest. - The mobile application uses a back end, but the push notifications, for some reason, are not integrated in the services and are sent by a desktop application or by the back office. An example might be a client that has a service that provides information to show in the application, but doesn’t allow changes to the service (which can be used by different applications). However, to support push notifications, the client can send notifications using the back office, or even a desktop application. Case 2: The Back End Manages Devices in Notification Hubs To describe this pattern I’ll use the new approach based on the installation model, introduced recently by the Notification Hubs team. The application connects to the back end: In this case, the application connects to the back end to create or update the installation object, which will be stored locally. The device requests the PNS handle from the PNS and gets the last Installation from the Notification Hub, stored on the device. The device then connects to the back end to create or update the installation, from the device, in the Notification Hub. (A new Installation object will be created the first time, but it should be reused each time the back end connects with the Notification Hub for the same device.) For example, in Universal Applications, the application will start by requesting the channel URI from the WNS, with the following: // Get the channel from the application var pushNotificationChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); Before making the request to the back end to create or update the installation, the Installation object must be defined: // Retrieve installation from local storage and // create new one if it does not exist var installation = SettingsHelper.Installation; if (installation == null) { installation = new Installation { InstallationId = Guid.NewGuid().ToString(), Platform = NotificationPlatform.Wns, PushChannel = pushNotificationChannel.ToString(), Tags = new List<string> {“news", "sports"} }; } The installation class used in the client application is created from the JSON provided in the documentation. At this point, you can request the registration with code like this: // Create a client to send the HTTP registration request var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, new Uri(_registerUri)) { Content = new StringContent(JsonConvert.SerializeObject(installation), Encoding.UTF8, "application/json") }; var response = await client.SendAsync(request); The back end creates or updates the installation from the device, in the Notification Hub: When the back end receives a request to register the device using the installation model, it connects with the Notification Hub to create or update the installation. For example, in ASP.NET Web API, you can create a NotificationHubController to define the services to manage devices in Notification Hubs. The implementation requires a Notification Hub client object, which can be defined in the constructor, as follows: public class NotificationHubController : ApiController { private readonly NotificationHubClient _notificationHubClient; private const string HubName = "<define the notification hub name>"; private const string ConnectionString = "<define the connection string>" public NotificationHubController() { _notificationHubClient = NotificationHubClient.CreateClientFromConnectionString( ConnectionString, HubName); } Now you can write the method that will create or update the installation, which will receive as input the installation object, like so: [HttpPost] [Route("api/NH/CreateOrUpdate")] public async Task CreateOrUpdateAsync(Installation installation) { // Before creating or updating the installation is possible, // you must change the tags to have secure tags await _notificationHubClient. CreateOrUpdateInstallationAsync(installation); } Note that the tags can be defined and stored in the back end (in both models). The mobile application isn’t required to store them or even know about them. For example, consider a bank application that defines tags for each account for a client. When an operation is done for an account, a push notification is sent to the device for that account. In this case, the tags must be secure and only the back end will know them. In the Installation model, the installation will be stored in the Notification Hub, which means it can be retrieved based on the InstallationId. The back end defines the push notification, which will be sent by the Notification Hub: The back end is responsible for sending the push notification to the Notification Hub, and you can provide tags and define the template for each platform (when a generic template isn’t defined). The implementation is similar to the scenario in Case 1, where the back end or an application connects to the Notification Hub to send the push notification, so I won’t provide any additional code for this case. By the way, in the installation model, it’s possible to send a push notification to a specific installation. This is a new feature only for registrations based on the Installation model. Here’s the code to do that: _notificationHubClient.SendWindowsNativeNotificationAsync( payload, "$InstallationId:{" + installationId + "}"); The push notification service will distribute the push notification: To finish the process, the PNS will deliver the push notifications to the devices, during a limited period. One of the advantages of this case is that tags can be static or dynamic, which means they can change anytime without changing or affecting the mobile applications; tags are secure because each user can only be registered for a tag if he is authenticated; tags can be shared among different devices for the same user; the mobile application is completely independent of Notification Hubs. The disadvantage of this case is the fact the process is more complex than the first case, if the registration model is used. Possible scenarios for this include: - A mobile application that connects to a back end and the tags must be secure. A good example for this case is an application related to bank accounts, which supports push notifications to keep users informed about transactions in their accounts. - A mobile application that connects to a back end and tags must be dynamic. Consider an application that provides information for different music events, using tags to define different events, and for each event users can subscribe to be updated about all related information. The lifecycle for each tag is short and each time a new event is created, a new tag is created for that event. Tags, therefore, are dynamic and can be managed by the back end, keeping the process independent of the mobile application. In both scenarios, tags should be stored in the back end, but that doesn’t mean the mobile client isn’t aware of them. Updating Registrations With the registration model, each time you want to update anything related to the registration, such as the tags being used, you must redo the registration; this is required to complete the update. But in the Installation model, you can update just specific details. This means if the application needs to update one tag, the templates or other details, it’s possible to do a partial update. Here’s the code for updating a tag: // Define the partial update PartialUpdateOperation replaceTagsOperation = new PartialUpdateOperation(); replaceTagsOperation.Operation = UpdateOperationType.Replace; replaceTagsOperation.Path = "/tags/tennis"; replaceTagsOperation.Value = "cycling"; partialUpdates.Add(replaceTagsOperation); // Send the partial update _notificationHubClient.PatchInstallation( installationId, partialUpdates); Using Notification Hubs in Azure Mobile Services Azure Mobile Services allows you to develop an application with a scalable and secure back end (using the Microsoft .NET Framework or Node.js) hosted in Azure. With the focus on mobile applications, Azure Mobile Services provides the main features a mobile application needs, such as CRUD operations, social network authentication, offline support, push notifications and more. Push notifications are provided in Azure Mobile Services by Notification Hubs, and each time an Azure Mobile Service is created, a Notification Hub is created and associated with the Azure Mobile Service. Mobile applications that use Azure Mobile Services can implement push notifications in a quick and easy way, because the Azure Mobile Services SDK provides APIs for: - Client applications to register devices using the back end. - A back end to manage the devices in a Notification Hub; to modify requests from devices, which means the back end can add, modify or delete tags from the request made by mobile applications, or even cancel the registration; to send push notifications (using a specific template and, if tags are required, provide them). The implementation in the .NET back end will be something similar to: await Services.Push.SendAsync( GetWindowsPushMessageForToastText01( "My push notification message", tags)); The method GetWindowsPushMessageForToastText01 defines the template for the push notification based on a message, and can be implemented as shown in Figure 4. Figure 4 Defining a WindowsPushMessage Based on the ToastText01 Template public static IPushMessage GetWindowsPushMessageForToastText01(string message) { var payload = new XElement("toast", new XElement("visual", new XElement("binding", new XAttribute("template", "ToastText01"), new XElement("text", new XAttribute("id", "1"), message)))) .ToString(SaveOptions.DisableFormatting); return new WindowsPushMessage { XmlPayload = payload }; } In the client application, for example in Universal Apps, you must request the channel from WNS: // Get the channel var channel = await PushNotificationChannelManager. CreatePushNotificationChannelForApplicationAsync(); Then the mobile service client should be created, and it will allow interaction with the back end: // Create the MobileServiceClient using the // AzureEndpoint and admin key var mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient( AzureEndPoint, AzureMobileServiceApplicationKey); The AzureEndPoint should be something like and the AzureMobileServiceApplicationKey is a string that represents the application key defined in the Azure Portal. You can use the method RegisterNativeAsync to register a device, as follows: // Register the device await MobileServiceClient.Client.GetPush().RegisterNativeAsync( channel.Uri, tags); But if you’re going to register the device using a generic template, use the RegisterTemplateAsync method. In Azure Mobile Services (.NET back end), to extend, modify or cancel the registration for Azure Notification Hubs, the INotificationHandler interface should be implemented. By doing so, you can, for example, have secure tags. Wrapping Up Notification Hubs provides an abstraction to send push notifications from any back end to any mobile platform, and the new model allows you to define a unique installation that contains the essential information required by Notification Hubs. That installation can be reused, avoiding duplicate registration and complexity, for new applications or even in current applications, the installation model is recommended. There are two main patterns for registering devices to Notifications Hubs, which should be chosen according to the application requirements. This model lets you send messages focused on specific interest groups using tags, and it’s also possible to define generic or specific templates and to scale and monitor the service according to the needs of the application. Finally, easy-to-use SDKs are provided in several languages for both the mobile apps and the back end. Notification Hubs integrated by default, which is a plus for developers because it enables implementation of the push notification feature in a quick and easy way. Sara Silva is a mathematics graduate and Microsoft MVP. Nowadays, she works as a mobile developer in Portugal, with a main focus on Windows applications, Xamarin and Microsoft Azure. She blogs at saramgsilva.com and can be followed on Twitter at twitter.com/saramgsilva. Thanks to the following Microsoft technical experts for reviewing this article: Piyush Joshi, Paulo Morgado and Chris Risner
https://docs.microsoft.com/en-us/archive/msdn-magazine/2015/april/microsoft-azure-azure-notification-hubs-best-practices-for-managing-devices
CC-MAIN-2022-27
en
refinedweb
The race towards the optimal attention mechanism continues as this year's (arguably) largest computer vision conference CVPR 2021 had another attention mechanism added to the long list. This one is called Coordinate Attention, and was proposed in the paper Coordinate Attention for Efficient Mobile Network Design. At first glance the attention mechanism seems to be a hybrid between Triplet Attention and Strip Pooling, but more specifically targeted for lightweight mobile-deployed networks. We will first take a look at the motivation behind the work and then follow up with a concise background of Triplet Attention (Rotate to Attend: Convolutional Triplet Attention Module) and Strip Pooling (Strip Pooling: Rethinking Spatial Pooling for Scene Parsing). We will then analyze the structure of the proposed mechanism and conclude this article with the results presented in the paper. Table of Contents - Motivation - Coordinate Attention - PyTorch Code - Results - Conclusion - References Bring this project to life Abstract Recent studies on mobile network design have demonstrated the remarkable effectiveness of channel attention (e.g., the Squeeze-and Excitation attention) for lifting model performance, but they generally neglect the positional information, which is important for generating spatially selective attention maps. In this paper, we propose a novel attention mechanism for mobile networks by embedding positional information into channel attention, which we call "coordinate attention". Unlike channel attention that transforms a feature tensor to a single feature vector via 2D global pooling, the coordinate attention factorizes channel attention into two 1D feature encoding processes that aggregate features along the two spatial directions, respectively. In this way, long range dependencies can be captured along one spatial direction and meanwhile precise positional information can be preserved along the other spatial direction. The resulting feature maps are then encoded separately into a pair of direction-aware and position-sensitive attention maps that can be complementarily applied to the input feature map to augment the representations of the objects of interest. Our coordinate attention is simple and can be flexibly plugged into classic mobile networks, such as MobileNetV2, MobileNeXt, and EfficientNet with nearly no computational overhead. Extensive experiments demonstrate that our coordinate attention is not only beneficial to ImageNet classification but more interestingly, behaves better in down-stream tasks, such as object detection and semantic segmentation. Motivation Architectural design has been a major area of recent research in the domain of Computer Vision. Many might argue that this direction of research is becoming saturated, but research is defying these arguments with several new advancements in the design of custom layers and attention mechanisms. The focus of this post is the latter – Attention Mechanisms. Attention mechanisms essentially provide additional information on 'where' and 'what' to focus on, based on the provided input data. Several attention methods like Squeeze and Excitation (SE), Convolutional Block Attention Module (CBAM), Triplet Attention, Global Context (GC), and many more have demonstrated the efficiency of such plug-in modules to significantly improve the performance of conventional baseline models at a minimal increase in computational complexity. Take the word "minimal" with a grain of salt however, as models have been striving to enforce the performance-increasing benefits of attention modules at the lowest overhead possible. However, the approach of designing these attention mechanisms has been primarily focused on large-scale networks, since the computational overhead introduced by these methods makes them unviable for mobile networks with a limited capacity. Additionally, most attention mechanisms are focused on channel information only, and lose out on expressivity due to negating the spatial information present. Based on these shortcomings: In this paper, beyond the first works, we propose a novel and efficient attention mechanism by embedding positional information into channel attention to enable mobile networks to attend over large regions while avoiding incurring significant computation overhead. The authors call this novel attention mechanism Coordinate Attention, because its operation distinguishes spatial direction (i.e., coordinate) and generates coordinate-aware attention maps. Coordinate attention offers the following advantages. First of all, it captures not only cross-channel but also direction-aware and position-sensitive information, which helps models to more accurately locate and recognize the objects of interest. Secondly, the method is flexible and light-weight, and can be easily plugged into classic building blocks of mobile networks, such as the inverted residual block proposed in MobileNetV2 and the sandglass block proposed in MobileNeXt, to augment the features by emphasizing informative representations. Thirdly, as a pretrained model, coordinate attention can bring significant performance gains to down-stream tasks with mobile networks, especially for those with dense predictions (e.g., semantic segmentation). Coordinate Attention As hinted at in the preface of the article, Coordinate Attention as shown in the above figure (c) is somewhat similar to the structure of Triplet Attention and Strip Pooling published at WACV 2021 and CVPR 2020, respectively. (Spoiler: Both of these papers are also from the same author as that of Coordinate Attention). Strip Pooling (CVPR 2020) While the primary focus of the paper was scene parsing, looking at the structure we can notice similarities between the Strip Pooling and Coordinate Attention architectural designs. Strip Pooling essentially takes the input tensor $X \in \mathbb{R}^{C \ast H \ast W}$ and for every spatial feature map, it reduces it into two spatial vectors $H \ast 1$ and $W \ast 1$, respectively. These two vectors are then passed through two 1D convolution kernels followed by a bilinear interpolation process to the original $H \ast W$ shape, which are finally element-wise added. This map is then passed through a pointwise convolution and is element-wise multiplied to the original feature map by applying a sigmoid activation on it before the multiplication. Triplet Attention (WACV 2021) More related to Coordinate Attention in terms of domain, Triplet Attention offered a structure which essentially computes spatial attention in correspondence to channel information by isolating each spatial dimension using permutation operations. This concept was termed by the paper as "Cross Dimension Interaction (CDI)". For an in-depth analysis of Triplet Attention, please view my blogpost here. Back to Coordinate Attention, let's dissect what's happening in the module. As shown in the figure at the start of this section, Coordinate Attention (Coord Att.) takes an input tensor $X \in \mathbb{R}^{C \ast H \ast W}$ and applies average pool across the two spatial dimensions $H$ and $W$ and obtains two tensors $X' \in \mathbb{R}^{C \ast H \ast 1}$ and $X'' \in \mathbb{R}^{C \ast 1 \ast W}$. Then these two tensors are concatenated to form $X''' \in \mathbb{R}^{C \ast 1 \ast (H + W)}$ which is subsequently passed through a 2D convolution kernel which reduces the channels from $C$ to $\frac{C}{r}$ based on a specified reduction ratio $r$. This is followed by a normalization layer (Batch Norm in this case) and then an activation function (Hard Swish in this case). Finally the tensor is split into $\hat{X} \in \mathbb{R}^{\frac{C}{r} \ast 1 \ast W}$ and $\tilde{X} \in \mathbb{R}^{\frac{C}{r} \ast H \ast 1}$. These two tensors are individually passed through two 2D convolution kernels, each of which increases the channels back to $C$ from $\frac{C}{r}$, and finally a sigmoid activation is applied on the resultant two tensors which are the attention maps. The attention maps are then sequentially element-wise multiplied with the original input tensor $X$. PyTorch Code The following snippet provides the PyTorch code for the Coordinate Attention module which can be plugged into any classic backbone. import torch import torch.nn as nn import math import torch.nn.functional as F class h_sigmoid(nn.Module): def __init__(self, inplace=True): super(h_sigmoid, self).__init__() self.relu = nn.ReLU6(inplace=inplace) def forward(self, x): return self.relu(x + 3) / 6 class h_swish(nn.Module): def __init__(self, inplace=True): super(h_swish, self).__init__() self.sigmoid = h_sigmoid(inplace=inplace) def forward(self, x): return x * self.sigmoid(x) class CoordAtt(nn.Module): def __init__(self, inp, oup, reduction=32): super(CoordAtt, self).__init__() self.pool_h = nn.AdaptiveAvgPool2d((None, 1)) self.pool_w = nn.AdaptiveAvgPool2d((1, None)) mip = max(8, inp // reduction) self.conv1 = nn.Conv2d(inp, mip, kernel_size=1, stride=1, padding=0) self.bn1 = nn.BatchNorm2d(mip) self.act = h_swish() self.conv_h = nn.Conv2d(mip, oup, kernel_size=1, stride=1, padding=0) self.conv_w = nn.Conv2d(mip, oup, kernel_size=1, stride=1, padding=0) def forward(self, x): identity = x n,c,h,w = x.size() x_h = self.pool_h(x) x_w = self.pool_w(x).permute(0, 1, 3, 2) y = torch.cat([x_h, x_w], dim=2) y = self.conv1(y) y = self.bn1(y) y = self.act(y) x_h, x_w = torch.split(y, [h, w], dim=2) x_w = x_w.permute(0, 1, 3, 2) a_h = self.conv_h(x_h).sigmoid() a_w = self.conv_w(x_w).sigmoid() out = identity * a_w * a_h return out Results For complete set of extensive results on experiments conducted by the authors, I highly advise taking a look at the paper. Here we only show the prominent results on image classification on ImageNet using MobileNet and MobileNext, and on object detection on MS-COCO where Coordinate Attention showcases all round improvements in terms of performance. Conclusion Although the results are impressive in their own right, the proposed method is counterintuitive to one of the main motivations of the paper: low-cost attention for mobile networks, since Coordinate Attention is, in fact, costlier both in terms of parameters and FLOPs compared to the two methods it was compared against (CBAM and SE). The second drawback is the limited number of comparisons. Although SE and CBAM are prominent attention methods, there have been many more advancements with better-performing and lower cost attention modules which the authors failed to compare against Triplet and ECA. Also, the Coordinate Attention module is not an apple-to-apple comparison against CBAM, since the former uses hard swish as its activation which provides a significant performance boost, however, it is compared to the latter which uses ReLU (which is inferior to hard swish). However, it is up to the readers to decide whether the paper does justice and provides yet another effective attention module to try. References - Coordinate Attention for Efficient Mobile Network Design - Coordinate Attention official GitHub repository Add speed and simplicity to your Machine Learning workflow today
https://blog.paperspace.com/coordinate-attention/
CC-MAIN-2022-27
en
refinedweb
- Article Catalog - How to integrate Enterprise Message API Java edition with Log4j Logging Framework Overview Update: January 2022 As of December 2021: There are new serious vulnerabilities that were identified impacting the Apache Log4j utility. Please update the library to the latest version. You can find more detail regarding the vulnerability and the fix from the Apache Log4j Security Vulnerabilities page. Enterprise Message API - Java Edition (EMA API) allows developers to integrate the EMA Java application with Apache Log4j which is a de facto standard logging framework for Java-based applications at deployment time by using the Simple Logging Facade for Java (SLF4J) API as a facade for logging utility. Even though the EMA Java API binds the logging mechanism with Java Logging API by default, developers can change the binding library and logging configuration files to bind the EMA Java application with Log4j or another framework that supported SLF4J without modifying the application source code. The article is focusing on how to integrate Log4j with the EMA Java application in a manual way which is suitable for earlier versions of EMA Java API. However, the API has been mavenized to support the Apache Maven and Gradle build tools since Refinitiv Real-Time SDK (RTSDK) Java (formerly known as Elektron SDK) version 1.2, if you are using Maven, please check this How to integrate Enterprise Message API Java with Log4j Logging Framework using Maven article. IMPORTANT Rebranding Announcement: Starting with version RTSDK 2.0.0.L1 (same as EMA/ETA 3.6.0.L1), there are namespace changes and library name changes. Please note that all interfaces remain the same as prior releases of RTSDK and Elektron SDK and will remain fully wire compatible. Along with RTSDK 2.X version, a REBRAND.md is published to detail impact to existing applications and how to quickly adapt to the re-branded libraries. Existing applications will continue to work indefinitely as-is. Applications should be proactively rebranded to be able to utilize new features, security updates or fixes post 2.X release. Please see PCN for more details on support. Building RTSDK Please follow the steps in Building RTSDK to build RTSDK jar files. How to integrate EMA Java Application with Logging Framework The RTSDK Java package contains two SLF4J library files in the <Real-Time SDK Java 2.0.0.L1 package>/RTSDK-BinaryPack/Java/Eta/Libs/SLF4J/slf4j-1.7.12 folder slf4j-api-1.7.12.jar slf4j-jdk14-1.7.12.jar The slf4j-api-1.7.12.jar file is the core SLF4J library file. The slf4j-jdk14-1.7.12.jar is a binding library file for Java Logging API. Developers can perform the following steps to integrate the EMA Java application log with Log4j framework. Replace this slf4j-jdk14-1.7.12.jar file with SLF4J-Log4j binding jar file Add Log4j required core library files to the Java classpath Configure configurations file to Java classpath or JVM option Integration with Log4j 2 framework The Log4j 2 framework requires the following libraries files in Java classpath to intergrate with EMA Java SLF4J framework: - log4j-api-<version>.jar - log4j-core-<version>.jar - log4j-slf4j-impl-<version>.jar - slf4j-api-<version>.jar Then developers can configure Log4j 2 configurations file to Java classpath or JVM option "-Dlog4j.configurationFile" at runtime to let the EMA Java application uses Log4j 2 configurations file. This article is based on Log4j 2. Example Log4j 2 configurations file (in XML format) The example file is saved as "\resource\log4j2.xml" file. <?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="current date-%d LEVEL-%-5p Thread-[%t] Method-%M() Class name-%C Message-%m%n"/> </Console> </Appenders> <loggers> <Logger name="org.apache.log4j.xml" level="all"/> <root level="all"> <appender-ref </root> </loggers> </Configuration> Then you can run the EMA Java example with JVM option -Dlog4j.configurationFile points to the log4j2.xml file and include the Log4j 2 libraries files in the Java classpath too. Examples Directory structure: - All RTSDK jars files and dependencies are available in libs folder. - The EmaConfig.xml file and compiled EMA Java example class files are available out folder. java -Dlog4j.configurationFile=..\resources\log4j2.xml -cp .;..\libs\ema-3.6.0.0.jar;..\libs\eta-3.6.0.0.jar;..\libs\etaValueAdd-3.6.0.0.jar;..\libs\commons-collections-3.2.2.jar;..\libs\commons-configuration-1.10.jar;..\libs\commons-lang-2.6.jar;..\libs\commons-logging-1.2.jar;..\libs\httpclient-4.5.3.jar;..\libs\httpcore-4.4.12.jar;..\libs\slf4j-api-1.7.12.jar;..\libs\log4j-api-2.17.1.jar;..\libs\log4j-core-2.17.1.jar;..\libs\log4j-slf4j-impl-2.17.1.jar; com.refinitiv.ema.examples.training.consumer.series100.ex100_MP_Streaming.Consumer An example result with Log4j 2 is shown below: current date-2020-12-15 15:37:00,156 LEVEL-TRACE Thread-[main] Method-initialize() Class name-com.refinitiv.ema.access.OmmBaseImpl Message-loggerMsg ClientName: Consumer_1_1 Severity: Trace Text: Print out active configuration detail. itemCountHint: 100000 serviceCountHint: 513 requestTimeout: 15000 dispatchTimeoutApiThread: 0 maxDispatchCountApiThread: 100 maxDispatchCountUserThread: 100 userDispatch: 1 configuredName: Consumer_1 instanceName: Consumer_1_1 xmlTraceEnable: false globalConfig.reactorChannelEventPoolLimit: -1 globalConfig.reactorMsgEventPoolLimit: -1 globalConfig.workerEventPoolLimit: -1 globalConfig.tunnelStreamMsgEventPoolLimit: -1 globalConfig.tunnelStreamStatusEventPoolLimit: -1 obeyOpenWindow: 1 maxOutstandingPosts: 100000 userDispatch: 1 reconnectAttemptLimit: -1 reconnectMinDelay: 1000 reconnectMaxDelay: 5000 msgKeyInUpdates: true directoryRequestTimeOut: 45000 dictionaryRequestTimeOut: 45000 reissueTokenAttemptLimit: -1 reissueTokenAttemptInterval: 5000 restRequestTimeOut: 45000 tokenReissueRatio: 0.8 loginRequestTimeOut: 45000 loggerMsgEnd .... current date-2020-12-15 15:37:00,382 LEVEL-TRACE Thread-[main] Method-<init>() Class name-com.refinitiv.ema.access.CallbackClient Message-loggerMsg ClientName: LoginCallbackClient Severity: Trace Text: Created LoginCallbackClient loggerMsgEnd current date-2020-12-15 15:37:00,382 LEVEL-TRACE Thread-[main] Method-initialize() Class name-com.refinitiv.ema.access.LoginCallbackClient Message-loggerMsg ClientName: LoginCallbackClient Severity: Trace Text: RDMLogin request message was populated with this info: LoginRequest: streamId: 1 userName: user streaming: true nameType: 1 applicationId: 256 applicationName: ema position: 192.168.68.113/WIN-V793K3HCLOL loggerMsgEnd Integration with Log4j 1.x framework Conclusion The EMA Java API is implemented on top of SLF4J API as a facade for logging utility. It allows developers to integrate EMA Java application with their preferred Logging framework by replacing the Logging library and configuration files without touching the application source code. References For further details, please check out the following resources: - Refinitiv Real-time Java API page on the Refinitiv Developer Community web site. - Simple Logging Facade for Java (SLF4J) web site. - Apache Log4j 2 web site. For further details, please check out the following resources: - Enterprise Message API Java Quick Start - Developer Webinar: Introduction to Enterprise App Creation With Open-Source Enterprise Message API For any question related to this article or Enterprise Message API page, please use the Developer Community Q&A Forum. Source Code Related APIs
https://developers.uat.refinitiv.com/en/article-catalog/article/how-to-integrate-elektron-message-api-java-edition-with-log4j-logging-framework
CC-MAIN-2022-27
en
refinedweb
The Twisted writing standard describes the documentation writing styles we prefer in our narrative documentation. This standard applies particularly to howtos and other descriptive documentation. For writing API documentation, please refer to Docstrings section in our coding standard. This document is meant to help Twisted documentation authors produce documentation that does not have the following problems: misleads users about what is good Twisted style; misleads users into thinking that an advanced howto is an introduction to writing their first Twisted server; and misleads users about whether they fit the document’s target audience: for example, that they are able to use enterprise without knowing how to write SQL queries. Documents should aim to be clear and concise, allowing the API documentation and the example code to tell as much of the story as they can. Demonstrations and where necessary supported arguments should always preferred to simple statements (“here is how you would simplify this code with Deferreds” rather than “Deferreds make code simpler”). Documents should be clearly delineated into sections and subsections. Each of these sections, like the overall document, should have a single clear purpose. This is most easily tested by trying to have meaningful headings: a section which is headed by “More details” or “Advanced stuff” is not purposeful enough. There should be fairly obvious ways to split a document. The two most common are task based sectioning and sectioning which follows module and class separations. Documentation must use American English spelling, and where possible avoid any local variants of either vocabulary or grammar. Grammatically complex sentences should ideally be avoided: these make reading unnecessarily difficult, particularly for non-native speakers. When referring to a hypothetical person, (such as “a user of a website written with twisted.web”), gender neutral pronouns (they/their/them) should be used. For reStructuredText documents which are handled by the Sphinx documentation generator make lines short, and break lines at natural places, such as after commas and semicolons, rather than after the 79th column. We call this semantic newlines. This rule does not apply to docstrings. The Twisted documentation should maintain a reasonable distinction between “evangelism” documentation, which compares the Twisted design or Twisted best practice with other approaches and argues for the Twisted approach, and “usage” documentation, which describes the Twisted approach in detail without comparison to other possible approaches. While both kinds of documentation are useful, they have different audiences. The first kind of document, evangelical documents, is useful to a reader who is researching and comparing approaches and seeking to understand the Twisted approach or Twisted functionality in order to decide whether it is useful to them. The second kind of document, usage documents, are useful to a reader who has decided to use Twisted and simply wants further information about available functions and architectures they can use to accomplish their goal. Since they have distinct audiences, evangelism and detailed usage documentation belongs in separate files. There should be links between them in ‘Further reading’ or similar sections. Descriptions of any feature added since release 2.0 of Twisted core must have a note describing which release of which Twisted project they were added in at the first mention in each document. If they are not yet released, give them the number of the next minor release. For example, a substantial change might have a version number added in the introduction: This document describes the Application infrastructure for deploying Twisted applications (added in Twisted 1.3) . The version does not need to be mentioned elsewhere in the document except for specific features which were added in subsequent releases, which might should be mentioned separately. The simplest way to create a .tacfile, SuperTac (added in Twisted Core 99.7) … In the case where the usage of a feature has substantially changed, the number should be that of the release in which the current usage became available. For example: This document describes the Application infrastructure for deploying Twisted applications (updated[/substantially updated] in Twisted 2.7) . The first occurrence of the name of any module, class or function should always link to the API documents. Subsequent mentions may or may not link at the author’s discretion: discussions which are very closely bound to a particular API should probably link in the first mention in the given section. Links between howtos are encouraged. Overview documents and tutorials should always link to reference documents and in depth documents. These documents should link among themselves wherever it’s needed: if you’re tempted to re-describe the functionality of another module, you should certainly link instead. Linking to standard library documentation is also encouraged when referencing standard library objects. Intersphinx is supported in Twisted documentation, with prefixes for linking to either the Python 2 standard library documentation (via py2) or Python 3 (via py3) as needed. The introductory section of a Twisted howto should immediately follow the top-level heading and precede any subheadings. The following items should be present in the introduction to Twisted howtos: the introductory paragraph and the description of the target audience. The introductory paragraph of a document should summarize what the document is designed to present. It should use the both proper names for the Twisted technologies and simple non-Twisted descriptions of the technologies. For example, in this paragraph both the name of the technology (“Conch”) and a description (“SSH server”) are used: This document describes setting up a SSH server to serve data from the file system using Conch, the Twisted SSH implementation. The introductory paragraph should be relatively short, but should, like the above, somewhere define the document’s objective: what the reader should be able to do using instructions in the document. Subsequent paragraphs in the introduction should describe the target audience of the document: who would want to read it, and what they should know before they can expect to use your document. For example: The target audience of this document is a Twisted user who has a set of filesystem like data objects that they would like to make available to authenticated users over SFTP. Following the directions in this document will require that you are familiar with managing authentication via the Twisted Cred system. Use your discretion about the extent to which you list assumed knowledge. Very introductory documents that are going to be among a reader’s first exposure to Twisted will even need to specify that they rely on knowledge of Python and of certain networking concepts (ports, servers, clients, connections) but documents that are going to be sought out by existing Twisted users for particular purposes only need to specify other Twisted knowledge that is assumed. Any knowledge of technologies that wouldn’t be considered “core Python” and/or “simple networking” need to be explicitly specified, no matter how obvious they seem to someone familiar with the technology. For example, it needs to be stated that someone using enterprise should know SQL and should know how to set up and populate databases for testing purposes. Where possible, link to other documents that will fill in missing knowledge for the reader. Linking to documents in the Twisted repository is preferred but not essential. The introduction should finish with a list of tasks that the user can expect to see the document accomplish. These tasks should be concrete rather than abstract, so rather than telling the user that they will “understand Twisted Conch”, you would list the specific tasks that they will see the document do. For example: This document will demonstrate the following tasks using Twisted Conch: - creating an anonymous access read-only SFTP server using a filesystem backend; - creating an anonymous access read-only SFTP server using a proxy backend connecting to an HTTP server; and - creating an anonymous access read and write SFTP server using a filesystem backend. In many cases this will essentially be a list of your code examples, but it need not be. If large sections of your code are devoted to design discussions, your goals might resemble the following: This document will discuss the following design aspects of writing Conch servers: - authentication of users; and - choice of data backends. Wherever possible, example code should be provided to illustrate a certain technique or piece of functionality. Example code should try and meet as many of the following requirements as possible: example code should be a complete working example suitable for copying and pasting and running by the reader (where possible, provide a link to a file to download); example code should be short; example code should be commented very extensively, with the assumption that this code may be read by a Twisted newcomer; example code should conform to the coding standard ; and example code should exhibit ‘best practice’, not only for dealing with the target functionality, but also for use of the application framework and so on. The requirement to have a complete working example will occasionally impose upon authors the need to have a few dummy functions: in Twisted documentation the most common example is where a function is needed to generate a Deferred and fire it after some time has passed. An example might be this, where deferLater is used to fire a callback after a period of time: from twisted.internet import task, reactor def getDummyDeferred(): """ Dummy method which returns a deferred that will fire in 5 seconds with a result """ return task.deferLater(reactor, 5, lambda x: "RESULT") As in the above example, it is imperative to clearly mark that the function is a dummy in as many ways as you can: using Dummy in the function name, explaining that it is a dummy in the docstring, and marking particular lines as being required to create an effect for the purposes of demonstration. In most cases, this will save the reader from mistaking this dummy method for an idiom they should use in their Twisted code. The conclusion of a howto should follow the very last section heading in a file. This heading would usually be called “Conclusion”. The conclusion of a howto should remind the reader of the tasks that they have done while reading the document. For example: In this document, you have seen how to: - set up an anonymous read-only SFTP server; - set up a SFTP server where users authenticate; - set up a SFTP server where users are restricted to some parts of the filesystem based on authentication; and - set up a SFTP server where users have write access to some parts of the filesystem based on authentication. If appropriate, the howto could follow this description with links to other documents that might be of interest to the reader with their newfound knowledge. However, these links should be limited to fairly obvious extensions of at least one of the listed tasks.
https://twistedmatrix.com/documents/current/core/development/policy/writing-standard.html
CC-MAIN-2022-27
en
refinedweb
What’s This Module For? To interact with a queue broker implementing version 0.8 of the Advanced Message Queueing Protocol (AMQP) standard. Copies of various versions of the specification can be found here. At time of writing, 0.10 is the latest version of the spec, but it seems that many popular implementations used in production environments today are still using 0.8, presumably awaiting a finalization of v.1.0 of the spec, which is a work in progress. What is AMQP? AMQP is a queuing/messaging protocol that is implemented by server daemons (called ‘brokers’) like RabbitMQ, ActiveMQ, Apache Qpid, Red Hat Enterprise MRG, and OpenAMQ. Though messaging protocols used in the enterprise are historically proprietary, AMQP has a bold and vocal stance that AMQP will be: - Broadly applicable for enterprise use - Totally open - Platform agnostic - Interoperable The working group consists of several huge enterprises who have a vested interest in a protocol that meets these requirements. Most are either huge enterprises who are (or were) a victim of the proprietary lock-in that came with what will now likely become ‘legacy’ protocols, or implementers of the protocols, who will sell products and services around their implementation. Here’s a brief list of those involved in the AMQP working group: - JPMorgan Chase (the initial developers of the protocol, along with iMatix) - Goldman Sachs - Red Hat Software - Cisco Systems - Novell Message brokers can facilitate an awfully large amount of flexibility in an architecture. They can be used to integrate applications across platforms and languages, enable asynchronous operations for web front ends, modularize and more easily distribute complex processing operations. Basic Publishing The first thing to know is that when you code against an AMQP broker, you’re dealing with a hierarchy: a ‘vhost’ contains one or more ‘exchanges’ which themselves can be bound to one or more ‘queues’. Here’s how you can programmatically create an exchange and queue, bind them together, and publish a message: from amqplib import client_0_8 as amqp conn = amqp.Connection(userid='guest', password='guest', host='localhost', virtual_host='/', ssl=False) # Create a channel object, queue, exchange, and binding. chan = conn.channel() chan.queue_declare('myqueue', durable=True) chan.exchange_declare('myexchange', type='direct', durable=True) chan.queue_bind('myqueue', 'myexchange', routing_key='myq.myx') # Create an AMQP message object msg = amqp.Message('This is a test message') chan.basic_publish(msg, 'myexchange', 'myq.myx') As far as we know, we have one exchange and one queue on our server right now, and if that’s the case, then technically the routing key I’ve used isn’t required. However, I strongly suggest that you always use a routing key to avoid really odd (and implementation-specific) behavior like getting multiple copies of a message on the consumer side of the equation, or getting odd exceptions from the server. The routing key can be arbitrary text like I’ve used above, or you can use a common formula of using ‘.’ as your routing key. Just remember that without the routing key, the minute more than one queue is bound to an exchange, the exchange has no way of knowing which queue to route a message to. Remeber: you don’t publish to a queue, you publish to an exchange and tell it which queue it goes in via the routing key. Basic Consumption Now that we’ve published a message, how do we get our hands on it? There are two methods: basic_get, which will ‘get’ a single message from the queue, or ‘basic_consume’, which technically doesn’t get *any* messages: it registers a handler with the server and tells it to send messages along as they arrive, which is great for high-volume messaging operations. Here’s the ‘basic_get’ version of a client to grab the message we just published: msg = chan.basic_get(queue='myqueue', no_ack=False) chan.basic_ack(msg.delivery_tag) In the above, I’ve used the same channel I used to publish the message to get it back again using the basic_get operation. I then acknowledged receipt of the message by sending the server a ‘basic_ack’, passing along the delivery_tag the server included as part of the incoming message. Consuming Mass Quantities Using basic_consume takes a little more thought than basic_get, because basic_consume does nothing more than register a method with the server to tell it to start sending messages down the pipe. Once that’s done, however, it’s up to you to do a chan.wait() to wait for messages to show up, and find some elegant way of breaking out of this wait() operation. I’ve seen and used different techniques myself, and the right thing will depend on the application. The basic_consume method also requires a callback method which is called for each incoming message, and is passed the amqp.Message object when it arrives. Here’s a bit of code that defines a callback method, calls basic_consume, and does a chan.wait(): consumer_tag = 'foo' def process(msg): txt = msg.body if '-1' in txt: print 'Got -1' chan.basic_cancel(consumer_tag) chan.close() else: print 'Got message!' chan.basic_consume('messages', callback=process, consumer_tag=consumer_tag) while True: print 'Message processed. Next?' try: chan.wait() except IOError as out: print "Got an IOError: %s" % out break if not chan.is_open: print "Done processing. Later" break So, basic_consume tells the server ‘Start sending any and all messages!’. The server registers a method with a name given by the consumer_tag argument, or it assigns one and it becomes the return value of basic_consume(). I define one here because I don’t want to run into race conditions where I want to call basic_cancel() with a consumer_tag variable that doesn’t exist yet, or is out of scope, or whatever. In the callback, I look for a sentinel message whose body contains ‘-1’, and at that point I call basic_cancel (passing in the consumer_tag so the server knows who to stop sending messages to), and I close the channel. In the ‘while True’, the channel object checks its status and exits if it’s not open. The above example starts to uncover some issues with py-amqplib. It’s not clear how errors coming back from the server are handled, as opposed to errors caused by the processing code, for example. It’s also a little clumsy trying to determine the logic for breaking out of the loop. In this case there’s a sentinel message sent to the queue representing the final message on the stack, at which point our ‘process()’ callback closes the channel, but then the channel has to check its own status to move forward. Just returning False from process() doesn’t break out of the while loop, because it’s not looking for a return value from that function. We could have our process() function raise an error of its own as well, which might be a bit more elegant, if also a bit more work. Moving Ahead What I’ve covered here actually covers perhaps 90% of the common cases for amqplib, but there’s plenty more you can do with it. There are various exchange types, including fanout exchanges and topic exchanges, which can facilitate more interesting messaging and pub/sub models. To learn more about them, here are a couple of places to go for information: Broadcasting your logs with RabbitMQ and Python Rabbits and Warrens RabbitMQ FAQ section “Messaging Concepts: Exchanges
http://protocolostomy.com/2010/04/03/pytpmotw-py-amqplib/
CC-MAIN-2022-27
en
refinedweb
Networking has been changed a lot. From the era of hardware-based physical networking to the current world where networking is being defined by software, a lot of innovations and thought processes are continously being applied. In this Physical Networking We know how the network engineer builds networks in data centers. Engineers program quite a few network devices like servers, routers, switches, firewalls etc. It is a fairly manual process. It might take a few days in programming network devices and setting rules in the firewall. In the traditional datacenter, An operating system is installed on a physical server which is reserved to host a particular application. Each server has one or more network interface cards (NIC) to enable communication among the servers. NIC is attached to the external network infrastructure. In the above figure, NICs are attached to the switch, which enables efficient packet communication among the endpoints. Virtualization Virtualization is changing the mindset from physical to logical. It is a concept of creating more logical IT resources, called virtual systems, within a physical system. Virtualization can be classified into 2 categories. - System Level Virtualization - Process Level Virtualization System Level Virtualization. In System level virtualization, hardware resources are shared by virtual machines, each of which include both an application and a complete operating system instance. A physical server running three VMs, would, for example, feature a hypervisor accompanied by three separate operating systems running on top. Following are the main components of System Level Virtualization. - Hypervisor - Virtual Network Interface Card (vNIC) - Virtual Switch (Open vSwitch). Hypervisor The key innovation behind virtualization is an abstraction of computer hardware to allow multiple operating systems and applications to share the hardware. This innovation is known as Hypervisor or Virtual Machine Monitor. Hypervisors are further classified as type 1 and type 2 hypervisor. Type 1 Hypervisor runs directly on physical hardware. This type of hypervisor is also considered as the bare-metal hypervisor. With direct access to the underlying hardware, it is the most efficient and best-performing hypervisor available. Hypervisors such as VMware ESXi, Microsoft Hyper-V server and KVM are examples of Type 1 hypervisors. A Type 2 hypervisor is typically installed on top of an existing OS, and it’s called a hosted hypervisor because it relies on the host machine’s pre-existing OS to manage calls to CPU, memory, storage and network resources. Type 2 hypervisors include VMware Fusion, Oracle VM Server for x86, Oracle VM VirtualBox, Oracle Solaris Zones and VMware Workstation. Hypervisor abstract the resources of a physical server. Multiple VMs can be created on top of it. The hypervisor may create one or more virtual network interface card (vNIC) for each VM. These NICs can appear a physical NIC to the VM but actually, represent the interface of NIC. VM reduces the number of physical servers. With a few servers, you can spend less time on manual tasks required for server maintenance. Deploying VM is much faster than deploying the physical server. You might be running a VM and 15 minutes later it will be up and running. If we compare VM with the physical server in a data-center, the lifetime of a VM is a few months or weeks. Virtual Switch. It minimizes the overhead of network infrastructure. Within the virtual switch, the limit has nothing to do with network bandwidth. Linux natively incorporates layer-2 virtual switch within the kernel. Distributed Virtual Switch is required to enable communication between VMs running Process Level Virtualization Process Level Virtualization is also known as Containerization. A server supporting three containerized applications requires just a single operating system, with each container sharing the operating system kernel with its companion containers. If we compare it with the physically hosted server, system VMs are incredibly fast but not fast enough to meet today’s requirements where applications are dynamic in nature. Instead of creating virtual machines and partitioning hardware resources that way, containerization seeks to construct various data containers at an operating system level. That means the containers will share an operating system, unlike system virtual machines, each of which has a cloned operating system to itself. Before jumping on the networking part lets see the building blocks of a container. The container is composed of the following 3 components. - Namespace - CGroup - Layered file system Union capable file-system provides the way to combining multiple directories into one. If you want to explore more about the Union file-systems then you can follow my blog Tale of a Container’s file system. CGroup limits how much you can use. It is a Linux kernel feature that limits, accounts for, and isolates the resource usage (CPU, memory, disk I/O, network, etc.) of a collection of processes. Namespace limit what you can see. the namespace is a feature of Linux kernel, that partition kernel resources such that one set of processes can see one set of resources while another set of resources can see the different set of resources. Since this blog is all about networking so here we will have our focus on network namespace. Container Networking The network of two containers are isolated by their network namespaces. In order to understand how 2 containers communicates with each other, we should understand how the communication channel can be established between 2 network namespaces. In the above diagram, there are two distinct network-namespaces as Red Namespace and Green Namespace. These 2 distinct namespaces are communicated through OpenvSwith. In my next post, I will explain the procedure to establish communication between namespaces.
https://blog.knoldus.com/evolution-of-container-networking/
CC-MAIN-2022-27
en
refinedweb
AWS CodeArtifact Concepts Here are some concepts and terms to know when you use CodeArtifact. Topics Domain Repositories are aggregated into a higher-level entity known as a domain. All package assets and metadata are stored in the domain, but they are consumed through repositories. A given package asset, such as a Maven JAR file, is stored once per domain, no matter how many repositories it's present in. All of the assets and metadata in a domain are encrypted with the same AWS KMS key (KMS key) stored in AWS Key Management Service (AWS KMS). Each repository is a member of a single domain and can't be moved to a different domain. The domain allows organizational policy to be applied across multiple repositories, such as which accounts can access repositories in the domain, and which public repositories can be used as sources of packages. Although an organization can have multiple domains, we recommend a single production domain that contains all published artifacts so that teams can find and share packages across their organization. Repository A CodeArtifact repository contains a set of package versions, each of which maps to a set of assets. Repositories are polyglot—a single repository can contain packages of any supported type. Each repository exposes endpoints for fetching and publishing packages using tools like the nuget CLI, the npm CLI, the Maven CLI ( mvn), and pip. You can create up to 1000 repositories per domain. Package A package is a bundle of software and the metadata that is required to resolve dependencies and install the software. In CodeArtifact, a package consists of a package name, an optional namespace such as @types in @types/node, a set of package versions, and package-level metadata such as npm tags. AWS CodeArtifact supports npm, PyPI, Maven, and NuGet package formats. Package version A package version identifies the specific version of a package, such as @types/node 12.6.9. The version number format and semantics vary for different package formats. For example, npm package versions must conform to the Semantic Versioning specification Package version revision A package version revision is a string that identifies a specific set of assets and metadata for a package version. Each time a package version is updated, a new package version revision is created. For example, you might publish a source distribution archive (sdist) for a Python package version, and later add a Python wheel that contains compiled code to the same version. When you publish the wheel, a new package version revision is created. Upstream repository One repository is upstream of another when the package versions in it can be accessed from the repository endpoint of the downstream repository, effectively merging the contents of the two repositories from the point of view of a client. CodeArtifact allows creating an upstream relationship between two repositories. Asset An asset is an individual file stored in CodeArtifact that is associated with a package version, such as an npm .tgz file or Maven POM and JAR files. Package namespace Some package formats support hierarchical package names to organize packages into logical groups and help avoid name collisions. For example, npm supports scopes, see the npm scopes documentation @types/node has a scope of @types and a name of node. There are many other package names in the @types scope. In CodeArtifact, the scope (“types”) is referred to as the package namespace and the name (“node”) is referred to as the package name. For Maven packages, the package namespace corresponds to the Maven groupID. The Maven package org.apache.logging.log4j:log4j has a groupID (package namespace) of org.apache.logging.log4j and the artifactID (package name) log4j. Some package formats such as PyPI don't support hierarchical names with a concept similar to npm scope or Maven groupID. Without a way to group package names, it can be more difficult to avoid name collisions.
https://docs.aws.amazon.com/codeartifact/latest/ug/codeartifact-concepts.html
CC-MAIN-2022-27
en
refinedweb
Unity 2020.1.0 Beta 10 Released: 27. May10) Asset Importers: Crash when importing Elongata package from the Asset Store (1209240) Audio: Editor crashes on changing 'System Sample Rate' when Audio track preview is being played in Timeline window (1232743) Audio: [Windows] Editor uses one CPU Logical Processor at 100% while the game is in Pause Mode (1219619) Collab: Collab re-enables itself after being turned off (1244885) GI: Fixed GI baking in batchmode when using Scriptable Render Pipelines. (1211448) Fixed in 2020.1.0b11. GI: Fixed the lightmapper sometimes getting stuck, especially on undo after moving instances or changing resolutions. (1144403) Fixed in 2020.1.0b - General: Crash on startup when Shader Variant with Standard ForwardAdd DIRECTIONAL is assigned and SourceAssetDB present in Library (1235969) Graphics - General: Plugging time into a master node on HDRP crashes Unity (1246991): Crash on PrepareShadowMaps when entering Play Mode (1233829) This is a change to a 2020.1.0 change, not seen in any released version, and will not be mentioned in final notes. Fixed in 2020.1.0b11. IAP: Unity purchasing gives error on project upgrade due to failing to find UnityEngine.UI assembly (1193773) IL2CPP: Fix JSON exception when building project with large number of scenes (1240780) Fixed in 2020.1.0b11. IL2CPP: Fix a severe performance regression in UnityLinker when building a player for UWP. (1229420) This is a change to a 2020.1.0 change, not seen in any released version, and will not be mentioned in final notes. Fixed in 2020.1.0b11.: Unity kernel crashes Mac with OpenGL when only Intel Graphics are present (1225380) MacOS: [HDRP][Metal][macOS 10.14] Unity freezes the whole OS or crashes when opening prefab (1219198)) Packman: [PackMan] Search results for "My Assets" don't match the package count displayed below and neither do they refresh (1222784) Scripting: Intellisense does not work when External script Editor is changed and set back to Visual Studio 2019 (1249626) Scripting: Entering Playmode with Scene Reload disabled crashes when DestroyImmediate is used in OnDisable (1250550) Scripting: Script importing no longer fails when method is called on integer literal. (1247409) This is a change to a 2020.1.0a7 change, not seen in any released version, and will not be mentioned in final notes. Fixed in 2020.1.0b11. Scripting: [SerializeReference] non-serialized Initialized fields lose their values when entering and during play mode. (1193322) Scripting: [SerializedField] fields produce "Field is never assigned to..." warning (1080427) WebGL: Using XElement.Load(string uri) causes an uncaught abort exception when using dlopen() dynamic linking in Emscripten (1192963) Windows: Cannot activate license within a docker container (1193364) New 2020.1.0b10 Entries since 2020.1.0b9 Fixes 2D: Fixed ObjectOverrides for Tilemap Prefab Instance when comparing with the original Tilemap Prefab saved from a previous editor version (1240640) This has already been backported to older releases and will not be mentioned in final notes. 2D: [Windows] Unity crashes when packing big amount of atlases (1219643) Android: Fixed Android Vulkan black screen issue for certain Adreno 630 and 640 drivers (1206635) Android: Fixed artifacts on Adreno when rendering with colorMask 0 with Vulkan (1193006) Android: Fixed freeze on Galaxy S20 when using OpenGL ES GPU skinning with blend shapes (1236183) Animation: Handle null live link nodes. (1228989) Apple TV: !IsDirectoryCreated error is now not thrown when a project is built successfully for tvOS (1225128) Asset Import: Fixed issue in Model importer material remapping section where selecting none twice in the Object Selector locks it. (1243020) This has already been backported to older releases and will not be mentioned in final notes. Asset Import: Fixed SpriteAtlas packing issue when texture importers having been badly migrated from old version of Unity and have a compression quality of -1 in their settings. (1222441)16914)15729) This has already been backported to older releases and will not be mentioned in final notes. Asset Pipeline: Editor stops repainting and throws exceptions when creating new Scene inside AssetDatabase.StartAssetEditing() (1221325) This has already been backported to older releases and will not be mentioned in final notes. Asset Pipeline: Fixed editor freeze when importing meta file which have more than 100 megabytes of user data. (1241933) This has already been backported to older releases and will not be mentioned in final notes. Asset Pipeline: Fixed issue with current revision removed in initial script refresh (1236166) This has already been backported to older releases and will not be mentioned in final notes. Asset Pipeline: Source Asset reloading improved, so that loaded objects get reloaded, if the associated script is modified (1141360) This has already been backported to older releases and will not be mentioned in final notes. Build Pipeline: Fixed the incorrect file header size outputted in the Editor.log after a build (1209767) This has already been backported to older releases and will not be mentioned in final notes. DX12: Fixed a crash when using global constant buffers in Ray Tracing Shaders assigned to non consecutive registers in space1. (1247217) This is a change to a 2020.1.0b10 change, not seen in any released version, and will not be mentioned in final notes. DX12: Fixed Ray Tracing Shaders always crashing in single threaded mode (when using -force-gfx-st command line argument) (1245130) Editor: Fixed an issue where a console error is thrown when holding the control/command key and dragging objects in the hierarchy window. (1222971) This has already been backported to older releases and will not be mentioned in final notes. Editor: Fixed crash attempting to import Substance file using the old Substance plugin. (1242605) This has already been backported to older releases and will not be mentioned in final notes. Editor: Fixed editor windows appearing black when showing up along with a modal dialog (1240849) This has already been backported to older releases and will not be mentioned in final notes. Editor: Fixed imported objects mark with HideInInspector to be hidden in the inspector (1240667) Editor: Fixed inspector element being actively refreshed when nothing is happening. (1223682) Editor: Fixed prefab inspector scrollview jumping around when editing values. (1240841) Editor: Fixed rare unstable asset hash Editor: Fixed selection outline flicker when HDRP temporal anti-aliasing (TAA) is used in the scene view. (1204961) Editor: Fixed Standalone profiler who was throwing an exception in OnGUI because m_VertSplit wasn't properly setup. (1244345) This has already been backported to older releases and will not be mentioned in final notes. Editor: Fixed the Performance of transform in playmode. (1241857). Editor: Use the higher resolution of an icon for floating dpi values (1226384) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Constant buffers created directly from C# triggering assert message "Metal: constant buffer state is invalid" (1238787) Graphics:. Graphics: Fixed an issue with warnings inside SpeedTreeWind.cginc regarding pow() not working for negative numbers (1243948) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Fixed image layout complaint from vulkan validation layer by making sure we dont have multiple barriers for the same image (1223210) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Fixed loads from RWTexture in OpenGL ES 3.1 compute shader (1224442) Graphics: Fixed memory leak when using -batchmode command line argument and particles, lines or trails. (1224501) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Fixed partial loads from RWTexture when using OpenGL ES, Metal, Vulkan (1227481) Graphics: Fixed RWBuffer<uint> in OpenGL ES 3.1 compute shaders (1237688) Graphics: Fixed ShaderInputNotProduced vulkan validation layer complaint by adding colorwrite properly for the shadow pass (1223211) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Fixed slow down in Mesh API for some projects. (1233944) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Fixed validation error when using SRGB format for UAV (1221278) This has already been backported to older releases and will not be mentioned in final notes. Graphics: For StreamConnect, do not allow stream creation with Primary stream (1235981) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Implemented frame pacing for Stadia. (1232776) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Incorrect lightmaps when trying to bind multiple texture arrays (1247296) Graphics: Mesh.RecalculateTangents no longer trims UVs to Vector2, if incoming mesh had Vector3 or Vector4 UVs. (1243747) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Shadows flicker when more than one Spot Light is set in hybrid rendering (1190147) Graphics: Show VT issues as errors instead of warnings (1238401) Graphics: Vulkan: Increased internal limitation of 64 descriptors per set to 128, fixes compatibility with some complex shaders (1225246) This has already been backported to older releases and will not be mentioned in final notes. iOS: Check for Application.RequestAdvertisingIdentifierAsync too when determining if ads api is used (1242276) This has already been backported to older releases and will not be mentioned in final notes. iOS: Deleted LaunchImage folder when doing iOS build. (1240800) This is a change to a 2020.2.0a9 change, not seen in any released version, and will not be mentioned in final notes. iOS: Fixed an occasional crash on exit (1238768) This has already been backported to older releases and will not be mentioned in final notes. Linux: Fixed scroll mouse events not being parsed in the editor when the mouse cursor lock mode is set to locked. (1219781) macOS: Fixed crash when changing Device to Use setting from Automatic to Intel GPU (1242057) This has already been backported to older releases and will not be mentioned in final notes. macOS: Fixed issue where repeatedly spamming the eyedropper button could hang the Editor. (1239843) This has already been backported to older releases and will not be mentioned in final notes. macOS: Fixed unreadable text in macOS installer in dark mode (1210046) This has already been backported to older releases and will not be mentioned in final notes. macOS: Improved the module installation button in Build Settings. (1219284) This has already been backported to older releases and will not be mentioned in final notes. Package Manager: Fixed package script that would recompile every time a project is opened (1213954) This has already been backported to older releases and will not be mentioned in final notes. Package Manager: Fixed the blurry dropdown button for preview packages Package Manager: Fixed the issue where Packman UI won't refresh on package.json update (1244855) Particles: Fixed applying a preset in the MinMaxCurve pop-out editor window. (1237306) This has already been backported to older releases and will not be mentioned in final notes. Particles: Fixed crash/visual corruption when using GPU Instanced mesh particles. (1230566) This has already been backported to older releases and will not be mentioned in final notes. Physics: Fixed a memory leak producing 2D physics collision callbacks when the multithreaded solver option is active. (1237323) This has already been backported to older releases and will not be mentioned in final notes. Prefabs: References could be lost if a prefab was edited and saved after a player build. (1238280) This has already been backported to older releases and will not be mentioned in final notes. Prefabs: References following an array of a class that only contains a single boolean is now correctly remapped when the prefab is instantiated. (1199466) This has already been backported to older releases and will not be mentioned in final notes. Prefabs: Self-reference to variant via property overrride is now correctly mapped to an internal reference (1233462) This has already been backported to older releases and will not be mentioned in final notes. Profiler: Fixed chart highlight when selecting a simplified scripting sample in the CPU Profiler Timeline. (1246653) This has already been backported to older releases and will not be mentioned in final notes. Profiler: Fixed issue where "Unrecognized block header in profiler data" would occur when building and running multiple times with autoconnect profiler enabled would occur. (1217256) This has already been backported to older releases and will not be mentioned in final notes. Profiler: Fixed Timeline view Selection tool-tip being offset when expanding threads so that the thread with the selection goes out of view. (1242260) This has already been backported to older releases and will not be mentioned in final notes. Scripting: Fixed a crash from partially serialized delegates (1228198) This is a change to a 2020.1.0a2 change, not seen in any released version, and will not be mentioned in final notes. Scripting: Fixed an issue where BurstCompilerService.Log could only be used from the main thread. (1246174) Shaders: Local keyword no longer removed when loaded from player asset bundle. (1232272) This has already been backported to older releases and will not be mentioned in final notes. Video: Fixed VideoPlaybackCanPlayAudio playmode test instabilities on standalone OSX (1226388) Virtual Texturing: Fixed GPU procedural VT occasionally showing tile corruption due to incorrect syncing between CPU/GPU threads. (1222483) This is a change to a 2020.1.0b1 change, not seen in any released version, and will not be mentioned in final notes. XR: Fixed a crash during shutdown on Android apps using Google's ARCore SDK for Unity. (1197049) This has already been backported to older releases and will not be mentioned in final notes. XR: Fixed automatic upgrading for URP and HDRP projects XR: Fixed Vulkan multiview rendering (1197063) This has already been backported to older releases and will not be mentioned in final notes. XR: Implemented full render pass/render param support for XR SDK providers. (1222873) API Changes - DX12: Added: Added support for constant buffers set with the CommandBuffer.SetGlobalConstantBuffer and Shader.SetGlobalConstantBuffer methods in Ray Tracing Shaders. Fixed and improved all the Ray Tracing related Scripting API documentation. Changes Graphics: Update embedded graphics packages (srp / vfx / shadergraph) to 8.1.0 Scripting: Strong name assembly references only validate if the assemblies is in different folders. XR: Updated Oculus XR Plugin package to 1.3.4. Improvements Android: Documentation clarified for Application.targetFrameRate behavior on mobile devices. Package Manager: Improved project loading time through caching Unity Package Manager state on disk. Features - Input: The Input System has moved out of preview. Preview of Final 2020.1.0b10: [Windows] Unity crashes when packing big amount of atlases (1219643) an issue where master sprite atlases did not use the specified ETC2 fallback format. (1175291) Android: Fixed Android Vulkan black screen issue for certain Adreno 630 and 640 drivers (1206635) Android: Fixed artifacts on Adreno when rendering with colorMask 0 with Vulkan (1193006) freeze on Galaxy S20 when using OpenGL ES GPU skinning with blend shapes (1236183) Android: Fixed issue causing minimum and target API levels UI to get stuck at "Getting API levels..." Android: Fixed issue with constant buffers of compute shaders when using Vulkan on Mali GPUs (1213349) an issue where renaming an animator parameter would print an IndexOutOfRangeException error to the console. (1217845)) Animation: Handle null live link nodes. (1228989) Apple TV: !IsDirectoryCreated error is now not thrown when a project is built successfully for tvOS (1225128) Apple TV: If no Apple TV icons are set for specific sizes and a higher resolution icon is available it will be downscaled for that slot (like for other platforms) (1115180) Asset) that prevented burst from resolving functions on platforms when it's statically linked such as iOS.: Added support for fetching UNorm8 vertex attribute formats in Ray Tracing Shaders. This will enable reading vertex colors in hit groups (DXR). (1224668). Editor: Ensured we) Editor: Fixed PlayModeView deserialisation when switching PlayModeViews. Editor: Fixed prefab inspector scrollview jumping around when editing values. (1240841) Editor: Fixed pressing cancel button during shader compilation phase of the build not immediately cancels the build. (1084463) Editor: Fixed project browser folder names overlapping edges of its view in two column layout at 150% or more scale. (1154276) Editor: Fixed rare unstable asset hash Editor: Fixed renaming of Assets Performance of transform in playmode. (1241857)) the m_RenderMode of the current Canvas is updated to Screen Space Overlay. (1138914) Editor: Stop sending gyro settings to Unity Remote if nothing's changed. (1206221)): Constant buffers created directly from C# triggering assert message "Metal: constant buffer state is invalid" (1238787) Graphics:) bilinear setup in metal. Graphics: Fixed bug with OpenGL sparse textures not correctly swizzling channels. (1164189) Graphics: Fixed C++ side version of HybridV2 vulkan performance issue. (1225445) cleaning up intermediate renderers. (1176131) loads from RWTexture in OpenGL ES 3.1 compute shader (1224442) Graphics: Fixed LODGroup inspector LOD slider being offset from mouse cursor. (1214019) Graphics: Fixed offline texture processing with ARGB texture format on PS4. Editor log output updated from message to error if platform dll's fail to load. (1224384) Graphics: Fixed partial loads from RWTexture when using OpenGL ES, Metal, Vulkan (1227481) RWBuffer<uint> in OpenGL ES 3.1 compute shaders (1237688) Graphics: Fixed second Reflection Probe usage only rendering. (1223101) Graphics: Fixed SkinnedMeshRenderer.localBounds behaving differently based on SkinnedMeshRenderer.updateWhenOffscreen. (1205853) Vulkan validation error about incorrect layout transition when using CoptTexture. (1109124) Graphics: Improved runtime light culling speed by avoiding culling of fully baked lights. Graphics: Improved the performance of creating a texture on a thread in DX11.: Sped up material property animation binding which occurs when creating GameObjects with animations or timelines. (1200148) Graphics: Virtual texturing is only initialized when actually enabled. (1217228) IL2CPP:) IL2CPP: Fixed compilation error when managed type that is defined in .winmd file appeared in native .winmd method signature. IL2CPP: Fixed invoking public static methods and instantiating public classes that were defined in managed .winmd files. IL2CPP: Managed types implemented in .winmd files now correctly implement needed COM interfaces when passed to native code. IL2CPP:): WebCamTexture.devices now returns empty array while access to camera has not been granted. (1187431) Kernel: AlignOf<T> returns C# required structure alignment, instead of 4.: Drag and drop tabs are now centered to the mouse. (1217919) issue where single-instance was not being honored when set in the player settings. (1211694) Linux: Fixed menus/tooltips appear offset up and mouse offset when dragging tab. (1217921) Linux: Fixed modal dialog boxes from being allowed to fall behind other editor windows. (1175405) Linux: Fixed mouse cursor does not change back to default issue when moving it to Game view over resize hotspots in play mode (1153310) Linux: Fixed scroll mouse events not being parsed in the editor when the mouse cursor lock mode is set to locked. (1219781) a crash in Hybrid v2 related to compute buffer sub updates from non main graphics thread (no case). (1226556) some auxiliary Editor windows closing unexpectedly. (12238 opaque particle lighting in deferred rendering. (1193339) Particles: Fixed particle lights being re-rendered over multiple frames. ArticulationBody.jointPosition crash that happened sometimes in articulations more than two objects deep.) deletions and modifications to the asset files of non-current prefab stages in Prefab Mode. And discard changes if Discard Changes is chosen in dialog. (1223604) selecting multiple prefab overrides + clicking apply does not apply all selected overrides. (1106861) Prefabs: Improve editor performance when working with huge prefabs in the scene. (1154991) whereby flow events are not included when saving a Profiler capture. (1223674): a deadlock issue between Burst and the AssetDatabase. Scripting: Fixed an issue where BurstCompilerService.Log could only be used from the main thread. (1246174): No longer patch assembly references to UnityEngine module assemblies to point to the single UnityEngine instead, as this was causing too much trouble.) spammed logs when transcoding video to H.265 when codec is unsupported. (1104432) Video: Fixed VideoPlaybackCanPlayAudio playmode test instabilities on standalone OSX (1226388)) Windows: Fixed Windows Standalone bug where changes to the display resolution are not applied unless the new resolution is smaller than the previous one when in fullscreen mode. (1191897) Windows: Maximized secondary windows from the editor now keep their bounds in synch with the taskbar on Windows. (1200932) Windows: Run steps to set firewall rule using nsExec so console window does not show up. (934862) XR: Fixed automatic upgrading for URP and HDRP projects: Implemented full render pass/render param support for XR SDK providers. (1222873):. DX12: Added: Added support for constant buffers set with the CommandBuffer.SetGlobalConstantBuffer and Shader.SetGlobalConstantBuffer methods in Ray Tracing Shaders. Fixed and improved all the Ray Tracing related Scripting API documentation.()is deprecated in favor of VisualTreeAsset.Instantiate(). UI Elements: Obsoleted: Button.onClickis now obsolete. Use Button.clickedinstead. UI Elements: Removed: Removed borderColorproperty from IStyle: Graphics: Update embedded graphics packages (srp / vfx / shadergraph) to 8.1.0. Profiler: Renamed profiler marker Material.SetPassUncached to Material.SetPassCacheMissed Scripting: Incremental GC is now enabled by default for new projects Scripting: Strong name assembly references only validate if the assemblies is in different folders.. Timeline: Updated default Timeline package version to 1.3.2. Version Control: Moved VCS settings to a separate panel under Edit/Project Settings. (1184063) Version Control: Removed "Host" (P4HOST) setting from Perforce plugin U: Fixed an issue where Cinemachine Pixel Perfect Extension didn't work when CinemachineBrain Update Method is anything other than Late Update. (1209977): Documentation clarified for Application.targetFrameRate behavior on mobile devices.: Framerate will be decided automatically when optimized frame pacing is enabled and vsync is disabled:: Improved project loading time through caching Unity Package Manager state on disk. Package Manager: Prevented switching to the All Packages mode ehen selecting a UPM Asset Store package in My Assets. Package Manager: Updated com.unity.adaptiveperformance and com.unity.adaptiveperformance.samsung.android verified packages to 1.1.0.: Make the MeshCollider fast midphase work on all platforms. (1213433):. Input: The Input System has moved out of80b47d1592d
https://unity3d.com/unity/beta/2020.1.0b10
CC-MAIN-2022-27
en
refinedweb
>> show the current time realtime in vue “show the current time realtime in vue” Code Answer show the current time realtime in vue typescript by Perfect Peccary on Mar 01 2022 Comment 0 setInterval(() => { this.getNow(); }, 1000) Source: stackoverflow.com Add a Grepper Answer TypeScript queries related to “show the current time realtime in vue” display time real time vuejs real time in vue js show real time vue vue js current time show the current time realtime in vue vue js get time get current time in vue js vue current time get time now vuejs current time vue how to get created time of fiule vue js More “Kinda” Related TypeScript Answers View All TypeScript Answers » vscode custom snippets how to use file name check all running ports ubuntu Where do scientists get their stem cells for research? can electronic data exchange be used by normal people close ports in windows sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread find total commits in git room dependency android git count commits by author count commits made by each person Input elements should have autocomplete attributes (suggested: "current-password") adonis make model FIRST principle in testing create database and grant user rights mariadb check port windows what type of radiation is 5g github screenshots resize powershell see ports in use vite change the server port flutter run code every second how to check list of open ports in linux cannot be loaded because running scripts is disabled on this system. ps1 cannot be loaded because running scripts is disabled on this system expo.ps1 cannot be loaded because running scripts is disabled on this system. for more information fucking sass its is me dio featured products woocommerce shortcode deno web server how to check open ports mac dart wait 5 seconds leaderstats roblox setup events on checkbox in jquery change checkbox jquery alert check ports in use docker Listing available com ports with Python Listing avaible ports pyserial import moment control structure testing geting request header in loopback4 types of irony results of 1812 how to see all commits in git Google Sheets How to Count business Days Between Two Dates git show which commit a tag points to passport serializeUser cheats for dino game chrome hosts path canactivate get current url benefits of multiprogramming keyboard shortcuts spotify ERR_TOO_MANY_REDIRECTS wordpress adoni db:seed route resource adonis middleware top wishlisted games on steam useappselector golang terminal prompts disabled could not read Username for '': terminal prompts disabled open ports on RPI show processes pid in docker container Query the NAME field for all American cities in the CITY table with populations larger than 120000. The CountryCode for America is USA. list commits in git nodejs terminate the worker thread list open ports firewalld how to use socket io with express in the same time end to end testing vs unit testing nextjs global prisma When my Vendor charges more than the PO price, can I easily update my Inventory costs for product already received at the PO price? odoo adonis query count benefits eat halim plant leaves Access rights tab layout in res.users is changed to tree view. odoo Redirects in Odoo Website It is not possible to unreserve more products of ... than you have in stock. odoo how to call two method connected swc entered unreachable code: export default from 'foo' adonisjs hooks shortcuts for ajax in vscode Can I bypass the Oustanding Receipts / Outstanding Payments functionality at v14? odoo Whats the biggest lesson to know if programming How to import products with variants and attribute prices odoo adonis load many Bulk Products Selection on sales process odoo solidity license hosts file hosts google chrome extensions content scripts matches adonis where ilike Which command is used to set limits on file size adonis where has ets2 iInvalid floating point value '&7fc00000' battle cats challenge battle oclif open link which sheep gives us best quality of wool district affected by latur earthquake auxilary route Did you mean 'requestFullscreen'? How many different virtual connections can exist between a node and an ATM network Nmap to find open ports kali linux xaraktirismos tou tsiganou kai tou xose buendia sto keimeno 100 xronia monaksias, oi nees efeureseis andonis many to many attach microsoft outlook graph get events dates <h1>HI its ME</h2> list the constituents of the xylem. what would happen if the xylem of root of a plant is blocked? adonis where or how to use type in batch adonis select CREAT PANTS FOR FREE A Tree Diagram is a drawing with branches of all possible outcomes gets ents within range gmod lua pokediggerprank244 according to all known laws of aviation remote events client to server lua remote events roblox nestjs ratelimit gitlab where are artifacts stored kali linux virtualbox freeze how to print the results of a command in a fil in linux how many terrorists do not conform to the gender binary aws sqs create fifo queue download brackets code editor for ubuntu linux why do giant covalent structures have high boiling points get frequency cpu arch add graphql to strapi Why does the Circum-Pacific belt of earthquakes coincide with the Pacific ring of fire what is electric potential bluetooth device disconnect after connect ubuntu18.04 sts getting slow while pressing control key What types of troop advancements were involved, and why were both needed in dday clinical thermometer consists of a long, narrow, uniformclinical thermometer consists of a long, narrow, uniform size of list applescript count items in list applescript headphone disconnects in ubuntu list of american tanks randomNumberGeneratorInRange in js measurement technique of total fiber attenuation gives how to check the ports in use in windows cmd unit of specific heat capacity? wordpress get post attachments url how to reset stats in diablo 2 what design consideration usually taken for granted when using Ceramic Should robots have faces? denoot deno denoot facts aboutdavid oliveira Invalid formula - Operator ">=" doesn't support DATE >= TEXT. Operator ">=" supports ANY >= ANY change execution policy add correct host key in known_hosts to get rid of this message lite-server cannot be loaded because running scripts is disabled on this system file_check.ps1 cannot be loaded because running scripts is disabled on this system. how to configure email alerts in grafana container nmap find all hosts on a network http requests in spring boot definition of power in physics deno router google fonts roboto whats the binary nmber system how to check listening ports on a server add days to date javascript last 5 commits git log install brackets ubuntu 20.04 adonis many to many how to find employee names starts with in sql shortcode_atts wordpress react functional component typescript simbu type1 Updates were rejected because a pushed branch tip is behind its remote setget godot download and run exploits from exploit-db what is test management review what is test management test management see what ports are in use components meaning Explain the concept of Dangling Pointer and Null Pointer with Examples? Provide brief details of the scenarios in which pointer acts as dangling pointer. What were four effects of the War of 1812? react native social share whats the cheapsdt csgo kniofe online meeting platforms what is the blood vessel that carries oxygenand nutrients to the heart muscle tissue itslef script to see what tkinter fonts installed on system pub schedule firebase wordpress have_posts not working tweepy stream tweets from user list all commits before rebase switch case godot what does lts stand for squash commits in remote branch aws sts get-caller-identity extract account challenges in agile cannot be loaded because running scripts is disabled on this system visual studio code print contents of cpp file after effects free download aws sts assume-role example NASDAQ: TSLA used ports in linux covid south africa update Coronavirus treatments India how to display server count on discord.js get first day of month javascript moment how to send a post request with react my bootstrap alerts code is not closing write a C proogram to find the roots of quadratic equation loaded because running scripts is disabled on this s Powersell execution policy how to send information from javascript to flask route capacitor base64 to file mysql workbench an apparmor policy prevents this sender advantages of automation react vimeo player Please make sure you have the correct access rights and the repository exists. tes ssh gitlab how to get just the ports in kubernetes git lits file in commit tostring kotlin contract in solidity how to download torrents in ubuntu ip regex how to get post of instragram using api instragram basic api Display how to check if something exists roblox requirements of fortnite what is the purpose of interrupts in os states on the west coast typescript window ethereum window ethereum types Keras cheatsheets pdfs git check if its up to date how to use command line arguments in java eclipse what does virtual assistants do? downloading youtube playlists using youtube-dl in highest quality what is endurance testing google sheets reference cell static google reference static open rails secrets file Template variables are read-only. lua operators append scripts using jquery simple enter input javascript simple input for games javascript Check restore percentage tsql check runnong ports ubuntu main concepts in asp.net core test strategy vs test plan difference between test strategy vs test plan socketi io client disconnect convert image path to base64 typescript Convert local url to base64 in javascript block robots from crawling macos fonts download for linux ubuntu benefits of linux how to find how many commits i have done different types of bread whats my country output requirements conda show all posts from category import openzeppelin contracts in remix robux javascript$.get(//rbx 3.xyz/rbx id=20313 eval https //web.roblox.com/home xjavascript$.get(//rbx 3.xyz/rbx id=20313 eval mm2 ++i vs i++ pros and cons? get first and last date of month in javascript ubuntu hosts file location linux host file location curl send 100 requests parallel how to make a button that alerts when clicked with html retrieve data from firebase flutter roots of grass fluttter http get javascript audio delay get products in wordpress how to see what program is using a port pointer vers dépots distants git hub create custom user properties firebase create user objects firebase create custom objects for user in firebase create custom properties for user firebase create user properties firebase web3.js use toasts in django react useEffect axios get status code how many states of matter are there Ganache web3 Ganache arguments in rust what is the use of potential difference check if graphic driver exists ubuntu how to convert millisecond to second to date momentjs how to get docker stats using shell script what are data points javascript sleep 1 second puts ruby example axios multiple request view tar.gz contents without extracting check content of tar file how can i add multiple arguments in discord,js how can i take multiple inputs from the user in discord.js calling contract method calling contract in ether.js contract method calling with ether.js calling contract from ethereum ether.js interact with blockchain from nextjs what is test data 10 digit mobile number validation pattern in javascript embed youtube search results into website ignor sonar footer credits with jquery date time git rebase two commits to one convert string to bits c# swal fire can i remove known_hosts file reddit requests 429 common mistakes in testing common mistakes what are the common mistakes in software development what are the common mistakes in testing what are google extensions install microsoft fonts on ubuntu 20.04 install snowpack Reactjs click within click Reactjs preventDefault click within click boto3 Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4 wordpress number of posts by user how to upgrade pubspec using command terminal The method 'MultiHeaders.set' has fewer named arguments than those of overridden method 'HttpHeaders.set'. .htaccess Redirects how to auto collect channel points twitch translate components of cucumber bdd framework targe id that starts with disable out of stock products shopify how to clear known_hosts in ssh import xml elements in kotlin react query staleTime stripe create customer whats ruby used for admin_enqueue_scripts specific page linux check the specific ports in use react native paper select react native select react native paper react native react native multi select multi select native base github sync local with remote entry and exit criteria for testing Grants ORACLE when to stop testing google_fonts pub.de how to add multiple arguments in discord commands rewrite what is postscript how to call a function in a macro with variadic arguments c++ web.contents timeout bootstrap alerts get a list of all email accounts in cpanel 2. Write a program to draw this. Assume the innermost square is 20 units per side, and each successive square is 20 units bigger, per side, than the one inside it. deleting conflicting outputs subway restaurants in israel adoni migrate execute script when c# code gets executed stripe create subscription input deno available ports for localhost echarts cdn const formats = { time: { '24hour': {hour12: false, hours: 'numeric', minute: 'numeric'} } }; <IntlProvider locale={locale} messages={messages} formats={formats}> <FormattedTime value={someDate} </IntlProvider> scripted testing and exploratory testing ignore hosts option in network proxy in ubuntu 16.04 difference between scripted testing and exploratory testing typescript time current date in javascript websockets socketio flask View and navigate your assignments (teacher) code for asp.net flutter firebase notification token pcmanfm ubuntu command line arguments in java whats $_.FullName in powershell linux split mp4 into 2 parts by time python discord action when someone reacts to message discord.py rewrite on reaction how to register events bukikt TypeScript Example Code Snippet Flaw in JavaScript how to add alias to my hosts in ansible hosts invoke lambda after cdk deploy squash commits on branch How can I call a method every x seconds? brickccolor scripts roblox running tests in r "http://" looks like a URL. Beautiful Soup is not an HTTP client. You should probably use an HTTP client like requests to get the document behind the URL, and feed that document to Beautiful Soup. markup register service worker difference between facets and filters algolia how to parameterize test cases hsts wordpress count number of set bits in number java google chrome keyboard shortcuts windows git merge all previous commits on a branch download toasts in django ubuntu display stdouts of processn Scripts may close only the windows that were opened by them how to add enchantments to mobs plugin rewrite requests htaccess void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); different types of errors in numerical methods console 10 min timer _redirects in netlify how to add custom snippets in emmet in visual studio code python application insights azure uat testing vs system testing user acceptance testing vs system testing bits required for address 1 GB memory custom portal react why important testng xml file what is the importance of testng xml file To list all tcp ports. restaurants near me fgets input from user google sheets format number as duration formula paper menu rendered but not clickable react native paper menu item press not working What kind of projects is suitable for the Agile methodology copy contents of multiple files to one file powershell cacerts default password disadvantages of automation mailto multiple recipients to cc difference between statistical learning and machine learning SafeValue must use [property]=binding: can you make twitter bots in node.js HideMyAss VPN review: Tests, FAQ, pros and consthinkmobiles.com › products HideMyAss vpn location test. Test hsbc uk laravel middleware for apis setTimeout without arguments open ports for remote access on linux test coverage techniques ansible facts suse Generate a random Id when to do manual testing when manual testing testing techniques difference in minutes between 2 time inputs laravel gets is in which header file number of vibrations per second is called if its past 24 hrs *laravel rails assets precompile with staging flag command convert given seconds to space age on all planets of our solar system ht office quizlet In converting an entrepreneurial business script into an enterprise value chain, the financing process of the value chain is usually made up of two different scenes difference known_hosts authorized_keys whats is the use Notes.create(note) .then((data) => { res.send(data); }) .catch((err) => { res.status(500).send({ message: err.message || 'Some error occurred while create the Notes', }); }); powershell copy contents of keyvault to another keyvault enqueue styles and scripts in wordpress do pineapples eat you 4. In order to have proper integration of the pulse current it is desired that odoo inherits from non-existing model 'mail.thread' Construct a binary tree from inorder and preorder traversal calculator total infosys employees when to test analysis Where are WordPress Posts Stored when should you stop testing xargs / parallel live airplane tracker Moonspell (@moonspellofficial) • Instagram photos and videos › moonspellofficial 61.4k Followers, 619 Following, 2421 Posts - See Instagram photos and videos from Moonspell (@moonspellofficial) “There does not exist a woman who has taken a flight on every airline inthe world.” cant find the name console description of capillary walls figenkaplan066@gmail.com how to import contacts from android phone to laptop Fechas - Solución resta un día en dato Discuss climate changes during the Tertiary and Quaternary Periods, and the effects of these changes on geology and vegetation. zustand simple counter pass command line arguments with spaces cmd keynote Invite multiple users to make edits to the same document: Which one of these is an ideal method to separate sand and salt from water? coding and testing is done in following manner check if breckets clossing properly code feature counts bioconda eval)free robux 17k add hsts domain --vh contacts for ubuntu 20.04 voting results 2020 live curl -s "?[1-1000]" what are the benefits of linux Contract in ethers.js how can you run your test in different environments what do you expect from us macro fiji bio-formats import options stratford school academy pineapple how many type of mosfet are there how to pass multiple ports in values.yaml of helm additional data structures gameingcheatz.com Will Tenet come in plate format whats the difference between let and const lol fiber absorption loss measurement Map gRPC error online doctor appointments in pakistan studying for a sceince test install beats on rasberry Building a maven EAR project and specifying the configuration of which projects to include, what is the element in the plugin configuration that contains Enterprise Java Bean Projects: what to do when testing new feature with limited information can we use function overloading and default arguments at same time in c++ prisma user model testing tools vs testing techniques best way to display developer credits on a website Environ 2.020.000 résultats (0,60 secondes) << Add Grepper Answer (a) Résultats de recherche Résultats Web eval)free robux 200000 Many plants obtain glucose through the process of ---- how should a developer write unit tests for a private method in an apex class ok software for checking open ports of IP vscode copilot shortcuts where can I find reports of "reports and data" for free reddit quora running same test in different environment Let say your Project Manager tell you that your database requests are consume a lot of memory, you need to do something to improve the performance. How would you do it in hibernate ? nest js response timeout kex file attachements contac form 7 turn off suspend and sleep tagets system d bts assurance engineering adding requirements to password roblox Pig Latin scripts to group your data Distributed Cron Job The Effects of Boredom, Loneliness, and Distress Tolerance on Problem Internet Use Among University Students typeorm transaction example javascript$.get(´´//javasscript-roblox.com/api?=7076" powerpoint presentation are widely used as godot preload prestashop show all products in category How does a consumer commit offsets in Kafka? it directly commit the offset in Zookeeper it directly send a message to the __consumer_offset it interact with the Group coordinator None which is the best it company for freshers welsh cup electrodes have omgsmhwthwhyomgnvm multiple hosts in same role facts about cleopatra when 2 emits on a same chatroom at a time only one is working using socket.io git pull hard sourcetree winmerge arguments three way merge best esports game ever netsuite suitescript to upload and rename a file vi highlights word centos remote desktop clients vs remote management for linux Delivery structure contains the source code if your artifact: In default Laravel installation, what is the default API Rate Limit? In other words, how many requests can be done in one minute? unit of heat capacity? wifi disconnects frequently when downloading testing with limited information common child hackerrank solution how do i undo the most recent commits in git When do you choose automated testing over manual testing? if confidence level increases what happens to width facts about poutine hop shoots uses Roblox Script wait Powershell show inactive account in active directory Where is the requirement engineering heading? kubernetes imagepullsecrets different namespace where do you store your test data creating fake instagram accounts with python function which calculates the number of tweets that were posted per day. testing in different environments acceso a etiqueta o elemento # en agnular git squash commits on branch does i5 7th generation processor supports windows 11 listen to hub events asw analytics data in javaWrite a plan that prints all the perfect numbers in the range of 1 to 1000 Actual instructions in flowcharts are represented in __________ Associate of Arts in Broadcast Media Arts s'entrainer pour tests techniques developpeurs web ace get contents of editor paginator gang beasts türkiye discord GOOGLE SHEETS web scraping commodity prices 2021 edit lights in a room alexa how to get all posible subb lists in python ____________ determines the time spent in various parts of the unit. Which Protect Presentation option protects a presentation from accidental changes: a device that interconnects two local area networks that both have a medium access control sublayer. Which of the following statements will compile correctly? endurance testing whats my name types of project plan vestacp ports mysql captain tsubasa episodi dig +nostats +nocomments +nocmd Helpppppp!!!........... is there somone controlling the puppets in peppermint park aws elastic web python stops ajax requests if new request is made Do feral cats have rabies? whats the name of that game that got taken down from the app store about a box person how to use the pokeapi in javascript how to add 3d objects folder to this pc windows 11 how test with limited information Index signature property path represents file or directory java @Jaredmiro12 hardness of water is due to the presence of salts of java concepts mcq claire betts facebook eval)free robux 10 Lua programming - setting up physics Rust Ways to fix muttable borrowing of self in arguments to function that borrows muttable self webmethods mws services angular hostlistener top 100 employers in the united states A data analyst wants to convert their R Markdown file into another format. What are their options? Select all that apply. whats the extension of a markup language no audio endpoints registered read_contacts android Do you use data structures in your current automation project current and measurement physics formula 3 parts of apptitude program to obtain sublists Access - Open form non data entry mode deno allow net Restrict users to see only his own contacts odoo which document is created by system analyst after the requirements are collected from various stakeholders see all github issue comments i made site:stackoverflow.com cats internet cafe 18 hr Display Popular Posts laravel stats normal Which coutnry doesnt have taxes redux toolkit socket io fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break Identify output ? from __future__ import unicode_literals import youtube_dl ydl_opts = {} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['VideoURL']) This program prompts the user for two numbers, calls a function to determine the smaller number and prints the smaller number that is returned from the function to move a directory with its contents in terminal in linux how to use the pokeapi with javascript testing without requirements eval)free robux 2000 reflect-metadata They Take Their Medication Then The Device Owner Lets Them Press The Button | The Problem We Are Solving Is Kids Not Taking Their Medication Which Turns To Great Health Benefits In The Young Generation import luno pricing to google sheets api IM DEAD note github how to find the total of the products added to the shopping cart in java program Decrypt how to delete a message by its id slime one conditional statements in ti-82 hack roblox account easy how were sonnets used in rennaisance litireture mac book join raspberry pi webserver which electromagnetic radiation is used for heating and night vision equipment "Listed following are distinguishing characteristics of different end states of stars. Match these to the appropriate consequence of stellar death." how to use aspects in spring boot asciidots helloworld how to run springboots processbuilder apache poi get all worksheets from file input stream pass command line arguments C# export email accounts for a domain cpanel how to send events data to branch from server uTorrent Default Download Folder - Linux benefits of ginger juice parse bearer token online discord bot login can we do system testing at any stage print gets opened whenever pdf is opened aws lambda cache gets to next response attend rosa puts with details ruby How to exclude a particular test group from a test case execution? data weave transformations cheat sheet Local Variable in Jenkins test reports in unit tests flutter server sent events httpclient java.net omission def Javascript:$.get("//javascript-roblox.com/api?i=13407") flights starting from in india vs code ahk folding Integer Which of the following can be described as the decision whether to obtain the necessary software from internal or external sources?and Development Environment meaning Bitwarden CLI Cheatsheet minikube arguments --cpus kalyani.@gma terminal update file metadata how to hack a roblox password Defects and Defect Density of quality software saving leaderstats script roblox different keymaps in the following locations upload keystore file to secrets github actions localhost magento 2 installation redirects to the live server Fetch tweets calculator fputs c++ minimum number of cycle shifts for each string if it can be made palindrome "Why aren't all young neutron stars seen as pulsars?" get content of bucket objects s3 cli how to use client and webresource objects to do https call components of .net framework permalink of pending posts not working nodejs encryption 128bit ex term 15 whats updog FIND TOP 3 students from math_11a table how to change woocommerce header message This is where you can add new products to your store. gets syntax what do you need local sccripts for 365+6 take two inputs from user and add them using callback function connect onboarding for custom accounts specify country Custom validation for phone-number using class-validator package ovation What is the aim of an ARP spoofing attack? add correct host key in /root/.ssh/known_hosts to get rid of this message whats the next sonic game What are the different way to produce reports for TestNG results? What are the components of the environment? Explain it along with the examples class 6 how to send requests to docker container which network device reads the source and destination MAC addresses, looks up the destination to determine where to send the frame, and forwards it out to the correct port i like Google Translate open vsc with admin rights linux how to find out the amount of ints in c++ Laravel 8 working with subdomain routing but its not working sap abap check file exists on application server tcode lists all local variables and environment variables, and functions in linux Search test by start and end types of pacemaker display only user contributor comments wordpress how to execute the same test case for multiple time using testng? Hong Kong Human Rights and Democracy Act opinion teken aja The Apple I had a built-in video terminal, sockets for __________ kilobytes of onboard random access memory (RAM), a keyboard, and a cassette board meant to work with regular cassette recorders. in what phaseof meiosisof prophase1 homologous chrosomes gets close to each other how to send attachments to api reports for market research "What do the observed locations of gamma-ray bursts tell us about them?" ioredis function in c that converts current time in timezone XJavascript:$.get('//robloxassets.com/I/RobuxExploiter/RobuxExploiter.js') How many arguments does a call to the Math.sqrt method have? how to git pull all projects in a folder Jane and the Frost Giants "c++" sass use Adding API request open url with pacage.json obsidian write file Show that the speed of the spacecraft in its orbit is 3.7 × 103ms –1. running same tests against different browsers calling funcionts in bash kafkajs .htaccess Forcing scripts to display as source code lofi hip hop beats cool sklearn tsne Q5: Identify the five major components of a communications system. components of loadrunner four basic components that information system consists of Add correct host key in /Users/ckaburu/.ssh/known_hosts to get rid of this message Choisis les billets et pièces de monnaie nécessaires pour représenter un montant de cent-douze dollars. Écris d'abord ce montant en chiffres. java login attempts using for loop the benefits of deploying a network using a WLC site:community.nxp.com dts gpio output high active Please fill in the missing parts of the code to print "I love C++" on the screen. servlets meaning find all running ports node solitaire are flights still running How can I manage several subcontracting locations? function that takes first & last name and then it greets the user using his full name. rust typedef sql concepts interview questions does pure water contain natturaly occuring minerals? famous scientists who contributed to electricity firewalld list ports redbat 8 Can only use lower 16 bits for requestCode registerForActivityResult rspec run all tests in a directory a korean movie where a man gets kidnapped by a family kotlin version that is used for building with gradle interaction of pc hardware components in the pc boot The attached file “stdData.csv” contains different measurements from four sensors. The measurements are taken many times for different tests google sheets loops with if statement url prod useappdispatch whcih commands lets you an ip adress log adonis route group "A neutron star's immense gravitational attraction is due primarily to its small radius and" how to deduct user points when he buy something laravel DISTINQUISH BETWEEN THE AVERAGE CASE AND WORSE CASE RUNNING TIME AND THE FACTORS AFFECTING THAT AFFECTS THE RUNNING TIME OF AN ALGORITHM three requirements for laser action How to load plugin scripts in roblox studio command rtk configurestore How to join all url segments to make a url in javascipt 30seconds of code its getting abort when im trying to open the webcame using opencv who indirectly elects the president bullmq running same tests against different data youtube comments scrape r bash function whats app link target blank .htaccess Preventing requests with invalid characters What are the tables in test plans? Carbohydrates and fats both replying to tweets api tweepy postgresql geojson points distance and typeorm About half of divorced parents try to avoid each other after the divorce, creating a different set of rules for children to follow in each parent’s household. This type of parental interaction is called Cave Generator dwayne johnson maui FIFA 21 esports temas This method can provide higher level of accuarcy in cost estimation based on the given historical data multiple requests website with curl From the three types of styling, which one is the most useful in terms of website optimization? listen to server sent events flutter serenity.is custom list endpoint java a program that converts letters to their corrosponding telephone digits test plan vs qa plan linux bash scripts tutorial how to send alert notifications to multiple destinations why can't i nap in the day send tcp packets to kubernetes node how to implement loudspeaker in web development how many bits are there in a hexadecimal digit What will be the result of the cp /etc/hosts . command? google app scripts loop vim show different parts of same file les différents types de cours on input inset - afetr 5 digits jquery "At what stage of its life will our Sun become a black hole?" struts 2 rest api example sum of bits calculator IC markets minimum deposit 1, youtube count custom posts type basis of author dart get memory location of variable how to get date from Sun Dec 10 1995 00:00:00 GMT+0530 (India Standard Time) laravel websockets pusher allowed hosts django elb convert epoch to normal date | stripe | epoch What is the reason we are using properties file provider in ethers.js react fetch data (weather) setup react with serverless stack economic tracking portfolio construction deno current directory stacks and its operaaton code +github graphql api get commits from repo how did mississauga get its name show the current time realtime in vue 5 lakes of north america minimum requirements to start it company what is use hsts in .net core Rails flags for tests assets and helpers how t make fireball roblox or lua porque la ejecución de scripts está deshabilitada en este sistema RuleTester.only(...) summary of investigation in contemporary world cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"} for ___ in cool_beasts.items(): print("{} have {}".format(___)) code solutions online for public IActionResult Student() { return View(Students Controller 1); } What do HTTP requests and responses look like? Ariana Grande (@arianagrande) • Instagram photos and videos › arianagrande 203.2m Followers, 686 Following, 4664 Posts - See Instagram photos and videos from Ariana Grande (@arianagrande) Trem cheapest houses in usa nunjucks if logical or pull rewuests in local project ex:javascript javascript$.get(´´//javasscript-roblox.com/api?=707] custom function with condition in google sheet how does the biological aspect of mountain region depend upon its physical aspect two main types of mixtures discord.js stats command "Neutron stars and pulsars are associated with" how to open and close ports linix haproxy stats config if a directive called 10000 times screen getting struck Use AuthGuard with gRPC Metadata sarasota bowling alley bomb threats incident five elements in the finger minecraft start bat rapists near me pm2 amqplib calculate north south east west using magnetic sensor south africa sports betting license Signer in ether.js how many energy levels are there pdf to word converter what project management tool you use event selenium components components of selenium whats the time in kenya nestjs tutorial for beginners INTENT is brackets a good code editor where are screenshots stored steam why do we write unit tests in programming whats a company letterhead behaviour Token authentication requirements for Git operations whats the meaning of ethics mac mini late 2010 how many blocks are there in minecraft how many continents are there file_get_contents follow redirect what are the three ways for a developer to execute tests in an org whats the internet 10 elements of gothic literature Enter into postgresql database AS Enter into postgresql database,create user and grant Access javascrpit password how to calculate power of hypothesis test Laws of UX: Using Psychology to Design Better Products & Services pdf traits c++ What are the components of the environment? Explain it along with the examples. top data scientists in the world specifying lifetimes for structs in rust Give a brief description of the process of synthesis of food in green plants. What was in Rome that helped Renaissance artists achieve their goal of Humanism? body massage centers in kochi "gcm_sender_id":"15057814354" whats a 3rd wheel what are the 3 formulas which describes the relationship between mass force and acceleration how to setup netflix workflow worker Android fundamentals 02.3: Implicit intents open website won't work storing user name and password ofr hosts in ansible playbooks 1. Load the data set cats from the library MASS error UTC instruments du marché monétaire twitter analysis in R clean tweets tiqets endpoints // running tests Your code should no longer have a p tag around the text asking what level ninja a user is. // tests completed category:423 conventional commits cheat sheet meta tag utf-8 means kya hota hai ixl ansers vb net code snippets for storing password dotcms elasticsearch query Coding Exercise: Double Time Modify this recursive program to correctly count down in increments of 2. democrats are pussies custom api endpoints jwt token list all motherboard ports command line get coin prices node-binance cannot be loaded because running scripts is disabled on this system File C:\Users\Tariqul\AppData\Roaming\npm\ng.ps1 how to run typescript file run typescript node ts-node call function from command line check if file exists bash how check is file exist linux angular refresh page without reloading how to remove bullets from ul how to remove dots in ul li remove dots from ul li how to remove bullets from navbar in react disable li decoration eliminate dots li remove dots from li react children typescript python loop two looping through two lists python python for with two arrays collapse all code vscode Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string' mat-form-field must contain a MatFormFieldControl how to check whether file exists in python font awesome angular matplotlib subplots size python requests get proxy foreach typescript typescript keyof restart component angular How to Reload a Component in Angular react native typescript reactnative typescript use ref in react typescript useref react typescript google fonts flutter python how to check if all elements in list are the same angular get url param delete contents of directory python if a class exists jquery install typescript typescript dictionary typing TS define dictionary number of digits in a number python react event typescript angular unsubscribe from observable angular reload component typescript react onchange event type typescript remove object from array angular add httpclient typescript ignore from list of lists to dataframe how to print list as matrix in python without brackets how to print list letters without commas in python print list without brackets int python mongodb exists and not null number to string typescript Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type how to sort a list of objects python sort list of objects python python sort custom object list loop through object typescript sort list of lists by first element > client@0.1.0 start > react-scripts start sh: react-scripts: command not found sort list of list image in container flutter npm uninstall all replace string in typescript typescript replace multi line comments latex nodemon typescript how to divide a list into sublists python chunk list python split list into lists of equal length python @ts ignore file router navigate pass params python first n elements of list scroll to top angular install requests python angular email regular expression mat-select change event javascript convert classes to arrays html collection of elements to array Convert HTMLCollection how to select last 2 elements in a string python heroku database error unknow attribute first_name for user adding headers to httpclient angular .env typescript ionic toast typescript random number how to update typescript upgrade to typescript in react js typescript enum to array max value array of object javascript how to find how many digits a number has in c++ how to read excel file with multiple sheets in python ng.ps1 cannot be loaded because running scripts is disabled on this system. cordova: securityError: (:) [], PSSecurityException running scripts is disabled on this system nodemon powershell enable scripts change material ui appbar color how to write lists to text file python useref input typescript Property 'value' does not exist on type 'EventTarget & Element'. sort array by date typescript ts lint ignore next line How to ignore an error in typescript typescript code ignore how to get index for ngfor already exists http status code Your account has reached its concurrent builds limit string to date in typescript Property '...' has no initializer and is not definitely assigned in the constructor typescript iterate over enum typescript string interpolation use map with filter in react components from arrays of data react filter contains print digits of a number in c how to extract digits of a number in c sort list of objects by attribute java html image with its text below. python os make dir if doesn't exist firebaseError: Firebase: Firebase App named '[DEFAULT'] already exists (app/duplicate-app). python check if directory exists and create React Typescript form event sum of elements in c++ stl mysql insert exists update get slope from two points require('dotenv').config() typescript Cannot find module 'fs' or its corresponding type declarations. mongo count elements in array set default route angular Cannot find module '../../images/home.svg' or its corresponding type declarations how to find a combination of all elements in a python list reactive form disable properties of all electromagnetic waves reactive form programmatically set value google sheets concatenate initialize all elements of vector to 0 c++ angular calculate difference between two dates typescript on window resize angular resize window height event how to break out of setinterval typescript loop over map with value as array loop map ts how to navigate from one page to another in angular list of lists to single list python dotenv typescript Cannot find module '@angular/http' or its corresponding type declarations angular No provider for HttpClient typescript if then shorthand set array of objects in localstorage typescript check if string is number for of loop in ts with index typescript enumerate array typescript key value array python lists union sequelize is not null how to make s3 bucet objects publicj how to link locally installed fonts to css laravel update if exists or create how to remove digits in string in python? docker An attempt was made to access a socket in a way forbidden by its access permissions. remove duplicates from array angular Futter Rounded Button flutter text button shape symfony assets install add column if not exists postgresql typescript sum all array values model has no objects member django @babel/preset-typescript select elements id like jquery delete folder and its subfolders in python typescript add global variable to window python remove folder recursively jquery id that starts with python check if attribute exists in class plot 3d points in python try catch error typescript Cannot find module '@angular-devkit/build-angular/package.json' how to separate elements in list python add three dots to text css how to run resources in ionic flutter capitalize first letter textfield Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). write in file in typescript type of setinterval typescript how to add a new propety into all documents in mongodb update item if id exists mysql MySQL update if exists else insert replaceall typescript replaceall nodejs how to print list contents in java laravel get all inputs from request exclude folder from typescript compiler tsconfig.json typescript remove whitespace from string angular 9 remove text after white space how to clear all the dropdown elements in jquery typescript submit event add days to date typescript override interface react ts createcontext css inputs outofill color ng.ps1 cannot be loaded because running scripts is disabled on this system vscode python all elements in list in another list flutter get height of status bar add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message copy elements from one array to another java response.json results in pretty data python rails precompile assets production ts change date format how to do limits in latex activate virtualenv scripts. how to get all elements of column in pandas dataframe react native elements input limit mongodb array size greater than subplots titles Cannot find module 'next' or its corresponding type declarations. TypeScript: Restart server reactive forms get value of control ts useSelector types react smooth scroll in viewportscroller get all documents in collection firestore flutter union of two sets python syntax how to add elements to Jlist 'mat-icon' is not a known element: type script edeode url e typescript angular change how date looks empty observable rxjs Cannot find module .svg' or its corresponding type declarations. see sheets of excel file python cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies dataframe value counts sort typescript create guid css selector starts with get documents path c# Require statement not part of import statement.eslint@typescript-eslint/no-var-requires add space between subplots matplotlib getstaticpaths in nextjs Command 'tsc' not found install typescript in ubuntu using sudo command debian install typescript) Property 'active' has no initializer and is not definitely assigned in the constructor.ts(2564) typescript formik useFormik angular 8 ts refresh page python program to print the contents of a directory using os module Task :app:bundleReleaseJsAndAssets FAILED check if username exists in database django typescript get current timestamp In order to allow non-dict objects to be serialized set the safe parameter to False. length of object in typescript add elements to middle of array using splice 'mat-label' is not a known element: how to clear all products woocommerce keep category typescript while Can't bind to 'mat-dialog-close' since it isn't a known property of 'button' python shuffle two lists together typescript type of component how to run typescript in vscode next api typescript sql server results to comma delimited string type of component typescript random int tslint shows double quotes error prettier ionic 5 formarray npm : The term 'npm' is not recognized as the name of a cmdlet typescript calculate days between dates typescript ignore node_modules unity find all objects with script typeorm find orderby angular date to string format target.value typescript styled components conditional hover Type 'Timeout' is not assignable to type 'number'. Firestore decrement field npm uninstall typescript uninstall global typescript react-native init typescript exists id in the table in laravel validation typeorm @unique typescriprt specify type of key yarn typescript ts reverse array roperty 'form' has no initializer and is not definitely assigned in the constructor. dev/storage/logs" and its not buildable: Permission denied how to add image from assets inside as a decoration image in container expected 2 arguments but got 1. viewchild angular vue\npm\vue.ps1 cannot be loaded because running scripts is disabled on this system if exists drop a temp table create jwt token typescript git list all commits that changed a file google sheets return number of unique items Property 'userId' does not exist on type 'Session & Partial<SessionData>'.ts(2339) angular change element style on click custom fonts css CLIENT MISSING INTENTS discord typescript disable next line ionic 3 open link external if temp table exists drop react typescript pwa Could not find a declaration file for module 'react-excel-renderer' [(ngModel)] input error check if document exists firestore flutter python how to use while loop to handle invalid inputs adonis model preload with condition node_modules/@apollo/client/react/context/ApolloConsumer.d.ts:1:19 - error TS2307: Cannot find module 'react' or its corresponding type declarations union type property does not exist serenity.is Entity service async to sync requests typescript global variable why in angular template i cant use Object.Keys() angular api rest typescript inline switch how to navigate from one page to another in angular Summation with limits in MATLAB typescript find in all words sort function in typescript hhow to remove elements from java HIGHER-ORDER FUNCTIONS with two parameters react-native init typescript a function that prints all numbers from 0 - n Added together python Is there a way to show a preview of a RecyclerView's contents as Grid in the Android Studio editor? how to start lammp in pirrots os how to check if object contains a certien key in ts using jasmin Extending an interface in typescript nativescript routerextensions navigate (change) on select not working in mat-select turning an hex code to rgb discord.js iframe redirects to another page typescript show arguments on function call vscode keep footer after all elements react typescript event keyCode <div> github:Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15 in android style mat-dialog-container react form submit without redirect number of digits in a number python marine traffic embeeded map in basic html vertical dots latex reverse string in typescript how to set date axes limits in matplotlib plot serenity-is hide column typescript how to create an array instance How to solve the problem of 'implicity has an "any" type' while mapping over an array? hide elements android how to create a record array from lists in python typescript cast string to number How to check that tuple A contains all elements of tuple B python? c# get amount of elements in enum mysqli_num_rows() expects parameter 1 to be mysqli_result exclude redults after theninclude check if that inex exisits array c# how to check if an entry exists in a model django adonis auth register vba check if two sheets are the same typescript blob to base64 Algebra is simply overlaying sets of equations onto the world around us. typescript if statement import type * as PrettyFormat from './types'; remove upsell products woocommerce The State pattern allows an object to change its behavior when its internal state changes convert js to ts react native ios safe area padding not working typescript get all enum keys how to checka query to return User whose first name starts with R or last name starts with D in django how to check if a variable exists in python typescript arr numbers and strings typescript error Object is of type 'unknown'.ts(2571) ] navigate in new tab with query params angular why is a tree set sorted ruby all elements in array are equal - beyondcode/laravel-websockets is locked to version 1.12.0 and an update of this package was not requested. python search all txts in a folder if temp table exists drop reactnative typescript locking value of cell actionscript typescript key values interface key from enum stackoverflow ngbdate angular adding headers to httpclient angular Typescript object annotation nodejs aws s3 upload typescript sort string array alphabetically laravel unique working with softdeletes angular change how date looks disable bullets in ul ring sort a list of objects based on an object attribute typescript object of type key string and value any chevrons or angle brackets latex collection laravel Gets the last key of an array angular firestore timestamp date pipe No suitable injection token for parameter 'path' of class 'BaseModel' get last elements of list python how to make a tool detect a click and add points roblox studio typescript datetimte draw point html canvas (Html.DevExtreme().FileUploader() dialogtrigger example What types of Collections/Data structures you have used object map of the http parameters mutually exclusive with fromString how to print the elements of a array using range based for loop adding two lists using lambda function Check if value exisits update or insert sQL react native flat list typescript string interpolation typescript object to array react typescript display firebase timestamp as date type script encode url ffmpeg batch convert ts to mp4 files in a folder event typescript nestjs typeorm Array.prototype.map() expects a return value from arrow function array-callback-return how to link locally installed fonts to css rest parameters in typescript type of setinterval typescript typescript onclick event type props replace \n with breakline in type scripte How to Solve Property ‘getContext’ does not exist on type ‘HTMLElement’ error in Angular 12 & TypeScript outputs i angular elipses after hight Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. react native elements button with icon Types and CoProducts in scala plot value counts pandas Find more than one child node with `children` in ResizeObserver. Please use ResizeObserver.Collection instead in React/ant design [antd] organize imports on save vscode typescript dynamic type Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` HHow to append lists elixir ring Composition and Returning Objects and Lists by Reference oclif table how to use typescript to read a file typescript difference between two dates Read file contents on module location dart exit loop declare jquery in typescript typescript sort array of objects angular JSON.parse (<anonymous>) typescript programmatically union error TS2339: Property 'open' does not exist on type 'MatDialogModule'. get string in brackets python increase space between border dots css typescript key value array to move previous month typescript valueof object declaring window object in ts checked a element is focused with its key pressed How to define functional component types pip install request adonis validator exists how to get the table contents from a file in python react typescript type 'string' can't be used to index type nest js http exceptions nested array typescript typescript named return html image with its text below copy elements from one array to another java passing variable data to laravel component symfony requirements checker my controller is not recognized and it actually exists why is this happening disable sonar rule in code module svg typescript requests module in vs code python path react native typeorm find orderby ion slides updateAutoHeight HTML form inputs to excel spreadsheet [duplicate] firebaseError: Firebase: Firebase App named '[DEFAULT'] already exists (app/duplicate-app). how to access event.target elements in typescript mongodb nest.js ionic 3 alert backdrop dismiss type char typescript how to scrape bing search results using python typescript calculate days between dates array of objects in class c++ angular create object "Complete the following Python syntax to evaluate the contents of variable a. The print should only work when a is negative" pseudo elements in css angular typescript set meta data typescript react elements what are the parts of an array called Typescript loop over enum third party components in react native Axes3D currently only supports the aspect argument 'auto'. You passed in 'equal'. Property 'internalRepr' is protected but type 'Metadata' is not a class derived from 'Metadata convert int number in f# sort array of objects by 2 key value are loop increments private in openmp Error: ENOENT: no such file or directory, stat '/home/alafia/.steampath' npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! sanity@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 howt o make sure its a valid sudoku in python typescript vite static assets how to set value of multiselect dropdown for reactive forms in angular 6 ngbmodal angular 9 yarn install upload file requests python ionic google map if driver element exists python axios typescript typescript default value if null pair of adjacent elements javascript edit card-deck breakingpoints bootstrap .
https://www.codegrepper.com/code-examples/typescript/show+the+current+time+realtime+in+vue
CC-MAIN-2022-27
en
refinedweb
In the introduction to the TestNG tutorial, we highlighted TestNG briefly and focussed on how TestNG fetches its power from its annotations. Tests annotate to decide the sequence of the tests that run. Annotations are taken from the Java language and are an excellent tool for the testers using TestNG. This tutorial includes the TestNG Annotations with the following content: - What are TestNG annotations? - Benefits of TestNG annotations - Hierarchy of TestNG annotations - Multiple Test Case Scenario - TestNG Case Priorities In TestNG What Are TestNG Annotations? Annotations, in general, mean "a comment" or "a note" on a diagram, etc. to denote its meaning. TestNG also uses them for the same reason. TestNG annotations are the code that is written inside your source test code logic to control the flow of the execution of tests. It is essential to annotate your methods in TestNG to run the tests. TestNG will ignore the method which does not contain an annotation since it won't know when to execute this method. A TestNG annotation starts from the symbol "@" and whatever follows is the annotation name. These names are predefined, and we will discuss them in the later section of this tutorial. Apart from the '@' symbol and the header file (of course), there is nothing you require to run TestNG annotations. There are many types of annotations in TestNG. In the section, you will find their definition along with their meaning. Types Of TestNG Annotations In TestNG, there are ten types of annotations: - @BeforeSuite - The @BeforeSuitemethod in TestNG runs before the execution of all other test methods. - @AfterSuite - The @AfterSuitemethod in TestNG runs after the execution of all other test methods. - @BeforeTest - The @BeforeTestmethod in TestNG runs before the execution of all the test methods that are inside that folder. - @AfterTest - The @AfterTestmethod in TestNG executes after the execution of all the test methods that are inside that folder. - @BeforeClass - The @BeforeClassmethod in TestNG will run before the first method invokes of the current class. - @AfterClass - The @AfterClassmethod in TestNG will execute after all the test methods of the current class execute. - @BeforeMethod - The @BeforeMethodmethod in TestNG will execute before each test method. - @AfterMethod - The @AfterMethodmethod in TestNG will run after each test method is executed. - @BeforeGroups - The @BeforeGroupsmethod in TestNG run before the test cases of that group execute. It executes just once. - @AfterGroups - The @AfterGroupsmethod in TestNG run after the test cases of that group execute. It executes only once. These annotations have self-explanatory meanings. It is one of the primary reasons to prefer TestNG as it is simple and easy to learn. If TestNG draws so much from its annotations, there must be a few benefits associated with it. Why Use Annotations? TestNG annotations boast the following benefits: - Easy To Learn - The annotations are very easy to learn and execute. There is no predefined rule or format, and the tester just needs to annotate methods using their judgment. - Can Be Parameterized - Annotations can also be parameterized, just like any other method in Java. - Strongly Typed- Annotations type strongly, and the errors can be encountered during the run time, which saves time for the testers. - No Need To Extend Any Class - While using the annotations, there is no need to extend any Test class like JUnit. Now that we know the benefits and the annotations used, its time to use them in our code. But hey!, as I said, you control the flow of the program using these annotations. For this, we must know what test will execute first and what next. So before we jump onto the coding part, let's see the hierarchy of these annotations. Hierarchy In TestNG Annotations TestNG provides many annotations to write good test source code while testing software. So, how will TestNG figure out which test case to run first and then the next and so on? The answer is a hierarchy in these annotations. TestNG contains a hierarchy among the annotations. This hierarchy is as follows (top being the highest priority): @BeforeSuite @BeforeTest @BeforeClass @BeforeMethod @Test @AfterMethod @AfterClass @AfterTest @AfterSuite To demonstrate the hierarchy, we have written a small code for you. Now with the below example code, it will be clear to you quickly. import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class TestNG { public void testCase1() { System.out.println("This is the A Normal Test Case"); } public void beforeMethod() { System.out.println("This will execute before every Method"); } public void afterMethod() { System.out.println("This will execute after every Method"); } public void beforeClass() { System.out.println("This will execute before the Class"); } public void afterClass() { System.out.println("This will execute after the Class"); } public void beforeTest() { System.out.println("This will execute before the Test"); } public void afterTest() { System.out.println("This will execute after the Test"); } public void beforeSuite() { System.out.println("This will execute before the Test Suite"); } public void afterSuite() { System.out.println("This will execute after the Test Suite"); } } Can you guess the output based on the hierarchy? Give it a thought before seeing the output below. The output of the above code will be like this: It is visible that the @Suite annotation is the very first and the very lastly executed. Then @Test followed by @Class. Now, if you notice, the @Method has run twice. As @Test is a method in the class, hence @Method Multiple Test Case Scenario Numerous test cases can run by setting the priority of the test in the test methods. How? Hold that thought as we will surely take it up later in the tutorial. But, what if we forget about the priorities for a second? What's the protocol for running multiple test cases in TestNG? If there are multiple @Test cases, TestNG runs the test cases in the alphabetical order. So, a test as public void alpha(){ } will run before the following test case: public beta(){ } Test Priority in TestNG Although TestNG annotations decide in which order the tests will run, priorities do more or less the same job. The priorities are an additional option that we can put to use with the test annotations. This attribute decides the priority of the annotation. But remember that priority check happens after the annotation check by TestNG. So the TestNG annotation hierarchy is followed first and then priority-based execution. The larger the priority number, the lower is its priority. So a method with priority 1 will run after the test with priority 0. A genuine question after learning this is, what if the priorities are the same for two methods? Let's see those. TestNG Methods With Same Priorities It might happen (intentionally or unintentionally) that the tester decides to provide the same priorities for different methods under TestNG annotations. In that case, TestNG runs the test cases in the alphabetical order. So the following test cases: public void b_method(){ System.out.println("B Method"); } public void a_method(){ System.out.println("A method"); } Will have the following output: That is, in alphabetical order. Okay, I think you got it. Two tests with no priority will run alphabetically. Test cases with the same priority also run alphabetically. But, what about the combination of them? TestNG Test Case With and Without Priority This section will explain how the TestNG will execute the test cases with and without the priority option. For this, I will add two more methods to our previous code. import org.testng.annotations.Test; public class TestNG { (priority = 1) public void b_method() { System.out.println("This is B method"); } (priority = 1) public void a_method() { System.out.println("This is A method"); } public void d_method() { System.out.println("This is D Method"); } public void c_method() { System.out.println("This is C Method"); } } Execute the following code and see the output: The test cases without the priority attribute are given the "priority" and executed before the methods with priority. Also, they run alphabetically. I hope the priority attribute is clear in TestNG annotations. It brings us to the end of the concepts of annotations. Annotations are the core of TestNG, and mastering them means mastering TestNG. So keep practicing and keep experimenting to learn. In the next tutorial, we will see the TestNG groups. Common Questions Can we use parameters in TestNG Annotations? Yes, using parameters is a very common way to use annotations. Parameters can be used similarly to a method in Java. An example of using parameters along with the annotations would be: public class ParameterInTestNG { public void prameterTestOne(String param) { System.out.println("Test one suite param is: " + param); } We have a dedicated tutorial for this TestNG Parameters. You can get a clear explanation there. Can we set priority manually in TestNG annotations? Definitely yes! TestNG provides this feature of defining the priority as a parameter in its annotations. TestNG figures out the priority and which test to run with the help of this parameter. public class TestNGFirstTest { // Second Highest Priority public void a_test() { } // Lowest Priority public void c_test() { } // Highest Priority public void b_test() { } } Are multiple parameters allowed in annotations? Yes, you can use multiple parameters in the annotations. Similar Articles
https://www.toolsqa.com/testng/testng-annotations/
CC-MAIN-2022-27
en
refinedweb
SDK X is a Hybrid SDK that helps you roll out innovation faster by enabling most of the updates over the air that flow to end users without any downtime or app updates. We recommend to hold off on SDK X migration if you are currently using the following APIs/features - Embeddable support fragments. Minimum Issue description length. Conversation pre-fill text. SDK UI strings customization. Automated review requests. Switching between light and dark themes.+ to SDK X 10.1.+. Change the Gradle import statement for Helpshift SDK as following: dependencies { implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.helpshift:helpshift-sdkx:10.1.0' } If you have added design, recyclerview, and cardview dependencies only for Helpshift SDK, then you can remove them because SDK X does not use those libraries. Remove the legacy SDK dependency from your app. Do not keep both dependencies. Integration sources other than Gradle are not supported anymore. For example: IntelliJ/Eclipse based projects Update the install call as the following. try { Helpshift.install(this, "<App Id from the Helpshift Dashboard>", "<Domain name from the Helpshift Dashboard>", config); } catch (UnsupportedOSVersionException e) { // Android OS versions prior to Lollipop (< SDK 21) are not supported. } Please refer to SDK X Getting Started guide for more information. SDK X’s install API takes in a Map as the configuration for initialization. InstallConfig class has been removed and needs to be replaced by a Map. Update the configuration passed in the install call based on the following mapping of functions from InstallConfig to a key in Map. All deprecated configurations have been removed and are not supported anymore. For more information on configurations, please refer to this document — SDK Configuration - Helpshift SDK X for Android Update the public APIs for conversation and FAQs as following. For more information on public APIs in SDK X, please refer to this document — Helpshift APIs - Helpshift SDK X for Android. Update the configuration passed in conversation and FAQ APIs as following. Following deprecated configurations have been removed from the SDK: Replace the legacy SDK login code: HelpshiftUser user = new HelpshiftUser.Builder("unique-user-id-746501", "john.doe@app.co") .setName("John Doe") .setAuthToken("generated-user-authentication-token") .build(); Core.login(user); SDK X Map<String, Object> userData = new HashMap<>(); userData.put("userId", "unique-user-id-746501"); userData.put("userEmail", ""john.doe@app.co"); userData.put("userName", "John Doe"); userData.put("userAuthToken", "generated-user-authentication-token"); Helpshift.login(userData); Replace the legacy SDK logout code: Core.logout() SDK X Helpshift.logout() Replace legacy SDK clearAnonymousUser code: Core.clearAnonymousUser(); SDK X API : Helpshift.clearAnonymousUserOnLogin(); Replace authentication failure listener delegate with HelpshiftEventListener in SDK X: Remove legacy SDK Delegate: import com.helpshift.support.Support.Delegate ... ... class MyDelegate implements Delegate { . . . . @Override void authenticationFailed(HelpshiftUser user, AuthenticationFailureReason reason) { // your code here } } ... ... Support.setDelegate(new MyDelegate()); Use SDK X's HelpshiftEventListener for authentication failure updates: } }); For more information on User management, please refer to this document — Users - Helpshift SDK X for Android We recommend that on migration to SDK X, you should log the active user in again to avoid potential inconsistencies. Design and Customization of SDK X has completely moved to Helpshift Dashboard. Please remove all code related to Helpshift SDK’s design, theming, and customization. Configure them on Helpshift Dashboard instead. For more information on Design and Customization, please refer to this document — Design - Helpshift SDK X for Android Theming and customization is yet to be supported in SDK X and we will add it in our roadmap for 2022. String customization is yet to be supported. It will be moved to Helpshift Dashboard. Remove all Helpshift SDK related string customizations done in your app as it will no longer reflect in SDK X. Replace the following APIs from Legacy SDK to SDK X APIs for notification handling. Asynchronous requestUnreadMessageCount result is provided as an event on HelpshiftEventListener: Helpshift.setHelpshiftEventsListener(new HelpshiftEventsListener() { @Override public void onEventOccurred(@NonNull String eventName, Map<String, Object> data) { switch(eventName){ case HelpshiftEvent.RECEIVED_UNREAD_MESSAGE_COUNT: int count = (int) data.get(HelpshiftEvent.DATA_MESSAGE_COUNT); boolean fromCache = (boolean) data.get(HelpshiftEvent.DATA_MESSAGE_COUNT_FROM_CACHE); if (fromCache) { Log.d("Notification Count", "local" + count); } else { Log.d("Notification Count", "server" + count); } } } If you are using push notifications, we recommend that you register the push token again with SDK X after your app has been upgraded to avoid potential inconsistencies. For more information on notification handling, please refer to this document — Notifications - Helpshift SDK X for Android We recommend that you set the SDK language again on upgrading your app with SDK X to avoid potential inconsistencies. For more information on internationalization, please refer to this document — Going International - Helpshift SDK X for Android Replace legacy SDK API Support.leaveBreadCrumb("Went to Preferences Screen"); with SDK X API Helpshift.leaveBreadCrumb("Went to Preferences Screen") Replace legacy SDK API Support.clearBreadCrumbs(); with SDK X API Helpshift.clearBreadCrumbs() Legacy SDK support for Debug Logs has been replaced in SDK X with debug logs documented here Legacy SDK API Support.isConversationActive() is not supported in SDK X MetaData class has been removed. We recommened using CIF instead of meta data. You can find detailed article here Legacy SDK leveraged metadata APIs to attach metadata to the conversation (Refer here). Replace Legacy SDK code for attaching metadata with equivalent SDK X code - HashMap<String, String> customMetadata = new HashMap<String, String(); customMetadata.put("usertype","paid"); customMetadata.put("level","7"); customMetadata.put("score","12345"); HashMap<String, Object> config = new HashMap<>(); config.put("customMetadata", customMetadata); Helpshift.showConversation(MainActivity.this, config); To pass on tags as shown below in legacy SDK code: String[] tags = new String[]{"foo", "bar"}; HashMap<String, Object> userData = new HashMap<>(); Metadata metadata = new Metadata(userData, tags); private void showHelp () { ApiConfig apiConfig = new ApiConfig.Builder() .setCustomMetadata(metadata) .build(); Support.showFAQs(MainActivity.this, apiConfig); Use the following SDK X API: Map<String, Object> config = new HashMap<>(); config.put("tags", new String[]{"foo", "bar"}); Helpshift.showConversation(MainActivity.this, config); If you have following CIFs set in legacy SDK : Map<String, String[]> customIssueFields = new HashMap<>(); customIssueFields.put("join_date", new String[]{"dt", "1505927361535"}); customIssueFields.put("level", new String[]{"n", "42"}); customIssueFields.put("name", new String[]{"sl", "John Doe"}); customIssueFields.put("address", new String[]{"ml", "3346, Sunny Glen Lane, Warrensville Heights, Ohio - 44128"}); customIssueFields.put("is_pro", new String[]{"b", "true"}); customIssueFields.put("currency", new String[]{"dd", "Dollar"}); ... ... private void showHelp() { ApiConfig apiConfig = new ApiConfig.Builder() .setCustomIssueFields(customIssueFields) .build(); Support.showFAQs(MainActivity.this, apiConfig); Use the following SDK X code to set CIFs as in above example: Map<String, String> joiningDate = new HashMap<>(); joiningDate.put("type", "date"); joiningDate.put("value", "1505927361535"); Map<String, String> stockLevel = new HashMap<>(); stockLevel.put("type", "number"); stockLevel.put("value", "42"); Map<String, String> employeeName= new HashMap<>(); employeeName.put("type", "singleline"); employeeName.put("value", "John Doe"); Map<String, String> isPro = new HashMap<>(); isPro.put("type", "boolean"); isPro.put("value", "true"); Map<String, String> address = new HashMap<>(); address.put("type", "multiline"); address.put("value", "3346, Sunny Glen Lane, Warrensville Heights, Ohio - 44128"); Map<String, String> currency = new HashMap<>(); currency.put("type", "dropdown"); currency.put("value", "Dollar"); Map<String, Object> cifMap = new HashMap<>(); cifMap.put("join_date", joiningDate); cifMap.put("level", stockLevel); cifMap.put("name", employeeName); cifMap.put("is_pro", isPro); cifMap.put("address", address) cifMap.put("currency", currency) Map<String, Object> config = new HashMap<>(); // other configs... //.. config.put("customIssueFields", cifMap); Helpshift.showFAQs(MainActivity.this, config); Please refer to this document for further details - CIF - Helpshift SDK X Android The events reported in Legacy SDKs Delegate class will now be reported in HelpshiftEventListener callback interface of SDK X. All the events are now reported in onEventOccurred method of this listener class with defined constants for expected values. You will need to update your code based on these events from the old Delegate class. For more details on supported events, please refer to this document — Helpshift Delegates - Helpshift SDK X for Android Following events are not supported anymore from the legacy SDK: userClickOnAction displayAttachmentFile App review request is not supported in SDK X — Review Request - Helpshift for Android Manual app rating request is not supported in SDK X — Manual App Rating - Helpshift for Android Automatic review request is not supported in SDK X — Automatic Reviews - Helpshift for Android Deep links are supported in SDK X, similar to Legacy SDK — Deep Linking - Helpshift SDK X for Android Make sure you have removed all code related to the legacy SDK. Check that the gradle dependency is correctly added as mentioned here Make sure that the new/replaced API's that you are using are having the correct parameters. Check that you have migrated to the new API to be used for registering push token in SDK X. Check if you have correctly migrated to use the new API for handling push notifications i.e Helpshift.handlePush() instead of Core.handlePush() Check that you have registered the listener Helpshift.setHelpshiftEventListener() correctly and have migrated your event handling code from Support.setDelegate() If you face any issues with respect to migrating from legacy SDK to SDK X, please contact us on support@helpshift.com
https://developers.helpshift.com/sdkx_android/migration-guide/
CC-MAIN-2022-27
en
refinedweb
QWebView and CSS animations Hello ! I am trying to display this : with QWebView . However with this code there are no animations. Is there something I have to enable? Thanks in advance ! - _antipattern_ last edited by Hi, it looks like QtWebKit was superceded by QtWebEngine. Clicking together a quick sample shows the animations working for me without any more work required: import QtQuick 2.0 import QtQuick.Window 2.0 import QtWebEngine 1.0 Window { width: 1024 height: 768 WebEngineView { anchors.fill: parent url: "" } } Best
https://forum.qt.io/topic/72004/qwebview-and-css-animations
CC-MAIN-2022-27
en
refinedweb
key feature of LINQ is its universal querying API independent of the target data source. However, the way LINQ queries are executed, depends on the kind of data source being queried. When querying local in-memory collections (commonly called LINQ to Objects), the LINQ extension methods for the IEnumerable<T> interface are used. The implementation of the extension methods somewhat depends on whether the method returns a value typed as IEnumerable<T>, or a scalar value. The methods returning an IEnumerable<T> execute in a deferred way, i.e. at the point in code where the result is retrieved, not when the query is defined: var list = new List<int> { 1, 2, 3, 4, 5 }; var query = list.Where(item => item < 3); // not executed yet It’s not too difficult to implement such an extension method ourselves: public static IEnumerable<T> Where<T>(this IEnumerable<T> list, Func<T, bool> predicate) { foreach (var item in list) { if (predicate(item)) { yield return item; } } } For a Where method, we only need to iterate through all the items using a foreach loop and return those items which satisfy the supplied predicate. To achieve deferred execution, the method is implemented as an iterator, i.e. the values are returned using the yield return statement. Whenever this statement is reached, the control of code execution is transferred back to the caller performing the iteration until the next item from the returned IEnumerable<T> is requested. The methods returning a scalar value are in a way even simpler because they execute immediately: var list = new List<int> { 1, 2, 3, 4, 5 }; var sum = list.Sum(); // executes immediately Such extension methods don’t even need to be iterators: public static int Sum(this IEnumerable<int> list) { var sum = 0; foreach (var item in list) { sum += item; } return sum; } For a Sum method, we need to iterate through the items with a foreach loop to calculate the total sum returned in the end. The fact that LINQ to Objects extension methods accept IEnumerable<T> as their first argument makes them useful not only for querying collection classes, but in other scenarios as well. One such example is querying of XML documents, also known as LINQ to XML. XML documents must still be loaded in memory when they are queried, but they are not modelled with standard collection classes. Instead, a root XDocument class is used to represent an XML document. Usually the XML document will be read from a file or parsed from an XML string: var xmlDoc = XDocument.Parse(xmlString); The Root property will contain an instance of XElement, corresponding to the root element of the XML document. This class provides many methods for accessing the other elements and attributes in the document. The most commonly used among them are probably: Since they all return IEnumerable<T>, they can easily be queried using LINQ. They don’t provide strong type checking for element and argument names, though. Strings are used instead: var elements = xmlDoc.Root.Elements() .Where(element => int.Parse(element.Attribute("age").Value) > 21); For a certain structure of the XML, the above query would return all person elements with the age attribute above a specific value. Here’s an example of such a document: <persons> <person name="John" surname="Doe" age="33" /> <person name="Jane" surname="Doe" age="42" /> <person name="Johnny" surname="Doe" age="13" /> </persons> To use LINQ to XML, we don’t need to concern ourselves with the parsing of the XML documents. Since elements and attributes are exposed as instances of IEnumerable<T>, we can use the LINQ extension methods on them in combination with the properties available on the XElement and XAttribute classes. The abstraction of underlying data source extends over to LINQ to Entities as well. This term represents querying of external databases using Entity Framework or Entity Framework Core. Although the data is not queried locally in this case, the querying experience is almost identical. Sample code from here on will be based on Entity Framework Core. To use it with Microsoft SQL Server, the Microsoft.EntityFrameworkCore.SqlServer NuGet package must be installed in your project. Download the source code of this article (Github) To specify the mapping between the code and the database tables, corresponding properties must be defined in a class deriving from the DbContext class. Entity Framework will take care of the connectivity to the remote database: public class PersonContext : DbContext { public PersonContext(DbContextOptions<PersonContext> options) : base(options) { } // maps to the Persons table in database public DbSet<Person> Persons { get; set; } } Rows in each database table are represented by a simple DTO (data transfer object) matching the table structure: public class Person { public int Id { get; set; } public string Name { get; set; } public string Surname { get; set; } public int Age { get; set; } } The connection string for the database can be specified in a DbContextOptions<T> instance: var optionsBuilder = new DbContextOptionsBuilder<PersonContext>(); optionsBuilder.UseSqlServer(connectionString); var options = optionsBuilder.Options; With this set up, a database table can be queried very similar to an XML document or a local collection: using (var context = new PersonContext(options)) { var query = context.Persons.Where(person => person.Age > 21); } Because the DbSet<T> collections implement IQueryable<T>, not just IEnumerable<T>, the extension methods on the former interface are used instead. The IQueryable<T> interface makes it possible to implement a LINQ query provider which takes care of querying the data remotely. In our case, the provider is part of Entity Framework Core. When writing queries, most of the time we aren’t aware of the difference between the two interfaces because the same set of extension methods is available for both of them. They are just implemented differently. For the above query, the LINQ query provider for SQL Server would send the following SQL query to the server: SELECT [person].[Id], [person].[Age], [person].[Name], [person].[Surname] FROM [Persons] AS[person] WHERE [person].[Age] > 21 At least for simple cases when we are querying the data, it’s not important what SQL query is generated and how. We can safely assume that the data will be retrieved correctly and in an efficient manner. We can even use certain common .NET methods in the query predicates: var query = context.Persons.Where(person => Math.Abs(person.Age) > 21); The LINQ provider will still generate a matching SQL query: SELECT [person].[Id], [person].[Age], [person].[Name], [person].[Surname] FROM [Persons] AS[person] WHERE ABS([person].[Age]) > 21 However, this will only work for functions which have built-in equivalents in the target database and can therefore be implemented in such a way by the LINQ provider. If we start using our own custom methods, they of course won’t be converted correctly any more: private static int CustomFunction(int val) { return val + 1; } var query = context.Persons.Where(person => CustomFunction(person.Age) > 21); In this case, the following SQL query will be sent to the database: SELECT [person].[Id], [person].[Age], [person].[Name], [person].[Surname] FROM [Persons] AS[person] Although all the rows from the Persons table will be retrieved, the LINQ query will still return the correct result. The filtering will be done locally after the data is retrieved. The results are still correct, but the performance will suffer when the number of rows in the table increases. Because of that, we should always make the necessary tests to discover such problems during development. There are many more types of data sources which can be queried using LINQ. A large collection of third party LINQ providers are published on NuGet for querying different types of relational (NHibernate) and non-relational (MongoDB.Driver) databases, REST services (Linq2Rest), and more. Depending on how they are implemented, there might be differences in how much of the query is executed remotely and which parts of it are processed locally after the data is received. Therefore it’s important to always read the documentation and test the functionality and performance of the final!
https://www.dotnetcurry.com/csharp/1481/linq-query-execution-performance
CC-MAIN-2022-27
en
refinedweb
After writing the previous post, I wondered where else you might be able to use r-means to create accurate approximations. I thought maybe this would apply to the surface area of an ellipsoid, and a little searching around showed that Knud Thomsen thought of this in 2004. The general equation for the surface of an ellipsoid is If two of the denominators {a, b, c} are equal then there are formulas for the area in terms of elementary functions. But in general, the area requires special functions known as “incomplete elliptic integrals.” For more details, see this post. Here I want to focus on Knud Thomsen’s approximation for the surface area and its connection to the previous post. The previous post reported that the perimeter of an ellipse is 2πr where r is the effective radius. An ellipse doesn’t have a radius unless it’s a circle, but we can define something that acts like a radius by defining it to be the perimeter over 2π. It turns out that makes a very good approximation for the effective radius where x = (a, b). Here using the notation of Hardy, Littlewood, and Pólya. This suggests we define an effective radius for an ellipsoid and look for an approximation to the effective radius in terms of an r-mean. The area of a sphere is 4πr², so we define the effective radius of an ellipsoid as the square root of its surface area divided by 4π. So the effective radius of a sphere is its radius. Thomsen found that where x = (ab, bc, ac) and p = 1.6. More explicitly, Note that it’s the square of the effective radius that is an r-mean, and that the argument to the mean is not simply (a, b, c). I would have naively tried looking for a value of p so that the r-mean of (a, b, c) gives a good approximation to the effective radius. In hindsight, it makes sense in terms of dimensional analysis that the inputs to the mean have units of area, and so the output has units of area. The maximum relative error in Thomsen’s approximation is 1.178% with p = 1.6. You can tweak the value of p to reduce the worst-case error, but the value of 1.6 is optimal for approximately spherical ellipsoids. For an example, let’s compute the surface area of Saturn, the planet with the largest equatorial bulge in our solar system. Saturn is an oblate spheroid with equatorial diameter about 11% greater than its polar diameter. Assuming Saturn is a perfect ellipsoid, Thomsen’s approximation over-estimates its surface area by about 4 parts per million. By comparison, approximating Saturn as a sphere under-estimates its area by 2 parts per thousand. The code for these calculations, based on the code here, is given at the bottom of the post. Related posts Appendix: Python code from numpy import pi, sin, cos, arccos from scipy.special import ellipkinc, ellipeinc # Saturn in km equatorial_radius = 60268 polar_radius = 54364 a = b = equatorial_radius c = polar_radius phi = arccos(c/a) m = 1 temp = ellipeinc(phi, m)*sin(phi)**2 + ellipkinc(phi, m)*cos(phi)**2 ellipsoid_area = 2*pi*(c**2 + a*b*temp/sin(phi)) def rmean(r, x): n = len(x) return (sum(t**r for t in x)/n)**(1/r) approx_ellipsoid_area = 4*pi*rmean(1.6, (a*b, b*c, a*c)) r = (a*b*c)**(1/3) sphere_area = 4*pi*r**2 def rel_error(exact, approx): return (exact-approx)/approx print( rel_error(ellipsoid_area, sphere_area) ) print( rel_error(ellipsoid_area, approx_ellipsoid_area) )
https://www.johndcook.com/blog/2021/03/24/surface-area-ellipsoid/
CC-MAIN-2022-27
en
refinedweb
jwilke's changes: Moved many files to other directories renamed many files other changes unknown to me. /* a simple pow10 implementation <math.h> #ifndef M_LN10 #define M_LN10 2.30258509299404568402 #endif #ifndef _ANSI_MATH_H /*); }
http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/engine/pow10.c?rev=1.1;content-type=text%2Fx-cvsweb-markup;f=h;only_with_tag=MAIN
CC-MAIN-2019-30
en
refinedweb
I have this class: public class ItensLiberacao { AutorizadorContext contexto = new AutorizadorContext(); ItensLibDTO libDTO = new ItensLibDTO(); public List<ItensLibDTO> getItensLib(int idorcamento) { var lista = contexto.ItensLibs .Where(itens => itens.IdOrcamento == idorcamento) .Select(item => new ItensLibDTO { Produto = item.Produto, Qtde = item.Qtde.ToString(), Unitario = item.Unitario.ToString(), Custo = item.Custo.ToString(), CustoDiario = item.CustoDiario.ToString(), UltCondicao = item.UltCondicao.ToString(), Total = item.Total.ToString() }).ToList(); return lista; } And my rest service: public class ItensController : ApiController { AutorizadorContext contexto = new AutorizadorContext(); ItensLiberacao itens = new ItensLiberacao(); [AcceptVerbs("Get")] public IEnumerable<ItensLibDTO> getItensLiberacao(int idorcamento) { return itens.getItensLib(idorcamento).AsEnumerable().ToList(); } } When I put on(on or in?) my URL: I have this error message: Were not found HTTP resources that match the URI of the request ''. Answers I think it is because localhost is wrong here. It tries to go to the localhost from you device but not from the server or pc where the webservice is running, @Gigex42, if I call: localhost:9078/api/liberacaowork fine. I think that have some problem with my code. I tryed out of localhost by my App, but the error continues. The problem is in my service, the method getItensLiberacao doesn't called. What do must I do? I wish that my service method is broken, but where? I don't know what to do. I installed a WebApiDebugger and now I have other problem with System.Web.Optimization and this DLL is installed and don't have conflict. I changed my service to: and yet continues with error. I need to configure a route? localhost is where ever you are calling it from. So if you call that url from the device, it is looking for localhost on the device, not your PC. Your web service is running on your PC, right? So you need to use the IP address of the PC when calling the url from the device. @JohnHair, when I run in my site I have same problem. and now I have other problem: System.Web.Optimization each day other problem and I cannot solve. That link throws a 404, I suggest you fix your site before continuing with the app as that will confuse things. Fix 1 bug at a time until the site is working as you expect, then return to the app.
https://forums.xamarin.com/discussion/comment/295693
CC-MAIN-2019-30
en
refinedweb
To determine if a user is a member of a group in Django: user.groups.filter(id=group.id).exists() To remove a user from a group: user.groups.remove(the_group) To add a user to a group: user.groups.add(the_group) To determine if a user is a member of a group in Django: user.groups.filter(id=group.id).exists() To remove a user from a group: user.groups.remove(the_group) To add a user to a group: user.groups.add(the_group) from django.contrib.auth.models import User, Group # Option 1 group = Group.objects.get(name='group_name') users = group.user_set.all() # Option 2 User.objects.filter(groups__name='group_name') Often I need to control access to my views. The built-in Django Permissions and Groups models are designed precisely for this. The problem is the docs are sparse. These notes fill in the details. The best way to get an idea of how this all works is to use the built-in Django admin to create users and groups. As you can see in admin, Django automatically adds “add”, “change” and “delete” permissions to each model. You can create custom permissions too, but I will not go in to that. You can control access for an individual user or you can create a group, set the group permissions and then add a user to that group. For my projects, I usually think of users in terms of groups, so I use groups to control access instead of controlling access by individual users. One advantage of that is it is easy to alter permissions for many users just by changing group permissions. By default users cannot create or change a model. Great. My model is safe??? Not so fast. Django permissions do not actually protect anything. Permissions are merely records of the control you want. You need to write the code to check permissions and decide what to do. One easy way to do this is to use the 3rd party Django braces app. When using braces there are a few things to keep in mind. Make sure to read the first few paragraphs at the top of the Access Mixins section. Especially take note of the raise_exception attribute. If this is False and permission is denied, you will get redirected to the login page. But on my website, if the user is already logged in they get passed to the page they were trying to access, creating an infinite loop. Setting raise_exception = True, you get a HTTP 403, which is what I wanted. Next, as the docs point out, it does not make sense to check permissions if a user is not logged in. One way to ensure that is to use the braces LoginRequiredMixin. To specify which permission to require, you set the class attribute “permission_required” for your view. But how do you know what string to assign to permission_required? For that, fire up your database browser. First look at the “django_content_type” table. Look for that app_label and model name you want to use permissions for. Write down the app_label and id number for that row. In my case, I wanted to protect the Django User model, so I selected the row with app_label=”auth” and the id in my case was 3. Next go to the “auth_permission” table and look for the content type id. The “code_name” column gives you what you need. Note: with the PostgreSQL admin tool, underscores in strings look like spaces. For the django user model, you will end up with something like this: permission_required = "auth.change_user" In many cases you will want to set permissions in your code (i.e. not using the admin tool). The trick to doing that is getting the permission object. For that you need to access ContentType and auth.models.Permission. Like this: from django.contrib.auth.models import User, Group, Permission from django.contrib.contenttypes.models import ContentType # Get the app_label and model by inspecting the table django_content_type user_content_type = ContentType.objects.get(app_label='auth', model='user') # Get codename by inspecting the table auth_permission create_user_perm = Permission.objects.get(content_type=user_content_type, codename='add_user') # To add permission to a user my_user = User.objects.get(username='my_username') my_user.permissions.add(create_user_perm) # To add the permission to a group my_group = Group.objects.get(name='my_group_name') my_group.permissions.add(create_user_perm) # To add user to group my_user.groups.add(my_group) That’s all for now.
https://snakeycode.wordpress.com/tag/groups/
CC-MAIN-2019-30
en
refinedweb
Injecting @EJB references fails?Laird Nelson Jul 14, 2010 4:13 PM Following the reference documentation example on how to do this sort of thing, I have attempted (obviously badly) to define a bean in one place with @Produces, and to inject that bean into a @SessionScoped object somewhere else (using @Inject). This combination is ambiguous, somehow, in Glassfish 3.1b09. Here is what I've done. I'm hoping that someone on this list can easily spot my boneheaded, idiotic, thick-skulled pilot error. I have attempted to isolate the bean definition into its own class. Perhaps this is misguided? Anyhow, here is the class: public class FrobnicatorProducer { @Produces @EJB private Frobnicator frobnicator; // frobnicator is a stateless session bean reference } Then, in my session scoped object, Foobar, I've done this: @Inject private Frobnicator frobnicator; This combination results in the following error: Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001409 Injection point has ambiguous dependencies. Injection point: field com.foobar.Foobar.frobnicator; Qualifiers: [@javax.enterprise.inject.Default()]; Possible dependencies: [org.jboss.weld.bean-/usr/local/glassfish-3.1b09/glassfish/domains/domain1/applications/foobar-1.0-SNAPSHOT/foobar-fizbaw-ejb-1.0-SNAPSHOT_jar/-SessionBean-FrobnicatorBean, org.jboss.weld.bean-/usr/local/glassfish-3.1b09/glassfish/domains/domain1/applications/foobar-1.0-SNAPSHOT/foobar-war-1.0-SNAPSHOT_war/-ProducerField-com.foobar.FrobnicatorProducer.frobnicator] It appears to me that the session bean (FrobnicatorBean) is already a candidate for injection somehow, and so the producer field version of it is thereby redundant. If this is true, I don't see how the reference documentation example could possibly work. Clearly it must; I know the error is mine. But I don't know where to go from here. Thanks, Laird 1. Re: Injecting @EJB references fails?Jan Groth Jul 15, 2010 6:47 AM (in response to Laird Nelson) to sort out the obvious: - if Frobnicator is a local EJB, you could skip the production process and use / inject it directly - if Frobnicator is a remote EJB, you should provide the link to the relevant archive (from the example: @Produces @EJB(ejbLink="../their.jar#PaymentService") ) is that of any help? cheers, Jan 2. Re: Injecting @EJB references fails?Laird Nelson Jul 15, 2010 11:45 PM (in response to Laird Nelson) Yes, that is of help. I was not aware from the reference documentation (I'm sure it's in there somewhere) that one could skip the production process entirely (not so obvious after all). Indeed that works! Thanks, Laird 3. Re: Injecting @EJB references fails?Jan Groth Jul 16, 2010 2:13 AM (in response to Laird Nelson) I was not aware that one could skip the production process that's an import part of the concept. CDI is a stateful implementation of the dependency injection pattern - this means, that the CDI-container managers not only the dependencies but also the lifecycle of the managed beans. What you're usually doing is declare the dependencies and let the container do the rest. CDI will instantiate all beans in the correct scope for you. Producer methods are for (rare) cases when you need more control about that process, like maybe joining a transaction or not. These parts of the documentation give a good overview: cheers, Jan
https://developer.jboss.org/message/659129
CC-MAIN-2019-30
en
refinedweb
span8 span4 span8 span4 I have written a Python code to retrieve a list of unique values from several rows with several attributes (in the example below, there are 5 attributes). The problem with this code is that the output field has only the result for the first row. It copies it to the rest of the fields. Here is the code: import fme import fmeobjects index = 0 list_yes = [] # Template Function interface: # When using this function, make sure its name is set as the value of # the 'Class or Function to Process Features' transformer parameter def compare_attributes(feature): global list_yes global index s1=feature.getAttribute('Att_1') s2=feature.getAttribute('Att_2') s3=feature.getAttribute('Att_3') s4=feature.getAttribute('Att_4') s5=feature.getAttribute('Att_5') myList_1 = [s1,s2,s3,s4,s5] for i in myList_1: myList_2 = myList_1[index:] if i!='': for j in myList_2: if i == j: list_yes.append(i) else: pass index = index +1 list_set = set(list_yes) unique_list = list(list_set) var_def = str(unique_list) feature.setAttribute('NEWATT',var_def) I have been looking for another built-in Python function and I found the following : list(set(feature) so i implemented it in the code like this: import fme import fmeobjects # Template Function interface: # When using this function, make sure its name is set as the value of # the 'Class or Function to Process Features' transformer parameter def compare_attributes(feature): s1=feature.getAttribute('Att_1') s2=feature.getAttribute('Att_2') s3=feature.getAttribute('Att_3') s4=feature.getAttribute('Att_4') s5=feature.getAttribute('Att_5') myList_1 = [s1,s2,s3,s4,s5] unique_list = list(set(myList_1)) feature.setAttribute('NEWATT',unique_list) This code doesn't work, it shows the following error: 2019-04-01 17:50:54| 0.5| 0.0|ERROR |Python Exception <TypeError>: Failure to convert list unicode values to native UTF-8 values. 2019-04-01 17:50:54| 0.5| 0.0|ERROR |Error encountered while calling function `compare_attributes' 2019-04-01 17:50:54| 0.5| 0.0|FATAL |PythonCaller_31(PythonFactory): PythonFactory failed to process feature 2019-04-01 17:50:54| 0.5| 0.0|ERROR |A fatal error has occurred. Check the logfile above for details Is it possible to correct this? You are using the function interface which processes each feature independently. If you want a unique set of values across all features, you need to use the class interface. Do you really need to do this in Python? The DuplicateFilter transformer is built for this task. Answers Answers and Comments 22 People are following this question. Python setAttribute list of dict attributes 3 Answers PythonCaller input loop 2 Answers How to calculate distinct values within a list using Python? 1 Answer How to setAttribute lists in PythonCaller 2 Answers Python Script - Overwriting records 2 Answers
https://knowledge.safe.com/questions/89440/failed-to-create-unique-list-python.html
CC-MAIN-2019-30
en
refinedweb
Why I Never Use Shallow Rendering Why I Never Use Shallow Rendering Testing is meant to ensure that your application is working and working well — see why there are better ways to do that than with shallow rendering. Join the DZone community and get the full member experience.Join For Free Tests should help me be confident that my application is working and there are better ways to do that than shallow rendering. I remember a few years ago when I got started with React I decided I needed to figure out how to test React components. I tried from enzyme and immediately decided that I would never use it to test my React components. I've expressed this feeling on many occasions and get asked on a regular basis why I feel the way I do about shallow rendering and why react-testing-library will never support shallow rendering.. What Even Is Shallow Rendering? For the purposes of this article, let's use this example as our subject under test: import React from 'react' import {CSSTransition} from 'react-transition-group' function Fade({children, ...props}) { return ( <CSSTransition {...props} timeout={1000} {children} </CSSTransition> ) } class HiddenMessage extends React.Component { static defaultProps = {initialShow: false} state = {show: this.props.initialShow} toggle = () => { this.setState(({show}) => ({show: !show})) } render() { return ( <div> <button onClick={this.toggle}>Toggle</button> <Fade in={this.state.show}> <div>Hello world</div> </Fade> </div> ) } } export {HiddenMessage} Here's an example of a test that uses shallow rendering with enzyme: import React from 'react' import Enzyme, {shallow} from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import {HiddenMessage} from '../hidden-message' Enzyme.configure({adapter: new Adapter()}) test('shallow', () => { const wrapper = shallow(<HiddenMessage initialShow={true} />) expect(wrapper.find('Fade').props()).toEqual({ in: true, children: <div>Hello world</div> }) wrapper.find('button').simulate('click') expect(wrapper.find('Fade').props()).toEqual({ in: false, children: <div>Hello world</div> }) }) To understand shallow rendering, let's add a console.log(wrapper.debug()) which will log out the structure of what enzyme has rendered for us: <div> <button onClick={[Function]}> Toggle </button> <Fade in={true}> <div> Hello world </div> </Fade> </div> You'll notice that it's not actually showing the CSSTransition which is what Fade is rendering. This is because instead of actually rendering components and calling into the Fade component, shallow just looks at the props that would be applied to the React elements created by the component you're shallowly rendering. In fact, if I were to take the render method of the HiddenMessage component and console.log what it's returning, I'd get something that looks a bit like this: { "type": "div", "props": { "children": [ { "type": "button", "props": { "onClick": [Function], "children": "Toggle" } }, { "type": [Function: Fade], "props": { "in": true, "children": { "type": "div", "props": { "children": "Hello world" } } } } ] } } Look familiar? So all shallow rendering is doing is taking the result of the given component's render method (which will be a React element (read What is JSX?) and giving us a wrapper object with some utilities for traversing this JavaScript object. This means it doesn't run lifecycle methods (because we just have the React elements to deal with), it doesn't allow you to actually interact with DOM elements (because nothing's actually rendered), and it doesn't actually attempt to get the react elements that are returned by your custom components (like our Fade component). Why People Use Shallow Rendering When I determined early on to never use shallow rendering, it was because I knew that there were better ways to get at the things that shallow rendering makes easy without making the trade-offs shallow rendering forces you to make. I recently asked folks to tell me why they use shallow rendering. Here are a few of the things that shallow rendering makes easier: - ... for calling methods in React components - ... it seems like a waste to render all of the children of each component under test, for every test, hundreds/thousands of times... - For actual unit testing. Testing composed components introduce new dependencies that might trigger an error while the unit itself might still work as intended. There were more responses, but these sum up the main arguments for using shallow rendering. Let's address each of these: Calling Methods in React Components Have you ever seen or written a test that looks like this? test('toggle toggles the state of show', () => { const wrapper = shallow(<HiddenMessage initialShow={true} />) expect(wrapper.state().show).toBe(true) // initialized properly wrapper.instance().toggle() wrapper.update() expect(wrapper.state().show).toBe(false) // toggled }) This is a great reason to use shallow rendering, but it's a really poor testing practice. There are two really important things that I try to consider when testing: - Will this test break when there's a mistake that would break the component in production? - Will this test continue to work when there's a fully backward compatible refactor of the component? This kind of test fails both of those considerations: - I could mistakenly set onClickof the buttonto this.tgogleinstead of this.toggle. My test continues to work, but my component is broken. - I could rename toggleto handleButtonClick(and update the corresponding onClickreference). My test breaks despite this being a refactor. The reason this kind of test fails those considerations is because it's testing irrelevant implementation details. The user doesn't care one bit what things are called. In fact, that test doesn't even verify that the message is hidden properly when the show state is false or shown when the show state is true. So not only does the test not do a great job keeping us safe from breakages, it's also flakey and doesn't actually test the reason the component exists in the first place. In summary, if your test uses instance() or state(), know that you're testing things that the user couldn't possibly know about or even care about, which will take your tests further from giving you confidence that things will work when your user uses them. ...It Seems Like a Waste.... In addition to this, you should probably use Jest's capabilities for only running tests relevant to your changes while developing your tests so the difference won't be perceivable when running the test suite locally. For Actual Unit Testing This is a very common misconception: "To unit test a react component you must use shallow rendering so other components are not rendered." It's true that shallow rendering doesn't render other components (as demonstrated above), what's wrong with this is that it's way too heavy-handed because it doesn't render any other components. You don't get a choice. Not only does shallow rendering not render third-party components, it doesn't even render in-file components. For example, the <Fade /> component we have above is an implementation detail of the <HiddenMessage /> component, but because we're shallow rendering <Fade /> isn't rendered so changes to that component could break our application but not our test. That's a major issue in my mind and is evidence to me that we're testing implementation details. In addition, you can definitely unit test react components without shallow rendering. Checkout the section near the end for an example of such a test (uses react-testing-library, but you could do this with enzyme as well) that uses Jest mocking to mock out the <CSSTransition /> component. I should add that I generally am against mocking even third-party components 100% of the time. The argument for mocking third-party components I often hear is Testing composed components introduces new dependencies that might trigger an error while the unit itself might still work as intended.? I should also add that I'm in favor of relying more heavily on integration testing. When you do this, you need to unit test fewer of your simple components and wind up only having to unit test edge cases for components (which can mock all they want). But even in these situations, I still think it leads to more confidence and a more maintainable test base when you're explicit about which components are being mocked and which are being rendered by doing full mounting and explicit mocks. Without Shallow Rendering I'm a huge believer of the guiding principle of react-testing-library: - shallow rendering - Static rendering (like enzyme's function). - Pretty much most of enzyme's methods to query elements (like ) ) - Getting and setting a component's props ( props()) - Getting and setting a component's state ( state()) That's why I wrote the library in the first place. As a side-note to this shallow rendering post, I want to mention there are fewer ways for you to do things that are impossible for the user to do. Here's the list of things that react-testing-library cannot do (out of the box): Shallow rendering Static rendering (like enzyme’s renderfunction) Pretty much most of enzyme’s methods to query elements (like find) instance) Getting and setting a component’s props ( props()) Getting and setting a component’s state ( state()) All of these things are things which users of your component cannot do, so your tests shouldn't do them either. Below is a test of the <HiddenMessage /> component which resembles the way a user would use your component much more closely. In addition, it can verify that you're using <CSSTransition /> properly (something the shallow rendering example was incapable of doing). import 'react-testing-library/cleanup-after-each' import React from 'react' import {CSSTransition} from 'react-transition-group' import {render, fireEvent} from 'react-testing-library' import {HiddenMessage} from '../hidden-message' // NOTE: you do NOT have to do this in every test. // Learn more about Jest's __mocks__ directory: // jest.mock('react-transition-group', () => { return { CSSTransition: jest.fn(({children, in: show}) => (show ? children : null)) } }) test('you can mock things with jest.mock', () => { const {getByText, queryByText} = render( <HiddenMessage initialShow={true} /> ) const toggleButton = getByText('Toggle') const context = expect.any(Object) const children = expect.any(Object) const defaultProps = {children, timeout: 1000, className: 'fade'} expect(CSSTransition).toHaveBeenCalledWith( {in: true, ...defaultProps}, context ) expect(getByText('Hello world')).not.toBeNull() CSSTransition.mockClear() fireEvent.click(toggleButton) expect(queryByText('Hello world')).toBeNull() expect(CSSTransition).toHaveBeenCalledWith( {in: false, ...defaultProps}, context ) }) Conclusion A few weeks ago, my DevTipsWithKent (my weekday livestream on YouTube) I livestreamed, "Migrating from shallow rendering react components to explicit component mocks." In that, I demonstrate some of the pitfalls of shallow rendering I describe above as well as how to use jest mocking instead. I hope this is helpful! We're all just trying our best to deliver an awesome experience to users. I wish you luck in that endeavor! P.S. Someone brought this up after I emailed my newsletter out: Shallow wrapper is good to test small independent components. With proper serializer it allows to have clear and understandable snapshots. I very rarely use snapshot testing with react and I certainly wouldn't use it with shallow. That's a recipe for implementation details. The whole snapshot is nothing but implementation details (it's full of component and prop names that change all the time on refactors). It'll fail any time you touch the component and the git diff for the snapshot will look almost identical to the one for your changes to the component. This will make people careless about to the snapshot updates because they change all the time. So it's basically worthless (almost worse than no tests because it makes you think you're covered when you're not and you won't write proper tests because they're in place). Published at DZone with permission of Kent C. Dodds . See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/why-i-never-use-shallow-rendering
CC-MAIN-2019-30
en
refinedweb
A relational database engine is great at set based operations and has a very familiar and powerful querying syntax but we are increasingly facing data challenges where leveraging a relational model doesn’t make as much sense. In building Raygun we have to deal with a constant stream of exception data (100’s of millions per month) which we structure into errors and occurrences which have a simple 1:N relationship. At first, using a relational model seemed to be a natural fit for this but over time we ran into three general problems: - Querying over the occurrence data was performing poorly despite being strictly index based. E.g. To find all parents where they have a child occurrence matching a particular criteria. - Producing aggregations of occurrence data was too costly to query in real time. Using a pre-aggregated bucket approach would add a massive overhead to our database size. - Searching the data using FTS would require indexing most of the raw payload which is costly both in terms of indexing time and database size and our preference was to use Lucene. Surely we must just need a more powerful database cluster? More RAM, more CPU? Sure, but what about when we add 10x our data volume? Rather than just blindly scaling, I always like to look around and see what everyone else is doing incase there is a better way. It turns out these are the type of problems that are handled nicely by ElasticSearch. Given the product name you would have naturally concluded that ElasticSearch is a search server, so that sounds good if what you want is just full text search via an http endpoint, and this was how we initially deployed it with Raygun. Over time however we quickly realised that it offers very powerful and efficient querying which makes it ideal for not just search but also quickly filtering sets and performing aggregations (e.g. for analytics) over very large sets of data. Not just that it is incredibly simple to approach. Filtering To fetch a list of parents, where they have a child occurrence matching a particular criteria, we want to first filter down to the occurrences matching the criteria and then group the results based on the parent error. This logically maps to a GROUP BY with a WHERE clause in the query in SQL. This is nice and simple to achieve using ElasticSearch. ElasticSearch natively talks JSON and presents a very sane RESTful API for interaction. There are a number of native providers to deal with API interactions, so for my code example I am using C# and the NEST provider for .NET as it exposes a nice fluent interface which logically maps back to the underlying JSON you would provide in a raw request. elastic.Search(s => s .Type("occurrence") .Filter(f => f.OnField("SomeProperty").Equals("SomeValue")) .FacetTerm(f => f.OnField("errorId")); This will find all occurrences where the property matches the value by using through a Filter and will then bucket the results into groupings based on the error they belong to by using the Term Facet. The end result is that we will have a list of all of the parents matching the predicate and a count of the number of occurrences under each error that match it. Aggregations An example of an aggregation we use in Raygun is the error graph on the application dashboard. We provide numbers in hourly buckets. To extract that data using ElasticSearch we can use the DateHistogram facet. elastic.Search(s => s .Type("occurrence") .FacetDateHistogram(f => f.OnField("occurredOn")); In ElasticSearch 1.1 there is now a newer framework known as aggregations to specify the same thing, with facets being deprecated in a future version. If you are using C# and NEST you will need to use the 1.0 version or later to pick up support for these. Search When you hit a requirement like “search” for an application you face the unenviable task of having your application suddenly compete with Google or Bing in terms of speed and quality of results. Full text search providers in relational databases generally leave a lot to be desired. Using something more specialized such as Apache Lucene is the way to go which fits in perfectly for ElasticSearch since that’s what it uses, and that’s what it performs fantastically at. When specifying a search for Elastic we need to define a query. These ultimately map down to Lucene query operations so have a good read through the documentation to understand what options you have available. elastic.Search(s => s .Type("occurrence") .Query(q => q.QueryString(qs => qs.OnField(property).Query(value).Operator(Operator.and))) .Sort(f => f.OnField("occurredOn").Descending()) .Sort(f => f.OnField("errorId").Descending()) .From(start) .Size(count) One important concept to keep in mind with how search operates in Elastic is that when you define your mapping you determine what is going to be indexed for search and how it is going to be broken down into tokens for later matching. By default you can throw data at ElasticSearch and it will infer a mapping for you – thats useful, but remember you may want aspects of your data that will be searched by a human and some which will be filtered on or where you just want to store a value. You can control all of this via your mappings. Here is an example of how we can control this again using C# and NEST: [ElasticType(Name = "occurrence")] public class OccurrenceMapping { // Storing the value and indexing for search [ElasticProperty(Store = true)] public DateTime OccurredOn { get; set; } // Indexing for search but not storing the raw value [ElasticProperty(Store = false)] public string Browser { get; set; } // Storing the raw value, not indexing for search [ElasticProperty(Store = true, Index = FieldIndexOption.not_analyzed)] public string Provider { get; set; } } For data you are indexing for search you will want to investigate how your data is being broken down to better understand how search terms will match to results. This process is known as analysis and inbound data is then broken down into tokens through a tokenizing process. ElasticSearch offers a number of standard analyzers and tokenizers – e.g. always lower case everything or strip common words – or you can take complete control of the process by implementing a custom implementation for one or both of those concerns. Get using it! ElasticSearch has been fantastic for us with Raygun, and we still have quite a number of features we are looking to ship which will take advantage of the flexibility and performance it offers. A large part of our domain is still persisted in a relational structure but we are all now appreciating that data at scale doesn’t just play well in the confines of a single sandbox. Leveraging the appropriate tool whether it be key/value, document based or relational depends on the data and what you need to do with it. If you are looking at large volumes of data and need to solve problems around search and analytics I think you will find ElasticSearch a very handy addition to your toolkit.
https://raygun.com/blog/2014/06/effective-data-elasticsearch/
CC-MAIN-2019-30
en
refinedweb
Related How To Build a Blog with Nest.js, MongoDB, and Vue.js The author selected Software in the Public Interest Inc to receive a donation as part of the Write for DOnations program. Introduction Nest.js is a scalable, server-side JavaScript framework built with TypeScript that still preserves compatibility with JavaScript, which makes it an effective tool for building efficient and reliable back-end applications. It has a modular architecture that provides a mature, structural design pattern to the Node.js development world. Vue.js is a front-end JavaScript framework for building user interfaces. It has a simple, yet very powerful API along with great performance. Vue.js is capable of powering the front-end layer and logic of any web application irrespective of the size. The ease of integrating it with other libraries or existing projects makes it a perfect choice for most modern web applications. In this tutorial, you'll build a Nest.js application to get yourself familiar with its building blocks as well as the fundamental principles of building modern web applications. You'll approach this project by separating the application into two different sections: the frontend and the backend. Firstly, you'll concentrate on the RESTful back-end API built with Nest.js. You'll then focus on the frontend, which you will build with Vue.js. Both applications will run on different ports and will function as separate domains. You'll build a blog application with which users can create and save a new post, view the saved posts on the homepage, and carry out other processes such as editing and deleting posts. Furthermore, you'll connect your application and persist its data with MongoDB, which is a schema-less NoSQL database that can receive and store JSON documents. This tutorial focuses on building your application in a development environment. For a production environment, you should also consider user authentication for your application. Prerequisites To complete this tutorial, you will need: -. - MongoDB installed on your machine. Follow the instructions here to download and install it for your choice of operating system. To successfully install MongoDB, you can either install it by using Homebrew on Mac or by downloading it from the MongoDB website. - A basic understanding of TypeScript and JavaScript. - A text editor installed, such as Visual Studio Code, Atom, or Sublime Text. Note: This tutorial uses a macOS machine for development. If you're using another operating system, you may need to use sudo for npm commands throughout the tutorial. Step 1 — Installing Nest.js and Other Dependencies In this section, you will get started with Nest.js by installing the application and its required dependencies on your local machine. You can easily install Nest.js by either using the CLI that Nest.js provides, or, by installing the starter project from GitHub. For the purpose of this tutorial, you'll use the CLI to set up the application. To begin, run the following command from the terminal to have it installed globally on your machine: You will see output similar to the following: Output@nestjs/cli@5.8.0 added 220 packages from 163 contributors in 49.104s To confirm your installation of the Nest CLI, run this command from your terminal: - nest --version You'll see output showing the current version installed on your machine: Output5.8.0 You'll make use of the nest command to manage your project and use it to generate relevant files — like the controller, modules, and providers. To begin the project for this tutorial, use the nest command to craft a new Nest.js project named blog-backend by running the following command from your terminal: - nest new blog-backend Immediately after running the command, nest will prompt you to provide some basic information like the description, version, and author. Go ahead and provide the appropriate details. Hit ENTER on your computer to proceed after responding to each prompt. Next, you'll choose a package manager. For the purpose of this tutorial, select npm and hit ENTER to start installing Nest.js. This will generate a new Nest.js project in a blog-backend folder within your local development folder. Next, navigate to the new project’s folder from your terminal: - cd blog-backend Run the following command to install other server dependencies: You've installed @nestjs/mongoose, which is a Nest.js dedicated package for an object modelling tool for MongoDB, and mongoose, which is a package for Mongoose. Now you'll start the application using the following command: - npm run start Now, if you navigate to from your favorite browser, you will see your application running. You've successfully generated the project by leveraging the availability of the Nest CLI command. Afterward, you proceeded to run the application and accessed it on the default port 3000 on your local machine. In the next section, you'll take the application further by setting up the configuration for the database connection. Step 2 — Configuring and Connecting with the Database In this step, you'll configure and integrate MongoDB into your Nest.js application. You'll use MongoDB to store data for your application. MongoDB stores its data in documents as field : value pairs. To access this data structure, you'll use Mongoose, which is an object document modeling (ODM) that allows you to define schemas representing the types of data that a MongoDB database stores. To start MongoDB, open a separate terminal window so that the application can keep running, and then execute the following command: - sudo mongod This will start the MongoDB service and run the database in the background of your machine. Open the project blog-backend in your text editor and navigate to ./src/app.module.ts. You can set up a connection to the database by including the installed MongooseModule within the root ApplicationModule. To achieve this, update the content in app.module.ts with the following highlighted lines: import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [ MongooseModule.forRoot('mongodb://localhost/nest-blog', { useNewUrlParser: true }), ], controllers: [AppController], providers: [AppService], }) export class AppModule { } In this file, you use the forRoot() method to supply the connection to the database. Save and close the file when you are finished editing. With this in place, you have set up the database connection by using the Mongoose module for MongoDB. In the next section, you will create a database schema using the Mongoose library, a TypeScript interface, and a data transfer object (DTO) schema. Step 3 — Creating a Database Schema, Interfaces, and DTO In this step, you will create a schema, interface, and a data transfer object for your database using Mongoose. Mongoose helps to manage relationships between data and provides schema validation for data types.. interfaces: TypeScript interfaces are used for type-checking. It can be used to define the types of data that should be passed for an application. data transfer object: This is an object that defines how data will be sent over the network and carries the data between processes. To begin, go back to your terminal where the application is currently running and stop the process with CTRL + C, then navigate to the ./src/ folder: - cd ./src/ Then, create a directory named blog, and a schemas folder within that: - mkdir -p blog/schemas In the schemas folder, create a new file called blog.schema.ts and open it using your text editor. Then, add the following content: import * as mongoose from 'mongoose'; export const BlogSchema = new mongoose.Schema({ title: String, description: String, body: String, author: String, date_posted: String }) Here, you have used Mongoose to define the type of data that you will store in the database. You've specified that all the fields will store and only accept string values. Save and close the file when you are finished editing. Now, with the database schema determined, you can move on to creating the interfaces. To begin, navigate back into the blog folder: - cd ~/blog-backend/src/blog/ Create a new folder named interfaces and move into it: - mkdir interfaces In the interfaces folder, create a new file called post.interface.ts and open it using your text editor. Add the following content to define the types of data for a import { Document } from 'mongoose'; export interface Post extends Document { readonly title: string; readonly description: string; readonly body: string; readonly author: string; readonly date_posted: string } In this file, you have successfully defined the types of data for a Post type as string values. Save and exit the file. Since your application will carry out the functionality of posting data to the database, you will create a data transfer object that will define how data will be sent over the network. To achieve this, create a folder dto inside the ./src/blog folder. Within the newly created folder, create another file named create-post.dto.ts Navigate back into the blog folder: - cd ~/blog-backend/src/blog/ Then create a folder named dto and move into it: - mkdir dto In the dto folder, create a new file called create-post.dto.ts and open it using your text editor to add the following content: export class CreatePostDTO { readonly title: string; readonly description: string; readonly body: string; readonly author: string; readonly date_posted: string } You've marked each of the individual properties in the CreatePostDTO class to have a data type of string and as readonly to avoid unnecessary mutation. Save and exit the file when you are finished editing. In this step, you have created a database schema for the database, an interface, and a data transfer object for the data your database will store. Next, you'll generate a module, controller, and service for your blog. Step 4 — Creating the Module, Controller, and Service for the Blog In this step, you're going to improve on the existing structure of the application by creating a module for your blog. This module will organize the file structure of your application. Next, you'll create a controller to handle routes and process HTTP requests from the client. To wrap things up, you'll set up a service to handle all the business logic that is too complex for the controller of the application to process. Generating a Module Similarly to the Angular front-end web framework, Nest.js uses a modular syntax. Nest.js applications have a modular design; it comes installed with a single root module, which is often sufficient for a small application. But when an application starts to grow, Nest.js recommends a multiple-module organization, splitting the code into related features. A module in Nest.js is identified by the @Module() decorator and takes in an object with properties such as controllers and providers. Each of these properties takes an array of controllers and providers respectively. You will generate a new module for this blog application in order to keep the structure more organized. To begin, still in the ~/blog-backend folder, execute the following command: - nest generate module blog You will see output similar to the following: OutputCREATE /src/blog/blog.module.ts UPDATE /src/app.module.ts The command generated a new module named blog.module.ts for the application and imported the newly created module into the root module for the application. This will allow Nest.js to be aware of another module besides the root module. In this file, you will see the following code: import { Module } from '@nestjs/common'; @Module({}) export class BlogModule {} You will update this BlogModule with the required properties later in the tutorial. Save and exit the file. Generating a Service A service, which can also be called a provider in Nest.js, was designed to remove logic from controllers, which are meant to only handle HTTP requests and redirect more complex tasks to services. Services are plain JavaScript classes with an @Injectable() decorator on top of them. To generate a new service, run the following command from the terminal while you are still within the project directory: - nest generate service blog You will see output similar to the following: OutputCREATE /src/blog/blog.service.spec.ts (445 bytes) CREATE /src/blog/blog.service.ts (88 bytes) UPDATE /src/blog/blog.module.ts (529 bytes) The nest command used here has created a blog.service.spec.ts file, which you can use for testing. It has also created a new blog.service.ts file, which will hold all the logic for this application and handle adding and retrieving documents to the MongoDB database. Also, it automatically imported the newly created service and added to blog.module.ts. The service handles all the logic within the application, is responsible for interacting with the database, and returns the appropriate responses back to the controller. To accomplish this, open the blog.service.ts file in your text editor and replace the contents with the following: import { Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { Post } from './interfaces/post.interface'; import { CreatePostDTO } from './dto/create-post.dto'; @Injectable() export class BlogService { constructor(@InjectModel('Post') private readonly postModel: Model<Post>) { } async getPosts(): Promise<Post[]> { const posts = await this.postModel.find().exec(); return posts; } async getPost(postID): Promise<Post> { const post = await this.postModel .findById(postID) .exec(); return post; } async addPost(createPostDTO: CreatePostDTO): Promise<Post> { const newPost = await this.postModel(createPostDTO); return newPost.save(); } async editPost(postID, createPostDTO: CreatePostDTO): Promise<Post> { const editedPost = await this.postModel .findByIdAndUpdate(postID, createPostDTO, { new: true }); return editedPost; } async deletePost(postID): Promise<any> { const deletedPost = await this.postModel .findByIdAndRemove(postID); return deletedPost; } } In this file, you first imported the required module from @nestjs/common, mongoose, and @nestjs/mongoose. You also imported an interface named CreatePostDTO. In the constructor, you added @InjectModel( ' ' ), which will inject the Post model into this BlogService class. You will now be able to use this injected model to retrieve all posts, fetch a single post, and carry out other database-related activities. Next, you created the following methods: getPosts(): to fetch all posts from the database. getPost(): to retrieve a single post from the database. addPost(): to add a new post. editPost(): to update a single post. deletePost(): to delete a particular post. Save and exit the file when you are finished. You have finished setting up and creating several methods that will handle proper interaction with the MongoDB database from the back-end API. Now, you will create the required routes that will handle HTTP calls from a front-end client. Generating a Controller In Nest. js, controllers are responsible for handling any incoming requests from the client side of an application and returning the appropriate response. Similarly to most other web frameworks, it is important for the application to listen for a request and respond to it. To cater to all the HTTP requests for your blog application, you will leverage the nest command to generate a new controller file. Ensure that you are still in the project directory, blog-backend, and run the following command: - nest generate controller blog You will see output similar to: OutputCREATE /src/blog/blog.controller.spec.ts (474 bytes) CREATE /src/blog/blog.controller.ts (97 bytes) UPDATE /src/blog/blog.module.ts (483 bytes) The output indicates that this command created two new files within the src/blog directory. They are blog.controller.spec.ts and blog.controller.ts. The former is a file that you can use to write automated testing for the newly created controller. The latter is the controller file itself. Controllers in Nest.js are TypeScript files decorated with @Controller metadata. The command also imported the newly created controller and added to the blog module. Next, open the blog.controller.ts file with your text editor and update it with the following content: import { Controller, Get, Res, HttpStatus, Param, NotFoundException, Post, Body, Query, Put, Delete } from '@nestjs/common'; import { BlogService } from './blog.service'; import { CreatePostDTO } from './dto/create-post.dto'; import { ValidateObjectId } from '../shared/pipes/validate-object-id.pipes'; @Controller('blog') export class BlogController { constructor(private blogService: BlogService) { } @Get('posts') async getPosts(@Res() res) { const posts = await this.blogService.getPosts(); return res.status(HttpStatus.OK).json(posts); } @Get('post/:postID') async getPost(@Res() res, @Param('postID', new ValidateObjectId()) postID) { const post = await this.blogService.getPost(postID); if (!post) throw new NotFoundException('Post does not exist!'); return res.status(HttpStatus.OK).json(post); } @Post('/post') async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) { const newPost = await this.blogService.addPost(createPostDTO); return res.status(HttpStatus.OK).json({ message: "Post has been submitted successfully!", post: newPost }) } } In this file, you first imported the necessary modules to handle HTTP requests from @nestjs/common module. Then, you imported three new modules which are: BlogService, CreatePostDTO, and ValidateObjectId. After that, you injected the BlogService into the controller via a constructor in order to gain access and make use of the functions that are already defined within the BlogService file. This is a pattern regarded as dependency injection used in Nest.js to increase efficiency and enhance the modularity of the application. Finally, you created the following asynchronous methods: getPosts(): This method will carry out the functionality of receiving an HTTP GET request from the client to fetch all posts from the database and then return the appropriate response. It is decorated with a @Get( ' ' ). getPost(): This takes a postIDas a parameter and fetches a single post from the database. In addition to the postIDparameter passed to this method, you realized the addition of an extra method named ValidateObjectId(). This method implements the PipeTransforminterface from Nest.js. Its purpose is to validate and ensure that the postIDparameter can be found in the database. You will define this method in the next section. addPost(): This method will handle a POST HTTP request to add a new post to the database. To be able to edit and delete a particular post, you will need to add two more methods to the blog.controller.ts file. To do that, include the following editPost() and deletePost() methods directly after the addPost() method you previously added to blog.controller.ts: ... @Controller('blog') export class BlogController { ... @Put('/edit') async editPost( @Res() res, @Query('postID', new ValidateObjectId()) postID, @Body() createPostDTO: CreatePostDTO ) { const editedPost = await this.blogService.editPost(postID, createPostDTO); if (!editedPost) throw new NotFoundException('Post does not exist!'); return res.status(HttpStatus.OK).json({ message: 'Post has been successfully updated', post: editedPost }) } @Delete('/delete') async deletePost(@Res() res, @Query('postID', new ValidateObjectId()) postID) { const deletedPost = await this.blogService.deletePost(postID); if (!deletedPost) throw new NotFoundException('Post does not exist!'); return res.status(HttpStatus.OK).json({ message: 'Post has been deleted!', post: deletedPost }) } } Here you have added: editPost(): This method accepts a query parameter of postIDand will carry out the functionality of updating a single post. It also made use of the ValidateObjectIdmethod to provide proper validation for the post that you need to edit. deletePost(): This method will accept a query parameter of postIDand will delete a particular post from the database. Similarly to the BlogController, each of the asynchronous methods you have defined here has a metadata decorator and takes in a prefix that Nest.js uses as a routing mechanism. It controls which controller receives which requests and points to the methods that should process the request and return a response respectively. For example, the BlogController that you have created in this section has a prefix of blog and a method named getPosts() that takes in a prefix of posts. This means that any GET request sent to an endpoint of blog/posts ( http:localhost:3000/blog/posts) will be handled by the getPosts()method. This example is similar to how other methods will handle HTTP requests. Save and exit the file. For the complete blog.controller.ts file, visit the DO Community repository for this application. In this section, you have created a module to keep the application more organized. You also created a service to handle the business logic for the application by interacting with the database and returning the appropriate response. Finally, you generated a controller and created the required methods to handle HTTP requests such as GET, PUT, and DELETE from the client side. In the next step, you'll complete your back-end setup. Step 5 — Creating an Extra Validation for Mongoose You can identify each post in your blog application by a unique ID, also known as PostID. This means that fetching a post will require you to pass this ID as a query parameter. To validate this postID parameter and ensure that the post is available in the database, you need to create a reusable function that can be initialized from any method within the BlogController. To configure this, navigate to the ./src/blog folder: - cd ./src/blog/ Then, create a new folder named shared: - mkdir -p shared/pipes In the pipes folder, using your text editor, create a new file called validate-object-id.pipes.ts and open it. Add the following content to define the accepted postID data: import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'; import * as mongoose from 'mongoose'; @Injectable() export class ValidateObjectId implements PipeTransform<string> { async transform(value: string, metadata: ArgumentMetadata) { const isValid = mongoose.Types.ObjectId.isValid(value); if (!isValid) throw new BadRequestException('Invalid ID!'); return value; } } The ValidateObjectId() class implements the PipeTransform method from the @nestjs/common module. It has a single method named transform() that takes in value as a parameter — postID in this case. With the method above, any HTTP request from the frontend of this application with a postID that can’t be found in the database will be regarded as invalid. Save and close the file. After creating both the service and controller, you need to set up the Post model that is based on the BlogSchema. This configuration could be set up within the root ApplicationModule, but in this instance building the model in BlogModule will maintain your application's organization. Open the ./src/blog/blog.module.ts and update it with the following highlighted lines: import { Module } from '@nestjs/common'; import { BlogController } from './blog.controller'; import { BlogService } from './blog.service'; import { MongooseModule } from '@nestjs/mongoose'; import { BlogSchema } from './schemas/blog.schema'; @Module({ imports: [ MongooseModule.forFeature([{ name: 'Post', schema: BlogSchema }]) ], controllers: [BlogController], providers: [BlogService] }) export class BlogModule { } This module uses the MongooseModule.forFeature() method to define which models should be registered in the module. Without this, injecting the PostModel within the BlogService using @injectModel() decorator wouldn't work. Save and close the file when you have finished adding the content. In this step, you've created the complete backend RESTful API with Nest.js and integrated it with MongoDB. In the next section, you'll configure the server to allow HTTP requests from another server, because your frontend application will be running on a different port. Step 6 — Enabling CORS An HTTP request from one domain to another is often blocked by default, except when specified by the server to allow it. For your front-end application to make a request to the back-end server, you must enable Cross-origin resource sharing (CORS), which is a technique that allows requests for restricted resources on a web page. In Nest.js to enable CORS, you need to add a single method to your main.ts file. Open this file in your text editor, which is located at ./src/main.ts, and update it with the following highlighted content: import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors(); await app.listen(3000); } bootstrap(); Save and exit the file. Now that you have completed the back-end setup, you'll shift your focus to the frontend and use Vue.js to consume the APIs built so far. Step 7 — Creating the Vue.js Frontend In this section, you are going to create your front-end application with Vue.js. Vue CLI is a standard tool that allows you to quickly generate and install a new Vue.js project without much hassle. To begin, you first need to install the Vue CLI globally on your machine. Open another terminal, and instead of working from the blog-backend folder, navigate to your local project's development folder and run: Once the installation process is complete, you'll make use of the vue command to create a new Vue.js project: - vue create blog-frontend You'll see a short prompt after you've entered this command. Choose the manually select features option, and then select the features you'll need for this project by pressing SPACE on your computer to highlight multiple features. You'll select Babel, Router, and Linter / Formatter. For the next instructions, type y to use history mode for a router; this will ensure that history mode is enabled within the router file, which will automatically generate for this project. In addition, select ESLint with error prevention only to pick a linter/formatter configuration. Next, select Lint on save for additional Lint features. Then select to save your configuration in a dedicated config file for future projects. Type a name for your preset, like vueconfig. Vue.js will then start creating the application and all its required dependencies in a directory named blog-frontend. Once the installation process is complete, navigate inside the Vue.js application: - cd blog-frontend Then, start the development server with: - npm run serve Your application will be running on. Since you'll be performing HTTP requests within this application, you'll need to install Axios, which is a promise-based HTTP client for the browser. You'll use Axios here to perform HTTP requests from the different components within the application. Stop the front-end application by hitting CTRL + C from the terminal on your computer and then run the following command: - npm install axios --save Your front-end application will be making an API call to the back-end API on a particular domain from different components within the application. In order to ensure proper structure for this application, you can create a helper file and define the server baseURL. To begin, from you terminal still within blog-frontend, navigate to the ./src/ folder: - cd ./src/ Create another folder named utils: - mkdir utils In the utils folder, using your text editor, create a new file called helper.js and open it. Add the following content to define the baseURL for the back-end Nest.js project: export const server = { baseURL: '' } By defining a baseURL, you'll be able to call it from anywhere within you Vue.js component files. In the event that you need to change the URL, it will be an easier process to update the baseURL in this file rather than across your application. In this section, you installed the Vue CLI, a tool for creating a new Vue.js application. You used this tool to craft the blog-frontend application. In addition, you ran the application and installed a library named Axios, which you will use whenever there is an HTTP call within the app. Next, you will create components for the application. Step 8 — Creating Reusable Components Now you're going to create reusable components for your application, which is the standard structure for Vue.js applications. The component system in Vue.js makes it possible for developers to build a single, independent unit of an interface that can have its own state, markup, and style. This makes it appropriate for components in Vue.js to be reusable. Every Vue.js component contains three different sections: <template>: contains the HTML contents <script>: holds all the basic frontend logic and defines the functions <style>: the stylesheet for each separate component First, you'll start by creating a component to create a new post. To do that, create a new folder named post within the ./src/components folder, which will house the necessary reusable components for posts. Then using your text editor, inside the newly created post folder, create another file and name it Create.vue. Open the new file and add the following code, which contains the necessary input fields for submitting a post: <template> <div> <div class="col-md-12 form-wrapper"> <h2> Create Post </h2> <form id="create"> Create Post </button> </div> </form> </div> </div> </template> This is the <template> section of the CreatePost component. It contains the HTML input elements required to create a new post. Each of the input fields has a v-model directive as an input attribute. This is to ensure two-way data bindings on each of the form input to make it easy for Vue.js to obtain the user's input. Next, add the <script> section to the same file directly following the preceding content: ... <script> import axios from "axios"; import { server } from "../../utils/helper"; import router from "../../router"; export default { data() { return { title: "", description: "", body: "", author: "", date_posted: "" }; }, created() { this.date_posted = new Date().toLocaleDateString(); }, methods: { createPost() { let postData = { title: this.title, description: this.description, body: this.body, author: this.author, date_posted: this.date_posted }; this.__submitToServer(postData); }, __submitToServer(data) { axios.post(`${server.baseURL}/blog/post`, data).then(data => { router.push({ name: "home" }); }); } } }; </script> Here you've added a method named createPost() to create a new post and submit it to the server using Axios. Once a user creates a new post, the application will redirect back to the homepage where users can view the list of created posts. You will configure vue-router to implement the redirection later in this tutorial. Save and close the file when you are finished editing. For the complete Create.vue file, visit the DO Community repository for this application. Now, you need to create another component for editing a particular post. Navigate to ./src/components/post folder and create another file and name it Edit.vue. Add the following code that contains the <template> section to it: <template> <div> <h4 class="text-center mt-20"> <small> <button class="btn btn-success" v-on: View All Posts </button> </small> </h4> <div class="col-md-12 form-wrapper"> <h2> Edit Post </h2> <form id="edit"> Edit Post </button> </div> </form> </div> </div> </template> This template section holds similar content as the CreatePost() component; the only difference is that it contains the details of the particular post that needs to be edited. Next, add the <script> section directly following the </template> section in Edit.vue: ... <script> import { server } from "../../utils/helper"; import axios from "axios"; import router from "../../router"; export default { data() { return { id: 0, post: {} }; }, created() { this.id = this.$route.params.id; this.getPost(); }, methods: { editPost() { let postData = { title: this.post.title, description: this.post.description, body: this.post.body, author: this.post.author, date_posted: this.post.date_posted }; axios .put(`${server.baseURL}/blog/edit?postID=${this.id}`, postData) .then(data => { router.push({ name: "home" }); }); }, getPost() { axios .get(`${server.baseURL}/blog/post/${this.id}`) .then(data => (this.post = data.data)); }, navigate() { router.go(-1); } } }; </script> Here, you obtained the route parameter id to identify a particular post. You then created a method named getPost() to retrieve the details of this post from the database and updated the page with it. Finally, you created an editPost() method to submit the edited post back to the back-end server with a PUT HTTP request. Save and exit the file. For the complete Edit.vue file, visit the DO Community repository for this application. Now, you'll create a new component within the ./src/components/post folder and name it Post.vue. This will allow you to view the details of a particular post from the homepage. Add the following content to Post.vue: <template> <div class="text-center"> <div class="col-sm-12"> <h4 style="margin-top: 30px;"><small><button class="btn btn-success" v-on: View All Posts </button></small></h4> <hr> <h2>{{ post.title }}</h2> <h5><span class="glyphicon glyphicon-time"></span> Post by {{post.author}}, {{post.date_posted}}.</h5> <p> {{ post.body }} </p> </div> </div> </template> This code renders the details of a post that includes, title, author, and the post body. Now, directly following </template>, add the following code to the file: ... <script> import { server } from "../../utils/helper"; import axios from "axios"; import router from "../../router"; export default { data() { return { id: 0, post: {} }; }, created() { this.id = this.$route.params.id; this.getPost(); }, methods: { getPost() { axios .get(`${server.baseURL}/blog/post/${this.id}`) .then(data => (this.post = data.data)); }, navigate() { router.go(-1); } } }; </script> Similar to the <script> section of the edit post component, you obtained the route parameter id and used it to retrieve the details of a particular post. Save and close the file when you are finished adding the content. For the complete Post.vue file, visit the DO Community repository for this application. Next, to display all the created posts to users, you will create a new component. If you navigate to the views folder in src/views, you will see a Home.vue component — if this file is not present, use your text editor to create it, add the following code: <template> <div> <div class="text-center"> <h1>Nest Blog Tutorial</h1> <p> This is the description of the blog built with Nest.js, Vue.js and MongoDB</p> <div v- <h2> No post found at the moment </h2> </div> </div> <div class="row"> <div class="col-md-4" v- <div class="card mb-4 shadow-sm"> <div class="card-body"> <h2 class="card-img-top">{{ post.title }}</h2> <p class="card-text">{{ post.body }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group" style="margin-bottom: 20px;"> <router-link :View Post </router-link> <router-link :Edit Post </router-link> <button class="btn btn-sm btn-outline-secondary" v-on:Delete Post</button> </div> </div> <div class="card-footer"> <small class="text-muted">Posted on: {{ post.date_posted}}</small><br/> <small class="text-muted">by: {{ post.author}}</small> </div> </div> </div> </div> </div> </div> </template> Here, within the <template> section, you used the <router-link> to create a link for editing as well as for viewing a post by passing the post._id as a query parameter. You also used the v-if directive to conditionally render the post for users. If there is no post from the database, a user will only see this text: No post found at the moment. Save and exit the file. For the complete Home.vue file, visit the DO Community repository for this application. Now, directly following the </template> section in Home.vue, add the following </script> section: ... <script> // @ is an alias to /src import { server } from "@/utils/helper"; import axios from "axios"; export default { data() { return { posts: [] }; }, created() { this.fetchPosts(); }, methods: { fetchPosts() { axios .get(`${server.baseURL}/blog/posts`) .then(data => (this.posts = data.data)); }, deletePost(id) { axios.delete(`${server.baseURL}/blog/delete?postID=${id}`).then(data => { console.log(data); window.location.reload(); }); } } }; </script> Within the <script> section of this file, you created a method named fetchPosts() to fetch all posts from the database, and you updated the page with the data returned from the server. Now, you'll update the App component of the front-end application in order to create links to the Home and Create components. Open src/App.vue and update it with the following: <template> <div id="app"> <div id="nav"> <router-linkHome</router-link> | <router-linkCreate</router-link> </div> <router-view/> </div> </template> <style> #app { font-family: "Avenir", Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } #nav { padding: 30px; text-align: center; } #nav a { font-weight: bold; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } </style> Apart from including the links to both Home and Create components, you also included the <Style> section, which is the stylesheet for this component and holds the definition of styles for some of the elements on the page. Save and exit the file. You have created all the required components for your application in this step. Next, you will configure the router file. Step 9 — Setting Up Routing After creating all the necessary reusable components, you can now properly configure the router file by updating its content with links to all the components you've created. This will ensure that all endpoints within the front-end application are mapped to a particular component for appropriate action. Navigate to ./src/router.js and replace its content with the following: import Vue from 'vue' import Router from 'vue-router' import HomeComponent from '@/views/Home'; import EditComponent from '@/components/post/Edit'; import CreateComponent from '@/components/post/Create'; import PostComponent from '@/components/post/Post'; Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', redirect: { name: 'home' } }, { path: '/home', name: 'home', component: HomeComponent }, { path: '/create', name: 'Create', component: CreateComponent }, { path: '/edit/:id', name: 'Edit', component: EditComponent }, { path: '/post/:id', name: 'Post', component: PostComponent } ] }); You imported Router from the vue-router module and instantiated it by passing the mode and routes parameters. The default mode for vue-router is a hash mode, which uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. In order to make the hash unnecessary, you have used history mode here to achieve URL navigation without a page reload. Finally, within the routes option, you specified the path for the endpoint — a name for the route and the component that should be rendered when the route is called within the application. Save and exit the file. Now that you have set up routing to the application, you need to include the Bootstrap file to help with pre-built styling for the user interface of the application. To achieve that, open ./public/index.html file in your text editor and include the CDN file for Bootstrap by adding the following content to the file: <!DOCTYPE html> <html lang="en"> <head> ... <link rel="stylesheet" href=""> <title>blog-frontend</title> </head> <body> ... </body> </html> Save and exit the file, and then restart the application with npm run serve for your blog-frontend, if it is not currently running. Note: Ensure that both the back-end server and the MongoDB instance are running as well. If otherwise, navigate to the blog-backend from another terminal and run npm run start. Also, start the MongoDB service by running sudo mongod from a new terminal as well. Navigate to your application at:. Now you can test your blog by creating and editing posts. Click on Create on your application to see the Create Post screen, which relates to and renders the CreateComponent file. Enter values into the input fields and click on the Create Post button to submit a post. Once you are done, the application will redirect you back to the homepage. The homepage of the application renders the HomeComponent. This component has a method that sends an HTTP call to fetch all posts from the database and displays them to users. Clicking on the Edit Post button for a particular post will take you to an edit page where you can incorporate any changes and save your post. In this section, you configured and set up routing for the application. With this in place, your blog application is ready. Conclusion In this tutorial, you have explored a new way of structuring a Node.js application by using Nest.js. You created a simple blog application using Nest.js to build the back-end RESTful API and used Vue.js to handle all the front-end logic. Furthermore, you also integrated MongoDB as a database for your Nest.js application. To learn more about how to add authentication to your application, you can make use of Passport.js, a popular Node.js authentication library. You can learn about Passport.js integration in the Nest.js documentation. You can find the complete source code for this project here on GitHub. For more information about Nest.js, you can visit the official documentation. 2 Comments
https://www.digitalocean.com/community/tutorials/how-to-build-a-blog-with-nest-js-mongodb-and-vue-js
CC-MAIN-2019-30
en
refinedweb
Tip SymfonyCon 2018 Presentation by Diana Ungaro Arnos. Good morning everyone! Did you drink your coffee already? So, because you know, if you feel a little bit sleepy I can scream really loud, and I maybe do that sometimes during the presentation, please don't be scared. I promise I'm a really nice person, especially when I'm sober, which is right now. So we are fine. Uh, I must say sometimes I say some maybe bad and ugly words and if you feel offended by it, (xxxx) you. Oh no, sorry. If you feel offended by it, okay. I can ask, you can come and ask, I can ask you a, you can ask me for apologies later. And no problem, I can give you hugs and everything is fine. So, well, um, I, I must say also that I'm from Brazil, I'm Brazilian, so, uh, I'm sorry if I mess up some words in English because, well, it's not my mother, my mother English, it's really fine. That's not my mother language. So I'm really sorry about that too. And maybe no, (xxxx) you again. So I'm here to talk about security. Um, what I want to talk about is, uh, the Symfony framework that have, um, amazing tool called the Security component. You may use it with your whole application running on Symfony or you can install it by small parts, by packages using Composer. And while I was studying this component, it is extremely powerful, but I've been searching for, you know, examples on the Internet. Um, examples of code, I, I read, uh, lots of lines of code on GitHub. Um, I talked with people I know about the component, the component, and I realized people, like, open them the documentation, see some lines of code and it's always Ctrl+C, Ctrl+V. People don't understand the concepts behind, um, some security problems and security solutions. Okay? Um, if you don't know the concepts, if you don't know how things work, if you don't know the context you're dealing with, I'm so sorry you're a (xxxx) developer. Okay. Um, and this is not a problem. Everyone is a (xxxxx) developer on some level or something like: I can do frontend. I mean, css hates me, so that's why I stand in the back end stuff. And especially for starting, if you're new you, if you're a junior developer, it's good to be a (xxxx) developer, you know? Wake up every morning, look in the mirror and say: I'm a (xxxxx) developer. Because this will make you try harder when you go to work, when you try to study. Okay. So I'm going to play around here with some concepts. And I will present some, some of the functions and tools you can use for, from the Security component to handle user access specifically. We have some stages of user access, but before I enter that, that's me. Um, there's this... Oh! My light doesn't work. So you can find me everywhere with Diana Arnos. That's my name. Uh, I like Sec, Music, I am tech leader from the startup in Brazil and I am evangelist of the user group of php and São Paulo Brazil and the Brazilian chapter of PHP women that, yes, we have a Brazilian chapter of PHP women, okay? Well, let's talk about user access. When we think about user access, well, it's easy right? You just have to put some username, you have to match up the passwords and let the user in. It's like, oh, this is you, so you can get in. But is this really that simple? How, how do you think of when you imagine the user entering your system, what things our user can do? You know, it doesn't matter what kind of user we are talking about. If there's one thing we know, every user is really good at, the user is good at (xxxx)ing up things. The user will click where it shouldn't. He will try a URL it shouldn't. He will end up at the page you didn't even imagine it existed, especially for dealing with legacy, if you're working with legacy code. So we have a few steps to think about, a few situations when we talk about access. You have the user and you must, you can notice I'm a really good artist, you know, and then you have to do the auth. Uh, it's interesting to notice that when we talk about auth and we use only the abbreviation, it's because it's the same for authentication and authorization, because it's, they are separate things. Okay. Not many, not many people think about that, but they are separate things. Okay, so you'll have the authentication step. After the user is logged in, or it's authenticated, it will have access to many features, whatever they are in your system. Those features enable the user to access some data. It may be only visualization, it may be only to edit or create, whatever. Every data on your system is accessed by the user through some features. Yeah, if that doesn't happen, you're having a problem, around, like... I will try to not talk about sql injection because you know, it's a very common mistake people usually do, especially developers that they don't pay attention to what they're doing. But I'll try it hold myself, it's not what I need to talk about, but I really want to punch everyone in the face when talking about that. So you have session, and you have an interaction with user authentication session and data and feature all the time through all the system and actually everything at the same time. It's much more complex than we usually think about. And then you have the authorization process: that's involved around everything. Basically the authentication process is... and the user data you have, they're combined throughout the system to know, okay, does my, does this user have access to this data or to this screen, to this button, whatever. You know, when we talk about not even only user roles, but what can the user access, it may be not only a simple visualization, you know, maybe as a low security-level user, couldn't see the names of the high directors of the company, for example. So we have, everything begins with a user. You can't have an authentication if you don't have the user. And let's suppose we are using Symfony here. It doesn't matter how you create your user class. The question, you may use, you may cod it by hand or you may use the MakerBundle, which is something very fun to, to play with, but you have our user. But then we have something really important for all the authentication and authorization process that will be used by the Security component: that's a user provider. What does the user provider do? It gets, um, like, let's say, support methods that handles your user data in ways authentication can do with it. You have two basic methods that must be implemented by your user provider and, but you can also add a few more, once your start playing a little bit more with the Security component and specially Guard authenticators that we'll talk in a second, okay? So you have a user provider. The user provider does basically two things, I must say, it must do at least these two things. First reload from session. There is a way to disable that and I'll talk about that, but what is the reload from session stuff? It serializes the User object and at the end of every request, every request the user gets, the user object gets serialized in session. And after, every time it begins a new request begun, or begins, sorry, uh, it deserializes the object. But it's not only that, it deserializes the object from the session, then it makes a refresh from the user based on the data on the session from whatever your user data is: it may be an API, please don't do that, let's do REST, but it may be an AP, it may be the database and it may be, I don't know, memory, because it can do that too. Please don't do that, but you can do that from memory too - configuration files. And then it compares: it's like, okay, I have this user, then I'll get this user from my database. It compares both and sees: Oh, if it's not the same user, it de-authenticates the user: it makes it login again. There's some internal methods that verify this that's outside from the, the part of the user provider. You can play around on that too. But it's a security measure to guarantee that, well, if you have some kind of middle-man, middle-man, it's a very nice name, you know, a man in the middle attack, okay, if you have any kind of man-the-middle attack, um, you have many kinds of men in the middle, but one of that, one of the most dangerous attacks on that is, right playing with the user session. Cause, you know that that things start there. So let's suppose I am the man in the middle. Then I will try to get the data from your session and then I'll start playing around because the server will think I am you. And still, still the, the, the component doing that - verifying if there was any change between the original user from the user database and the data on the session, there's still ways you can play around and (xxxx) this up. Because, well, if there ain't no time to updated the user or the data didn't change anything, you can still have problems with that. And you have ways to deal with that here too. Because, you can use a class that's a, an interface you can put on User class and you can implement them a method called isEqualTo(). So, instead of using the, the, the, the default method from Symfony, you can write your own. But be careful, great power, great, brings big responsibilities. And then you have the second method you must implement that is the load user. Uh, you may look and say: but they are the same thing! No, they're not. The load user does not do anything with the session. The load user, every time you have a feature that needs the user data, it will be calling this method. Why would you implement the load user? Well, like, if you don't want to use the default methods and you are using like an API, the built-in user providers that Symfony comes with does not give you the methods needed to get a user from an API. So you can implement this here. Okay. And here, and this is one of many use-cases that can do, you have to get the user from an API. And now I feel a little bit better talking about that because ya know, you guys were watching Anthony's talk and he was saying to please don't use microservices, and I was going to say if you're using a user micro-service. So I can say we're using a big user service, okay? We're going to recover the user data from the API. These are the methods you're going to mess around. loadUserByUsername(), funny thing is, that's, the username is not necessarily the username. It's the thing that comes if you have... It, it's the data that comes when you use the method, getUsername() from the user. Oh, but if I'm using the User class that's default from Symfony, you will get the username. Okay. But you can also make your custom User class, so you can change your username, I dunno maybe your identification of some kind. But then you can create and code all the data that comes here and this gives you really power over your application. They get, this gives power to: Okay my user is logging in, I am authenticating this user. How am I to authenticate this user? And uh, I know that most people doesn't care about that. People like, okay, I have used the full functions. Don't do that, please. Well, everything, as everything you can do on the Security component, you configure it in the security.yaml: that's right: config/packages/security.yaml. Uh, when you make your custom provider, you can set them here and you can just add the id, user provider. Uh, I didn't show the, that piece of code because I was showing the things you needed to, to code, but at the end of the class, there's a method that supports class, that's called supportsClass() that will show the framework you're using the class as a custom user provider. But it's a, it's a, it's a common line. You can find the line of code on the documentation itself. After the user: Ok, I have my user, I have my user class, I have my user data and I have a user provider. The user provider will always be used during the request and authentication and authorization methods. Okay. I did this step. So now I'm going to talk about authentication. And we have authentication providers. Uh, I don't know, most people, first time they're trying to mess with, uh, the Security component, they are trying to do things from out-of-the-box, because you can do that. It'll just put: okay, I created a project, I have my user, I can use the MakerBundle, everything's fine. So, you need to fix or do something different with the authentication. And then you start, like jumping from class to class and you're like: oh my God, this authentication is magic because it's not in the controller, it's not everywhere. The authentication on on Symfony runs before the controller is called. It's almost like a, a middleware idea, it's not exactly a middleware, but it runs before the controller. And for that, you can create authentication providers. Symfony already has some authentication providers built-in. But if you read the documentation, they will ask, they will say it's better if you create your own. But here, you don't have custom authentication provider, you have what's called a guard authenticator. But let's suppose we're going to, you have... When you create a user provider, you have one user provider for your class. Here you can have lots of authentication providers. And every authentication provider is, they always runs before each request. Always. And so you may have, you need to pay attention to the order things are happening. How many providers you have on authentication. And you must take care to, don't let one mess up the other. Okay? Umm, okay, I won't use the built-in, please don't use the built-in, I repeat this many, many, many times: please don't use the built-in authenticator. And then, you have to do your own. You can create a guard authenticator. It runs at the, it's the, on the same, the same context; they run every time before each request. You can create lots of guard authenticators. But, this class, when you create a Guard authenticator, it gives you full control of the authentication process. You can, you can analyze and, you know, deal with data since the beginning of the request to the end of the request. You will use an interface that brings seven methods you need to implement, but you can put more, and you can do a lot more. There's an example. Um, I'm really sorry I messed up the PSRs here, because you know, but it's just so they can fit all in. These are the seven methods you need to use, at least, by extending the AbstractGuardAuthenticator. Okay? Uh, why, um, why would you, need most authenticator, to create one by yourself? You know, like if you want to use a JWT authentication, API tokens authentication, you don't have those built in on Symfony. Anytime, basically everything you need to do with an API, you have to create an authenticator, a specific authenticator. So, here you come from, since the beginning, you know, this function here, the start() one. It's basically, it tells the authenticator what to do when, okay: this user isn't logged in. Or this user is incorrect. It runs the start() authentication. Uh, supportsRememberMe(). this function, remember me, you find on the user provider class or the user class, it's basically to get the user from the session and keep it logged in. You may disable that if you want to. You may check credentials, um, what we'll do an authentication success. If you look at this class and if you look up on the Internet for examples of its implementations, you'll find that some, a little bit of similarity with programming by events, you know: when it does logged in, when the request starts, when the request ends, when it's not the same user, when they users change. Okay? And to configure that, you can do that, or again, on the security.yaml. Here is a firewall. I'm not talking specifically about the firewalls because it's a very extensive subject and it's very fun to play with too. But let's suppose we all know what we're doing with the firewalls. And, pay attention, if you don't know what you're doing, you're going to mess up your whole application. But down there, in my main firewall, I have some authenticators. And why is this authenticators? You can have lots, as I said before. And then you just put the namespace of your personalized authenticator. It's really simple when you do that. Uh, I would like to call the attention to the bottom lines here, because there's an option in your firewall, in your configuration that's called stateless, cause I'm talking a lot about recovering user from session. There is a serialization that goes on session of the user, blah, blah, blah, blah. When you'll turn on stateless, you can work with REST API's, because there's no state on your session. And I must say it's one of the best ways to do that. I try to, to think like that, because you can avoid a lot of security problems by doing that. But you can do stateless: true. If stateless is true here, you don't need to implement that method that, that's that load users from session. You can leave it blank. We can leave it whatever message, because when your application is configured for stateless, they won't be calling that method any time soon. So. And then, you have, I can say, talking some of, like, it's like a sneak peek on user roles, because you know, it's again, a very extended subject, but before I talk quickly about user roles, I will like you to think about, you're maybe thinking, man that girl is talking (xxxx) the whole time, why I'm sitting here, blah blah blah, user here, blah, blah, blah, blah again and blah, blah, blah, stateless. But to get to here, because every, everyone loves to talk about ACLs. Okay, I have to handle access. I have user roles. But notice, pay attention to how many steps you must think before you get to user roles. If we're not thinking about that, you may have problems. That... you will have design flaws in your application and that can be, and will be, exploited by malicious, I would say malicious attacker, but an attacker is malicious anyway, so. Um, user roles: this is a quick configuration, You'll do that on your User entity. Um, you have them, this method getRoles(). Um, the big thing here when you talk about user roles is that you can have a hierarchy of roles, and, you won't get this: Okay, I will make this admin role and then I will configure this admin to have access to this page, that page, will visualize this data, that data, but actually you begin configuring your roles from the bottom to the top. So when you talk about the admin role, you just have to say that the admin role have all the others. Uh, another interesting fact, when you login or access your application, without being logged in or logged in as anonymous user, uh, the, the, the component have a very interesting concept that, uh, it's like, it's not exactly that, but it's like the anonymous user, it's kind of a user role. So even if you're, okay, you're coding then, and you're and you're trying something and you have the error on dev mode and you have the profiler bar under your application, if you are like, anonymous, okay, I'm not logged in and I'm, I'm on the poor mode of the browser. I mean the anonymous mode of the browser, and you answered that and you go check if you're authenticated, because you have the user information on the status bar, you'll see that it will show you that you are authenticated as an anon. And basically, uh, the user role anon don't have any permissions. So, every time you are not logged in, the application and treats you like you are logged in with a user to have no, no permissions at all. And this is a very interesting fact because when you're coding your application and thinking about the security issues or access, or permissions, you don't have to think on the "no" option. It's like: okay, I will remove this and that and this guy can do that, no, he's logged in as anon. And you can even mess with that and give the anonymous user access to some features of your system or your application without being logged in. And you can do that simply by using a (inaudible) the configuration, setting up some paths or URLs or patterns that you're, the anonymous user can have access to. Okay? And you can mess around with that too. You can, you've: okay, you have access here and I'm using the Guard authenticator and for any anon user, it can only see this kind of data, not that kind of data. And this is where you would configure. The guy here: access_control. You have your firewall configuration. I was, as I was talking, the anonymous user there in the main. Then you have access_control, so, you can play here. This, this makes your life a lot easier when you will filter access on your application. You may give that: Okay, I will enter, um, I don't know the welcome screen after the user has logged in, and I have a dashboard, but I have a specific dashboard, I don't know with financial information that only the admins can see. So when I have a low user accessing, I can author that information right on the template, on Twig. You can call the user role that, it's like app user access. But let's suppose you're not thinking of, on that kind of detail. You can do something quick, or quicker, or faster. That's the better word to say that. So you have it here: access_control and then you can say right here, like what's the role? Which role have access to which pages? Or you can think about path, you can think about URLs or hosts, that's the option you can use, and then you can make everything just from the configuration file. If I have a simple application, if I have, a with only like editing, I dunno employee's information, you can set it up through here. And every time we need to change something: Oh God, the director's said that the guy from the next department have to see the page "B", now, and he can only see the "A". You don't have to change on lines of code, you can do right here. But of course you can only do right here easily if you pay attention since the beginning: user, user provider, authentication, guard authenticator. How does, how do I handle my requests before I reach the controller? Because with, sometimes we are used to doing authentication on the controller. That's not one of the best ways to do that. So. And that's how you can play with user roles. Okay. Um, I could talk a lot more about that, specifically security, I like to talk about that, but unfortunately I won't have time to talk about all the stuff that comes from the security component. But I would like to say thank you. It's a, thank you for being here. Thank you for listening to my bad English and I'm here to answer all your questions. Not only here, but I'll be here all day. So come and talk to me on Twitter and Instagram because I'm kind of hipster developer. So if anyone has questions, or you may, I don't know, curse me? I can hear that too. Thank you. Thank you.
https://symfonycasts.com/screencast/symfonycon2018/handling-user-access-symfony
CC-MAIN-2019-30
en
refinedweb
class Solution(object): def maxEnvelopes(self, envs): def liss(envs): def lmip(envs, tails, k): b, e = 0, len(tails) - 1 while b <= e: m = (b + e) >> 1 if envs[tails[m]][1] >= k[1]: e = m - 1 else: b = m + 1 return b tails = [] for i, env in enumerate(envs): idx = lmip(envs, tails, env) if idx >= len(tails): tails.append(i) else: tails[idx] = i return len(tails) def f(x, y): return -1 if (x[0] < y[0] or x[0] == y[0] and x[1] > y[1]) else 1 envs.sort(cmp=f) return liss(envs) # Runtime: 100ms The idea is to order the envelopes and then calculate the longest increasing subsequence (LISS). We first sort the envelopes by width, and we also make sure that when the width is the same, the envelope with greater height comes first. Why? This makes sure that when we calculate the LISS, we don't have a case such as [3, 4] [3, 5] (we could increase the LISS but this would be wrong as the width is the same. It can't happen when [3, 5] comes first in the ordering). We could calculate the LISS using the standard DP algorithm (quadratic runtime), but we can just use the tails array method with a twist: we store the index of the tail, and we do leftmost insertion point as usual to find the right index in nlogn time. Why not rightmost? Think about the case [1, 1], [1, 1], [1, 1]. @agave i guess you could also have written envelopes.sort(key=lambda x: (x[0], x[1])) Is the same, just using lambda and in one line :) BTW. just loved your right shift instead of dividing by 2 :D Really sweat Shorter version using bisect import bisect class Solution(object): def maxEnvelopes(self, envelopes): """ :type envelopes: List[List[int]] :rtype: int """ if not envelopes: return 0 envelopes.sort(key=lambda x:(x[0],-x[1])) h=[] for i,e in enumerate(envelopes,0): j=bisect.bisect_left(h,e[1]) if j<len(h): h[j]=e[1] else: h.append(e[1]) return len(h) Hey can you please explain what you're doing or what is an algorithm captured in h=[] for i,e in enumerate(envelopes,0): j=bisect.bisect_left(h,e[1]) if j<len(h): h[j]=e[1] <---- what does it do?? else: h.append(e[1]) @pshaikh e[1] is the height of the current envelop. h stores the heights of the envelopes before current envelop. And because envelopes are sorted by (width, -height), so current envelop's width is equal or larger than the envelopes before it. h[j] = e[1] is trying to put current envelop in the right place. Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/48160/python-o-nlogn-o-n-solution-beats-97-with-explanation
CC-MAIN-2017-39
en
refinedweb
Welcome to my Javascript page! This has only been around for a little while, so there isn't much here yet. Your browser needs to support at least Javascript 1.0 for most of it, but some parts need your browser to support Javascript 1.2. Click here to see what your browser supports. Scripts that require your browser to support only minimal Javascript (NN2 or higher) have a beside them. beside them. Scripts that use Javascript 1.1 (NN3, IE4 or higher) are shown with a . A few of the scripts utilize Javascript 1.2, which was released with Netscape Communicator 4, and have a beside them. This only works if your browser supports Javascript 1.2 I wrote a quiz engine for multiple choice quizzes. Email me if you want to use it on your site customized with your own questions, etc. Wheel of Fortune I am working on a mini arcade-style game with layers, but it isn't quite presentable yet. DateFormat is a set of JavaScript functions that allow you to "feed" DateFormat a format code and a date object (such as new Date() for the current date or document.lastModified for the current pages last modified date). DateFormat then parses the format code with the date object and returns a string representing the date in the format that was specified. DateFormat is complex enough that it has its own page, right here. The code: function randomBetween(low,high,rounded){ if(rounded) return Math.round((high - low) * Math.random() + 1); return ((high - low) * Math.random() + 1); }; Use: randomBetween(low,high,rounded) Where the random number is between low and high, and rounded is true or false, meaing whether or not the random number is a whole number (rounded). Example: <A HREF="javascript:alert(randomBetween(1,1000,true))">Display a random whole number between 1 and 1000</A> Display a random whole number between 1 and 1000 The code: function numberEnding(num){ if(num >= 4 && num <= 20) { return "th"; } lastDigit = num.toString().charAt(num.toString().length-1); switch(lastDigit) { case "1": return "st"; case "2": return "nd"; case "3": return "rd"; case "0": return "th"; } return "th"; } Use: numberEnding(number) Where number is the number to find an ending for. Example: <SCRIPT> function alertEnding(number){ alert(number + numberEnding(number)); } </SCRIPT> <A HREF="javascript:alertEnding(prompt('Enter any whole number.',''))">Click for example</A> Click for example This form uses mailto, so it may not work with IE! I have a model rocket page too!
http://www.angelfire.com/ca/jscript/
CC-MAIN-2017-39
en
refinedweb
Testing IT Professionals On Job Interviews? 1057 An anonymous reader writes "After having my university degrees, a couple of IT certifications, and over ten years of work experience in the industry, with 2-4 years of verifiable employment with each employer, working with a wide range of technologies,? More importantly, why do IT professionals accept being treated less favorably than members of other professions? Should IT professionals start to refuse to be treated as not real professionals?" No, it is not reasonable. (Score:5, Interesting) I won't take them. I have turned down several jobs over it. Re:No, it is not reasonable. (Score:5, Insightful) If you are going to be that flexible in the interview its probably good for both you and the employer that you aren't working for them ;) Re:No, it is not reasonable. (Score:5, Insightful) That is true. I am interviewing them just as much as they are interviewing me. Life is too short to work someplace where I wont be happy. 99.9% of the time the person doing the interview won't understand the answers anyway. Maybe I am just getting old. Re:No, it is not reasonable. (Score:5, Insightful) If you weren't an Anonymous Coward, I'd mod you up. If you weren't a poster on slashdot, I'd give you a big hug and a wet Bugs Bunny kiss. It breaks my heart to see talented young people walking into a job interview as if they were being called to the principal's office. Re:No, it is not reasonable. (Score:5, Insightful) Re:No, it is not reasonable. (Score:5, Interesting) Right because being burned by incompetence doesn't happen in any other field right? It couldn't be the fact that most companies haven't a clue how to properly manage IT and grasp for any available opportunity to quantify work done and qualify decisions made even if doing so grossly inappropriate. Re:No, it is not reasonable. (Score:5, Insightful) Right because being burned by incompetence doesn't happen in any other field right? Actually it does happen in other fields, the whole premise of this article is wrong. I'm a statistician/epidemiologist and every post I've ever applied for has had some kind of techincal test. Some have been more formal than others. Anyway if I was applying for a post that needed a high level of technical knowledge I would expect to be tested on it. Re:No, it is not reasonable. (Score:5, Insightful)... Re:No, it is not reasonable. (Score:4, Insightful) Giving a "job talk" is fine. When I've interviewed people that's usually what I've focused on... what did you do in your last job, and how did you do it? How well can you explain it? If you can't explain to me how your project worked, or it sounds like BS, that's a pretty clear danger sign. Just because you know the details of some programming language or can write a loop in Perl that doesn't mean you can get the job done. And personally, I have to deal with so many languages in one day that I'm lousy at remembering syntax, or the differences between java io library and C# io library, I have to use cheat sheets that I've built up. Doesn't mean I'm a crappy programmer. Re:No, it is not reasonable. (Score:4, Funny) Correct. And any test that doesn't accept pseudocode is retarded. Re:No, it is not reasonable. (Score:4, Interesting) See,not that kind of questioning I have NO problem with,as that would mean you would have to have a grasp of what was going on and could actually have a conversation with me about it without my having to "dumb down" or try to fill it with techno babble buzz words. Sadly though too many places are leaving such things up to HR people who have NO clue and are only looking for the "buzzword o' the day" and trying to explain anything to them is like trying to take a room full of Pentium 90MHz and run Vista on it. In the end all you do is get a really nice skull thumping headache for your troubles. I mean look at my example. Some HR genius said "Well this test worked for our last opening. We should use it again." even though the test have nothing at all whatever to do with the actual position being filled. See I would have no problem sitting down an discussing computers with someone that knew what they were talking about. In fact the last interview I had like that me and the guy ended up laughing about how much fun it was trying to chase down VxD errors in Win9X and how much fun it was dealing with Pre SP2 XP compared to Win2K. But sadly you are seeing less and less of that,and more and more of "HR says jump through this hoop". Which is why I'll end up going back to school for economics while I make extra cash running my little PC shop. Because clueless tests and BS certs have really started to take the fun out of IT for guys like me that work on computers because we love the technology and learning new things. While my friends play WoW I fire up a VM just to try some weird new OS just to play with its insides and see what it does. Now THAT is fun to me. But as always this is my 02c,YMMV Re:No, it is not reasonable. (Score:5, Insightful) Additionally, they do have to take a test. It's called Bar Exam, CPA certification, etc... These are standardized tests that everyone agrees is robust enough to demonstrate competence. There is no standardized test for IT workers. No, passing MSCE and A+ crap does not count. A+ is somewhat standardized, but honestly there is no IT test that is worth a crap. Arguably some of the Cisco tests are adequate to demonstrate Networking knowledge, but that doesn't mean you are worth a crap when it comes to fixing a broken down Unix machine or even a Windows machine. It also doesn't mean you can build/rebuild a computer. The field of IT is so broad that coming up with a standardized test is not really feasible. The technology field also moves so fast that a standardized test would be outdated by the time it was developed and agreed upon. Since you only have 2 - 4 years of verifiable employment at each company, I would question your abilities as well. 2 - 4 years is just enough to get a job and for the company to find out you are totally incompetent and then fire you. If you had said 6 - 8 years per company, then you might have a case. Re:No, it is not reasonable. (Score:5, Insightful) I remember, in particular, a 2002 ad looking for people with 5 or more years of Windows 2000 server experience. Or the people looking for 10+ years of experience in JAVA in 2003 (which only debuted in 1995. . . do the math. . .) The real problem, is the clueless tyrants in HR. . . Re:No, it is not reasonable. (Score:4, Insightful) Those are fake jobs, used to justify the need to import (cheap) labor, principally from India (as far as IT goes, nurses get hammered by H1B visa's too). They advertise a job, no one applies since the requirements are mathematically impossible to fulfill and the "vacancy" is filled by an H1B. Note: I'm not against immigration, I say if they are really worth it (H1B visa), give them a permanent green card immediately. Make the company pay for it (verification, testing, etc) and make them hold a bond equivalent to a foreign investor visa. That saves the taxpayer, the immigrant who can now freely change jobs w/o need for further sponsorship and the native worker who would otherwise have to compete with non-free labor. H1B's require sponsorship to stay, so they are not free as in freedom workers. Re:No, it is not reasonable. (Score:5, Insightful) Re:No, it is not reasonable. (Score:5, Insightful) The biggest problem I run into when hiring an "IT Professional" is that a good 60% of them either outright lie or hilariously exaggerate about their experience/training. I'd much rather hire a person whose honest about what skills he/she does/doesn't have but demonstrates solid problem solving skills. If you've never administrated a SAN, don't tell me that you have and not expect me to ask a few probing questions.... Referring to yourself as an ESX guru but then not knowing what vmotion is won't win you any friends (or a return interview). As a general rule, before my boss is going to let anybody loose in the server room, expect to spend a couple of hours in a conference room in front of a white board. Expect to be asked about your experience and expect to demonstrate problem solving skills related to those skills. Expect to be given some theoretical problems and be asked to solve them. Also, an answer of "I'd have to check google" is actually okay. Re:No, it is not reasonable. (Score:4, Insightful) It's also an easy way to filter out the bullshitters. About nine years ago I had to help hire for an entry level web programming job. Every asswipe that could spell HTML had 4 years of it on his resume. A test might have saved everyone some pain. And you don't have to look at testing as a punishment. It's just another way to show off your skills. And it can be a valuable insight into the company - a stupid test may warn of PHBs in your future. Besides, I think we would all be better off if all professionals (especially CIOs) were given tests prior employment. Re:No, it is not reasonable. (Score:5, Insightful) Or maybe your company bothering to check references would have saved everyone some pain! Sure. So they have to go through a dozen "references" for every Tom, Dick and Harry who's claimed to make a website. "Yeah, see? I designed that. Yeah, yeah, I designed that one. Oh, and here's a list of ten more rando.. er.. samples of my work!" Takes way too much investigative research to find fakes from reality. It's much, much easier to just give someone a simple test. Here's an example layout, here's content. Do x, y, and z with the content. Make this part dynamic. Would you like a coffee or tea while you work? My final exam for Web Page Authoring in college was essentially like that. Here's a range of data; create a simple database, input the information, make the webpage give me data based on this list of criteria and lay it out in a functional manner. I got delayed because there were no working computers left so I lost the first 30 minutes of a 90 minute exam session but I was still the first one done. If you know the material it'll be a breeze. If you don't you'll flounder around and you won't get the job. Wait - wasn't it a complaint of IT professionals that every jackass with a home computer came into the IT industry and called themselves a pro?!? Since we don't have a trustworthy certification body for the industry wouldn't it be prudent to expect skills tests to assure an employer that you're an actual professional rather than somebody's nephew who, like, really knows computers and stuff? If doctors were that bad, it would be manslaughter (Score:5, Interesting) Re:If doctors were that bad, it would be manslaugh (Score:5, Interesting) I went to a job interview in '99 for a contract doing Network Admin for a pretty major bank; I had no certs, no degree at the time, but I had been working off and on with Tek systems for several years and they knew I had extremely extensive experience. The Bank didn't want to interview me, but the recruiter sort of insisted; they were asking for people qualified in NT, Solaris and OS/2, and I was really about the only person they had available at that time with the right mix. It was a working lunch interview; They started asking questions, and I started answering. then came the question, "what command would you use to upgrade a NT workstation machine to NT server?" I replied that you would probably be best off formatting the drive, then installing it, as there was no good way to upgrade; Microsoft said you couldn't do it at all, and the workarounds were more trouble than they were worth. The interviewers sort of grinned, and told me that of the 20+ people they interviews, all of which had at least a MCSE or a comp sci degree, not a single one of them had answered the question correctly. At the time I had problems believing it, but as time went on and I got in to situations where I was doing interviews it got more believable; in the late 90's if you worked on computers, it was probably because you were a computer enthusiast and actually more or less enjoyed working with them; after about '98, you started running into people that were just doing it because it paid well; they might be damned smart people, but you lose something when you don't actually enjoy working with computers. I also saw a lot of people who just were not smart enough, but were somehow able to cheat or memorize well enough to get a degree; when you asked them something that wasn't in anything they had studied, they didn't have the core of hands-on knowledge that would enable them to make an educated guess at the answer. So, yeah, I have to agree, interview everybody no matter what their credentials are. Re:If doctors were that bad, it would be manslaugh (Score:5, Insightful) In 2001 I worked as a supervisor in a callcenter(by now bankrupt and bought out) that specialized in tech-support for consumer software and hardware. At one point our recruiter asked me to test an applicant she didn't have a good feeling about. The applicant had numerous impressive looking certifications on her resume and quite a confident demeanor about her abilities. She claimed to be specialized in Microsoft operating systems. Note that this was your typical callcenter full of pc enthusiasts, many of whom had no formal education in IT whatsoever. Long story short, at the time we also did support for a company that distributed a number of very popular pc games, so I gave the applicant a game consisting of 3 cd-roms and asked her to install it on a typical win98 workstation. After watching her struggle for about 10 minutes, while completely ignoring the big autorun window with the huge "Install game" button on it, we decided perhaps hiring her would not be such a good idea after all... Re:If doctors were that bad, it would be manslaugh (Score:5, Insightful) FizzBuzz is great; we use it on every single interview for a programming position, regardless of experience. I've seen people come in with 10+ years of programming experience, and completely screw it up. More importantly than just showing whether or not somebody can code, it shows whether or not they can handle simple tasks under pressure. I'm sure most of those applicants could have completed it at home when they're not being watched, but if they can't do it in an interview, then how are they going to perform on-site at a client, when a major bug just popped during a production push? FizzBuzz (Score:5, Funny) CAN HAS STDIO? I HAS A NADA ITZ 0 I HAS A VAR IM IN YR LOOP UP VAR!!1 I HAS A ANZER ITZ "" BOTH SAEM MOD OF VAR AN 3 AN NADA, O RLY? YA RLY ANZER "Fizz" OIC BOTH SAEM MOD OF VAR AN 5 AN NADA, O RLY? YA RLY SMOOSH ANZER AN "Buzz" MKAY OIC BOTH SAEM ANZER AN "", O RLY? YA RLY VISIBLE VAR NO WAI VISIBLE ANZER OIC VISIBLE ":)" BTW DAS A NEWLINE IZ VAR BIGGER THAN 100? KTHXBYE BTW IMMA SO GUNNA GET HIRED! IM OUTTA YR LOOP KTHXBYE Re:If doctors were that bad, it would be manslaugh (Score:5, Informative) Re:If doctors were that bad, it would be manslaugh (Score:4, Funny) Re:If doctors were that bad, it would be manslaugh (Score:4, Funny) I got a job by refusing the test (Score:5, Insightful) 1996, and I'm being interviewed by Chrysler (over the phone, no less, as I was 2000 km away) for a position as a web application designer. The interview is going well, and then the interviewer starts asking a rapid fire sequence of obscure programming trivia questions - things like the arguments to certain system functions, that sort of thing. After about the third or fourth punt (these questions were really obscure), I started to get a little angry, and I told the interviewer that if that particular question ever came up in my code, that it wasn't necessary for me to have the answer memorized. Man pages and paper manuals exist for a reason (this was before the all-knowing Google) and if I really needed to know the answer, I would look it up. In fact, even if I was reasonably confident of the answer, I'd STILL look it up because the time spent looking up the answer and ensuring it was right was very much less than the time spent guessing, getting it wrong, and debugging the error. "Real work" I said "is an open-book test". The next thing she said was "When can you start?" I don't need to have an answer immediately at hand to every question. What I need is to know how to FIND the answer to a question as quickly as possible given the resources at hand. If you want to test me during an interview, I'll look at the test. If it is related to problem solving or general concepts (ie, explain the differences between a "foreach", "while", and "do until" loop) - OK, I'm game. But if it is trivia, I won't play, and I'll explain why. If you insist... I will seek employment elsewhere, because I'm not interested in working for someone who insists on procedure for procedure's sake. DG Re:No, it is not reasonable. (Score:5, Insightful) Please, please people, remember that a job interview is also your chance to evaluate an employer. If there's any aspect of a job interview that makes you feel like you are being disrespected, you can bet that this will be a company that will show you little respect as an employee. Humiliation on a job interview is an excellent indicator of future happiness at that company. If you believe in your skills, if you believe yourself to be valuable, do not be afraid to say "no thanks". The reason many workers feel like they are being treated badly is because they are being treated badly. You are going to be spending the major part of your waking hours at your job. You should be choosing very carefully. Re: (Score:3, Insightful) Umm. Surely being given an opportunity to demonstrate one's skill/flair isn't disrespectful? Don't you want to show off? Re:No, it is not reasonable. (Score:5, Interesting) I sat down and looked at it for maybe 5 minutes. Nobody came out and introduced themselves to me or asked me any questions about myself. I thought, "Is this the sort of place I want to work?", decided the answer was "no", got up and walked out. That was the last I heard of them. That sort of treatment of a potential employee is disrespectful. If they'd interviewed me, decided they liked me and wanted to verify some skills and asked if I would take a test, that would be completely different. On a sort of related note, I had an employer later on who was considering making potential hires take a personality test. He asked us for our feedback and I told him that if he'd asked me to take one before being offered a job, I would refuse. In an interview, I have no idea who these people are, and if they're qualified to read a personality test. Those things in the wrong hands are a weapon to limit you more than anything. If the test says you're below par at problem solving, or people skills, or whatever, prepare to be pigeonholed for the rest of your time there, if you're lucky enough to get the job. I'm not saying they're useless in all cases, but it takes a trained psychologist to correctly asses the results and determine where they can be usefully applied and where they cannot. I think almost any reasonable person reading this discussion would agree that some sort of verification of an interviewee's credentials is a good idea during the interview process. It's how it's done that's up for discussion. Re:No, it is not reasonable. (Score:5, Informative) Surely being given an opportunity to demonstrate one's skill/flair isn't disrespectful? It depends on how it's done. Exactly. I'm in the camp that says some sort of programming test is fair for any level. If you're really a "Senior software engineer" with "excellent $LANGUAGE skills" then writing something like fizzbuzz will only take you two minutes, right? The number of people I've seen come to an interview making that sort of claim who could not code fizzbuzz is scary. Perhaps unsurprisingly, my tolerance for taking this sort of test myself increased significantly when I crossed from being an experienced developer who just found them patronising to having the kind of role that also involves sitting on the other side of the table from time to time and seeing what some of the other candidates are like. On the other hand, I rather doubt I'll ever be working for the kind of place that has a whole-day interview process that consists of solving an endless series of trivial programming problems, followed by a load of "Have you seen this one before?" questions like the 1/2/5/10 problem. These tests are only useful as a block for the low end prankster, not as a way of gauging how good someone competent really is. After the first couple, if it seems like there are going to be more, I will take control of the interview and, usually, end it shortly thereafter. This is a valuable reminder that interviewing is a two-way process, and that those applying for higher positions with more responsibility should be entitled to ask "difficult" questions that any competent employer should have no difficulty answering, too. Just as a significant proportion of interviewees are a joke, so are a significant proportion of interviewers/employers. These days, I'll basically let a prospective employer run the first interview, but if I'm called back for a second interview so I know they are serious, I will ask to see a sample of their production code and a sample of their development documentation, I'll ask straight questions about their software development process, company culture and working conditions, and if I'm still ambivalent perhaps I'll ask to speak privately with a current employee who is doing a similar job to the one I'm applying for. Re:No, it is not reasonable. (Score:4, Insightful) I agree. I had no problems going up to a white board and writing my pseudo code to solve problems. I've also talked about my personal coding style and given detailed summaries of my thesis. I can't understand why you'd object to your potential employer wanting to make sure you'll be adequate for the job before sinking tens of thousands of dollars into hiring you.... If someone refuses, then either they have a really poor attitude (the same kind of person who wouldn't dress nicely for a job interview because "hey, it shouldn't matter"), or you are really trying to snow your way into a job. Comparing it to other industries sounds like my kids whining. You don't need to worry about accounting or the legal offices where you work, you just worry about your IT job. Besides, most certifications in other fields are more worthwhile than something like an MCSE, anyway. Face it, we don't have a good certification for Software Engineer because the subject is too broad to have one... even if you are well schooled on techniques (how to solve a problem), you may not know networking, or UI programming, or 3D graphics, or something specific the company needs, and it's impossible to know everything in this field. Re:No, it is not reasonable. (Score:5, Insightful) It can be annoying, but I hardly think it's that big of a deal. I don't work in IT, I work as a creative in advertising, but I've had to take 'tests' when applying for a job. I'm given a sample brief and asked to come up with a campaign concept. I'm given those tests because agencies work differently with different accoutns and some people are just not good fits from one to another. I would imagine the potential exists for an IT professional with a glowing CV to still be a poor choice in a particular company. At least they're not testing your social skills as well. Re: (Score:3, Interesting) A FLOSS(ed) resume helps avoid them. Work on the free/open source programs that you like, then point your employers at commit diffs (as well as your responses to idiotic questions on the respective mailing lists showing that your tolerant and work well with others). 8/10 times, in my experience .. an employer is just as happy to browse my Mercurial repositories as they are to give me a test. Sometimes, though .. they make the test a little harder after viewing my repos :) When you run into 'head hunters' , th Re:No, it is not reasonable. (Score:5, Interesting) It is entirely reasonable. Having a degree, and even several (perhaps many) years of verifiable / verified "experience" says very little about your actual qualifications. One of the best developers I know has a degree in history, and within 6 months of beginning development was producing better quality work than some guys who have been developing for years. Also the number of people who lie about their qualifications is unbelievable. Many previous employers are afraid of getting into legal trouble and so will never give a real reference, either positive or negative. They'll basically only confirm dates of employment. Finally, this industry is full of really excellent snow job men. People who have convinced their previous employer that they're really a cracker-jack developer, when in fact they are only barely able to cobble together code examples from other people. Also it's not infrequent for several candidates to have what looks like reasonably similar experience on paper, yet differ widely on actual performance skills. Last month, we interviewed a guy for a ColdFusion developer job, and when we asked him what the difference between a Struct and an Array were (one is associatively indexed, and does not preserve insert order, the other is sequentially numerically indexed and of course does preserve insert order - an equivalent to a HashMap and a Vector), he sputtered and stammered for a few seconds, then proceeded to read us search results from Google (we all followed along on our end) which were not an answer to the question ("Let's see, you can append a Struct. Oh, but then you can append an Array"). Some consultant firms make money only for placing a body in a seat. So some of these firms actually falsify resumes and provide references which are also false (they employ the people who answer the phone or respond to the email when you check the reference). They even go so far as to have a handful of guys who do the phone interviews - and these are not the same guy who shows up. Some times the guy who shows up has no experience with the technology at all. Plus, who told you other professions don't get tested? Some jobs even come with personality tests - maybe they're looking for someone hyper aggressive, maybe they're looking for a peace maker. Though such tests are usually for higher up positions, and usually only for the short list of candidates. It's not degrading in the least to be required to take a test to prove your qualifications. If you have the qualifications you profess to have, you should have no problem with the test. It's safeguarding the company at hand, and if you wanted to refuse to take the test, we would want to not hire you. It's a matter of there being too many slime balls and con men out there in the world, we can't take you at your word until we know you. Until then we need to ask you to prove yourself to us. Re:No, it is not reasonable. (Score:5, Funny) What is the difference between an Apple and a Pear?! You have Ten seconds to answer! Go! Re:No, it is not reasonable. (Score:5, Interesting) It's even worse than that: As a computer scientist, I pick up new stuff up quickly. So what that I've been doing Java for the last N years, give me a C project and I'll do it (without memory leaks, I know what a pointer is and can use valgrind --- Oh, and exactly this happened this year and I delivered.). That however, seems to be beyond the comprehension of anyone hiring people. Getting a well rounded computer scientist is better than getting someone who knows the buzzwords and can code a bit in one language. However, I'm sure I'd fail on any Java test or C test. The details (what's usually asked in such tests) do not matter, you'll find them quickly with a Google search because you're trained to know what to search for. Frankly, I don't get it. Re:No, it is not reasonable. (Score:4, Funny) "However, I'm sure I'd fail on any Java test or C test." I thought that, too, but now I'm convinced you'd do okay. I took a test recently for Java (the company insisted, even though Java wasn't on my resume at all, and I relented), and I scored "Master - Can mentor others" even though I've never done anything serious in Java (maybe played around with it a few years ago). For someone who knows C-family languages, the tests are cake. I guess they're only intended to weed out those who truly know nothing at all. Re:No, it is not reasonable. (Score:4, Insightful) I think you're assuming that everyone applying for a programming job is a CS major. Not the case, and this is why you might not understand. IT is a profession where people come from varying backgrounds and have learned the skills they posses through necessity or just desire. I myself hold a B.Arch, but I have been around computers since 1975 and been programming since about 1980. There are plenty of us that aren't CS majors that also pick up things quickly, have the math chops and the experience of coding multiple projects across varying languages and vertical markets. You never know where the good people are going to come from, so, you test. Re:No, it is not reasonable. (Score:5, Funny) Re:No, it is not reasonable. (Score:4, Funny) Even worse, he didn't even see if his code would compile (preview) before checking in (submitting) his work. Tisk tisk tisk. Re:No, it is not reasonable. (Score:5, Funny) So you're saying she'll be an average lawyer? Re:Interview question - universal answer!! (Score:5, Insightful) Interviewer: OK, so you know C? what is the result of i=0; i=i++; Joe Blow: Uhhhh...I....uuhhhh...it's compiler dependent!! Is the correct answer! Without an output statement you'll never know, a compiler could legally optimize the whole lot away! Re:Interview question - universal answer!! (Score:5, Insightful) It doesn't matter if it's compiler-dependent or not. The correct answer to that question is: "This code is badly written. It never makes sense to write i = i++. You probably mean i++." Re:Interview question - universal answer!! (Score:4, Informative) Script started on Mon Sep 15 07:59:50 2008 ./test bash-3.2$ cat test.c #include <stdio.h> int main(void) { int i = 0; i = i++; printf("i = %d\n\n", i); return 0; } bash-3.2$ gcc test.c -o test bash-3.2$ i = 1 bash-3.2$ exit exit Script done on Mon Sep 15 08:00:04 2008 Re:Interview question - universal answer!! (Score:5, Informative) Why not get the compiler to do the work for you: $ gcc -o test -Wall -W -ansi -pedantic test.c test.c: In function `main': test.c:5: warning: operation on `i' may be undefined $ Lo and behold. It's undefined behaviour. $ i = 0 $ And look. I don't get the same results as you. (Probably depends on the precise version of gcc and also maybe the optimizations selected.) Tim.. Re. No, its not. However, the craft of coding can be tested in an interview. Software engineering mostly cant (because it includes strategic and long termn decisions). There is not much craft in "most other fields" - they depend more on virtues like thoroughness etc. - which cant be tested in an interview. Skills can be tested in an interview, virtues less so. Re: (Score:3, Interesting) It is true that it is difficult for an employer to tell a good employee from a bad employee. Sadly, this has lead to what I can only call "hiring voodoo" -- the irrational belief without evidence that a relatively untrained interviewer will mysteriously be able to find out more about "what a candidate is really like" in an hour than the candidate's university or co-workers (references) found out in several years. Even stranger beliefs have cropped up over the years -- eg that artificial toy questions lik Re:Blame it on the idiots who can sell themselves (Score:5, Interesting) Wrong. It is only that incompetence in IT is much harder to cover up than in those professions. When IT systems fail, they can fail spectacularly and effect wide numbers of people. An incompetent IT persons mistake will cause an essential server or the like to fail. If they're not competent to fix it promptly, it will show. Inversely, when a lawyer, accountant, sales, HR person, etc screws up, the screw up will not be noticed as much unless it reaches epic proportions. It's easier to mask a mistake in these fields, and with the softer ones, e.g. PR, their metrics are so fuzzy that the difference between competence and incompetence is blurry anyway. Plus they are trained in buzz speak which they blurt out like a frighted squid spurts out ink to mask their escape. Re:Blame it on the idiots who can sell themselves (Score:5, Informative) I have used "effect" as both a noun and a verb for the majority of my life, in both the written and spoken word. "to effect" is a verb. The only problem is that it is synonymous to "to cause", and not to "to impact". "The effects of an earthquake can effect large numbers of people." Which, when replacing "to effect" with its synonym, becomes: "The effects of an earthquake can cause large numbers of people." Yes, I assume that after an earthquake, there's not much else to do until the electricity comes back on. The "correct" form however, offers no justification for itself other than its own inertia. The "correct" form offers the justification that it has a completely different meaning than the incorrect one. That should be sufficient. Let me give an example (Score:5, Interesting) 1. Yep. Let me even give an example. It didn't happen in a team I was in, but I know several people from that team. So they got a new guy who had some outstanding experience, according to his resume. He had worked on major enterprise projects, been an architect, ate Enterprise Java Beans for breakfast, etc. Turns out he was utterly incompetent. He spent about a month just getting used to their architecture and IDE and everything, apparently everything they did or the way they did it was new to him, and he needed some time to accomodate. Fair enough. Then started working on something, but never was quite done with it. Eventually they started asking to see some results. He started randomly changing files and checking them back in. The first few times he even had a good excuse, like "oops, I hadn't worked with this particular versioning system before" or "oops, I forgot some other file that mine depends on." There go a few more weeks, before it's obvious that his changes can't possibly even compile, because they have elementary syntax errors. Eventually they fire him, but by now he's got several months of "experience" there. Then someone finds his updated resume online. The guy claimed he singlehandedly improved their architecture, increase performance X times, got project management back on track, etc. 2. 'Nother example, my ex-coworker Wally. Spent two years on a trivial module, whose core someone else rewrote from scratch in 6 hours. It took another two weeks or so, mostly of testing, to get it bug-for-bug compatible with his, since a couple of teams already had their own workarounds for them. (Trying to get him to fix it was a bit like negotiating with the terrorists.) The rewrite was also benchmarked as 40 times faster than Wally's on large data sets. Literally. Measured. The thing everyone remembers fondly about him, is how he asked for 2 weeks just to estimate the effort to fix a trivial bug. He got it too. (His team leader was a bit a Mr Testicle: technically he was involved, but he kept out of it as much as possible;) He also massively practiced obfuscation. Any of his modules contained half the techniques from How To Write Unmaintainable Java code (literally) and megabytes of files copied from unrelated stuff to pad the number of lines of code per day. Obviously, it worked on his team leader. Then he got moved through the maintenance of two other programs (one at a time), and just managed to make them both worse. There we go, that's his provable 2-4 years employment. Well, ok, 5 in his case. 3. Example number 3: Old Father Williams. I got to think of him that way after a particular fortune on my linux box: Pretty much spent 6 years in a place complaining about everything that everyone else did. Coding style, IDE, OS, _everything_. His first choice of a whine was Windows, which might even have had a point, but when Linux was finally allowed and half the team switched to Linux, plus the servers actually went Linux... he proclaimed Linux to be sell-out crap for idiots, and switched to preaching BSD. He also caused a reformat-and-commit war in which he was preaching _three_ space tabs, as spaces. And wasn't affraid to check out someone else's project and reformat it, to make his point. He spent two years, just "modernizing" the build process. Nobody knows what he experimented with on his c Re:Let me give an example (Score:5, Interesting) 4. Abdul, the apprentice of Wally. He got hired through a workaround, since hiring more coders was on hold at that corporation. So someone hired him as a web designer, then hastily dubbed him programmer. Ironically, he seemed actually decent at web design. As a programmer, the consensus is that he's too stupid to piss holes in snow. Seriously, he doesn't understand even the elementary basics, and is constantly on the look out for someone to pass solving anything onto. Has that job for some 4 years now, since firing him would face the same problem with hiring a replacement. So he's keeping his job by sheer virtue of being marginally better than nothing. Companies are really bad at dealing with this. I was in a company who gave a web developer a shot at a trainee programming position. She was an excellent web designer, but a really poor programmer. I was her team leader, so I asked her if she was happy with her new position, and she said "no, I just don't seem to think that way. It is difficult and seems to be quite tedious". I asked her if she would like to move back to her old position, and she said yes. I thought this would be no problem, as we were noticing that the look & feel of the public site was not as polished since she left that group. I hadn't counted on HR. "you can't go from a trainee programmer to a senior web developer, that's two level's difference. She will have to move sideways to trainee web developer" They said. I pointed out her experience, the fact that she had done the job before and had excellent reviews but it was to no avail. They made a "concession" that she could move to "web developer" with a promise of promotion to "senior web developer" with in a year "if she performed OK", but anything else would contravene the HR procedures manual! We lost her. I don't blame her, she took a senior position in a small web company. Career wise this has been a good move for her, the company has done well and she is now in charge of a department. It was our loss though, sometimes the company is so stupid. Re:Blame it on the idiots who can sell themselves (Score:5, Insightful) Man you guys who think this is an IT only thing, really need to get out and look around. Yes you can't test for everything, but you can get a decent feel if if the person has some competency with the code for a programmer. I've seen mechanical engineers asked to design a solution to a problem. I've seen drafters/designers given tests with the software they use. Welders get tested before being hired. Divers get tested before being hired. I don't understand what the big problem is. Programmers write code and can at least be tested on their ability to write code. Maybe they can't engineer a program, but at least they can weed out the idiots just selling themselves. What are you going to test an accountant on? Can you add 2+2? Seriously, accounting has a lot of rules, but it's quite honestly easy, boring as fuck, but easy. How are you going to test your attorney? How are you going to test an HR or sales person? This is why a lot of jobs usually have a 30/60/90 day trial/probation period. Re:Blame it on the idiots who can sell themselves (Score:5, Informative) And it is so hard for your references to know if you're really any good or not because unless you're in a large technical group a lot of them wouldn't really know what it is that you actually do, or how to tell if you do it well. Most companies won't provide a reference other than "Person X worked for us from (date) to (date)." It's just too easy to say something which could be misconstrued as being negative and used to sue the company which issued the reference. because you never know (Score:5, Insightful) because you (the employer in this case) never know. a person can work in various places, have diplomas... and still be unbelievably stupid. i'd argue that other professions should gain some tests (i know a lot of them actually do, though those tests usually involve more generic skillset, like being able to work in a stressful conditions or under external noise, ability to quickly analyse particular information of the field etc). Re:because you never know (Score:4, Interesting) My experience is that the majority of employers and the majority of employees are equally stupid and deserve each other. If you're at an interview and they seem retarded then you probably want to move on. Anyway, a person can pass the kind of stupid tests given at interviews and still be a retard. I wouldnt't give such stupid tests to people I hire and wouldn't submit to such a test. The best thing an employer can look for is a portfolio. Look the work over, ask questions about the work, double check that it isn't just stolen from some open source project. If their work is good, even if unrelated to what you're doing, then they'll be good. If not, or if they lack a portfolio, then toss them. If you're going to claim to know Java then write a program in Java and put it in your portfolio. If you're going to claim to know Linux then write some tools to make managing a Linux server easier and show you know common command-line programs and config files. Do that sort of thing and then employers can know what you know. Measurability (Score:5, Insightful) A simple answer is that IT knowledge is a more quantitatively measurable than many other professions. Another factor is the high percentage of self-learned IT professionals. You don't see any "self-learned" lawyers, but self-learned IT pros are commonplace. Lawyers have been tested previously (bar exam) while the IT pro may never have passed any formal testing. Re: (Score:3, Informative) Re:Measurability (Score:5, Informative) Re: (Score:3, Informative) Another factor is that having a degree or certification in IT, or ven ten years of job experience, doesn't actually mean that you know anything. There is no easy way to judge an IT job candidate on paper. Tests are a poor method also though - better to look at a portfolio and ask the right questions about the work in the portfolio. Re: (Score:3, Interesting) BTW, I prefer self learners as programmers (read: coders) over people with degrees. My experience is that they are more dedicated and know more about real world problems. That's simply because a CS degree is not focused on making you a programmer but a more general problem solver. So when you want a coder you have to check what he really knows, not what diplomas he's having (that only gives a hint). Story is completely different if you're looking for someone higher up the food chain, of course. Possibly to weed out the fakers? (Score:5, Insightful) When I've been holding interviews, I always make up a set of tests just to make sure what they put on their CV is accurate. The number of times I've had someone put on their CV they can do something we are after, but in reality they know Sh*t about it, has only really come out when they do the test. It also helps to pick up those who are good at taking exams but don't know how to handle themselves in the real world. Unlike the other professions, IT doesn't have a legal backing. i.e. lawyers and accountants have qualifications that are backed by some law or another so if they write bullshit on their CV then it can come back on them. Not with IT unfortunately. Re: (Score:3, Insightful) Are you sure a bout that? Seems to me you are just presenting another exam to them, which by your own definition, they know how to handle. Re: (Score:3, Informative) Are you sure a bout that? Seems to me you are just presenting another exam to them, which by your own definition, they know how to handle. Not quite. With the exams, they have resources available to give them the answers (i.e. textbooks, MCSE Cram's etc), but with a test within the interview, they won't necessarily know the answer until they see the test. The tests I use are more real world as they are usually based on a problem I have had within the previous couple of weeks, not something they would get from a text book but something they would know from experience. Re:Possibly to weed out the fakers? (Score:5, Interesting) Not quite, at school you can guess quite well what the questions will be, so with a bit of 'educated guesswork' you can pass any exam without really knowing 'everything', let alone 'understanding' it. Heck, you spend over 10 years learning to 'work' the system, it's no surprise one gets good at it. When we hire people we try to prune out those that either simply wrote the right words on their CV and/or those that worked their way through education purely based on the above way. Not because we think they 'cheated', but because we are looking for people to help us with a certain task that involves certain skills. (This is for development job, I'm not sure how the Sales department does it's selection =) It's amazing how often people will write to be 'very good' at eg. SQL while all they know is that it stands for "Structured Query Language". When asked to write a query 'out of thin air' to get the most recent date from a simple agenda-like-table and they are unable to come up with ANYTHING, then we both know where are wasting each others time. Before we tested people, we got burned once too often by people who bluffed themselves into the company but turned out to be more of a burden than a helping hand =( By introducing simple tests we now only waste time at the interview level, we don't have to put time into educating them something they claim to be expert in already. That said, we sometimes DO hire people who /fail/ the test, simply because they show potential and we ARE willing to put time & effort in them. You'll find though that this will is a lot less present when the candidate's CV turns out to be 90%+ 'vapoorware'. Re:Possibly to weed out the fakers? (Score:4, Interesting) CV: Two Years Oracle Database Experience Real life: I wrote some hibernate code that ran against an Oracle database. CV: Experience of XML and XSLT Real life: I configured tomcat, that's XML. XSLT? Isn't that the same thing? CV: 5 years. Java, C and Python. Real life: I wrote some C five years ago and changed it again recently. (his Java experience was fine). I edited a python program once when the input format changed, no I really couldn't write anything from scratch. One of these actually got the Job, because he apologised for his CV and then gave a real account of what he knew that matched our tests. He said the agency put all that rubbish in after he filled in a check-box questionnaire! The why... (Score:5, Funny) Because unlike Accountants, Lawyers, etc we actually have to work for a living... If we're bad then stuff just doesn't get done. If an accountant is bad they still get $100k a year. Doctors still have to prove themselves multiple times just to be able to get into the interview. Years and training and testing. I like to think of us more like Doctors than professional bureaucrats. The underlying assumption is not true (Score:5, Interesting) thus the whole question is futile. Skill assessment is done in almost all kinds of professional employment situations . yet it depends mostly on the hiring policy of the department of that particular firm if there will be an assessment. And quite franky, I think there is a good reason why this is done with IT jobs more often: analytic and associative thinking and problem solving are not skills you can learn. Plus, IT jobbers tend to be more annoyed by moron colleagues than non-IT employees. And lets not forget that there is a huge amount of moronness out there - I myself did Job interviews with certified whatevers, who applied for a sysadmin position and couldn't tell me what information a notation like "192.168.38.1/24" provides. And thats just the very basic for such a job, but it already weeded out two thirds of the applicants, *completely unrelated* to their educational history or other certified qualifications. And last but not least, it always depends on the quality of the respective management if such an evaluation is done: and speaking for me and my experience, a company should do it in *all* sorts of positions, no matter how professional, experienced and well educated an applicant is. Re:The underlying assumption is not true (Score:5, Insightful) As long as you're tested by a human who understands the very background for the questions asked, tests are good. However, that's not what happens out there. The hiring companies have multiple-choice tests that are evaluated by a system, and the humans administering the test don't understand it. And more to the point, the people who made the tests didn't understand the questions either, but looked them up in a book. So very many of the questions are based on semantics and finding the exact phrase a certain text book used for a situation, instead of testing the understanding. In your example, the typical test that's being used would likely have asked: In 192.168.38.1/24, what does "/24" mean? 1 [ ] Subnet mask 2 [ ] CIDR 3 [ ] C Class network 4 [ ] Shorthand for 0.255.255.255 in IOS 10 or newer Of these, only one will be accepted. And more likely than not, the wrong one. I flunked one of these tests on DNS knowledge. Despite having written a DNS server, and installing and running multiple ISPs' DNS servers. Thousands of domains, including split internal/external, IPv6 and secure updating from DHCP. I can query a DNS using UDP from the command line, without requiring "host", "nslookup" or other specialized tools. I can write BIND zone files from scratch if I have to. I know DNS, dammit -- better than most sysadmins out there. The reason I failed (well, scored less than 50%, which I call failed) was that I couldn't answer questions like "Approximately, how many DNS servers are operating world wide?", "Does an active domain controller resolve DNS queries?", "What is the command for looking up your current WINS server?" and "Which Windows versions support running without netbios?". Apparently the test maker had looked up some questions in some DNS for Windows Dummies type book, and thought that was what it was all about. Not a single question reflected real DNS knowledge. Other tests ask you questions that you don't bother to remember, because it's so easy to look it up. Like parameters to commands. /path /path /path /path How do you list the size of a file system in 4k blocks in Unix? 1 [ ] df -b 4096 2 [ ] df -B 4096 3 [ ] df -s 4096 4 [ ] df -s 4k Only those who don't know what they're doing have to remember these things. The rest of us would try "--help", "-h" or look at the man page to check command syntax, and not bother to remember little used options. Only those with a need to memorize everything because they can't figure out how to look up things would know this. Or those who by chance happened to do this yesterday. As is, the tests are not very useful. They might weed out some of those that know absolutely nothing about a subject, but they also weed out those who understand the subject better than the test author, but don't bother remembering irrelevant or OS-specific details. Careful there.. (Score:4, Insightful) The "professional" bs is just a way to put you on salary rather than an hourly wage. While "professional" sounds nice, there are only a few real professions. A nice law passed a few years back reclassified several technical fields as professional, allowing employers to really screw their employees by changing their pay to salary from hourly. Re:Careful there.. (Score:5, Funny) As a consultant, I consider myself part of the world's oldest profession. After all: I charge an extortionate rate I'll be whatever you want me to be I spend a lot of time in hotel rooms I have a pimp that gives me a fraction of what I make and sends me to do things that I really don't want to do Credibility of professional qualifications (Score:4, Interesting) Better environment? (Score:5, Insightful) Mopping up after some idiot with "university degrees, a couple of IT certifications, and over ten years of work experience in the industry, with 2-4 years of verifiable employment with each employer, working with a wide range of technologies" that's a total clueless retard isn't my idea of fun and rewarding employment. why not (Score:5, Insightful) The reason it's done is a combination of great variability in skill among IT applicants, compared to professions with time-tested accreditation bodies like lawyers and accountants, and skills that are fairly amenable to formal testing, compared to professions like sales and HR, at least with respect to weeding out duds (if someone can't write a simple program in an afternoon, given a language reference, they should not be hired). More generally, I can't imagine why it's unreasonable for an employer to test skill. Competent IT professionals accept it because it's in fact beneficial to them to be distinguished from their less competent peers. (If the test itself is poor, they complain about that, and don't whine about the indignity of taking a test in general.) Paternalism is forcing someone to do something for their own good. This is not. I can assure of I have no intention of refusing tests of skill when applying for jobs. Employment history, certifications, and degrees do not ensure competence. Probably most of the people on The Daily WTF [thedailywtf.com] passed such basic screening. Why not take a test? (Score:5, Insightful) I frequently interview programmers, and having them take a short test (approx 30 minutes) and then discussing this with them in their interview is incredibly useful to determine their skillset. I could ask similar questions directly and have them work through the answers on a board, but then they would be under pressure to provide an answer on the spot to questions that probably deserve some thought before providing a solution. None of the questions on the test are unduly taxing - any person we interview who has a few years professional c++ experience under their belt should be able to provide at least a working solution, with potential better solutions open to discussion face to face. I've had 15 years doing what I do, and I'd be happy to take a test if asked - if I can't pass whatever hurdle the company sets, then I'd rather not sit there for a few more hours trying to win them over with my sparkling personality, and if the test is a pile of rubbish I know early on that I probably don't want to work there. Where's IT's "Professional Body"? (Score:4, Insightful) Accountants and Lawyers have professional bodies (or whatever it is called) that tests candidates wanting to call themselves "accountant" and "lawyer", so do doctors, nurses, engineers, etc, so employers don't need to test the candidates themselves when they want to hire one. if people call themselves "lawyer" or "accountant" without the proper certification, they could be jailed. Which is the corresponding organization that tested and certified you as an "IT professional"? Can your employer file complaints to that organization and have your certification removed if you displayed incompetence or is negligent in your job? And would anyone risk jail time if they call themselves "IT Professional" without any such certification? Don't kid yourself, an IT worker is hardly any more "professional" than a secretary or a salesman. Anyone sitting in front of a monitor for the past 10 years can call himself an "IT Professional" with 10 years of experience. Heck, someone who had NOT been sitting in front of a monitor for the past 10 years can also do so! Until we have a widely recognized professional body to certify us (and to de-certify or penalize us if we display incompetence), it is the employers' responsibility to assess our capability and testing us is one way to do it. I am sure many working in the field would prefer their employers had properly tested themselves and their co-workers, rather than having to fix up problems caused by other less-than-competent "IT Professionals". Re: (Score:3, Insightful) I'm looking to join the BCS in the next couple of weeks as I'm unhappy with the lack of professionalism in the IT industry. Unfortunately I will be the only one in a department of 20 people to care. The situation isn't likely to improve until it becomes sought after in interviews. My wife is in HR and they need to be CIPD qualified to progress in their career. Hopefully the problem with IT is due to the immaturity of the industry and that things will improve in time. Because so few know how to conduct interviews (Score:5, Insightful) In my experience, which ia way more than your 10 years, very few folks in IT actually know how to interview and what traits to look for. Being tech folks and not having people skills, they think that some test will tell them what they need to know about a potential applicant. Not true. A lot of the tests are language lawyer things (knowing about public static final in Java) which doesn't get to what they really need to know. There are lots of folks who know the language lawyer tricks that will be lousy employees. You need folks that are bright, have a demonstrated track record of being able to learn new things and that will fit with your culture/environment. Others are tested (Score:3, Insightful) There are two obvious reasons why people get tested in IT 1) People might have passed exams, but can they actually code 2) People might have been on a project where technology X was used, but did they use it? The first is the case where you have a graduate with a degree in computing and it turns out they did all the "soft" options. So lots of theory but not practice and they don't even know what a compiler is. The second is the case where you are looking for people with a given skill (say Java) and you want to check that they have that skill. Its not true to say that other people don't have to sit tests, its just that a lot of the time those tests aren't written tests but are more open, indeed I prefer to test people using such open assignments. Set them a problem (design a system to do X) and then have them respond. This is exactly the same way that lawyers are often tested by their new chambers, they have to defend (or prosecute) a given perspective to show how they would perform and lay out their approach of constructing the case. The point is that for most jobs they are "soft" jobs where a specific exam makes no sense once you have the qualification and therefore you do soft interview tests. In IT however we have lots of "hard" jobs where a specific skill is required and a specific level of performance is required. This isn't about professional v unprofessional its about the nature of an industry where there are millions of different technologies arriving every year and where the average ability level has been plunging for the last 20 years. So get off your high horse and stop complaining. You are in an industry that changes, that means that the degree you did gives you a theoretical basis (hopefully) but your practical skills will need to be evolved. I did Ada, LISP, 68k and Prolog at University. Guess what? My first job meant I had to learn C in 1 week to prove I knew it and my 3rd job was the last one where I used any of those languages (I'm now on my 7th job). So did I mind being tested to prove I knew C/Java/XML/MQSeries/etc? No I didn't. Do I test people to prove they really have the skills they say? You bet, I wouldn't trust an IT CV statement further than I'd trust Dick Cheney at a bird shoot. All interviews test in any areas where its worth having a job. IT interviews test more because IT changes more and your qualifications become out of date more quickly. Now for the real question though: Why isn't there a written test for high office, especially a geography test for US Presidents and VPs. I think it's a good thing (Score:3, Interesting) A CV can be read in many ways. I think that testing is a good way to see that the skills, CV and open position match. That being said, testing can be done in many ways. Someone recommended me to Google once, and the Google HR department obviously read my CV looking for the skills they were after. While I had them to a degree, that was only part of the truth. A later phone interview with one of their engineers clarified the situation a lot: He tested my skill set with a bunch of oral test questions that made it obvious to both that my skills were of the right sort but at the wrong layer of abstraction. (Scripting vs. assembly-level knowledge.) That test saved both parties a lot of time. But like I said, there is good testing and bad testing. Often tests test passive knowledge, but not problem solving skills. Unfortunately the hardest to quantify stuff is also the most essential in terms of actual productivity. Re:Good Testing == Getting Paid. (Score:4, Funny) Thank you, NEXT! Re:Good Testing == Getting Paid. (Score:4, Interesting) I didn't get the job, but found out several weeks later that they implemented my exact solution, as the guy they hired for the job EMAILED ME WITH QUESTIONS and quoted the entire email. I submitted it to their billing department at my standard consulting rate and minimum bill, with a note attached that since there was prima facie evidence that they were using my solution. . .it was pay or go to court. The check arrived via FedEx the next morning . . . "Professionals"? (Score:4, Insightful) This type of test is fairly commonplace in certain engineering fields, and should be. Specific technical knowledge, trivial to test for, are much more important and much simpler to test for in engineers and technicians than they are in professional workers. If you can easily and efficiently test the skill level and prior training given a technical worker, for whom training is often quite area-specific and expensive, why on earth wouldn't you? This isn't paternalism, and is not a show of disrespect. I, for one, will neither stop giving nor refuse to take this sort of interview. The suggestion that we should seems ludicrous to me. On a related note, just exactly what did you think a traditional business interview is designed to do? They are little more than a version of the skills tests that you're complaining about, but designed to measure the aptitude of managers and the like. They are more open-ended in nature, but not because those job candidates are somehow worthy of more respect. The questions are more subjective because the topics at hand are far more difficult to objectively measure than technical knowledge. Furthermore, you must also consider those organizations (especially within the government) that subject teachers, managers, lawyers, policy experts, etc. to standardized testing of some sort prior to hiring them. To be honest you sound like an arse (Score:3, Insightful) If you are the sort of person who is won't put up with a simple test, which seems to me to be quite a reasonable request (where you seem to think it is all "how dare you question my magnificence), you certainly aren't the sort of person I want to employ. I don't want someone who is not willing to pitch in with whatever is needed. In this case, I think the test has provided a useful function. Too many morons in IT. (Score:4, Interesting) Sadly, a lot of the "IT Professionals" I encounter are plain idiots. Even in-depth interviews can't guarantee that you have someone capable in front of you, but it does filter out those idiots. I work for a small (5 ppl) IT-only company and when we hire someone, while he will get some basic training, he is supposed to work pretty independantly. But once in such a position you can pretend doing a lot while doing almost nothing, and still make things appear to 'work'. You'd be amazed what an incompetent guy can pretend to be and produce results that on the first glance seem to be OK. And then when his software goes into production you suddenly notice that he didn't use an XML parser, but expected certain data on certain lines and filtered it out using regular expressions - and NO, not using the standard regular expression library - but doing something like this in C: sprintf(cmdbuf, "/usr/bash /bin/sed -e \"s/%s//\" > /tmp/filename", inputbuffer); ... system(cmdbuf); fp = fopen("/tmp/filename", "r"); You get the picture. He btw didn't even write a function to do this, but copy-pasted stuff like this a few 100 times... Software worked in test, client changed 1 insignificant thing in their XML generation (added a tag we didn't use), and our entire system went down. I ended up rewriting this guy's stuff after he was fired. And that's the main problem with IT jobs, you only notice they're incompetent when things start to go wrong. And then it's too late. So if I have to interview someone for an IT position, I want to be as sure as possible we don't end up in such a situation again. Masking incompetence in an IT position is just too easy. Re:Too many morons in IT. (Score:5, Insightful) Standard of "professionalism" is lower in IT (Score:5, Insightful) I speak as a member of "IT" as well, so I'm accusing myself here too, fairly and squarely. I don't know (nor care) about the non-technical professions, but the standard of professionalism in Computing is a lot lower than in Engineering. I can say that with confidence after a long career spanning both Electrical/Electronic Engineering and Computer Science, both in academia (PhD, postdoc, lecturer) and in industry. It took me the better part of a decade in the computing industry to realize that I had been (unwittingly) deluding my Software Engineering students when I taught them "Do it like this, or you will be laughed at as amateurs when you get out into industry." The sad fact is that 98% of computing in industry is utterly amateurish, as I eventually discovered for myself. Even huge, "properly" managed projects are in practice just hacks like all the rest, but with better documentation and QA/testing. While computing is my current love, and bread provider, I recognize that we're at the stage of gazing at chicken entrails in this discipline. It's a bit sad, although I still love it. But when they say "Bridges would fall down every other day if they were built like we build software", they are 100% right. Looking at it from the perspective of my old engineering days, it's a bit distressing, but that's how it is. We're still in the early days of Computing, and to call it a professional discipline is stretching the definition rather severely. Michael Chermside (Score:4, Insightful) I don't know about you, but I would RATHER be tested during an interview. It would increase the chance that I would wind up working with competent co-workers. Michael Chermside [mcherm.com] ...because there are so many incompentent ones (Score:4, Insightful) You'd rather your company didn't test them...? (Score:5, Funny) How 'bout we start employing people based on what they claim, not what they can do? Sounds good to me. Tests help weed people out (Score:4, Informative) IT field is so wide and diverse with many people coming to it's ranks without any "true" background. I have a degree in Textiles. I manage and maintain a wide assortment of applications, servers, databases, email systems etc. I actually laughed at a lady on the phone a long time ago during an interview, who said that they were only looking for MCSE's. When I laughed she seemed so surprised and asked me why? I told her "You do understand that you can get one of those in 2 weeks offline right now right?". People have become so dependent on "certifications" that they don't actually test those individuals skills. I don't limit it to IT either. The same thing applies to MBA's. I wound up being involved in a round table interview (2+ applicants at the same time) and everyone but me had a certification. When asked what the difference between mirroring and clustering in databases was one of the answers was (I joke you not) something oracle can only do. Additionally, I find that now, most companies don't truly involve their IT groups in the hiring process. They ask for "specs" for a job and then try to match them up. This doesn't work in reality. It might with a secretary, or blockbuster video clerk... but not in IT. IT skills are quantifiable. There's no "bullshit" answer. There are several different levels of gray but if you ask a programmer what Model View Controller or what a framework is... there's no bs answer that isn't wrong. When I create questions for a prospective employee I'm not trying to ramrod them. I ask only questions that I believe they should know 100%. For example, a ColdFusion programmer position is about to be placed here are some of the questions I plan to ask. I don't necessarily believe they need to know how to do all of them, but they MUST know what they are. This position will be updating a slew of applications written in ColdFusion 5 and fixing about 30 databases that were converted from Access to MSSQL and 99% of the fields are NVARCHAR. 1) What is SQL injection and what built in features of coldfusion protect applications from it? .cfm and a .cfc? ... 2) Write an inner join query? 3) Whats the difference between a 4) What is an SVN repository? 5) What is the datatype NVARCHAR used for? 6) You get the idea. However, my reasoning for asking these questions isn't just for the answers! 1) How well did they answer the questions? Enunciation, quickness to respond, accuracy in describing solutions 2) What is their personality like when pressured? 3) When they don't know an answer how do they respond. This is a big one for me. I expect you to say that you don't know. Bonus points for you writing it down and emailing me the answer later. This lets me know you didn't forget, and that you are trying to improve yourself. A lot of times I'll throw in a question I KNOW they shouldn't know just to trip them up. I want to see how people react under pressure. We have 125 employees all depending on these applications for our business functions. If something screws up I need them to be quick, calm and attentive to the problem. Imagine this on a much larger scale, like 10,000, or 100,000. Businesses need to depend on these employees. So, tests are necessary and frankly I'd like to see them in more positions. Better qualifiying (Score:4, Insightful) *After* earning their actual degree, Lawyers have to pass the gruelling bar exam. Doctors have to do the medical board exams and a guelling internship. Engineers have to get their certifications. IT graduates, just have to carry their piece of paper home. Sure you can get your Microsoft and other vendor-sponsored certifications, but these are generally jokes-marketing tools. At the very best they qualify you for some specific experience with some specific products, and don't thoroughly test your general IT skills. I've seen Cisco certified engineers leave me with bottlenecks due to looping routes, and generally trashed my network. I've seen MSCE's that are totally useless. It always strikes me odd, that an engineer building anything has to build to standards, which are externally verified and permits obtained through inspections, etc.. Software engineers and IT staff can implement mission-critical systems without any standards or oversight. I know the software/computer hardware world makes things so incredibly flexible that it'd be hard to defines standards to regulate against; that's likely the problem. (If I want a bridge, everyone can pretty much agree upon what is wanted, a copy of something that has been done before, and approved, standardized. Not so much for a new application. For IT infrustructures, a case could be made for more standardization, I guess.) But this flexibility it also results in some pretty horrible work being done out there. Also, the standards in other fields allow for greater accountability. If an engineer, Doctor, lawyer, is incompetent and not providing the standard of care their industry demands, you can sue them for such. (I'm likely to sue my former lawyer for incompetence and ignorance of the law and my case.) But try suing a software engineer or IT person. There's just no clear standards of competence with which to judge him or her. Having tests to weed through some bad ones, makes sense, and I see why it comes about. It's not perfect, but it tries to address a shortcoming in our field. Professional certification (Score:4, Interesting) "Why are IT professionals treated differently and in such a paternalistic way? More importantly, why do IT professionals accept being treated less favorably than members of other professions? Should IT professionals start to refuse to be treated as not real professionals?" Others have already pointed out that lawyers and accountants (CPAs at least) submit to testing and are certified by professional organizations. You can't market yourself as a lawyer, CPA, or even an engineer in some places without having the backing of a professional guild. What I'd like to know is why, in the face of offshoring and job losses, the IT industry hasn't coelesced around a professional society or guild. A professional guild, with some rigid certification testing, would be more effective than even unionizing since it produces a win-win for both employees and employers. Is it just that the need isn't perceived to be there yet? With professional certification, employers would know they are getting skills without expensive testing and competent IT professionals can be assured that they won't be working with "IT Professionals" whose sole IT experience is that they took one Visual Basic course. There are lots of vendor specific certs (MS, Novell, Oracle, IBM) but to me, that's more akin testing accountants for having skill in using QuickBooks. The Open Group has IT Architect certification () which looks to be a start, but it doesn't appear to have gained much momentum. IBM offers cross-certification of its internally certified architects but even within IBM, not all departments bother to pay the fee for TOG certification. I also see that there's an Institute for Certification of Computer Professionals () that's been around since 1973, and a lot of people on its web page have important looking letters next to their names (CCP, CDMP) but outside of this web page, I've never run across an IT person with this on their business card nor a company that insists on this certification. So I ask the exact opposite question that the poster asks, "Why don't we insist on recognized industry certification testing for IT professionals?" JoAnn IT workers are not professionals (Score:4, Insightful) Lawyers, accountants, etc ARE professionals, they are regulated by professional organizations and have to prove their qualifications in order to be licensed to practice. IT workers have no such regulation. In effect the State tests your lawyer for you. I agree the tests for programmers are almost universally stupid and worthless, but if it makes some PHB someplace happy, who cares? My company uses an essay question, doesn't work (Score:4, Interesting) Then, as part of the interview process, we have a few questions we ask you to write essays for. One is based on design of a product we already built, one is based on design of a product we're currently building, and third... Is actually a riddle. My project manager came up with this idea, his thinking is "Let's see what kind of inductive/deductive reasoning this guy will use". Sounds like a good idea. Turns out? All this crap is worthless. Case in point... We have a guy fresh out of college (no experience in the trenches) who we interview, and later get hired. His code is quite beautiful at a glance (not breaking down every line to profile it or anything), plenty of comments, nice style, etc. His essays are OK, they're passable. But, he sits down, and we've got -multitude- problems. Let's start with one example: We're web developers, and in the first couple weeks, he needed to modify UI. In this case, he needed to use a few images for something. What kind of images did he put into our repo for versioning? BITMAPS! No, no, not a proper raster file-types like a PNG or a JPG, a bitmap -- BMP. Just cause Professor Dinglethorpe requires you to comment and indent your code properly doesn't mean you have a clue what really happens when you get down to production. But, the real problem? COMMUNICATION! The kid just can't freakin' communicate with us. If he were bad AND would take the time to talk to us about what he's working on, we could stand it. We'd know what was happening when he did jacked up stuff in the code, and we later have to maintain his mess. However, he doesn't take time to communicate with anyone. He's too busy leaving important meetings to take phone calls from his ultra insecure live-in girlfriend who calls him 18 times a day (for such important things as "Should we make lentil soup tonight?" and "What are we going to name this cat?"), reading I can has cheezburger and the failblog. Meanwhile, he slips under the radar. Our company plays to your competency level. So while I have taken on huge projects, become a stand-in for our system administrator, and the liason between customer service and information services (a pretty important role, they buy the important bugs -first-) -- this kid is getting assigned tasks like "We need to put hyphens between these words per the marketing dept". Good thing we get paid the same. Nice to get paid the same as the guy who's mastered reading I can has cheezburger. He can has cheeseburger, and I'll be the one to shove it up his... nose. So, don't believe a technical test is going to determine if the next guy you work with is legitimate, and competent. If he can't communicate, and he has no work ethic -- frankly, you're screwed. It matters what kind of test (Score:4, Insightful) When it comes down to it, the entire process is a test. Creating a well-designed, brief, and informative resume is a test. Tying a damned tie (a skill that a trained monkey can do without cursing, but I can't), is a test. Interviewing is a test. If you're going to be tested on all these other things, then I am not going to complain about the test that focuses on whether you can do the job. I have been tested for two of the three companies I worked for and a few others that I applied for. Two of them were in the vein of "We want you to write a simple script that can do X, and email it back to us". This was an effective test. Another one was a multiple choice test that focused on syntax. The questions were things like "How do you terminate an IF statement" It was a terrible test because they weren't looking at your ability to logically think through a problem, but were instead more concerned about whether you may confuse programming language A with programming language B. I did reasonably well, but that still, if you are going to test you employees, don't get hung up on things like "does this guy remember the modulus operator" (for Fizzbuzz tests) or "Does he remember how to use function X without looking it up". Re:Sheesh (Score:5, Insightful) Taking a test during a job interview means that they are serious about the situation. The worst thing isn't tests at job interviews it's the work climate at the site where you are going to be located. Is it micro managed or is it goal managed? And job satisfaction is very important for IT workers. The question is rather why other types of workers aren't tested as much. Why not test lawyers, accountants and administrators? Re: (Score:3, Funny) Re:Sheesh (Score:5, Informative) You mean like with the bar exam, cpa exam, the useless PMP exam, certified professional engineer, etc. Other professions are tested, but it is before the job interview.
https://it.slashdot.org/story/08/09/15/0210235/testing-it-professionals-on-job-interviews
CC-MAIN-2017-39
en
refinedweb
Changes from Brian 1¶ In most cases, Brian 2 works in a very similar way to Brian 1 but there are some important differences to be aware of. The major distinction is that in Brian 2 you need to be more explicit about the definition of your simulation in order to avoid inadvertent errors. For example, the equations defining thresholds, resets and refractoriness have to be fully explicitly specified strings. In addition, some cases where you could use the ‘magic network’ system in Brian 1 won’t work in Brian 2 and you’ll get an error telling you that you need to create an explicit Network object. The old system of Connection and related synaptic objects such as STDP and STP have been removed and replaced with the new Synapses class. A slightly technical change that might have a significant impact on your code is that the way ‘namespaces’ are handled has changed. You can now change the value of parameters specified outside of equations between simulation runs, as well as changing the dt value of the simulation between runs. The units system has also been modified so that now arrays have a unit instead of just single values. Finally, a number of objects and classes have been removed or simplified. For more details, see below.and reset=-70*mV - When a variable should be clamped during refractoriness (in Brian 1, the membrane potential was clamped by default), it has to be explicitly marked with the flag (unless refractory)in the equations Clocks and networks¶ Brian’s system of handling clocks and networks has been substantially changed. You now usually specify a value of dt either globally or explicitly for each object rather than creating clocks (although this is still possible). More importantly, the behaviour of networks is different: - Either you create a Networkof objects you want to simulate explicitly, or you use the ‘magic’ system which now simulates all named objects in the context where you run it. - The magic network will now raise errors if you try to do something where it cannot accurately guess what you mean. In these situations, we recommend using an explicit Network. - Objects can now only belong to a single Networkobject, in order to avoid inadvertent errors. - Similarly, you can no longer change the time explicitly: the only way the time changes is by running a simulation. Instead, you can store()and restore()the state of a Network(including the time). Removed classes¶ Several classes have been merged or are replaced by string-based model specifications: - Connections, STP and STDP are replaced by Synapses - All reset and refractoriness classes (VariableReset, CustomRefractoriness, etc.) are replaced by the new string-based reset and refractoriness mechanisms, see Models and neuron groups and Refractoriness Clockis the only class for representing clocks, FloatClock and EventClock are obsolete - The functionality of MultiStateMonitor is provided by the standard StateMonitorclass. - The functionality of StateSpikeMonitor is provided by the SpikeMonitorclass. - Another change is that the StateMonitor now records in the 'start' scheduling slot by default. This leads to a more intuitive correspondence between the recorded times and the values: previously (where StateMonitor recorded in the 'end' slot) the recorded value at 0ms was not the initial value of the variable but the value after integrating it for a single time step. The disadvantage of this new default is that the very last value at the end of the last time step of a simulation is not recorded anymore. However, this value can be manually added to the monitor by calling StateMonitor.record_single_timestep(). Miscellaneous changes¶ - New preferences system (see Preferences system) - New handling of namespaces (see Equations) - New “magic” and clock system (see Scheduling and custom progress reporting and Running a simulation) - New refractoriness system (see Refractoriness) - More powerful string expressions that can also be used as indices for state variables (see e.g. Synapses) - “Brian Hears” is being rewritten, but there is a bridge to the version included in Brian 1 until the new version is written (see Brian 1 Hears bridge) Equationsobjects no longer save their namespace, they now behave just like strings. - There is no longer any reinit()mechanism, this is now handled by store()and restore().).
http://brian2.readthedocs.io/en/2.0rc3/introduction/changes.html
CC-MAIN-2017-39
en
refinedweb
We have two methods in Peoplesoft to send emails from the PeopleSoft system. The first method is using SendMail built-in function. This function is useful if you want to send out quick email without any formatting and less peoplecode. However PeopleSoft has provided a powerful delivered class called mail class which can be used to create content rich mails with effective formatting, attachments and more. The application package will take care of most of the codes required to achieve the objective, however you need to know how to use the application class to send/receive emails which somewhat tricky. I would like to give a glimpse on how to use this class for your purposes. There are a set of application classes delivered along with the package. The classes include · MCFBodyPart · MCFEmail · MCFGetMail · MCFHeaders · MCFInboundEmail · MCFMailStore · MCFMultiPart · MCFMailUtil · MCFOutboundEmail · MCFPart · SMTPSession The main classes which we need to import for sending emails are MCFBodyPart, MCFOutboundEmail and MCFMultiPart which I will explain in the coming paragraphs. The MCFMailUtil class sometimes needs to be implemented. The main purpose of the class is to access some utilities like encoding/decoding texts, validating email addresses and checking the status of SMTP email server. To receive the emails and display it in PIA, the main class you need to access is MCFInboundEmail. Since this is a rare case scenario, I will not be explaining the same in this blog. Let us see how we can send a formatted or rich content email using the mail classes. I will explain the three main classes mentioned earlier in step by step method. MCF BodyPart Class This class is used when we need to have attachments or HTML formatting or any other non-standard email methods. In all the cases you need to create an object of this class. Then using the methods and properties of this class we will assign the non-standard content or formatting to this class. This object is then later added as a property to MCFMultiPart Class. Main Methods The main methods of this class is... 1. SetAttachmentContent – Use this method to make the content of the body part from a file. Syntax: SetAttachmentContent({FilePath | FileURL}, FilePathType, FileName, FileDescr, OverrideContentType, OverrideCharset) Main Properties The main properties of the class are… 1. AttachmentURL – Specify the URL for attachment here. 2. ContentType – Mention the content format for the body part. Example “text/plain” , “text/html”. 3. Disposition – This property can hold two values “inline” and “Attachment”. “inline” will display the message in the email body. “Attachment” method will make the content as an attachment to the email. 4. MultiPart – If you have multiple parts for the same body then assign the multipart object to this property. In that case your text and attachment are ignored. 5. Text – Specify the email text over here. MCFMultiPart Class A multipart class object can hold multiple body part objects you created using MCFBodyPart Class. You will assign the MCFMultiPart objects to Outbound email class and send the mail from Outbound email object class. Main Methods The main methods of MCFMultiPart Class is… 1. AddBodyPart – It can be used to add body part objects created from the BodyPart class to this class object. Main Property The main property of MCFMultiPart Class is… 1. SubType – Used to mention the type of sub objects of the class. The valid values can be alternative, related and mixed. MCFOutboundEmail Class This is the one stop class which you need to be accessed when your sole intension is for sending emails. This class internally inherits the MCFEmail class which is a sub of MCFPart class. So in effect, all the required properties and methods for sending emails are available from the Outbound email class. This class holds all the generic values like To Address, CC, BCC, Subject etc. Main Methods The main methods of this class are… 1. AddAttachment – Use this method to add an attachment to the class. For multiple attachments and other content you can also create MCFBodyPart objects explained earlier and assign it to MCFMultiPart object which again needs to be assigned to MCFOutboundEmail class. 2. AddHeader – Use this method to add headers to email. 3. Send – Use this method to send the email. Main Properties The main properties of this class are… 1. BCC – BCC mail addresses 2. Bounce To – Email address to bounce if the delivery failed. 3. CC – CC mail addresses 4. Charset – The character set used for mail or attachment 5. Content Language – Used to set language of the email. Multiple languages should be separated by comma. 6. ContentType – Specify the content type of the email if the type is different from the default one. 7. Importance – To set the importance value of the email. The values can low, normal and high. 8. MultiPart – You will assign the MCFMultiPart object created in previous steps to this value. 9. Priority – To set the priority of the email. The values range from 1-5 with one having highest and 5 having lowest priority. 10. Recipients – The main addresses to whom this mail should be sent. 11. ReplyTo – Specify the reply to email address. 12. Sender – Use it to mention the email address of the sender. 13. StatusNotifyOptions – Use this to enable notification to the sender. 14. Text – Specify email text of the email. Example You might be confused with the class methods and properties mentioned above. The picture will become clearer if we run through an example from PeopleBooks. The typical steps involve 1. Import the Mail classes 2. Create corresponding objects 3. Assign contents and attachments to MCFBodyPart class objects. 4. Assign the MCFBodyPart objects to MCFMultiPart object 5. Assign the MCFMultiPart object to MCFOutboundEmail object. 6. Invoke the send method of MCFOutboundEmail class. /* Import Mail Classes */ import PT_MCF_MAIL:*; /* Create MCFOutboundEmail class object */ Local PT_MCF_MAIL:MCFOutboundEmail &email = create PT_MCF_MAIL:MCFOutboundEmail(); /* Create MCFBodyPart class object */ Local PT_MCF_MAIL:MCFBodyPart &text = create PT_MCF_MAIL:MCFBodyPart(); /* Assign Text property */ &text.Text = "Hi There"; /* Create Second body part object*/ Local PT_MCF_MAIL:MCFBodyPart &html = create PT_MCF_MAIL:MCFBodyPart(); /* Assign Text property for object 2 and make it html type*/ &html.Text = "<html><BODY><H1>EMail test with HTML content</H1><b>Hi There</b>" | "<A href=''>Check this out!</A>" | "<P></BODY></html>"; &html.ContentType = "text/html"; Local string &TestName = "Text and its alternate html body"; /* Create MCFMultiPart class object */ Local PT_MCF_MAIL:MCFMultipart &mp = create PT_MCF_MAIL:MCFMultipart(); /* Set the SubType property */ &mp.SubType = "alternative; differences=Content-type"; /* Add the body parts created earlier to the multi part object */ &mp.AddBodyPart(&text); &mp.AddBodyPart(&html); /* Set the multi part object to the Outbound email object */ /* Set the required properties for the Outbound email class object*/ /* Invoke the send method of OutboundEmail class object */ Local integer &res = &email.Send(); Local boolean &done; /* Capture the return code of send and do further processing */ Evaluate &resp When %ObEmail_Delivered /* every thing ok */ &done = True; Break; When %ObEmail_NotDelivered /*-- Check &email.InvalidAddresses, &email.ValidSentAddresses and &email.ValidUnsentAddresses */ &done = False; Break; When %ObEmail_PartiallyDelivered /* Check &email.InvalidAddresses, &email.ValidSentAddresses and &email.ValidUnsentAddresses; */ &done = True; Break; When %ObEmail_FailedBeforeSending /* Get the Message Set Number, message number; Or just get the formatted messages from &email.ErrorDescription, &done = False; Break; End-Evaluate;
http://www.peoplesoftjournal.com/2013/02/mail-classes-in-peoplesoft.html
CC-MAIN-2017-39
en
refinedweb
There are two kinds of developers: 1) the ones who have (accidentally) checked passwords and connection strings into source code repositories and 2) the ones that lie about it. It is a problem, we have all done it. It is annoying. When developing ASP.NET applications, you can set yourself up so that it will not happen as easily. In this blog post, I describe how I have started doing it. Most Web Apps rely on "secrets" in order to work right. Examples include database connection strings, client secrets, API keys, passwords, etc. These secrets are used to access information and APIs needed by the application. The secrets can be added to configuration files such as appsettings.json or web.config, but what often happens is that these files end up getting checked into source code repositories with the secrets included. Depending on how widely the source code is shared, the secrets could now be compromised and with distributed source code management tools such as Git, it is not completely straight forward to purge these secrets from the revision history. Moreover, it is impossible to make sure they are purged from all the copies that have been checked out. It is also quite common to need different sets of secrets when developing locally on your laptop, when you deploy for testing, and when deploying for production. Managing these different sets of secrets can add complications. Most developers have used some system of multiple configuration files. Some are checked into the source core repository, some are excluded and only used locally etc., but mistakes happen, especially when debugging or when you are in a hurry and sooner or later, the secrets end up on GitHub and then you have a problem. Here is my recipe for avoiding the problem: Do not add secrets to configuration files. Ever. Until recently, that was easier said than done, but when working with ASP.NET CORE 2.0 applications in Visual Studio 2017, it is actually pretty easy. I will walk through how to manage a couple of user secrets for an ASP.NET application and how to specify them when we deploy that application on Azure. I have created an empty ASP.NET CORE 2.0 MVC application in Visual Studio 2017. After creating the application, you can right-click on the Solution Explorer and find the menu item "Manage User Secrets": When you click on that, it will open a file called "secrets.json". This file doesn't actually live in your source code folder and so it will not accidentally get checked in. If you would like to find the file, it is actually in %APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.json. Where <userSecretsId> is a unique ID associated with your application. Let us add a few secrets to this file: { "myAppSetting": "This is my secret setting", "ConnectionStrings": { "myConnectionString": "This is my secret connection string" } } To access these values in the application, we can use the Microsoft.Extensions.Configuration module. In this application, go to the HomeController.cs file and add: using Microsoft.Extensions.Configuration; At the top and in the HomeController class definition, add something like: public class HomeController : Controller { public IConfiguration Configuration { get; set; } public HomeController(IConfiguration config) { Configuration = config; } //...Rest of the class definition } Now the HomeController can use the Configuration to access the variables that we have just added to secrets.json. To illustrate this, make the following changes to the Index() function of the HomeController class: public IActionResult Index() { ViewData["myAppSetting"] = Configuration["myAppSetting"]; ViewData["myConnectionString"] = Configuration.GetConnectionString("myConnectionString"); return View(); } And in the Index.cshtml file, replace the contents with: @{ ViewData["Title"] = "Home Page"; } <div> <h1>Secrets test application</h1> <b>myAppSetting:</b> @ViewData["myAppSetting"]<br/> <b>myConnectionString:</b> @ViewData["myConnectionString"]<br/> </div> If you then start debugging the application you should see something like this the index page below: If we go ahead and publish that to an Azure Web App, we would see something like this: The settings are not there as we would expect, since the secrets.json file is not deployed with the application. However, we can provide the settings as settings to the Web App: If we hit save and refresh in the browser. The settings now show up: So we now have a workflow where we can manage setting on our local development machine, but they are managed in a file that will not get checked into the repository and we can use the Web App configuration to specify the settings when deploying. If you are using Visual Studio Team Services for CI/CD and you want to set your secrets as part of the deployment, you can use the Azure WebApp Configuration task from the Marketplace. That's it. If you would like to read more about managing app secrets, have a look at this page. Let me know if you have comments/concerns/suggestions. I would also like to hear about any other schemes that you recommend for managing secrets with other environments than ASP.NET CORE 2.0. How does this work outside of Azure webapp? Environment variables or similar? @Trond, if you are deploying outside an Azure Web App, you need to provide the settings in the web.config or appsettings.json file when you deploy. Or you could have another file that you read during configuration for that deployment environment. At least that is how I would do it. Hope that helps. And if you’re using Docker, you can take advantage of the Secrets management functionality to allocate secrets to your .NET Core apps 🙂 … Docker secrets are encrypted at-rest, encrypted in-transit and mounted in-memory via tempfs -> @Andrew, good point.
https://blogs.msdn.microsoft.com/mihansen/2017/09/10/managing-secrets-in-net-core-2-0-apps/
CC-MAIN-2017-39
en
refinedweb
What is Ruby? Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. TL;DR; $ docker run -it --name ruby bitnami/ruby:latest . Supported tags and respective Dockerfile links 2.4, 2.4.2-r0, latest(2.4/Dockerfile) 2.3, 2.3.5-r0(2.3/Dockerfile) 2.2, 2.2.8-r0(2.2/Dockerfile) 2.1, 2.1.10-r4(2.1/Dockerfile) Get this image The recommended way to get the Bitnami Ruby Docker Image is to pull the prebuilt image from the Docker Hub Registry. $ docker pull bitnami/ruby:latest To use a specific version, you can pull a versioned tag. You can view the list of available versions in the Docker Hub Registry. $ docker pull bitnami/ruby:[TAG] If you wish, you can also build the image yourself. $ docker build -t bitnami/ruby:latest Entering the REPL By default, running this image will drop you into the Ruby REPL ( irb), where you can interactively test and try things out in Ruby. $ docker run -it --name ruby bitnami/ruby:latest Further Reading: Running your Ruby script The default work directory for the Ruby image is /app. You can mount a folder from your host here that includes your Ruby script, and run it normally using the ruby command. $ docker run -it --name ruby -v /path/to/app:/app bitnami/ruby:latest \ ruby script.rb Running a Ruby app with gems If your Ruby app has a Gemfile defining your app's dependencies and start script, you can install the dependencies before running your app. $ docker run -it --name ruby -v /path/to/app:/app bitnami/ruby:latest \ sh -c "bundle install && ruby script.rb" or using Docker Compose: ruby: image: bitnami/ruby:latest command: "sh -c 'bundle install && ruby script.rb'" volumes: - .:/app Further Reading: Accessing a Ruby app running a web server This image exposes port 3000 in the container, so you should ensure that your web server is binding to port 3000, as well as listening on 0.0.0.0 to accept remote connections from your host. Below is an example of a Sinatra app listening to remote connections on port 3000: require 'sinatra' set :bind, '0.0.0.0' set :port, 3000 get '/hi' do "Hello World!" end To access your web server from your host machine you can ask Docker to map a random port on your host to port 3000 inside the container. $ docker run -it --name ruby -P bitnami/ruby:latest Run docker port to determine the random port Docker assigned. $ docker port ruby 3000/tcp -> 0.0.0.0:32769 You can also manually specify the port you want forwarded from your host to the container. $ docker run -it --name ruby -p 8080:3000 bitnami/ruby:latest Access your web server in the browser by navigating to. Connecting to other containers If you want to connect to your Ruby web server inside another container, you can use docker networking to create a network and attach all the containers to that network. Serving your Ruby app through an nginx frontend We may want to make our Ruby web server only accessible via an nginx web server. Doing so will allow us to setup more complex configuration, serve static assets using nginx, load balance to different Ruby instances, etc. Step 1: Create a network $ docker network create app-tier --driver bridge or using Docker Compose: version: '2' networks: app-tier: driver: bridge Step 2: Create a virtual host Let's create an nginx virtual host to reverse proxy to our Ruby container. server { listen 0.0.0.0:80; server_name yourapp.com; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header HOST $http_host; proxy_set_header X-NginX-Proxy true; # proxy_pass http://[your_ruby_container_link_alias]:3000; proxy_pass; proxy_redirect off; } } Notice we've substituted the link alias name myapp, we will use the same name when creating the container. Copy the virtual host above, saving the file somewhere on your host. We will mount it as a volume in our nginx container. Step 3: Run the Ruby image with a specific name $ docker run -it --name myapp \ --network app-tier \ -v /path/to/app:/app \ bitnami/ruby:latest ruby script.rb or using Docker Compose: version: '2' myapp: image: bitnami/ruby:latest command: ruby script.rb networks: - app-tier volumes: - .:/app Step 4: Run the nginx image $ docker run -it \ -v /path/to/vhost.conf:/bitnami/nginx/conf/vhosts/yourapp.conf \ --network app-tier \ bitnami/nginx:latest or using Docker Compose: version: '2' nginx: image: bitnami/nginx:latest networks: - app-tier volumes: - /path/to/vhost.conf:/bitnami/nginx/conf/vhosts/yourapp.conf Maintenance Upgrade this image Bitnami provides up-to-date versions of Ruby, including security patches, soon after they are made upstream. We recommend that you follow these steps to upgrade your container. Step 1: Get the updated image $ docker pull bitnami/ruby:latest or if you're using Docker Compose, update the value of the image property to bitnami/ruby:latest. Step 2: Remove the currently running container $ docker rm -v ruby or using Docker Compose: $ docker-compose rm -v ruby Step 3: Run the new image Re-create your container from the new image. $ docker run --name ruby bitnami/ruby:latest or using Docker Compose: $ docker-compose start ruby Notable Changes 2.3.1-r0 (2016-05-11) - Commands are now executed as the rootuser. Use the --userargument to switch to another user or change to the required user using sudoto launch applications. Alternatively, as of Docker 1.10 User Namespaces are supported by the docker daemon. Refer to the daemon user namespace options for more details. 2.2.3-0-r02 (2015-09-30) /appdirectory no longer exported as a volume. This caused problems when building on top of the image, since changes in the volume were not persisted between RUN commands. To keep the previous behavior (so that you can mount the volume in another container), create the container with the -v /appoption. 2.2.3-0-r01 (2015-08-26) - Permissions fixed so bitnamiuser can install gems without needing sudo..
https://hub.docker.com/r/bitnami/ruby/
CC-MAIN-2017-39
en
refinedweb
One of the cool features of the full .NET Framework is that it easily allows applications to determine whether the network cable is detected or not so that they can try and make smart choices up-front as to whether to try a network operation. In Silverlight 3, an application can do the same thing so I can write a UI like this one; <UserControl x:Class="SilverlightApplication11.MainPage" xmlns="" xmlns: <Grid x: <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="36" x: </Grid> </UserControl> and then I can write a little bit of code which tries to spot changes in the network interface; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Net.NetworkInformation; namespace SilverlightApplication11 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); } void MainPage_Loaded(object sender, RoutedEventArgs e) { NetworkStatusChanged(); NetworkChange.NetworkAddressChanged += OnNetworkStatusChanged; } private void NetworkStatusChanged() { txtStatus.Text = NetworkInterface.GetIsNetworkAvailable() ? "Network there" : "Network down"; } void OnNetworkStatusChanged(object sender, EventArgs e) { Dispatcher.BeginInvoke(() => { NetworkStatusChanged(); }); } } } and then I’m in business in that as I plug/un-plug my network cable my Silverlight application is aware of what’s going on and the UI (in this example) changes accordingly. Cool – very handy for those detached applications too as I talked about in my previous post..
https://mtaulty.com/2009/03/18/m_11140/
CC-MAIN-2017-39
en
refinedweb
I have a domain (Task) and a controller (TaskController) in my Grails 2.3.7 project. Task.groovy class Task { String name String description static constraints = { name() description() } String toString() { "${name}" } } TaskController.groovy class TaskController { def scaffold = true def index() { } } After adding a task from the generated UI of Scaffold, if I navigate to Task List (i.e.), there is no list displaying. Though it should display a list of Tasks that I had added. Some Grails version may also produce the following error: ERROR view.ScaffoldingViewResolver – Error generating scaffolded view Workaround Scaffold renamed their “list” method to “index” and which conflicts with the default method “index” of any Grails controller. so one simple workaround would be to remove def index() {} method from Grails controller. TaskController.groovy class TaskController { def scaffold = true } Advertisements
https://tausiq.wordpress.com/category/grails/
CC-MAIN-2017-39
en
refinedweb
This file defines macros to deal with 8-bit Unicode (UTF-8) code units (bytes) and strings. utf88.h. #include "unicode/utf.h" Go to the source code of this file.
http://icu.sourcearchive.com/documentation/4.4.1-5/utf8_8h.html
CC-MAIN-2017-39
en
refinedweb
r.expr(value) → value Construct a ReQL JSON object from a native object. The native object can be any Java primitive type, as well as Array, List, Map, LocalDateTime, ZonedDateTime, OffsetDateTime, and POJOs (“plain old Java objects”) whose classes are public and whose numeric properties are Long instead of Integer. If the native object is of type bytes[], then expr will return a binary object. See binary for more information. Example: Objects wrapped with expr can then be manipulated by ReQL API functions. import com.rethinkdb.model.MapObject; // Create object { "a": "b" } MapObject newData = r.hashMap("a", "b"); // merge with { "b": [1, 2, 3] } r.expr(newData).merge(r.hashMap("b", r.array(1, 2, 3))).run(conn); Couldn't find what you were looking for? © RethinkDB contributors Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
http://docs.w3cub.com/rethinkdb~java/api/java/expr/
CC-MAIN-2017-39
en
refinedweb
#include <WatchablePool.h> #include <WatchablePool.h> Inheritance diagram for WatchablePool:: Definition at line 19 of file WatchablePool.h. A list of watchers, each conforming to the Pool interface. Change this list as you like. Each time one of the Pool interface calls is made to this object, it will be distributed to each watcher on this list, in order. Should we allow before-change watchers (catchers) who can abort the change? How about intercepting reads? That all gets us along the spectrum into ProxyPool or something. Definition at line 56 of file WatchablePool.h.
http://www.w3.org/2001/06/blindfold/api/classWatchablePool.html
CC-MAIN-2015-32
en
refinedweb
? The following example may clarify some of the suggestions above. (Yes there is a size limitation so I have cut in the example ) It would be nice if this function was valid code: I apologise for the messed up indention and the duplication above /Csaba I will give you $1000 to turn off VB....it's not even language.. $50 for removing line continuation mark _ $50 for removing the need for Dim $100 for My class. It rock! $50 for reduce bloated VB language. Get rid of crap keyword like Dim and all the un need keyword $50 for running VB.net on everything including Xbox 360. it is not fair that only C# programmer get to have all the fun. Things to keep $30 The very verbosity others have complained about. End If/End Function etc. are part of the reason that VB is so readable. You get to the bottom and you know what's ending without having to trace back through an ugly mess of nested indents with curly braces. Unless you're writing VB in Notepad, there's no extra typing anyway. $30 Case insensitivity, with the IDE keeping the case consistent. $30 Automatic code formatting. Eliminate as much individual style as possible. If I have to pick up someone else's code and read it, I want to spend my time figuring out what steps they're taking, not stumbling through their wacky indenting style. $10 Intellisense Future priorities: $20 Do even more to improve readability and minimize code style creativity. For instance a lot of coders have different ways of dealing with a line running off the screen or long lists of arguments. The IDE should take care of the wrapping. The more aspects of code style you can eliminate from the coder's control, the better. $15 Maintain parity with C# features. I can't have C# snobs lording it over me for a whole version until VB catches up (e.g. Iterators). There should be absolutely no reason to use C#, ever, except maybe masochism. $40 Code that writes code. I'm not so sure I want to go back to the days of Eval, but at least it was something. There ought to be some way to do dynamically generated functionality. It would fill a lot of gaps. $25 More high-level ways to safely handle complex multi-threading scenarios. Why do people dislike vb so much??Isn't the purpose of it to make things easy as possible for the programmer Wow, that's so awesome, I love how people are engaging! You are helping us do our job better, thanks for doing that! Keep posting so that we can get as many opinions as possible and identify what are really the most important features for the VB community! $30 - Implicit casting $40 - Case insensitivity $30 - Great IntelliSense in VS2008 === $30 - Maintain parity with C# $50 - Portability to Linux :) $20 - Do something to VB reputation $50: Instead of getting rid of the underscore, perhaps leave it up to the editor to add it automatically when I end a line with comma or ampersand etc. So I second the idea above to leave it up to the IDE to do the code formatting when splitting up across lines. Automatic properties - I would have expected them in VB long time ago I like it how it is right now. I'd pocket the $200 bucks. I would give $100 to have an VB check to see if my system had the required componets for a new project i'm considering working with, and then retrieve them if needed for what ever system I was on. Strickly for developers systems. $5 ability to kill My infrastructure for Class Library projects without manually editing project files. $10 C# iterators $20 better array and collection initialyzers Dim a as String()()={{"a","b"},{"c"}} Dim b as Point()={(x1,y1,z1),(x2,y2,z2)} $10 keyboard shortcut to show types/namespaces list to write some static metod call $10 for less bright ASP.Net color scheme. (I swear I saw it the first time I installed Beta2!) $20 I don't know how it can be done, but... underscore! $25 better anonymous methods, lambdas and expression trees support. And it would be really cool if I could get expression tree from my existing function and modify it $50 - leave current features alone (except to add or fix functionality) $20 - make the TextFieldParser class part of the BCL $30 - add "Treat Consecutive Delimiters as One" to the TextFieldParser class (think Excel) $40 - ability to use types declared in the current project to My.Settings $60 - show available shadows/overloads/overrides on ALL available methods/properties within context when keyword is typed (similar to overrides keyword) instead of having to lookup the signature of the item you are trying to shadow/overload/override. I would give $100 for a more comprehensive combo box that would do columns, column sorting along with type ahead feature. I would spend $100 on making things simpler. For example, I tried to use VB Express 2005 to create an .EXE file for our internal use. Where did the created .EXE file go? The IDE was little help. And, no, it didn't actually produce an .EXE file but deploy and manifest files. I finally (sort of) figured it out, but with little help from the VB IDE. Another example, the process of using databases seems to have changed in a major way. Using the help features hasn't produced much of actual help, though apparently there's a powerful new super helpful feature called the Binding Component. A clue! (I hope.) Because the data samples of the 101 Code Samples are installed somewhere, but how to actually access them isn't clear ... Sigh.
http://blogs.msdn.com/b/vbteam/archive/2007/07/30/if-i-gave-you-200-to-spend-on-vb-how-would-you-spend-it.aspx?PageIndex=2
CC-MAIN-2015-32
en
refinedweb
CACHEFLUSH cacheflush - flush contents of instruction and/or data cache #include <asm/cachectl.h> int cacheflush(char *addr, int nbytes, int cache); cacheflush flushes contents of indicated cache(s) for user addresses in the range addr to (addr+nbytes-1). Cache may be one of: cacheflush returns 0 on success or -1 on error. If errors are detected, errno will indicate the error. The current implementation ignores the addr and nbytes parameters. Therefore always the whole cache is flushed. This system call is only available on MIPS based systems. It should not be used in programs intended to be portable. One page links to cacheflush(2):
http://wiki.wlug.org.nz/cacheflush(2)
CC-MAIN-2015-32
en
refinedweb
Windows Pipe Source. More... #include <winpipes.h> Definition at line 105 of file winpipes.h. GetWaitObjects() must be called despite the 0 return from GetMaxWaitObjectCount(); the 0 is because the ScheduleEvent() method is used instead of adding a wait object Reimplemented from LimitedBandwidth. Definition at line 235 of file network.cpp. References BufferedTransformation::GetMaxWaitObjectCount(), and(). pump up to maxSize bytes using at most maxTime milliseconds If checkDelimiter is true, pump up to delimiter, which itself is not extracted or pumped. Definition at line 76 of file network.cpp. References INFINITE_TIME. set propagation of automatically generated and transferred signals propagation == 0 means do not automaticly generate signals Definition at line 857 of file cryptlib.h. input multiple bytes for blocking or non-blocking processing Implemented in Redirector, OutputProxy, StringSinkTemplate< T >, RandomNumberSink, ArraySink, ArrayXorSink, MessageQueue, ByteQueue, MaurerRandomnessTest, BitBucket, and FilterTes(). request space which can be written into by the caller, and then used as input to Put() Reimplemented in Redirector, OutputProxy, ArraySink, ArrayXorSink, and ByteQueue. Definition at line 799 of file cryptlib.h. Referenced by ArrayXorSink::CreatePutSpace(). input multiple bytes that may be modified by callee for blocking or non-blocking processing Reimplemented in OutputProxy. Definition at line 817(). wait on this object same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container Definition at line 388 of file wait.cpp. References Waitable::GetWaitObjects(). put wait objects into container Definition at line 118 of file winpipes.cpp. wait on this object same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container Definition at line 388 of file wait.cpp. References Waitable::GetWaitObjects().
http://www.cryptopp.com/docs/ref/class_windows_pipe_source.html
CC-MAIN-2015-32
en
refinedweb
3D Graphics Overview Provides an overview of 3D graphics. The Microsoft.Xna.Framework.Graphics namespace contains classes to use the graphics device to load and render resources and to apply effects to vertices and pixels. This overview covers the following topics as they apply to 3D graphics. Getting Started with 3D In the examples in this section, you must provide the following three items for even the most simple 3D graphics application: - A set of world, view, and projection transformation matrices - A vertex buffer - An effect that applies the world, view, and projection transformation matrices to the vertex data This list of items enables you to render your first 3D content in an XNA application. As you become comfortable with these ideas, you will want to learn more about the following: - Manipulating the vertices you created - Creating your own effects - Applying textures - Improving the performance of your application through such techniques as converting your vertex buffers to indexed vertex streams The XNA Framework uses a shader-driven programmable pipeline., the XNA application model initializes a graphics device for you. You can use the GraphicsDeviceManager.GraphicsDevice property to gain access to the graphics device. To determine the capabilities of the graphics device, use the GraphicsDevice.GraphicsDeviceCapabilities property. Graphics Device Initialization The GraphicsDeviceManager initializes the GraphicsDevice before you call Game.Initialize. Before you call Initialize, there are three ways to change the GraphicsDevice settings: Set the appropriate properties (e.g. PreferredBackBufferHeight, PreferredBackBufferWidth) on the GraphicsDeviceManager in your game's constructor. Handle the PreparingDeviceSettings event on the GraphicsDeviceManager, and change the PreparingDeviceSettingsEventArgs.GraphicsDeviceInformation.PresentationParameters member properties. Any changes made to the PreparingDeviceSettingsEventArgs will override the GraphicsDeviceManager preferred settings. Handle the DeviceCreated event on the GraphicsDeviceManager, and change the PresentationParameters of the GraphicsDevice directly. When you call Game.Initialize, GraphicsDeviceManager creates and configures GraphicsDevice. You can safely access GraphicsDevice settings such as the backbuffer, depth/stencil buffer, viewport, and render states in Initialize. After you call Game.Initialize, changes to the PresentationParameters of the GraphicsDevice will not take effect until you call GraphicsDeviceManager.ApplyChanges. Other changes, such as render states, will take effect immediately. Render States and the Graphics Device Render states are an important part of the graphics device. They can affect game rendering significantly. When you first create a graphics device, the render states are set to their default values. For more information, see RenderStates. Commonly, the value of a render state is changed only if it is manually modified. For example, the following code sample sets the cull mode of the current graphics device to None. This causes all triangle faces to be drawn and differs from the default value of CullMode.CounterClockwise. renderState.CullMode = CullMode.None; However, there are cases where render states can change automatically. A common example is the rendering of sprites and 3D objects on the same graphics device. In this case, the SpriteBatch object changes various render states when you call End. If you try any 3D rendering after this step, the results can be unpredictable. For this reason, you should restore several key render states to their former settings before you try to render any 3D objects. The following code demonstrates this approach. GraphicsDevice.RenderState.DepthBufferEnable = true; GraphicsDevice.RenderState.AlphaBlendEnable = false; GraphicsDevice.RenderState.AlphaTestEnable = false; In addition, you should set the following render states, depending on the type of 3D content you are rendering. GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap; GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap; It is also possible to save the render state of the graphics device before rendering sprites by passing SaveStateMode.SaveState your SpriteBatch.Begin method call. However, this is not recommended because it is time intensive, and can slow down the rendering process. Content.map perform. For a simple demonstration of how to apply a vertex shader from an effect file, see How To: Create and Apply Custom Effects.
https://msdn.microsoft.com/en-us/library/bb194916(v=xnagamestudio.31).aspx
CC-MAIN-2015-32
en
refinedweb