text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
that of many others – it was confusing and frustrating, and required a ton of XML. The next major release was renamed Spring Security 2.0 and it was officially brought in as a Spring subproject, and fortunately it made configuration dramatically simpler by using Spring XML namespaces. When I started using Grails and found that it supported plugins one of the first I looked at was the acegi plugin, and I eventually became the plugin maintainer and later wrote most of the newer Spring Security plugins. I keep working with Spring Security because it’s very powerful and because I know it well, having struggled with learning Acegi 1.0.x, and then moving on to Spring Security 2.x and 3.x. Grails has another popular security plugin, the shiro plugin. I haven’t used it but it has the reputation that it’s easier to use than Spring Security. I think that’s less the case with the plugins since spring-security-core and its dependent plugins are quite user-friendly, but more so when you’re not using the plugins or are working directly with the underlying APIs. For the most part the feature set of Spring Security and Shiro overlap with Spring Security having a few more features (but Shiro is catching up quickly). But one feature that is strangely implemented and hard to use in Spring Security but easy to use in Shiro is ACLs and permissions. It took me a long time to get the spring-security-acl plugin finished, in large part because the Spring Security ACL implementation is overly complicated and hard to use. It works, but it’s far from user-friendly. But looking at the Shiro plugin’s documentation I was jealous to see that you can do simple things like grant the “printer:print:*” permission to a user, and the wildcard implies the “printer:print:lp7200? and “printer:print:epsoncolor” permissions. Then you can guard a service method with @RequiresPermissions('printer:print:*) and a user granted “printer:print:*” (or a more specific permission like “printer:print:lp7200?) can call the method, and others will be denied. A while back I thought it would be cool to be able to use Shiro’s permission support in addition to Spring Security. I started working on it a few months ago and picked it up again this weekend and got it working. Basically it just adds a filter that runs after the Spring Security SecurityContextPersistenceFilter which populates the SecurityContext (typically from the HTTP session) with your current Authentication, and creates a Shiro Subject with the same information and registers it in the ThreadContext. In addition it adds support for storing permission information. This is done by default with a domain class that has a many-to-one relationship with the existing user class, but this is customizable. So now you can install the spring-security-shiro alongside the spring-security-core and any of its dependent plugins and use both approaches. You can even use Spring Security ACLs and Shiro ACLs at the same time. Check out the plugin page and the documentation for more information Reference: A Grails plugin to bridge Spring Security and Shiro from our JCG partner Burt Beckwith at the An Army of Solipsists blog. Cool plugin. I like the flexibility of being able to use both frameworks simultaneously (I have LDAP-specific security needs that Shiro meets well). And props to Mr. B for providing User Guides for his plugins! Wow…Thanks. Very cool…I was wondering if Grails support Shiro and found this page :-)
http://www.javacodegeeks.com/2013/01/a-grails-plugin-to-bridge-spring-security-and-shiro.html
CC-MAIN-2015-40
refinedweb
598
52.49
Agenda See also: IRC log david giving an update <dF> david: registration will open ... cfp is closed by now ... registration will open 4 April ... topics: two thematic tracks ... one is "XLIFF symposium", 5th symposium ... other track is "content analytics meets localization", chaired by dave + felix ... one day will have 4 separate session. One will be run by LIDER ... felix can say more about the topics ... after lunch will be run as XLIFF TC info sessions ... xliff 2.0, 2.x requirements etc. ... xliff 2.1 is shaping ... consensus coming on what is in 2.1 - two major features: ... ITS mapping will be an official module ... other feature will be advanced validation support ... xliff has many constraints that will be beyond xsd validation ... so there is a need to work on that, felix will do that ... xliff 2.1 will also merge with media type registration template ... 2.x requirements gathering also a topic ... felix + dave thought it would be good to have external participants ... to discuss also how to work with quality related requirements ... another topic would be general requirements gathering ... and general roadmapping christian: general question about xliff ... I saw the call for comments ... saw one call for dissent ... what is the general timing for xliff 2.0? david: it is an official committee spec <dF> SOU david: this week we will launch a questionnaire for getting statement of use ... you can see these on the public TC archive christian: will statement of use contain questions about compliance? david: the questionnaire is pretty detailed ... check boxes for every attribte + element in the spec ... it is very qualified <Yves_> survey is here: (will be modified later today) leroy: I have an xliff 2.0 compliant application <Yves_> not much to add to my email <Yves_> if people could review <Yves_> the TO REVIEW entries <Yves_> that would be good <Yves_> yes <Yves_> <Yves_> so what direction should we take for mtConfidence? felix: its:mtConfidencePointer question from Yves: "are we going to have many ITS-only processor looking at XLIFF2 files" david: think it was good that all mappings were generic for ITS processors ... not sure if there will be many generic processors look at ITS 2.0 felix: so you think the private mapping is no an issue? david: no problem for XLIFF TC ... general ITS processors is a separate topic <Yves_> ok felix: just need to separate ITS - XLIFF namespace from general ITS experimental extensions <Yves_> We can just state that the ITS to XLIFF is not available for MT Confidence christian: question related to mt confidence <Yves_> it should work with quest christian: how far would be able to cover information generated by quest? <Yves_> that's my use case :) <Yves_> no for MT confidence we can use the XLIFF attribute directly ok <Yves_> yes <Yves_> I think it'll work the same felix: any impact on e.g. ocelot who visualizes mt:confidence in xliff 1.2 ? <Yves_> they would just get the info from matchQuality yves' answer above <Yves_> or mtConfidence if the annotation is directly in the unit (rather than the match) felix: tool becomes an "ITS + XLIFF" tool? <Yves_> I guess <scribe> ACTION: felix to talk to phil about mt confidence, xliff2 and ocelot [recorded in] <trackbot> Created ACTION-42 - Talk to phil about mt confidence, xliff2 and ocelot [on Felix Sasaki - due 2014-04-09]. david: schema for its 2.1 felix: schema is not normative part of ITS david: no further comments pablo: no time to move forward on readiness <scribe> .. pending issues are the same - need to review semantic process list UNKNOWN_SPEAKER: no further update felix: do you need input from people in the group? pablo: people to check the text, help with the process list, help to review felix: any volunteer? please consider helping out felix encouraging people to contribute as their time permits <pnietoca> I anybody is interested you can email me and then we could talk about how to distribute the tasks <pnietoca> I'll try to move forward but this month I was very busy <Yves_> I'll try to look at it Pablo, but like you I'm a bit busy. its-ta-ident-ref <pnietoca> thanks Yves much appreciated :) multilingual article christian: good point in time to thank people on the phone ... what we did was: including information that people provided to us ... e.g. the percentage of improvement came from Pedro +1 leroy: we will document ITS ontology for falcon ... the linport vocabulary - for workflow with translation documents. We translated that vocabulary into linked data felix: where will that be made avail? leroy: should be up in falcon site soon ... in deliverable section <leroy> <leroy> more information on falon adjourned This is scribe.perl Revision: 1.138 of Date: 2013-04-25 13:59:11 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/topic: FEISGILTT/topic: FEISGILTT and xliff/ Succeeded: s/xliff/its/ No ScribeNick specified. Guessing ScribeNick: fsasaki Inferring Scribes: fsasaki Present: yves David felix chriLi Yves pablo ankit Ankit (irc only) leroy Agenda: Got date from IRC log name: 02 Apr 2014 Guessing minutes URL: People with action items: felix[End of scribe.perl diagnostic output]
http://www.w3.org/2014/04/02-i18nits-minutes.html
CC-MAIN-2015-06
refinedweb
870
65.62
We need to combine this two codes to create a game in which we have to count how many times we pressed enter for a matter of time. we need to display the instructions above and how many times we hit or pressed the enter button and also the time. #include <iostream> #include <stdio.h> #include <time.h> #include <conio.h> using namespace std; int main () { while(_kbhit() ) { int c = getche(); int counter = 0; if( c == '\n', counter++ ) { printf("got one\n"); [COLOR="Green"]// but instead of this one we need to show the counter // which we dont know how we can declare it. [/COLOR] } } int main () { time_t start,end; // start time and end time int score=0; char ans[10]; int ctr; time (&start); //start timer printf("GO!"); while(_kbhit() ) { int c = getche(); if( c == '\n' ) { printf("got one\n"); } cout<<"\n"; ctr++; cout<<ctr; } int minutes = 1 ; while ( timer < (minutes * 60 )) // convert minutes to seconds { printf(""); scanf("%s", &ans); getchar() ; // for the extra new line because of scanf() if (strcmp(ans, "hello") == 0) score++; if (strcmp(ans, "goodbye") == 0) score++; time (&end); timer = difftime (end,start); } //end while puts("Time Up!"); printf("score is %d over 2",
https://www.daniweb.com/programming/software-development/threads/351876/help-can-someone-check-this-codes
CC-MAIN-2017-09
refinedweb
199
76.86
Back to: C#.NET Tutorials For Beginners and Professionals Extension Methods in C# with Examples In this article, I am going to discuss the Extension Methods in C# with examples. Please read our previous article where we discussed Sealed Class and Sealed Methods in C#. At the end of this article, you will understand what exactly C# Extension Methods are and when and how to use these extension methods in C#? What are Extension Methods in C#? It is a new feature that has been added in C# 3.0 which allows us to add new methods into a class without editing the source code of the class i.e. if a class consists of a set of members in it and in the future if you want to add new methods into the class, you can add those methods without making any changes to the source code of the class. Extension methods can be used as an approach to extending the functionality of a class in the future if the source code of the class is not available or we don’t have any permission in making changes to the class. Before extension methods, inheritance is an approach that used for extending the functionality of a class i.e. if we want to add any new members into an existing class without making a modification to the class, we will define a child class to that existing class and then we add new members in the child class. In the case of an extension method, we will extend the functionality of a class by defining the methods, we want to add into the class in a new class and then bind them to an existing class. Both these approaches can be used for extending the functionalities of an existing class whereas, in inheritance, we call the method defined in the old and new classes by using object of the new class whereas, in the case of extension methods, we call the old and new methods by using object of the old class. Extension Methods Example in C#: Let us understand C# Extension Methods with an example. Create a console application and then add a class file with the name OldClass.cs and then copy and paste the following code in it. public class OldClass { public int x = 100; public void Test1() { Console.WriteLine("Method one: " + this.x); } public void Test2() { Console.WriteLine("Method two: " + this.x); } } Now our requirement is to add three new methods to the class OldClass. But we don’t want to change the source code of OldClass. Then we can achieve this with the help of extension methods. Let’s create a new class with the name NewClass.cs and then copy and paste the following code in it. public static class NewClass { public static void Text3(this OldClass O) { Console.WriteLine("Method Three"); } public static void Text4(this OldClass O, int x) { Console.WriteLine("Method Four: " + x); } public static void Text5(this OldClass O) { Console.WriteLine("Method Five:" + O.x); } } Let us first test the application, then we will understand the extension methods. Now to test whether the methods are accessed using the old class objects or not, add a class Program.CS and write the following code public class Program { static void Main(string[] args) { OldClass obj = new OldClass(); obj.Test1(); obj.Test2(); //Calling exrension methods obj.Text3(); obj.Text4(10); obj.Text5(); Console.ReadLine(); } } Now, run the application and see everything is working as expected and it will display the following output. Points to Remember while working with C# Extension methods: - Extension methods must be defined only under the static class. - As an extension method is defined under a static class, compulsory that the method should be defined as static whereas once the method is bound with another class, the method changes into non-static. - The first parameter of an extension method is known as the binding parameter which should be the name of the class to which the method has to be bound and the binding parameter should be prefixed with this keyword. - An extension method can have only one binding parameter and that should be defined in the first place of the parameter list. - If required, an extension method can be defined with a normal parameter also starting from the second place of the parameter list. Extension Method Real-time Example: Let us see one real-time scenario where you can use the extension method. As we know string is a built-in class provided by .NET Framework. That means the source code of this class is not available to us and hence we can change the source code of the string class. Now our requirement is to add a method to the String class i.e. GetWordCount() and that method will return the number of words present in a string and we should call this method as shown in the below image. You can achieve the above using Extension Methods. First, create a class with the name StringExtension and then copy and paste the following code into it. As you can see, here we created the class as static and hence the GetWordCount as static and provide the first parameter as the string class name so that we can call this method on the String class object. namespace ExtensionMethodsDemo { public static class StringExtension { public static int GetWordCount(this string inputstring) { if (!string.IsNullOrEmpty(inputstring)) { string[] strArray = inputstring.Split(' '); return strArray.Count(); } else { return 0; } } } } Once you have created the extension method, now you can use that method on the String class object. So, modify the Main method of the Program class as shown below. namespace ExtensionMethodsDemo { class Program { static void Main(string[] args) { string myWord = "Welcome to Dotnet Tutorials Extension Methods Article"; int wordCount = myWord.GetWordCount(); Console.WriteLine("string : " + myWord); Console.WriteLine("Count : " + wordCount); Console.Read(); } } } That’s it. Now run the application and you should get the output as expected as shown in the below image. In the next article, I am going to discuss C# 7 new Features with examples. Here, in this article, I try to explain Extension Methods in C# with examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this Extension Methods in C# with examples article. 4 thoughts on “Extension Methods in C#” its amazing………. i appreciate it Hi, Although Content is really really good. It would be nice to have a official definition of each topic described. nice nice
https://dotnettutorials.net/lesson/extension-methods-csharp/
CC-MAIN-2022-21
refinedweb
1,094
63.7
PHP Cookbook 238 The approach that the authors use in PHP Cookbook is great. Like most computer books, the authors usually include a summary (in sentence forms) to illustrate what the readers will expect in each chapter. Skalar and Trachtenberg take this even further by including some preliminary (code) examples to explain the general ideas behind each chapters. The examples in the book are self-contained. In most cases, I've found examples to exactly fit my needs -- this makes it one of the better reference books. Each chapter in the book is divided into multiple sections of Problem / Solution / Discussion with a FAQ style. In each case, a simple description of a problem is followed by a PHP script as the solution. But the meat is actually in the discussions: in-depth details are included here, where the authors also include references, extended ideas, and scripts to inform the readers how much more they can do about the issue. For example, I was going to add a simple script to my website to parse RSS/RDF files from certain news websites (CNN, Slashdot, ...), and use it as my Mozilla homepage. (Who wouldn't?) This script seems to be simple, but I may make a mistake here and there. As reference, I opened up the book to the section "Parsing XML with SAX." Then I realized the authors already had the script to parse RSS/RDF files in the discussion. Bravo! For myself, the most useful chapters I found are: Web Basics, Forms, Database Access, and XML. There are also good examples in topics such as security, internationalization, and file processing/management. However, this book does not cover the basics of PHP. If you are a good programmer, you should be able to get away with this using the PHP Manual. A good book to learn PHP is Programming PHP, also by O'Reilly. Although this book covers a wide range of topics, it does not cover topics like generating PDFs. I would also like to see the authors add one (maybe two) case studies in later editions. That would give the reader a more concrete example of how to combine tricks presented by this book. Other than that, at the price of $39.95 (or $61.95 CAD), this book is a great buy! Topics - Strings - Numbers - Dates and Times - Arrays - Variables - Functions - Classes and Objects - Web Basics - available online as example chapter - Forms - Database Access - Web Automation - XML - Regular Expressions - Encryption and Security - Graphics - Internationalization and Localization - Internet Services - Files - Directories - Client-Side PHP - PEAR You can purchase the PHP Cookbook from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page. PHP Security (Score:5, Interesting) One thing I would like to see more PHP books do is to cover the various Security problems that are prevalent in many PHP based web applications. Don't get me wrong, I find PHP to be the best and friendliest solution for many things, but some of the Security problems could easily be avoided with some common sense security advice. Re:PHP Security (Score:4, Interesting) Of course, writing secure code isn't specific to a language and any book on writing secure code should help to pave the way to avoid common mistakes, just substitute PHP for language X. For instance Writing Secure Code [amazon.com] by Michael Howard could be a good companion book to any programmer's library. Hopefully, in a few years PHP will have a large enough installed user base (as I think it already does) that the advances issues such as security, tolerance, etc. will be dealt with in entire book(s). Can you tell I am a PHP afficianado? Re:PHP Security (Score:5, Insightful) PHP has a couple of common mistakes, but I'm far more apt to trust an inexperienced PHP programmer over an inexperienced Perl programmer, as far as secure code goes. Re:PHP Security (Score:2) One thing I would like to see more PHP books do is to cover the various Security problems that are prevalent in many PHP based web applications. I completely agree with you. David Sklar (one of the authors of the book reviewed here) gave a very interesting presentation about the subject of security in web applications at the International PHP Conference (May 2003) in Amsterdam. You can view the slides of his talk here [php.net]. JP Re:PHP Security (Score:3, Informative) It's called phpkeychain [sourceforge.net] and it's modelled after the keychain mechanism in OS X. 'web apps' (Score:3, Insightful) I think a large part of the problem is that PHP is illsuited for many of the larger web applications it is being used for. Traditional Application Server features such as tag libraries found in JSP, ColdFusion, etc. would be good for separating the 'coders' from the 'presentation designers' in large projects, but that's not pertinent to security. What gets l Re:'web apps' (Score:2) Yes, but PHP has sessions. At my work, we use the session features to do variable persistance. What am I missing? I'm sure I've failed to grasp the crux of your argument. Re:PHP Security (Score:2) some of the worst problems e.g. register globals on as the default setting has disappeared in the latest versions, but I generally agree. I have this book, and it has got some good examples I have been able to adapt and use, but it does need a good understanding of PHP, SQL and HTML to get the most out of it. If you want a starter/ reference book, wait a few weeks until PHP5 comes out, and I will be spending my dollars on Leon Atkinson's latest edition in the Core series. YES!!! (Score:5, Funny) In all seriousness I enjoy PHP because it is pretty self explanatory, and it can use plain old html inside it too. It's just nice to use a scripting language for the web that was made for webpages originally, not a language that was created for ... Re:YES!!! (Score:3, Funny) OR Pathologically Electic Rubbish Lister Re:YES!!! (Score:2) A backronym [science.uva.nl], and not a really good explanation of Perl's reason for being. See here [thepen.com] and here [perldoc.com] for a better background on Perl. Re:YES!!! (Score:5, Informative) Duck tape was invented during WWII by Johnson+Johnson for the purpose keeping water out of ammunition cases -- it was relatively waterproof, hence the reason people in the military started calling it "duck tape." You should try watching the History Channel more often. Re:YES!!! (Score:2) Re:YES!!! (Score:2) Re:YES!!! (Score:2) To manipulate text. Funny since everything is going to a text/XML type of meta format Perl is very well suited to the Web and to system management or for small GUI programs. I think Perl would be a great replacement for say VB. *Obligatory PHP flame from the Perl guy* of course Perl can do all that and it doesn't need_a_function_for_everything() to accomplish it either. */Obligatory PHP flame from the Perl guy* Re:YES!!! (Score:3, Funny) No, it just needs a module_for_everything.pm Re:YES!!! (Score:2) What seems to scare people about perl is that there as so many different ways that you can tackle a job like building dynamic web sites. Perl on it's own doesn't forcefeed anything to you, it lets you find your own style. Many people who start with perl will try to do everything from scratch instea Re:YES!!! (Score:2) Anyway, because the brunt of most simple CGI applications is text processing, perl got moved into being used for that. Re:YES!!! (Score:2) Perl stansds for "Practical Extraction and Reporting Language". Invented in 1987 by Larry Wall, it was originally used for in system maintenance tools for UNIX, mostly parsing logs and foramatting the results for display on the screen. Another book with similar title (Score:5, Informative) Re:Another book with similar title (Score:2) Most of books are for most of peoples. The smarter the subject the fewer people can understand and demand it. That's why you see most of books about VB, ASP, JSP, PHP. Less about Perl/CGI. Even less about Python/CGI. Just 2 good (totally 4 found) books about Zope. No books (at least in several stores I've checked) about web-programing with Lisp, Scheme, OCaml or Haskell. Well, in the past the reading the hard-printed books was a sign of smart/educate Ain't php great? (Score:2) It would take a whole lot of perl code to achieve the same functionality that can be accomplished in 200 well-written php code. (Depending on what it did - it's based off my personal experiences). In addition, the ability to mix and match html/php on a cross-platform programming language, as well as write scripts that also run on the command line is worth it's weight in gold (note to people who don't understand that saying, it's really valuable to me). Re:Ain't php great? (Score:3, Informative) You obviously don't know Perl, at the very least you don't know about CPAN. How about a decent HTML parser for PHP. XML? How about this: write a program that reads an Excel spreadsheet and uploads its content into a database and let me know how long it takes you in PHP. PHP sucks because there is no standard way to extend it, and don't mention PEAR as it so poorly documented its a Re:Ain't php great? (Score:2) For general web stuff, I normally choose PHP because of it's ease of use in most situations. F Re:Ain't php great? (Score:4, Informative) If that is a challenge, then I accept. I can guarantee you that for every command in PHP, there is an equivalent command (or module) in Perl. Hence you should be able to write this imaginary program in exactly the same number of lines... Have a look at Embperl, HTML::Mason, Apache::ASP for a couple of examples of how to do this. Most people who knock perl have never discovered the right tools. Personally I would never use those tools, because I am a strong believer in the separation of Code and HTML. I use a templating system for all my projects, and you will never see one HTML tag in my code. Once you work with a team of developers and a separate team of designers you will understand the need for this separation. PHP is a great tool! I have used it for several applications in the past (6 or 7 years ago). But if you think that PHP can do more than perl can then you are mistaken... Re:Ain't php great? (Score:2, Insightful) Well, it'll be a module, not a built-in; Perl's built-ins are often powerful in the broad thermonuclear sense, but are never web-specific. Two key differences remain, though. One: The Perl modules will have 15 dependencies each, 3 of which are no longer available at CPAN and which have to be hunted down from a Taiwanese mirror using archive.org. Two: The various Perl modules you need will use differe Perl HERE docs (Score:2) For example, php embeds code-like active statements in between static html. where as perl embeds HTML text in between perl commands. Each of them requires designated separators to keep the text and commands separated. to be a little more specific, since perl had HERE stat Re:Ain't php great? (Score:2, Funny) rmstar Buy a Book v.s Web Resources (Score:5, Insightful) I've been doing PHP web development on and off for a couple of years now and I've always found that it's greatest strength has been the availability of very god online resources. PHP.net [php.net] and many other excellent resources are only a browser click away and remain up to date for free. PHP is one of those areas where I'll save my money and buy a book I'll get genuine reference use from. Re:Buy a Book v.s Web Resources (Score:3, Insightful) Re:Buy a Book v.s Web Resources (Score:2) Re:Buy a Book v.s Web Resources (Score:2) I can still fit more useful content on my desk than I can on a single visible desktop. Re:Buy a Book v.s Web Resources (Score:2) Just because I can easily find a way to do X on the php.net site (which is admittedly where I've learned shitloads), doesn't mean the methods found are any good... The Cookbooks are wonderful! (Score:2, Insightful) Things PHP is missing (Score:4, Insightful) 2) Native XML support - It's just not there? Why re-invent the wheel each time? Give us a good XML tree-walking engine DAMMIT! 3) sane and consistant functions. Single quotes, double quotes, some functions work with both, some work with one or the other, embedded html in an echo screws up if you don't double quote it, etc. 4) In short, PHP is a good language for small projects, but just doesn't cut it in an enterprise setting. Re:Things PHP is missing (Score:2, Informative) Re:Things PHP is missing (Score:5, Informative) I believe there is a PEAR package [php.net] that abstracts an OO layer over the functions to various databases. Think DBI for PHP. 2) Native XML support - It's just not there? Why re-invent the wheel each time? Give us a good XML tree-walking engine DAMMIT! Natvie XML support is there. A SAX parser is usually built in by default. I'm happily using a DOM XML interface that I compiled into my version. 3) sane and consistant functions. Single quotes, double quotes, some functions work with both, some work with one or the other, embedded html in an echo screws up if you don't double quote it, etc.). 4) Um.... why? Re:Things PHP is missing (Score:2)). Not yet, AFAIK, but you can always use the heredoc [php.net] syntax to achieve the same effect -- the only problem is that the heredoc terminators kind of disturb your indentation. Still very useful for large string literals.... You aren't looking in the right places. (Score:2) The parent poster complains about "consistant (sp) database integration" as one of the main problems with PHP. This is usually a problem noted only by those who haven't used PHP in serious development. Sure, if you're writing a 20-line script that you know is only going to use MySQL, then who cares what database connection statements you're Don't judge PHP/XML yet, look forward to PHP5. (Score:2, Interesting) There is a lot of work on a complete new DOM extension, which should clean up the mess done in domxml as of PHP 4. It will follow the W3C DOM API as much as possible and is completely rewritten from scratch. Furthermore Sterling Hughes is working on SimpleXml [edwardbear.org]. An extension which should make it much easier to access XML Documents with the usual PHP functions. The SAX Parser in PHP 5 will also be based on libxml2 and not anymore on the aging expat library. XML Val Re:Things PHP is missing (Score:2) Try ADOdb [weblogs.com]. It is a database access library for PHP which seems to work well. Re:Things PHP is missing (Score:2) There are legitimate criticisms of PHP, but these aren't them. Re:Things PHP is missing (Score:2) 1) consistant database integration - Why not have a SetDBType() function, rather than hardcoding mysql_connect, mssql_connect, myodbc_connect, pgqsl_connect, etc? Because different databases do different things, and abstracting degrades performance -- you CAN, however use ODBC with PHP. I do abstract whenever time allows. Manual abstraction is easy. There's a DB:: class in PEAR [php.net] as well as ADOdb [weblogs.com]. 2) Native XML support - It's just not there? Why re-invent the wheel each time? Give us a good XML tree-walki Re:Things PHP is missing (Score:2, Informative) As a side effect, implementing one database call, even with a db_type parameter in the database calls, gives a certain level of abstraction which would allow for greater cross portability. It also helps with application debugging, generating the error closer to the actual failure point, rather than in the wrapper class itself. Sick and tired of this (Score:2, Insightful) I'm a PHP/MySQL junkie, and every time I see anything about PHP on </rant> Good learning tool (Score:2, Insightful) The examples of integrating to MySQL were especially useful as I have been playing with Microsoft Access using MySQL as server, and now I can easily create web Hmm (Score:2) Re:Hmm (Score:2, Informative) An entire chapter [php.net] in the manual for it. The perfect companion for this book... (Score:4, Informative) JP Re:The perfect companion for this book... (Score:3, Funny) News? Publish date = Nov 2002 (Score:2, Insightful) Excellent book, I heartily recommend it to any... (Score:4, Informative) Relevant, real-life useful examples are given and even a seasoned pro like me picked up a few gems like the example user authentication code that utilizes a hash instead of having to go back to the database on each page fetch. My bookshelves are full of PHP books but most of them are inferior to the online documentation at php.net. They add nothing and are a true waste of trees. This one, however, does not fall into that category. I'd give anything (Score:3, Insightful) At worst, every database connection is hard-coded in a different place and there are no comments anywhere. In either case, my God help anyone who wants to add functionality. These same people need a good book on relational database design, or be subjected to 4 years of universigy RDBMS design courses like I was. IMO, if you aren't willing to slit your wrists to get out of an RDBMS design class, you haven't taken enough of them. Re:I'd give anything (Score:2) What? No OOP fight? (Score:2, Funny) Re:What? No OOP fight? (Score:2) Wait for PHP5. :) Definitely Worth the Buy (Score:2, Informative) I would be ecstatic... (Score:2) Instead, I've got to write ugly crap like "if (strpos($alltext, "This string") >-1)" in order to check if a variable contains a string. In Perl? "if ($alltext ~= "This string")". Much nicer. Re:I would be ecstatic... (Score:2) if (preg_match('This string', $alltext)) Re:PDFs? (Score:3, Informative) Re:PDFs? (Score:5, Informative) "An open file format specification, PDF is available to anyone who wants to develop tools to create, view, or manipulate PDF documents." Re:PDFs? (Score:2) *Obligatory PHP flame from the Perl Guy * Of course unlike Perl there are no easy/good ways to create one in PHP */Obligatory PHP flame from the Perl Guy* All PDF generators suck (Score:3, Insightful) Of course unlike Perl there are no easy/good ways to create one in PHP */Obligatory PHP flame from the Perl Guy* There are no good ways to create one in any language. Current solutions are either: (1) A thin shell over text and graphics primitives or (2) dependent on an external rendering engine which creates another format like Postscript. I'd like a high-level PDF creation library that would let me, say, directly create a table that is sized to fit the contents lik Re:PDFs? (Score:3, Informative) Re:PDFs? (Score:2) No, PDF is open... (Score:5, Informative) If you're interested in generating PDFs from PHP, there are a myriad of options available by searching Google [google.com]. Some web hosting companies [simpli.biz] also support generating PDFs from PHP, which makes generating PDFs a cinch. HTH! Re:PDFs? (Score:3, Informative) And, yes, it appears to be legal. (It better be, considering I use it at my job.) Re:PDFs? (Score:4, Informative) Can you generate a PDF with PHP without also generating an Adobe lawsuit? There's no liability shield built in, but FPDF [fpdf.org] is a great tool that can generate PDFs using PHP without the need for using a commercially-licensed (read "expensive") PDF generating library. I like it because it is distributed under a BSD-like license. Student Suspended Over Suspected Use of PHP (Score:3, Funny) sch Re:Student Suspended Over Suspected Use of PHP (Score:2) Re:Best of all (Score:2) Re:Best of all (Score:2) Re:Best of all (Score:2) Re:Speaking of FUD (Score:3, Insightful) That doesn't even remotely make sense. Most browsers have javascript built-in, so that should decide what language to use server-side? Personally, keeping javascript for client-side and PHP or whatever for server-side is less confusing. That contextual switch is easier when the client-side / server-side code looks different. Now I'm off to f Re:Speaking of FUD (Score:3, Informative) Remember, PHP is to ASP as Zend is to VBScript. Re:Speaking of FUD (Score:5, Informative) You have that ass-backwards. PHP is the language, Zend, the engine. Any other scripting language could be developed and used with the Zend engine. cool (Score:2) Can I get an ECMA engine for it? Re:Speaking of FUD (Score:5, Insightful) So what are you saying is better than PHP? Running ASP with Javascript (or ECMAscript to be pedantic)? If you can tell me that handling forms and working with databases can be done better with something other than PHP please do. Also, please tell us what is a 'bigger' language, if PHP and *gasp* Perl are so little? I wonder because I started in ASP with VBScript. I learned Perl and PHP and now I do PHP pretty much full time. If I want a script that is blantent CGI I use Perl. To me PHP and Perl completely blow away (not blow chunks) ASP with VBScript -- they are far better languages for web development. I can't say exactly why I think that, but one of the main things for me is the quality of the community surrounding the language. There's a lot more user support for PHP and Perl which to me is more helpful than the MSDN library will ever be. I also like a lot of punctuation -- but that's just a personal preference. As far as switching back and forth between languages (JavaScript and PHP, for example), I never thought it was so silly. To me, doing things client-side is distinctly different from doing things server-side. It's no problem to have different languages for those two things. Especially when have to limit what you do on the client side because every browser is different. It seems to me like wasted effort to spend to much time on JavaScript stuff, because lo and behold browser X won't support what I'm trying to do. If I do it server side in PHP, I have an easier time writing portable code. You certainly have a right to advocate your language of choice, and probably a right to bash others, but could you explain yourself a little better? Re:Speaking of FUD (Score:2) I followed pretty much the same path as you, and once I tried PHP there was no turning back, especially once I discoverd the Smarty Template Engine [php.net]. Everyone doing PHP development should check it out. Re:Speaking of FUD (Score:2) This is going to sound like such a flame, but it's not, honest. What's the benefit of using something like Smarty over just not putting anything besides control flow or variable output in your HTML files? I keep all the real work in a separate file, and never have anything more interesting than for(;;){ foo } in the file with the HTML. And no HTML in the code file, ever. It's always seemed like another layer of complexity (and overhead) for very little return. Or am I missing something? Re:Speaking of FUD (Score:2) Some template solutions are not much better then mixing PHP and HTML but others like Smarty are kick ass. In Smarty, you can put simple presentation lo Re:Speaking of FUD (Score:2) You seem to have missed it before so I'll say it again: you do not need MS in order to u Re:Speaking of FUD (Score:2) Netscape's "solution" was proprietary and costly. They were in the wrong place at the wrong time with the wrong solution; apache was catching on quite well when they were trying to sell kilobuck server "solutions" and balkanize the web - and the geeks who spoke "web" back then (ie you couldn't walk down the street and sho Re:More PHP (Score:5, Interesting) 1 - It lets you mix html and code in. Sure, it's not the only language that lets you do it, but it's still a strength. 2 - It's free, open source (zend crap excluded) 3 - Microsoft hates it. That's always a plus. 4 - It's increadibly flexible and forgiving. Coming from a c background, this is one of it's most useful features to me. As far as I can tell, most programmers are inherantly lazy; They don't want to work harder than necessary to do a good job. In PHP, types are incredibly loose. If you want to use a string as a integer, a float, and a string all in the same line, you don't have to cast it. It just does it, and the incredibly vast majority of the time, it does just how you expected it to. Why can't C be that smart? Re:More PHP (Score:3, Funny) Having a pretty broad background in VisualBasic... *puts on asbestos suit and goggles* And, of cou Re:More PHP (Score:2) How on earth is this a strength? This "feature" is probably single handedly responsible for a significant portion of the absolute crap webapp code out there. Seriously why would you ever, ever want to mix your code with HTML? That's just so 1990's... Re:More PHP (Score:2) When writing web applications, you should always check for error conditions before writing any HTML to the page. You can do that with any language. Obligatory Smarty plug (Score:3, Informative) I thought that PHP did a great job of mixing HTML and code until my PHP apps started reaching a certain size. Even using function calls and classes, templates started getting convoluted. Then I discovered Smarty [php.net] and my whole way of working changed. Smarty is a template manager that allows for more precise separation of content and code. As a super-simple example, lines like become {$vari Re:Obligatory Smarty plug (Score:2) I don't understand this. Why is {$variable} so much easier or less confusing than <?=$variable?> The last time I was hiring PHP developers (thanks Slashdot!), I had a few people in who did this, and they'd walk me through the code. After looking at it, I'd simply change a few characters to make it use "native" PHP code, and ask, "what's the difference, why did changing a few characters make thin Re:More PHP (Score:3, Funny) Types aren't hidden in PHP As anyone can plainly see They are not hidden from your code, They're right there from the time you load. With gettype() they're revealed to you, With *val() you can set them too. There's so much flexibility I can hardly contain my glee. Setting, seeing, casting types, PHP Re:More PHP (Score:2) But consider the number of man hours that are in the slash code... it works... it does what they want... and it's in a language that they know well. There's no reason to ever change it. Re:PHP most pervasive? PERL (Score:2) while ($phpzealots == "annoyed") { utter($meaningless_nonsense); } } That wasn't so hard, was it? Re:Kiss and say goodbye to Java language!! (Score:2) Re:Kiss and say goodbye to Java language!! (Score:2) Actually, PHP really needs an app server (ala Websphere) and some sort of Servlet or EJB-like server-side object. The app server could handle databas Re:Kiss and say goodbye to Java language!! (Score:2) Forget Java man and go to PHP! PHP is 4 times faster than Java technology 'JSP' (Java server pages). This tallies because compiled "C" program is 4 times faster than Java. How on Earth was the above article modded as "interesting"? It's absolute garbage! I use both PHP and Java (and C from time to time) and Mr Coward's "statistics" have zero basis in reality. For one, C is a hell of a lot faster than Java or PHP (unless really really really badly writt Re:Enough MySQL (Score:3, Informative) just like PHP if you want a big, complex, very scalable website; it might be better to go with java, for everything else (>90% of cases, i'm sure) it's easier to do it with PHP. just the same; if you want a heavy duty database, with lots of concurrent updates, and/or triggers, stored procedures and so... well you can do it with Postgres or mortgage your house and use Oracle. for everything else, it's easier, quicker; and MySQL is not easier than PostgreSQL (Score:2) Re:The superiority of PHP over Perl (Score:4, Informative) I did a lot of Perl development before switching to PHP, and some of the things you mention that are missing from Perl are readily available as modules from CPAN [slashdot.org]. But that just adds another point in PHP's favour -- the default install comes with all the stuff you mentioned. Before anyone gets their Perl backs up, let me point out why a good default install is important for web development: you don't always have control over the server, so you can't always get the Perl modules you want. (But if you want to re-write your code, sometimes, you'll get what you need! (Couldn't resist.)) Re:The superiority of PHP over Perl (Score:2) I both agree and disagree... I hate having every_goddamn_function() in the global namespace. I would much rather drag in what I need when I need it, a la perl. However, what drove me from mostly perl development to mostly PHP development is that you're pretty sure you'll have most everything you need built in with the latter. The simple fact of not necessasrily having perl's DBI module installed on a server you don't control (and have no access to gcc on) forced the decision to use PHP for most things over Re:The superiority of PHP over Perl (Score:2, Interesting) some (?) web design (??)... how much of it to begin with? >>Previously I'd used Perl because I'd heard from many people that Perl was the end all and be all of scripting languages for the web. Imagine my suprise to discover that PHP was vastly superior! Perhaps your surprise came from the fact that you were using CGI Perl and that PHP was a fast Apache module? You'd be surprised to learn, though, that today there's also a Perl Apache
http://developers.slashdot.org/story/03/06/06/1611233/php-cookbook
CC-MAIN-2013-48
refinedweb
5,308
72.05
Before knowing the steps. the user should understand what Binding actually means as it is a simple to do and also know as Model Binding in ASP.NET MVC framework. The purpose of Binding is to take data from database and store data into database or in other words we can say Binding helps in retrieving the information and storing information.It is done with the help of HTTP that carries the data you need which can be performed by DefaultModelBinder Now here are the following points that should be followed while Binding in ASP.NET MVC Application 1. Binding Should be preferred over Request.FormThat is in case you are writing like this : [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create() { Recipe recipe = new Recipe(); recipe.Name = Request.Form["Name"]; // return View(); } If you use like the above code that will be wrong because the Model Binder can restrict you from Request and HttpContext properties.Another way will be to use FormCollection parameter public ActionResult Create(FormCollection values) { Recipe recipe = new Recipe(); recipe.Name = values["Name"]; // return View(); } In this way user don't need to dig into the Request object but the ultimate way will be if your data is in Request.Form that should be like this [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Recipe newRecipe) { // return View(); } As this will bind the object automatically 2. Second point to remember is to use Custom Model Binder Extensibility point in the MVC framework is Model Binding that means we can customize the binding according to our use in place of Default Binding for that purpose user need to implement the IModeBinder Interface. public interface IModelBinder { object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext); } 3. Now third point that should be remember while binding is Custom Model Binding via Inheritance As in the second point we got to know about Custom Model Binder now in this point in which Inheritance is highlighted that will help the user to cut down the required amount of work by inheriting the DefaultModelBinder and can add some custom, logic that are required by the user. 4. As while Binding user should use some validation i.e Data Annotations for Validation These types of validation that are applied while Binding are generally used for server-side validation by simply manipulating your model with attributes . public class Recipe { [Required(ErrorMessage="We need a name for this dish.")] [RegularExpression("^Bacon")] public string Name { get; set; } // } 5. Fifth point to remember is recognize Binding and Validation as two phase As binding is to take data from database and store data into database and on the other hand validation is use for checking the application but if you want to perform validation along with binding together in a MVC Model Binder that will be same as DataAnnotationsModelBinder will work For simple property validation then user can override the OnPerpertyValidating method. 6. And the last point to remember is Binding is all about the EnvironmentAs Model Binder helps in separating the code from the request and its associated environment and binder which means to move the data from the routing data into the model.In this case there is no restriction of finding the required data for the model. In Conclusion While Binding in ASP.NET MVC Application keep these points in mind and take the benefits and that will enhance your Binding. Points to Remember while Binding in ASP.NET MVC framework Manipulation of appearance using templates in ASP.NET MVC Application
http://www.c-sharpcorner.com/UploadFile/15812c/points-to-remember-while-binding-in-Asp-Net-mvc-framework/
crawl-003
refinedweb
579
52.19
fewer - use fewer units of a countable resource version 0.203 use fewer 'top level namespaces';, with the introduction of new strictures in perl5 version 18, the following code will stop working: use strict 'English'; use less 'filehandles'; To clarify the matter for our foreign readership, "less" is used for things which are uncounted, while "fewer" is used for counted resources. This library corrects this error by allowing the user to write: use fewer 'filehandles'; Then, both of the following conditions will be true: if ( less->of('filehandles') ) { ... } if ( fewer->of('filehandles') ) { ... } Ricardo SIGNES <rjbs@cpan.org> This software is copyright (c) 2014 by Ricardo SIGNES. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
http://search.cpan.org/~rjbs/fewer-0.203/lib/fewer.pm
CC-MAIN-2016-50
refinedweb
130
50.87
22 November 2011 14:20 [Source: ICIS news] WASHINGTON (ICIS)--The US Commerce Department on Tuesday revised downward the nation’s third quarter gross domestic product (GDP) growth, saying the economy grew at only 2% rather than the 2.5% GDP expansion estimated in late October. This second estimate of US GDP performance in the third quarter was based on more complete source data than were available, the department said, when the first estimate was issued on 27 October. At 2%, the third quarter’s economic performance was still better than the 1.3% GDP advance recorded in the second quarter and marks a reassuring improvement compared with the first quarter’s barely positive 0.4% GDP gain. However, the third quarter’s downward revision from 2.5% to 2% indicates that the ?xml:namespace> In addition, 2% growth is not expected to make any headway in reducing the nation’s 9% unemployment rate. To make any substantial inroads on the jobless figures, the The department will issue its third and final estimate of the nation’s third quarter GDP performance on 22 De
http://www.icis.com/Articles/2011/11/22/9510632/us-q3-gdp-revised-downward-to-2-slower-than-first-thought.html
CC-MAIN-2014-49
refinedweb
184
54.12
Today's Page Hits: 472 Yes, JDK 6 has been released today. As many of you know already, scripting is one of the important features of JDK 6. Scripting API is in the javax.script package which is specified by JSR-223. It is very simple API to use scripting languages from Java code. To use scripting language from your Java code, you need to have JSR-223 compliant "script engine" - i.e., implementation of the javax.script API for your language of choice. Sun's implementation of JDK 6 comes with JavaScript script engine - which is based on Mozilla's Rhino implementation. So, you can "eval" JavaScript code from your Java code! Scripting API helps you javax.script.ScriptEngineManager. Please note that to use any language other than JavaScript [which is bundled with JDK 6], you need script engine implementation for your language. You can download jsr-223 script engine most popular scripting languages such as Groovy, JRuby and many other languages from scripting.dev.java.net javax.script.ScriptEnginefor your scripting language, you just evaluate code in that language by calling, guess what, by calling evalmethods. You can evaluate script code from a String or from a java.io.Reader. javax.script.ScriptEnginehas putand getmethods to expose Java objects as "global" variables to script. In addition, there are interfaces such as javax.script.Bindings[Bindings is "scope" - a set of name, value pairs] and javax.script.ScriptContextmay be used for finer control. The later is used to support one or more scopes in the script global namespace. javax.script.Invocable[yes, the bundled JavaScript engine and most engines at scripting.dev.java.net support this optional interface], you can use it to call a specific script function from Java code. This may be used to call script function, say for example, from a user interface event handler. javax.script.Invocablefor this purpose as well. Simple main class to evaluate JavaScript to print "hello world": There are two samples in JDK installation:There are two samples in JDK installation: import javax.script.*; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine jsEngine = manager.getEngineByName("JavaScript"); jsEngine.eval("println('hello world')"); } } If you are interested in using scripting on the serverside code, you may want to look at the Phobos project. This project uses JSR-223 scripting feature. Posted by scriptics on December 14, 2006 at 12:45 PM IST #
http://blogs.sun.com/sundararajan/entry/the_horse_starts_running_jdk
crawl-002
refinedweb
407
67.15
Join the community to find out what other Atlassian users are discussing, debating and creating. Hi, I have a single line text custom field on a project with 7000+ issues that is called Due Time Users have been entering the time in any format into that custom field. What I'd like to do is enforce the simple PHP-style regex below onto the field to standardize it. \d\d?:\d\d (AM|PM)$ Is there an easy way to do this with ScriptRunner's Scripted Fields? I think I would need to copy my existing custom field over to a new Scripted Field first, but I'm not quite sure where to go from there, or if there is a better solution. Thanks, Raina Isn't a better solution just to use a date-time custom field? Failing that you can use a DateFormat in a simple scripted validator as @Vasiliy Zverev suggests. @Jamie Echlin [Adaptavist] I complete agree with you and @Vasiliy Zverev! The problem that we were having was that our users were not properly selecting the time on the date-time custom field in the past. Rather than re-invent the wheel here, I'm going to add the new date-time custom field to replace my old single line text Due Time field and my date picker for Due Date with a date-time custom field called Due Date and Time on the create screen along with a bold red note in the field configuration that says something along the lines of "please set your due time when selecting your date on the calendar". Thank you both! You can use SimpleDateFormat java class to parse string to Date. Here is a example: import com.atlassian.jira.component.ComponentAccessor import java.text.ParseException import java.text.SimpleDateFormat //here we create all requared date fortas SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd") SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd") SimpleDateFormat resultFormat = new SimpleDateFormat("dd/mm/yyyy") String stringToParse = ComponentAccessor.getCustomFieldManager().getCustomFieldObjectByName("fieldName").getValue(issue) Date parsedDate = null; //here we parse it try { parsedDate = format1.parse(stringToParse).toString() } catch (ParseException e){ parsedDate = format2.parse(stringToParse).toString() } if(parsedDate != null) return resultFormat.format(parsedDate) else return "not parsed" Agree with @Jamie Echlin [Adaptavist], use this code to parse date and use date or datetime filed further and you will never have such troubles anymore..
https://community.atlassian.com/t5/Jira-Core-questions/Enforce-regex-on-a-single-line-text-custom-field/qaq-p/368491
CC-MAIN-2019-39
refinedweb
395
53.71
Here is a listing of C++ interview questions on “Declaration” along with answers, explanations and/or solutions: 1. Choose the correct option. extern int i; int i; a) both 1 and 2 declare i b) 1 declares the variable i and 2 defines i c) 1 declares and defines i, 2 declares i d) 1 declares i,2 declares and defines i View Answer Explanation:The keyword extern is not a definition and is not allocated storage until it is initialized. 2. Pick the right option Statement 1:A definition is also a declaration. Statement 2:An identifier can be declared just once. a) Statement 1 is true, Statement 2 is false. b) Statement 2 is true, Statement 1 is false. c) Both are false. d) Both are true. View Answer Explanation:An identifier can be declared many times must be defined just once. 3. Which of the given statements are false. 1. extern int func; 2. extern int func2(int,int); 3. int func2(int,int); 4. extern class foo; a) 3 and 4 only b) 2 and 3 only c) only 4 d) 2, 3 and 4 View Answer Explanation:No extern are allowed for class declarations. 4. Pick the right option Statement 1:Global values are not initialized by the stream. Statement 2:Local values are implicitly initialised to 0. a) Statement 1 is true, Statement 2 is false. b) Statement 2 is true, Statement 1 is false. c) Both are false. d) Both are true. View Answer Explanation:Global values are implicitly initialised to 0, but local values have to be initialised by the system. 5. What is the output of this program? #include <iostream> using namespace std; int g = 100; int main() { int a; { int b; b = 20; a = 35; g = 65; cout << b << a << g; } a = 50; cout << a << g; return 0; } a) 2035655065 b) 2035655035 c) 2035635065 d) none of the mentioned View Answer Explanation:The local values of a and g within the block are more dominant than the global values. Output: $ g++ dec1.cpp $ a.out 2035655065 6. Can two functions declare variables(non static) with the same name. a) No b) Yes c) Yes, but not a very efficient way to write programs. d) No, it gives a runtime error. View Answer Explanation:We can declare variables with the same name in two functions because their scope lies within the function. 7. What is the output of this program? #include <iostream> using namespace std; void addprint() { static int s = 1; s++; cout << s; } int main() { addprint(); addprint(); addprint(); return 0; } a) 234 b) 111 c) 123 d) 235 View Answer Explanation:The variable that is declared as static has a file scope. Output: $ g++ dec2.cpp $ a.out 234 8. What is the output of this program? #include <iostream> using namespace std; int main() { int a = 10; if (a < 10) { for (i = 0; i < 10; i++) cout << i; } else { cout << i; } return 0; } a) 0123456789 b) 123456789 c) 0 d) error View Answer Explanation:We will get compilation error because ‘i’ is an undeclared identifier. 9. Identify the incorrect statements. int var = 10; int *ptr = &(var + 1); //statement 1 int *ptr2 = &var; //statement 2 &var = 40; //statement 3 a) Statement 1 and 2 are wrong b) Statement 2 and 3 are wrong c) Statement 1 and 3 are wrong d) All the three are wrong View Answer Explanation:In statement 1 lvalue is required as unary ‘&’ operand and in statement 3 lvalue is required as left operand. 10. Identify the type of the variables. typedef char* CHAR; CHAR p,q; a) char* b) char c) CHAR d) unknown View Answer Explanation: The statement makes CHAR a synonym for char*. Sanfoundry Global Education & Learning Series – C++ Programming Language. Here’s the list of Best Reference Books in C++ Programming Language. To practice all features of C++ programming language, here is complete set on 1000+ Multiple Choice Questions and Answers on C++.
http://www.sanfoundry.com/interview-questions-answers-c-plus-plus-declaration/
CC-MAIN-2017-30
refinedweb
660
73.47
(For more resources related to this topic, see here.) Quick start – using GLEW You have now installed GLEW successfully and configured your OpenGL project in Visual Studio to use it. In this article, you will learn how to use GLEW by playing with a simple OpenGL program that displays a teapot. We will extend this program to render the teapot with toon lighting by using shader programs. To do this, we will use GLEW to set up the OpenGL extensions necessary to use shader programs. This example gives you a chance to experience GLEW to utilize a popular OpenGL extension. Step 1 – using an OpenGL program to display a teapot Consider the following OpenGL program that displays a teapot with a light shining on it: #include <GL/glut.h> void initGraphics() { glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); const float lightPos[4] = {1, .5, 1, 0}; glLightfv(GL_LIGHT0, GL_POSITION, lightPos); glEnable(GL_DEPTH_TEST); glClearColor(1.0, 1.0, 1.0, 1.0); } void onResize(int w, int h) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, w, h); gluPerspective(40, (float) w / h, 1, 100); glMatrixMode(GL_MODELVIEW); } void onDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0); 11 Instant GLEW glutSolidTeapot(1); glutSwapBuffers(); }; } Create a new C++ console project in Visual Studio and copy the above code into the source file. On compiling and running this code in Visual Studio, you will see a window with a grey colored teapot displayed inside it as shown in the screenshot below: Let us briefly examine this OpenGL program and try to understand it. The main function shown below uses the GLUT API to create an OpenGL context, to create a window to render in and to set up the display function that is invoked on every frame. Instead of GLUT, you could also use other cross-platform alternatives such as the OpenGL Framework (GLFW) library or the windowing API of your platform.; } Here, the call to glutInit creates an OpenGL context and the calls to glutInitDisplayMode, glutInitWindowSize, and glutCreateWindow help create a window in which to render the teapot. If you examine the initGraphics function, you can see that it enables lighting, creates a light at a given position in 3D space, and sets the background color to white. Similarly, the onResize function sets the size of the viewport based on the size of the rendering window. Passing a pointer to the onResize function as input to glutReshapeFunc ensures that GLUT calls onResize every time the window is resized. And finally, the onDisplay function does the main job of setting the camera and drawing a teapot. Passing a pointer to the onDisplay function as input to glutDisplayFunc ensures that GLUT calls onDisplayfunction every time a frame is rendered. Step 2 – using OpenGL extensions to apply vertex and fragment shaders One of the most common uses of GLEW is to use vertex and fragment shader programs in an OpenGL program. These programs can be written using the OpenGL Shading Language (GLSL). This was standardized in OpenGL 2.0. But, most of the versions of Windows support only OpenGL 1.0 or 1.1. On these operating systems, shader programs can be used only if they are supported by the graphics hardware through OpenGL extensions. Using GLEW is an excellent way to write portable OpenGL programs that use shader programs. The program can be written such that shaders are used when they are supported by the system, and the program falls back on simpler rendering methods when they are not supported. In this section, we extend our OpenGL program to render the teapot using toon lighting. This is a simple trick to render the teapot using cartoonish colors. We first create two new text files: one for the vertex shader named teapot.vert and another for the fragment shader named teapot.frag. You can create these files in the directory that has your OpenGL source program. Copy the following code to the teapot.vert shader file: varying vec3 normal, lightDir; void main() { lightDir = normalize(vec3(gl_LightSource[0].position)); normal = normalize(gl_NormalMatrix * gl_Normal); gl_Position = ftransform(); } Do not worry if you do not know GLSL or cannot understand this code. We are using this shader program only as an example to demonstrate the use of OpenGL extensions. This shader code applies the standard transformations on vertices. In addition, it also notes down the direction of the light and the normal of the vertex. These variables are passed to the fragment shader program which is described next. Copy the following code to the teapot.frag shader file: varying vec3 normal, lightDir; void main() { float intensity; vec3 n; vec4 color; n = normalize(normal); intensity = max(dot(lightDir, n), 0); if (intensity > 0.97) color = vec4(1, .8, .8, 1.0); else if (intensity > 0.25) color = vec4(.8, 0, .8, 1.0); else color = vec4(.4, 0, .4, 1.0); gl_FragColor = color; } Again, do not worry if you do not understand this code. This fragment shader program is executed at every pixel that is generated for display. The result of this program is a color, which is used to draw that pixel. This program uses the light direction and the normal passed from the vertex shader program to determine the light intensity at a pixel. Based on the intensity value, it picks one of three possible shades of purple to color the pixel. By employing these shader programs, the teapot is rendered in toon lighting like this: However, to get this output our OpenGL program needs to be modified to compile and load these shader programs. Step 3 – including the GLEW header file To be able to call the GLEW API, you need to include the glew.h header file in your OpenGL code. Make sure it is placed above the include files of gl.h, glext.h, glut.h, or any other OpenGL header files. Also, if you include glew.h, you don't really need to include gl.h or glext.h. This is because GLEW redefines the types and function declarations that are in these OpenGL header files. #include <GL/glew.h> #include <GL/glut.h> Step 4 – initializing GLEW GLEW should be initialized before calling any of its other API functions. This can be performed by calling the glewInit function. Ensure that this is called after an OpenGL context has been created. For example, if you are using GLUT in your OpenGL program, call glewInit only after a GLUT window has been created. The code shown below initializes GLEW: GLenum err = glewInit(); if (GLEW_OK != err) { printf("GLEW init failed: %s!\n", glewGetErrorString(err)); exit(1); } else { printf("GLEW init success!\n"); } The call to glewInit does the hard work of determining all the OpenGL extensions that are supported on your system. It returns a value of GLEW_OK or GLEW_NO_ERROR if the initialization was successful; otherwise, it returns a different value. For example, if glewInit is called before an OpenGL context was created, it returns a value of GLEW_ERROR_NO_GL_VERSION. You can find out the cause of a GLEW error by passing the return value of glewInit to the function glewGetErrorString as shown above. This returns a human-readable string that explains the error. Step 5 – checking if an OpenGL extension is supported New or enhanced functionality in the OpenGL API is provided by the means of an extension. This typically means that new data types and API functions are added to the OpenGL specification. Details of the name and functionality of any extension can be found in the OpenGL. In our example, we want our OpenGL program to be able to use GLSL vertex and fragment shaders. This functionality has been provided using extensions that are named GL_ARB_vertex_shader and GL_ARB_fragment_shader. These extensions provide functions to create shader objects, set the shader source code, compile it, link it, and use them with an OpenGL program. Some of the functions provided by this extension are listed below: glCreateShaderObjectARB(); glShaderSourceARB(); glCompileShaderARB(); glCreateProgramObjectARB(); glAttachObjectARB(); glLinkProgramARB(); glUseProgramObjectARB(); To be able to use these functions in our OpenGL program, we first check if the extension is enabled in our system. Depending on the graphics hardware and drivers on your system, not every OpenGL extension might be available and usable on your system. For example, most versions of Windows support only OpenGL 1.0 or 1.1. The drivers supplied by graphics hardware vendors, such as NVIDIA or AMD for example, might support more recent versions of OpenGL and OpenGL extensions. Every OpenGL extension has a name of the form GL_VENDOR_extension_name. The VENDOR may be NV, ATI, APPLE, EXT, ARB, or any such supported vendor name. An extension created by a single vendor is called a vendor-specific extension. If it is created by many vendors, it is called a multivendor extension. If many users find an extension to be a good enhancement, it is promoted to an ARB-approved extension. Such extensions might be integrated into future versions of OpenGL as a core feature. To check for an extension using GLEW, you check if a global boolean variable named GLEW_VENDOR_extension_name is set to true. These variables are defined and their values are set when you initialize GLEW using glewInit. So, to test if vertex and fragment shaders are supported, we add the following code: if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader) { printf("No GLSL support\n"); exit(1); } In this example, we exit the program if these extensions are not supported. Alternatively, you could write the program so that it switches to a simpler or alternate rendering method if the extension you want is not supported. Summary This article provided you the details to use GLEW with OpenGL code using a simple example of teapot rendering. Resources for Article : Further resources on this subject: - Introduction to Modern OpenGL [Article] - Tips and Tricks for Getting Started with OpenGL and GLSL 4.0 [Article] - Android Native Application API [Article]
https://www.packtpub.com/books/content/using-glew
CC-MAIN-2016-30
refinedweb
1,651
63.7
#include <CCAENChain.h> List of all members. Chains consist of a start card (left most module in the chain), an end card (right most module in the chain) and a set of intermediate cards which must not skip any slots, and must live to the right of the start card and to the left of the end card. Sample good chain for a crate: +-+-+-+-+-+-+-+-+-+ |S I I I E x x x x| +-----------------+ S - Start card I - Intermediate card E - End card x - Don't care - - Empty slot. Sample invalid chains: +-+-+-+-+-+-+-+-+-+ |S I - I E x x x x| +-----------------+ Empty slot in the middle of a chain. +-+-+-+-+-+-+-+-+ |I S I I E x x x| +---------------+ Intermediate card not in between Start and End cards. In general, if you have a system of geographical addressing, you won't need to worry about this, just plug the cards in and designate to the constructor the range of slots you'll be using. If you don't have slot addressable cards, you'll have to be sure that the STD(vector) of base addresses you supply really corresponds to a valid chain or errors will occur. Definition at line 99 of file CCAENChain.h. Destroy the chain. This involves: Definition at line 220 of file CCAENChain.cpp. References FreeModules(), and m_pHandle. forbidden!! Card driver objects for the chain. forbidden!! Forbidden!! Forbidden!!! Definition at line 127 of file CCAENChain.h. Definition at line 130 of file CCAENChain.h. References m_nCBLTAddress. Definition at line 133 of file CCAENChain.h. Definition at line 136 of file CCAENChain.h. Definition at line 139 of file CCAENChain.h. References m_nMaxBytes. Definition at line 148 of file CCAENChain.h. Definition at line 151 of file CCAENChain.h. References m_nCBLTAddress. Definition at line 154 of file CCAENChain.h. Definition at line 157 of file CCAENChain.h. Definition at line 160 of file CCAENChain.h. References m_nMaxBytes. Retrieve a card pointer. Select a module from the chain. Definition at line 236 of file CCAENChain.cpp. Read an event from cards. Read an event from the chain. This is done by issuing a read of m_nMaxBytes long. The cards set themselves up in a chain to Buserr on end of data so the actual number of bytes read will, in general, be fewer. CCAENChain chain(...); ... long buffer[chain.getMaxBytes()/sizeof(long)]; ... ReadEvent(buffer); ... long* pBuffer = new long[chain.getMaxByte()/sizeof(long)]; ... ReadEvent(pBuffer); Definition at line 282 of file CCAENChain.cpp. References DMA_THRESHOLD, m_nCBLTAddress, m_nCrate, m_nMaxBytes, and m_pHandle. Clear constituent cards. Clear the data in all cards. Definition at line 308 of file CCAENChain.cpp. Turns on the EMPTY_PROG bit of the Bit2 control/status register on the right most module in the chain.. When enabled, this bit implies that the last module in the chain will provide a header/trailer longword if it got a gate, if there is no data. This is intended to help unambiguously identify the end of data. The SBS PCI/VME interface has a deeply pipelined DMA engine. It is not able to reliably deliver partial transfer counts for DMA that end in a BUSERR e.g. However, in most cases, doing a CBLT read will result in a partial transfer terminating in a BUSERR. If the modules in the chain all have a common GATE, this ensures there are always a header/trailer from the last module in the chain, and that data can allow an unambiguous determination of the end of the chain data. Typically one would use this by placing the data from the chain read in a packet. Processing the data in the packet until the trailer from the last ADC in the chain, but using the packet word count to determine where the next chunk of data is. Definition at line 351 of file CCAENChain.cpp. References CAENcard::emptyEnable(), and lastCard(). This turns off the EMPTY_PROG bit of the Bit2 stat of the right most module in the chain. See lastModuleEmptyEnable for an full discussion of what that means. This is the default state (disabled). Definition at line 365 of file CCAENChain.cpp. References CAENcard::emptyDisable(), and lastCard(). Kill all modules driver objects. (utility). Frees the set of moudules that exist in the chain. This is done both at destruction and for exceptions that occur in the constructor. Definition at line 324 of file CCAENChain.cpp. Referenced by ~CCAENChain(). Definition at line 375 of file CCAENChain.cpp. Referenced by lastModuleEmptyDisable(), and lastModuleEmptyEnable(). CBLT address assigned to the chain. Definition at line 103 of file CCAENChain.h. Referenced by getCBLTAddress(), ReadEvent(), and setCBLTAddress(). VME crate containing the chain. Definition at line 104 of file CCAENChain.h. Referenced by getCrate(), ReadEvent(), and setCrate(). Handle to he VME crate for Read. Definition at line 105 of file CCAENChain.h. Referenced by getVmeHandle(), ReadEvent(), setHandle(), and ~CCAENChain(). Calculated maximum transfer size. Definition at line 106 of file CCAENChain.h. Referenced by getMaxBytes(), ReadEvent(), and setMaxBytes(). Ptr to base address. Definition at line 107 of file CCAENChain.h.
http://docs.nscl.msu.edu/daq/modules/alldoxy/classCCAENChain.html
CC-MAIN-2013-20
refinedweb
832
68.87
UpdatePV Sample: Implements an Updatable OLE DB Provider The UpdatePV sample is an OLE DB Provider Templates sample that demonstrates how to implement an updatable (read/write) provider. Specifically, it demonstrates how to perform immediate and deferred inserts/updates/deletes. UpdatePV also demonstrates how to use schema rowsets (which make it easier for some wizards to interact with a provider). UpdatePV also demonstrates the IRowsetLocateImpl class, as does MyProv. See the AdvancedPV sample for illustrations of additional techniques on loading and saving data with a provider. Building and Running the Sample To demonstrate the sample's intended features, build the sample, create a consumer project with an accessor for the provider, and create a console application to access and output the data. To build and run this sample Open the solution file UpdatePV.sln. From the Build menu, click Build Solution. Create a consumer project with the ATL Project wizard (make it an attributed .dll). Add an OLE DB consumer to the consumer project (from Add Class, select ATL OLE DB Consumer). In the ATL OLE DB Consumer wizard, click the Data Source button and in Data Link Properties, select UpProv OLE DB Provider. (The UpProv provider should be registered automatically when you build UpdatePV, but if you don't see it listed here, run regsvr32.exe on UpdatePV.dll.) Click Next to go to the Connection tab, then under Enter the initial catalog to use, make sure the path name to MyData.txt is correct. Click Ok. The Select Database Object dialog will appear, then open Tables; there is only one item: the path name for MyData.txt. Select it and click OK. You return to the ATL OLE DB Consumer wizard. In the ATL OLE DB Consumer wizard, select Table, rename the class to something shorter (if necessary) such as CMyCons, and click Finish. Dismiss the security warning dialog that pops up by pressing OK. Remove this line from CMyCons.h: This line will prevent compilation, but is inserted to alert you to the fact that (in real-world scenarios) sensitive information should be protected. Build the consumer project by right-clicking on the project's node in the Solution Explorer and clicking Build. Create a new console application. In the .cpp file, include the consumer header and modify the code as follows: #include "stdafx.h" #include <atldbcli.h> #include "..\consumer\cmycons.h" int _tmain(int argc, _TCHAR* argv[]) { HRESULT hr = CoInitialize(NULL); CMyCons c; hr = c.OpenAll(); ATLASSERT( SUCCEEDED( hr ) ); hr = c.MoveFirst(); while( SUCCEEDED(hr) && hr != DB_S_ENDOFROWSET ) { printf( "%d %s %s %s %s\n", c.m_Fixed, c.m_Command, c.m_Text, c.m_Command2, c.m_Text2 ); hr = c.MoveNext(); } c.CloseAll(); CoUninitialize(); return 0; } Place a breakpoint on the CoUninitialize function; this will make the console stay open so you can view the results. Run the console application from the development environment by clicking the Start button. You should see five columns of text printed out (one index column and four text columns). How the Sample Works UpdatePV is built on top of the C run-time file I/O functions. This represents a data store. Specifically, the sample takes a text file consisting of a pair of data elements and turns it into a rowset. The sample comes with a text file, MyData.txt, that contains pairs of data elements. However, you can run it against any text file (it will just parse everything into two-word tuples). UpdatePV performs its read operations with RUpdateRowset::Execute (rowset.h). The write operations are handled with RUpdateRowset::FlushData (rowset.h). These are functions called by the OLE DB Provider Templates as part of the normal provider operation. The sample uses the OLE DB Provider Templates IRowsetChangeImpl and IRowsetUpdateImpl classes. The IRowsetChangeImpl class provides support for immediate inserts/updates/deletes. The IRowsetUpdateImpl class support deferred inserts/updates/deletes. The IRowsetUpdateImpl class inherits from IRowsetChangeImpl. For more information on getting/setting data, read Creating an Updatable Provider in the Visual C++ documentation, and Updating Data in Rowsets in the OLE DB Programmer's Reference in the Platform SDK documentation. UpdatePV also provides support for schema rowsets. These schema rowsets allow consumers to find out information about a provider without opening a rowset or executing a command. The Visual C++ wizards use schema rowsets to generate client side accessors. The primary functions are CUpdateSessionTRSchemaRowset::Execute, CUpdateSessionColSchemaRowset::Execute, and CUpdateSessionPTSchemaRowset::Execute. All three functions return information on what tables the provider supports, columns on the tables, and the data types on the tables. For further information on schema rowsets, see the IDBSchemaRowset interface in the OLE DB Programmer's Reference. Keywords The sample demonstrates the following interfaces: IRowsetChange, IRowsetUpdateImpl The sample demonstrates the following properties: DBPROP_IRowsetChange, DBPROP_IRowsetUpdate
https://msdn.microsoft.com/en-us/library/vstudio/w87e7c27(v=vs.80).aspx
CC-MAIN-2015-14
refinedweb
784
57.87
As for the problem, the length of two linked list are not guaranteed to be the same. so in the while loop. "||" is used in order to go through all the nodes in both lists. the additional condition is that what i added after the OJ throws out a error as for 5->null 5->null ------------ 0->1->null; without the additional condition, 0->null will return, which is definitely not correct. In each loop, res gets values from both lists(), res % 10 returns the digit value for current position; res/10 returns the value which is called carry used for the calculation for the next position. Hope it may help you. ''' public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode head = dummy; int res =0; while(l1 != null || l2 != null|| res != 0){ if(l1 != null){ res += l1.val; l1= l1.next; } if(l2 != null){ res += l2.val; l2 = l2.next; } ListNode anode = new ListNode(res%10); head.next = anode; head = head.next; res = res/10; } return dummy.next; } } '''
https://discuss.leetcode.com/topic/62168/java-solution-with-explanation
CC-MAIN-2017-47
refinedweb
176
77.13
Opened 5 years ago Closed 5 years ago Last modified 3 months ago #5178 defect closed wontfix (wontfix) Traceback object removed from Failure when it reaches end of Deferred callback chain Description (Moved from mention in #3622) When a Deferred is errback'd with no handlers currently in the callback chain, the Failure is cleaned (with cleanFailure) and then stored in the Deferred's DebugInfo. However, the Deferred's Failure is not copied, but instead used for this, mutating it. If the Deferred is used in an @inlineCallbacks function and caught as a normal exception, it then Attachments (1) Change History (7) comment:1 Changed 5 years ago by forrestv - Type changed from enhancement to defect Changed 5 years ago by forrestv comment:2 Changed 5 years ago by forrestv - Keywords defer review added comment:3 Changed 5 years ago by exarkun - Keywords review removed - Owner set to forrestv Thanks for your interest in this area, forrestv. I think the solution in the patch is problematic. The rest of the _runCallbacks code takes great care to ensure that an uncleaned Failure will not last past the end of the callback processing. It is not an accident that the Failure on the Deferred is shared with the _DebugInfo and that it gets cleaned, it is intentional. If the Failure remains uncleaned, then it keeps references to every local on the call stack at the time of the exception. This has terrible consequences for memory usage and cyclic garbage creation. The issue described here, that tracebacks associated with Deferreds with failure results are not always fully informative, is real. However, limitations in the Python runtime mean that it is very, very difficult to fix this. On the one hand I want to close this ticket as wontfix (or cantfix, but we don't have that status). On the other hand, it is a real shortcoming, and it would be nice if someone figured out a real way to fix it. Another approach you might consider, though, is that maybeDeferred only serves to introduce this problem in this particular example. Stop using it and the problem goes away: import traceback from twisted.internet.defer import inlineCallbacks def bad(): raise RuntimeError("foo") def good(): return 42 @inlineCallbacks def foo(): for f in good, bad: try: result = yield f() except: print 'Failure' traceback.print_exc() else: print 'Success', result foo() produces output: Success 42 Failure Traceback (most recent call last): File "foo.py", line 16, in foo result = yield f() File "foo.py", line 7, in bad raise RuntimeError("foo") RuntimeError: foo comment:4 Changed 5 years ago by radix also, if you use log.err() instead of traceback.print_exc(), you'll get a better traceback, even if you do use maybeDeferred. comment:5 Changed 5 years ago by exarkun - Resolution set to wontfix - Status changed from new to closed Thanks again for your interest. In the light of the above comments, I think I will close this as wontfix. Improvements to Failure are welcome, but they need to be made carefully and with consideration of Failure's more subtle (often undocumented) goals. I encourage you to raise the issue on the twisted-python mailing list or the #twisted irc channel on freenode. comment:6 Changed 3 months ago by forrestv Thanks for the responses. They all make complete sense, of course. However, I just ran into the same problem again, and reduced it down to your example, exarkun, except with bad() and good() being inlineCallbacks functions too: import traceback from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def bad(): raise RuntimeError("foo") yield # just to make this a generator @inlineCallbacks def good(): returnValue(42) yield # just to make this a generator @inlineCallbacks def foo(): for f in good, bad: try: result = yield f() except: print 'Failure' traceback.print_exc() else: print 'Success', result foo() produces: Success 42 Failure Traceback (most recent call last): File "y.py", line 19, in foo result = yield f() RuntimeError: foo It happens in this situation because the Deferred produced by calling bad/good doesn't have a callback attached until after it has already errback'd. I thought that it was interesting that this could happen in such a surprising manner: exceptions raised in an inlineCallbacks function after it waits on something for the first time get through with their traceback intact, but exceptions raised before the first yield don't. There's no apparent way to avoid this issue (besides using log.err), unlike my first example, which had to use maybeDeferred. Leaving closed because all the previous discussion still applies; this is just a postmortem that might help others. However, in #3622, spiv said *Perhaps* we could skip the cleanFailure call you mention if setDebugging(True) is active? which seems like a potential fix for the headaches this has caused me (and probably others). Another useful avenue might be stating that log.err is preferred to traceback.print_exc in the documentation for using inlineCallbacks. patch to duplicate the Deferred's Failure before cleaning it to store it in DebugInfo
http://twistedmatrix.com/trac/ticket/5178
CC-MAIN-2016-07
refinedweb
840
59.53
Tutorial: Deploy an Azure Kubernetes Service (AKS) cluster Kubernetes provides a distributed platform for containerized applications. With AKS, you can quickly create a production ready Kubernetes cluster. In this tutorial, part three of seven, a Kubernetes cluster is deployed in AKS. You learn how to: - Deploy a Kubernetes AKS cluster that can authenticate to an Azure container registry - Install the Kubernetes CLI (kubectl) - Configure kubectl to connect to your AKS cluster In additional tutorials, the Azure Vote application is deployed to the cluster, scaled, and updated. Before you begin In previous tutorials, a container image was created and uploaded to an Azure Container Registry instance. If you haven't done these steps, and would like to follow along, start at Tutorial 1 – Create container images. This tutorial requires that you're running the Azure CLI version 2.0.75 or later. Run az --version to find the version. If you need to install or upgrade, see Install Azure CLI. Create a Kubernetes cluster AKS clusters can use Kubernetes role-based access controls (RBAC). These controls let you define access to resources based on roles assigned to users. Permissions are combined if a user is assigned multiple roles, and permissions can be scoped to either a single namespace or across the whole cluster. By default, the Azure CLI automatically enables RBAC when you create an AKS cluster. Create an AKS cluster using az aks create. The following example creates a cluster named myAKSCluster in the resource group named myResourceGroup. This resource group was created in the previous tutorial. To allow an AKS cluster to interact with other Azure resources, an Azure Active Directory service principal is automatically created, since you did not specify one. Here, this service principal is granted the right to pull images from the Azure Container Registry (ACR) instance you created in the previous tutorial. az aks create \ --resource-group myResourceGroup \ --name myAKSCluster \ --node-count 2 \ --generate-ssh-keys \ --attach-acr <acrName> After a few minutes, the deployment completes, and returns JSON-formatted information about the AKS deployment. Note To ensure your cluster to operate reliably, you should run at least 2 (two) nodes. Install the Kubernetes CLI To connect to the Kubernetes cluster from your local computer, you use kubectl, the Kubernetes command-line client. If you use the Azure Cloud Shell, kubectl is already installed. You can also install it locally using the az aks install-cli command: az aks install-cli Connect to cluster using kubectl To configure kubectl to connect to your Kubernetes cluster, use the az aks get-credentials command. The: $ kubectl get nodes NAME STATUS ROLES AGE VERSION aks-nodepool1-12345678-0 Ready agent 32m v1.13.10 Next steps In this tutorial, a Kubernetes cluster was deployed in AKS, and you configured kubectl to connect to it. You learned how to: - Deploy a Kubernetes AKS cluster that can authenticate to an Azure container registry - Install the Kubernetes CLI (kubectl) - Configure kubectl to connect to your AKS cluster Advance to the next tutorial to learn how to deploy an application to the cluster. Feedback
https://docs.microsoft.com/en-us/azure/aks/tutorial-kubernetes-deploy-cluster
CC-MAIN-2019-51
refinedweb
512
53
This is how you run the program: java FooFirst, notice the command to run a Java program is called java. The compiler, by contrast, is called javac (pronounced Java-see). Second, you give the name of the class, without any extension. In particular, you do not put Foo.class (nor Foo.java). What happens when a program is run? It looks for the main() method, and runs all the statements in the body. For example, suppose the following code is in Foo.java. public class Foo { public static void main( String [] args ) { System.out.println( "Greetings, fellow programmer!" ) ; int count = 2 ; count *= 2 ; System.out.println( "I say \"hi\"" + count + " times " ) ; } }There are four statements in main(). The first statement prints a greeting. The second statement declares count and initializes it to 2. The third statement does a compound assignment statement, and multiplies count by 2 which makes it 4. Finally, the last line prints: I say "hi" 4 times. Notice that we needed an escape sequence to print out the double quotes within a String. C and C++ programmers may be surprised to learn that more than one class can have a main() (in C/C++, there can only be one main()---and it's isn't even in a class!). This doesn't cause a problem. When you run a program, you must pick a single class, and it runs the main() method of that class. If that class does not have a main(), then the program won't run. Classes can also have other methods besides main(). Here's an example: public class Foo { public static void main( String [] args ) { System.out.println( "Greetings, fellow programmer!" ) ; int count = 2 ; count *= 2 ; System.out.println( "I say \"hi\"" + count + " times " ) ; } void printHi() { System.out.println( "Hi" ) ; } } Now you might ask "Why would you write a method in a class that's not run? Why write it in the first place?". It turns out these methods can run, but you have to do something special to make it happen. These methods have to be invoked (which means that somewhere else, some method must "call" this method). Only main() is automatically invoked when you run it. Methods in a class (except main()) don't run, unless they are invoked. Alas, you have to wait to figure out this means. For now, only the code in main() runs, and then only if you call java on the class which this main() exists.
http://www.cs.umd.edu/users/clin/MoreJava/Cycle/run.html
crawl-003
refinedweb
411
85.28
This is part of a series I started in March 2008 - you may want to go back and look at older parts if you're new to this series. First of all, here's the biggest reason I've been so excrutiatingly slow with getting this part together (at least that's my story, I guess I've had other things on my plate too...): Tristan is 13 months now, and a real menace to my laptop (pulling off keys and drooling on the screen) and anything else within reach, and a real attention seeker... So, whenever I'm slow at posting a new part, I'll blame him. I have no part in the delays at all, of course. None. I'm completely faultless... For starters, here's the commit that covers most of this To support define_method we need to support blocks with arguments. Really, full closures. If you haven't already, you should read my post on closures We want this: define_method(:foo) do |a,b| # Do something with a,b end to be mostly equivalent to: def foo a,b # Do something with a,b end For our attr_* implementation we actually want more: def attr_reader sym define_method sym do %s(ivar self sym) # FIXME: Create the "ivar" s-exp directive. end end (or, as it turns out, not really that, as I realize the above can be simplified - if we have a lookup function to lookup the symbol to instance var slot, we can just use our index primitive to get the address; we'll return to that, but the above is the current state of attr_reader) What that calls for is actually proper closures. One step harder. There's the other issue that the above will be really inefficient. As in, requiring a hashtable lookup on every call inefficient, when we can statically determine the offset for any instance variable we know about at compile time. We'll get back to that at some point too, but if you've been following this series you know I care about getting things working first, efficient second. For now attr_reader and friends still serve as a useful test case for basic closure support. The first step towards closures is actually easy (we've already done it). We have our :lambda primitive that creates an anonymous function (which isn't really anonymous, it's just that the name is quitely created in the compiler and not accessible to the programmer). But an anonymous function is only of relatively limited use if you can't bind variables to it - it's not much more than a function pointer in that case. So how do we let "sym" hang around, and how do we take advantage of that for define_method? First, let us consider how you can call a lambda in Ruby: yield Proc#call We could implement Proc#call via yield by passing the block as an argument to a method, if we wanted to, but that would probably be more inefficient than implementing both in terms of a primitive. But this means those are the only things that has to explicitly know how to deal with the environment. That gives us an interesting option. We could turn: c,d = somevalues do |a,b| ... uses c,d end into class SomePrivateUniqueClassName def initialize c,d @c,@d = c,d end def call(a,b) ... code here with access to c,d rewritten end end And we could have it inherit Proc. yield in that case is just rewritten to block.call This does however have the troubling implication of messing with self, and as this irb session shows, we'd have to fix that: >> lambda { p self }.call main => nil >> The other alternative is to create a lightweight environment binding of sorts. Oh wait, we already have that. It's called an object. The problem is not the class above as such, but creating a full class for each block. We could do something like this instead: class Proc def initialize & block # So Proc#initialize takes a block, but we're using this # to create blocks... Uh oh, I sense endless recursion. # We need to make it work so we can initialize a Proc # both from a block and from a raw function pointer end def call *args %s(call @block_func (res args)) end end Our code needs to be rewritten, so that blocks get wrapped in code to create the appropriate Proc object. Additionally, if the method uses variables from the surrounding scope, we need to alter the surrounding method and the block to refer to instance variables in this object, and if any of those variables are arguments to the surrounding scope, we need to copy them. Here's a simple example using a closure. Note the use of s-expressions here because we're now starting to get bitten by the changes we've done to turn Ruby code by default into method calls (the way it should be) without having put in the pre-requisite work to implement the number classes and Kernel methods (such as printf). Ignore that for now. def mkcounter step cnt = 0 lambda do %s(assign cnt (add cnt step)) %s(printf "cnt: %d\n" cnt) end end cnt = mkcounter(5) cnt.call puts "Calling again..." cnt.call puts "Done" And here's the expected output: cnt: 5 Calling again... cnt: 10 Done And here's the syntax tree after we've done the required transformations (more about that in a second): [:do, [:defm, :mkcounter, [:step], [:let, [:__env__, :__tmp_proc], [:sexp, [:assign, :__env__, [:call, :malloc, [8]]]], [:assign, [:index, :__env__, 1], :step], [:assign, [:index, :__env__, 0], 0], [:do, [:assign, :__tmp_proc, [:defun, ".L2", [:self, :__closure__, :__env__], [:let, [], [:sexp, [:assign, [:index, :__env__, 0], [:add, [:index, :__env__, 0], [:index, :__env__, 1]]]], [:sexp, [:printf, "cnt: %d\n", [:index, :__env__, 0]]]]]], [:sexp, [:call, :__new_proc, [:__tmp_proc, :__env__]]]]]], [:assign, :cnt, [:call, :mkcounter, 5]], [:callm, :cnt, :call], [:call, :puts, [[:sexp, [:call, :__get_string, :".L0"]]]], [:callm, :cnt, :call], [:call, :puts, [[:sexp, [:call, :__get_string, :".L1"]]]]] That's a bit of a mouthful, so lets go through it the new bits [:let, [:__env__, :__tmp_proc], This is added to hold a pointer to the environment we create to hold cnt and step, and to hold a pointer to the function we use to create the Proc respectively. [:sexp, [:assign, :__env__, [:call, :malloc, [8]]]], [:assign, [:index, :__env__, 1], :step], [:assign, [:index, :__env__, 0], 0], Then we allocate the environment. We copy the argument, and from now on we use (index env 1) to refer to step. We then carry out the cnt = 0 statement. cnt and step are both moved into the environment because they are used inside the closure. (You may have already picked up that we currently won't handle nested closures - lets leave some fun for later) [:assign, :__tmp_proc, [:defun, ".L2", [:self, :__closure__, :__env__], Then we create a function and assign the address of the function to __tmp_proc. As you can see there are tree synthetic arguments to it: self, __closure__ and __env__. The first is, as you'd expect, the object the method is called on. The second is to be used when passing blocks to a method, and the third is used to refer to the environment when inside. (Something I just realized: We're begging for a name clash, if there's a closure defined inside that needs a separate environment. Obnoxious details; later) [:assign, [:index, :__env__, 0], [:add, [:index, :__env__, 0], [:index, :__env__, 1]]]], And this monstrosity is what cnt = cnt + step was turned into. Now, to make this work, we obviously need this __new_proc function, and a Proc#call that's sensible. Here's our current Proc: class Proc # FIXME: Add support for handling arguments (and blocks...) def call %s(call (index self 1) (self 0 (index self 2))) end end # We can't create a Proc from a raw function directly, so we get # nasty. The advantage of this rather ugly method is that we # don't in any way expose a constructor that takes raw functions # to normal Ruby # %s(defun __new_proc (addr env) (let (p) # Assuming 3 pointers for the instance size. Need a better way for this (assign p (malloc 12)) (assign (index p 0) Proc) (assign (index p 1) addr) (assign (index p 2) env) p )) Very simplistic and rather ugly, but it does the work. As you can see, the environment pointer is stored in the Proc object, and Proc#call hides the ugliness. You may notice that this is inefficient - an extra level of indirection. Indeed it is - we can in theory make the environment part of the Proc object and save an indexed lookup, and there's a bunch of other tricks waiting. But again, that's optimizations we wont deal with now. For now, lets move on to how to do the appropriate changes to get the example output above. Almost all the changes for this is in the Compiler class, and the code in question is now in the transform.rb file. There are some other small changes, but I don't think they need to be covered in detail. Specifically, transform.rb represents the start of a bit of refactoring. Some constructs in the Compiler class can be built easily on top of more primitive operations. lambda was an example of that. Overall, a lot of things can be done by rewriting the parse tree. Doing it that was has the distinct advantage that it's possible to switch the various rewrites on/off to debug their effects, and to see the result long before it ends up as machine code. It also helps isolate the CPU architecture specific parts further. As a first step, transform.rb contains methods that solely rewrite the syntax tree. They are still currently part of the Compiler class, and do make use of the Emitter (specifically Emitter.get_local to get a unique label), but this can be changed later. Unfortunately not all of these rewrites are small and simple. In this round, we're left with three: rewrite_strconst rewrite_let_env rewrite_lambda rewrite_strconst used to be in compiler.rb and is mostly unchanged. rewrite_lambda replaces the lambda handling in compiler.rb with a rewriting step that looks like this: def rewrite_lambda(exp) exp.depth_first do |e| next :skip if e[0] == :sexp if e[0] == :lambda args = e[1] || [] body = e[2] || nil e.clear e[0] = :do e[1] = [:assign, :__tmp_proc, [:defun, @e.get_local, [:self,:__closure__,:__env__]+args, body] ] e[2] = [:sexp, [:call, :__new_proc, [:__tmp_proc, :__env__]]] end end end What this rewrite does, is use our Array#depth_first method from extensions.rb to descend down the parse tree looking for :lambda nodes. It will skip any :sexp nodes, as they are used as "guards" to mark areas that should not be touched by rewrites. When it finds a :lambda, it will replace the :lamda with this: %s(do (assign __tmp_proc (defun [result of @e.get_local (self __closure__ __env__ [ + args]) [body])) (sexp call __new_proc (__tmp_proc __env__)) ) Effectively defining the lambda (as we did before), but then calling __new_proc with the result. You'll note __tmp_proc is seemingly superfluous. It is in fact a workaround for a slight problem: The call needs to be within a sexp to not be rewritten to a callm (Ruby method call), but the defun can't be within a sexp, or other rewrites won't touch the body of the defun. We'll clean that up later. Now for the hairy bit. Really hairy. The goal of this one is to identify variables in the methods - this used to happen in the parser in a really simplistic way - combined with identifying :lambda nodes (and so this must run before rewrite_lambda) and lifting variables that are used inside the closure into an environment, and update the :let in the surrounding method definition to have a suitable environment. It then also adds code to allocate the environment, as well as to shadow method arguments. Finally it rewrites accesses to variables that have been lifted into the environment, so that it uses %s(index __env__ offset) instead of the variable name. Let's go through the code. def rewrite_let_env(exp) exp.depth_first(:defm) do |e| We're hunting for :defm nodes only. Everything else will be ignored. vars,env= find_vars(e[3],[Set[*e[2]]],Set.new) First step is to find a candidate set of variables. find_vars is another new method, and we'll go over that next. e[3] is the body of the method. find_vars is recursive, and we pass in the methods arguments ( e[2]) as the starting "scope". Third we pass in an empty Set as the the starting point for the environment. vars -= Set[*e[2]].to_a We remove the method arguments, as we'll use vars to create a :let node later on. if env.size > 0 If find_vars found any variables to make part of the environment, we need to: body = e[3] rewrite_env_vars(body, env.to_a) Rewrite access to the members of the environment notargs = env - Set[*e[2]] aenv = env.to_a extra_assigns = (env - notargs).to_a.collect do |a| [:assign, [:index, :__env__, aenv.index(a)], a] end Create assigns to copy all arguments that are used in the closures from the arguments on the stack into the environment e[3] = [[:sexp,[:assign, :__env__, [:call, :malloc, [env.size * 4]]]]] Allocate the environment e[3].concat(extra_assigns) e[3].concat(body) Tack on the extra assigns and the body. end # Always adding __env__ here is a waste, but it saves us (for now) # to have to intelligently decide whether or not to reference __env__ # in the rewrite_lambda method vars << :__env__ vars << :__tmp_proc # Used in rewrite_lambda. Same caveats as for __env_ e[3] = [:let, vars,*e[3]] Then we create a :let node with the new variable set, including __env__ and __tmp_proc which we've seen elsewhere. :skip end end Finally we skip any nodes below the :defm so the depth_first call does not waste time. The purpose of find_vars is to identify variables that should be put in a let node as well as that should be part of a closure environment. This one is hairy, and a clear candidate for looking for ways to clean up later def find_vars(e, scopes, env, in_lambda = false, in_assign = false) return [],env, false if !e First of all, if we've been called with a nil expression, there are now variables to return, and the same environment passed in. e = [e] if !e.is_a?(Array) e.each do |n| if n.is_a?(Array) An expression? if n[0] == :assign vars1, env1 = find_vars(n[1], scopes + [Set.new],env, in_lambda, true) vars2, env2 = find_vars(n[2..-1], scopes + [Set.new],env, in_lambda) env = env1 + env2 vars = vars1+vars2 vars.each {|v| push_var(scopes,env,v) } If it's an assignment, then we want to process both the left hand and right hand, but we need to mark the left hand since variables on the left hand introduce a new variable in the scope. elsif n[0] == :lambda vars, env = find_vars(n[2], scopes + [Set.new],env, true) n[2] = [:let, vars, *n[2]] Special casing on :lambda because if we're handling a closure, and variables found inside the closure that were defined outside means that those variables needs to be lifted into the closure environment we're creating so that they're not allocated on the stack. else if n[0] == :callm then sub = n[3..-1] elsif n[0] == :call then sub = n[2..-1] else sub = n[1..-1] end vars, env = find_vars(sub, scopes, env, in_lambda) vars.each {|v| push_var(scopes,env,v) } end Finally we special case on :callm and :call when handling the remainder, because they have arguments that are not sub-expressions to be considered when creating the closure environment. elsif n.is_a?(Symbol) sc = in_scopes(scopes,n) if sc.size == 0 push_var(scopes,env,n) if in_assign If n is a variable that does not exist in any of the scopes we keep track of, and it is not part of the environment, and it's on the left hand of an assign, we add it to the top scope. NOTE: This current version is buggy. Not every variable potentially occuring on the left hand side should be added, just the one assigned to. elsif in_lambda sc.first.delete(n) env << n end If it is in a scope and we're in a lambda, then the variable needs to be moved (deleted) from that scope and added to the closure environment. end end return scopes[-1].to_a, env end Finally we return the innermost scope from this level and the environment Finally let's look at rewrite_env_vars. When we've gathered together all the variables for the closure environment, we have an array, and any accesses to those variables needs to be rewritten to (index __env__ num). That's done like this, and I hope this one is simple enough not to go through line for line: def rewrite_env_vars(exp, env) exp.depth_first do |e| STDERR.puts e.inspect e.each_with_index do |ex, i| num = env.index(ex) if num e[i] = [:index, :__env__, num] end end end end We still haven't actually added support for define_method, but we now finally have most of the plumbing. That's the next step. Then I want to start alternating between something more practical: Making the compiler compile early/simple versions of itself, and let it "eat its own tail" so to speak, and secondly to start refactoring and cleaning it up.
https://hokstad.com/writing-a-compiler-in-ruby-bottom-up-step-25
CC-MAIN-2021-21
refinedweb
2,931
70.13
Hello, I have very basic questions and below is my music player code. #include <stdio.h> #include <conio.h> #include <fmod.h> #include <windows.h> FMOD_SYSTEM *g_system; FMOD_SOUND *g_sound = NULL; FMOD_DSP *g_DSP; char* g_musicFiles[] = { "c:\\music1.mp3", "c:\\music2.mp3" }; int g_musicFilesCount = 2; void init() { FMOD_System_Create(&g_system); FMOD_System_Init(g_system, 1, FMOD_INIT_NORMAL, NULL); FMOD_System_CreateDSPByType(g_system, FMOD_DSP_TYPE_PITCHSHIFT, &g_DSP); } void release() { if (g_sound) FMOD_Sound_Release(g_sound); FMOD_DSP_Release(g_DSP); FMOD_System_Release(g_system); } int main(void) { int nKey, nFileID = -1; float fVolume = 0.5f, fPitch = 1.f, fStep = .1f; FMOD_CHANNEL *channel = NULL; init(); while (1) { if (_kbhit()) { nKey = _getch(); switch (nKey) { case 'p': if (g_sound) FMOD_Sound_Release(g_sound); nFileID = ++nFileID % g_musicFilesCount; FMOD_System_CreateSound(g_system, g_musicFiles[nFileID], FMOD_DEFAULT, NULL, &g_sound); FMOD_System_PlaySound(g_system, g_sound, NULL, false, &channel); FMOD_Channel_SetVolume(channel, fVolume); FMOD_Channel_AddDSP(channel, FMOD_CHANNELCONTROL_DSP_HEAD, g_DSP); FMOD_DSP_SetParameterFloat(g_DSP, 0, fPitch); break; case '0': fVolume += fStep; if (fVolume > 1.0f) fVolume = 1.0f; FMOD_Channel_SetVolume(channel, fVolume); break; case '9': fVolume -= fStep; if (fVolume < 0.0f) fVolume = 0.0f; FMOD_Channel_SetVolume(channel, fVolume); break; case '=': case '+': if (2.f <= fPitch) break; fPitch += fStep; FMOD_DSP_SetParameterFloat(g_DSP, 0, fPitch); break; case '-': case '_': if (0.5f >= fPitch) break; fPitch -= fStep; FMOD_DSP_SetParameterFloat(g_DSP, 0, fPitch); break; case 'q': release(); return 0; } } FMOD_System_Update(g_system); printf("\r Pitch : %f | Volume : %f", fPitch, fVolume); Sleep(100); } return 0; } The main part I’m wondering is case ‘p’ section. If I need to release the sound, do I have to call FMOD_Channel_RemoveDSP() before FMOD_Sound_Release() too? Does FMOD_Sound_Release() cancel when FMOD_System_CreateSound() is called and a sound file is still being loaded?? Is there something wrong, forgot to do, or any advice as for the code above? This is not my production code, of course, but I wanted to make sure if I’m missing or misunderstanding something before starting the project. - Jiyong Park asked 1 year ago - last edited 1 year ago - You must login to post comments If I need to release the sound, do I have to call FMOD_Channel_RemoveDSP() before FMOD_Sound_Release() too? No, you can if you want, but addDSP will remove it from wherever it was previously so you should be ok. Does FMOD_Sound_Release() cancel when FMOD_System_CreateSound() is called and a sound file is still being loaded? No they are not running side by side, they operate in order that you call it. If you call release first, then createSound will happen second.? playSound resets all Channel values, so you will have to re-set everything. The DSP has its own properties, so the parameters for that are not affected. Is there something wrong, forgot to do, or any advice as for the code above? FMOD_System_PlaySound is not pausing the sound with startpaused=true This means the addDSP and setVolume will happen slightly after you start playing the sound, which might cause a small burst of noise that you dont want. It is better to set startpaused=true and then after changing attributes, call FMOD_Channel_SetPaused(channel, false); - brett answered 1 year ago So, if I understood correctly, it means there’s no way to cancel FMOD_System_CreateSound() for some reason when it’s still loading a big file? Thanks for other explanations too, especially the last one is really helpful. Never thought that way! Thanks again! A big file would still only take a second or so to load, but no, you can’t cancel it. You can override fmod’s file system, and make the read callback give data back to fmod in small chunks. If you wanted to cancel in the middle of a load your file callback could return FMOD_ERR_FILE_BAD or something and the createSound would bail out half way. Oh, I see. Thanks a lot.
http://www.fmod.org/questions/question/reusing-channels/
CC-MAIN-2018-43
refinedweb
597
55.54
You: #Specify the VHD to be mounted $VHDName = "F:\Windows.vhd" #Get the MSVM_ImageManagementService $VHDService = get-wmiobject -class "Msvm_ImageManagementService" -namespace "root\virtualization" -computername "." #Mount the VHD $Result = $VHDService.Mount($VHDName) Join the conversationAdd Comment Thanks, great help it brought to my deployment. 🙂 I've also tried Core Configurator coreconfig.codeplex.com on the Hyper-V R2 … and it works like a charm, with the ability to monitor Your virtual machines locally (connected from Windows XP and Linux using RDP). Actually I've also managed to run SharpDevelop version 3 on Hyper-V R2 – You ask what for ? To develop and compile some GUI managment extensions. – one gets warning about missing IE COM components, that SharpDevelop use at the startup to present some news, but after You click Continue, the IDE just working fine and You are able to compile any Windows Forms or console app. Before You run the SharpDevelop installer, You need to install NET Framework 3.0 and perform Windows Update routine. I've just used ocsetup: start /w ocsetup NetFx3-ServerCore start /w ocsetup NetFx3-ServerCore-WOW64 Actually not able to use IE, I downloaded and used alternative webbrowser. Also works. Ben, when I call Msvm_ImageManagementService::Mount(), in some rarely cases, it took a very long time. My code is waiting 20 minutes, but sometimes, after 20 minutes, it's state is still RUNNING (4) I dont't know what's the exactly reason, and want to know how to do in the followling: Continue to wait, or Unmount() it and try Mount() again. Any of your reply is appreciated. Thanks Thank you very much, Ben, this helped me and saved a lot of time and health : ) Is this referring to older versions of Hyper-V (i.e. pre-Windows Server 2012)? On Windows Server 2012, I just go on the host system to the location where the VHD file is stored, right-click it and select 'Mount'. Much quicker and easier than any script. But I'm guessing you gave us the script because at the time you posted this capability didn't exist? Thank you! used the powershell script on a Virtual server with bluescreenofdeath.
https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/02/02/mounting-a-virtual-hard-disk-with-hyper-v/
CC-MAIN-2017-26
refinedweb
360
55.34
The Functions Of A Command Line Interpreter Computer Science Essay Published: Last Edited: This essay has been submitted by a student. This is not an example of the work written by our professional essay writers. A system program that accepts user commands and converts them into the machine commands required by the operating system or some other control program or application. COMMAND.COM was the command processor that accompanied DOS and Windows 95/98. Subsequent Windows versions replaced COMMAND.COM with CMD.EXE. In Unix/Linux, command processors are called "shells" The main ideas of CLIP are to support interpreter based teaching and to give students better and clearererror messages in their native language. In additionto these, it should be possible to integrate a visualization module with the interpreter. This requirementhas its roots in our visualization tool VIP (Virtanenet al. 2005), since we are not willing to maintain two separate interpreters Default availability dramatically changed role of Perl in Unix system scripting and routine text processing. For most administrators it is much easier to use Perl that any of the older alternatives. The main consideration here is the power of the language and availability of a very good, built-in debugger. Neither bash nor AWK has built-in debugger installed by default. And that alone tips the scales in Perl favor, as each administrator has a lot of things to do to spend time guessing where he made mistake using multiple  echo/print statements. That's why Perl is gradually displacing older Unix utilities such as cut, sed,  wc,and, of course, AWK. Often you can replace quite complex set of pipe stages that use classic UNIX utilities with one Perl loop. Don't interpret me wrong, pipes are a blessing and extremely powerful tool that each UNIX admins should use to the max, but if you can avoid unnecessary complexity, why stick to old practices. Applications Perl has many and varied applications, compounded by the availability of many standard and third-party modules. . Perl is known as one of "the three Ps" (along withPython and PHP), the most popular dynamic languages for writing Web applications. It is also an integral component of the popular LAMPsolution stack for web development. Large projects written in Perl include cPanel, Slash, Bugzilla, RT, TWiki, and Movable Type. Many high-traffic websites use Perl extensively. Examples include Amazon.com, bbc.co.uk, Priceline.com, Craigslist, IMDb,[37] LiveJournal, Slashdotand Ticketmaster. Perl is often used as a glue language, tying together systems and interfaces that were not specifically designed to interoperate, and for "data munging", that is, converting or processing large amounts of data for tasks such as creating reports. In fact, these strengths are intimately linked. The combination makes Perl a popular all-purpose language for system administrators, particularly because short programs can be entered and run on a single command line. Perl is also widely used in finance and in bioinformatics, where it is valued for rapid application development and deployment and for its capability to handle large data-se Implementation Perl is implemented as a core interpreter, written in C, together with a large collection of modules, written in Perl and C. The source distribution is, as of 2009, 13.5 MB when packaged in a tar file and compressed. The interpreter is 150,000 lines of C code and compiles to a 1Âhandles.[40] In Perl, the phases are the major stages in the interpreter's life-cycle. Each interpreter goes through each phase only once, and the phases follow in a fixed sequence. (ii favourite system isn't listed here, it may still be supported, if there's a C compiler for it. Ask around on comp.lang.python -- or just try compiling Python yourself. The Python implementation is copyrighted but freely usable and distributable, even for commercial use. The Python interpreter is usually installed as /usr/local/bin/python on those machines where it is available; putting /usr/local/binÂ., /usr/local/python is a popular alternative location.) On Windows machines, the Python installation is usually placed in C:\Python27, though you can change this when you're running the installer. To add this directory to your path, you can type the following command into the command prompt in a DOS box: set path=%path%;C:\python27 Functions Functions and methods within Python are created through the def command. These are extremely useful when you might otherwise repeat the same piece of code. A typical simple function might appear thus: def square(x): return x*x # note, one can also use x**2 for x squared, # x**3 for x cubed, x**4 for x^4 and so on... This function takes one input (x) and returns x^2 to whatever called it. So if your code contains the above function, you might access it in the following ways: print square(9) # prints 81 (9*9) a=5 print square(a) # prints 25 (5*5) b=square(3) # assigns the value 9 to b (3*3) c=square(b) # assigns the value 81 to c (b*b) Functions can be called from within functions: def to_the_power_of_four(x): return square(x) * square(x) # gets x^2^2 (i.e. x^4) A note about comments: If a hash (#) sign is used in the code body (i.e. not part of a print statement) then whatever follows it is a comment. A comment is ignored by the Python interpreter and it is considered good practise to use them to make the code more readable by a human - especially useful when one creates larger pieces of code. A function does not necessarily need to return a value, nor does it need to receive a value. Look at these two functions: def say_hello(name): print "Hello", name def give_me_a_number(): return 1234 (iii)PHANTOM Phantom is a powerful Windows automation scripting language. The Phantom interpreter runs standard ASCII Phantom scripts (syntax similar to C) to interact with Windows common controls. Virtually any number of common or repetitive tasks can be automated. It is also a useful tool for automated testing. The Phantom language has many features, including built-in functions, the ability to add functions and user-defined DLLs, flow control, and script error and log output. In order to use the automation features, you will have to learn the scripting language first in order to create your custom scripts. The download comes with everything including some sample scripts and full documentation. Phantom is a powerful scripting language used toautomate Graphical User Interfaces (GUIs) • Used for - Test Automation - Process Automation - Application Performance Analysis • Three products are provided that support the Phantom language - Phantom Test Driver (PTD) - Phantom Sidekick - Phantom Command Line Utility • Phantom can be customized to support customer needs Features • Large built-in GUI automation function set • Exception handling • Full script flow control • Complex built-in data types - windows - bitmaps - option sets • User-defined functions • Intuitive window access Hierarchy Phantom Uses • QA Test Automation - Automate scripted manual test procedures - Regression testing - Functional testing - Performance testing • Process Automation - Repetitive manual tasks - Time consuming tasks - Process scheduling • Application Performance Analysis - Repetitive stress analysis - Response time analysis - Load response analysis Phantom is a powerful  (iv) The Java Interpreter java interprets (executes) Java bytecodes. java [ options ] classname <args> java_g [ options ] classname <args> DESCRIPTION The java command executes Java class files created by a Java compiler, for instance, javac. The classname argument is the name of the class to be executed. classname must be fully qualified by including its package in the name, for example: % java java.lang.String Note that any arguments that appear after classname on the command line are passed to the main method of the class. java expects the binary representation of the class to be in a file called classname.class which is generated by compiling the corresponding source file with javac. All Java class files end with the filename extension .class which the compiler automatically adds when the class is compiled.classname must contain a main method defined as follows: class Aclass { public static void main(String argv[]){ . . . } } java executes the main method and then exits unless main creates one or more threads. If any threads are created by main then java doesn't exit until the last thread exits. When you define your own classes you need to specify their location. Use CLASSPATH to do this. CLASSPATH consists of a colon separated list of directories that specifies the path. For example: .:/home/xyz/classes . OPTIONS -debug Allows the Java debugger, jdb, to attach itself to this java session. When -debug is specified on the command line java displays a password which must be used when starting the debugging session. -cs, -checksource When a compiled class is loaded, this option causes the modification time of the class bytecode file to be compared to that of the class source file. If the source has been modified more recently, it is recompiled and the new class file is loaded. -classpath path Specifies the path java uses to look up classes. Overrides the default or the CLASSPATH environment variable if it is set. Directories are separated by colons. Thus the general format for path is: .:<your_path> For example: .:/home/xyz/classes:/usr/local/java/classes -v, -verbose Causes java to print a message to stdout each time a class file is loaded. -verify Performs byte-code verification on the class file. Beware however, that java -verify does not perform a full verification in all situations. Any code path that is not actually executed by the interpreter is not verified. Therefore, java -verify cannot be relied upon to certify class files unless all code paths in the class file are actually run. PHP Command Line Interpreter PHP. he simplest use of PHP command line mode is to run a phpfile directly:   php phptest.php However before you do so it is worthwhile making the following changes to setups in to your running environ:   1)put the folder containing the php.exe on the path. For Windows users this is -     Path = c:\phpfolder;%Path%   2)make a copy of the php.ini file and store it in this directory/folder;   3)make the following changes to the php.ini file:    a- output_buffering=off //in interactive mode buffering stalls output until buffer fill    b- implicit_flush=on // this guarantees output is immediate    c- max_execution_time = 30000 //second of elapsed time the program can run Conclusions Selection of the Ist programming language for teaching should be done. However, when facing cruel reality, this cannot always be the case. In this stage it is hard to tell how successful CLIP will be. With the new lecture material and integration of a visualization module, we expect to get a system in which the learner only uses the properties he or she knows, and in which the visualization will help the students not only to understand the program behaviour but also to debug their code.
https://www.ukessays.com/essays/computer-science/the-functions-of-a-command-line-interpreter-computer-science-essay.php
CC-MAIN-2017-13
refinedweb
1,884
52.7
One of the major causes of issues is that as new devices get released the cameras in them get better and better allowing you to take very high resolution images. Now when you specify a few parameters to our getPicture method like quality or targetWidth/targetHeight you can get out of memory errors. Why do you get out of memory errors you ask? Well in my honest opinion it is because Android does a real poor job of handling Bitmaps. In order to do any manipulation on an image like scaling or compression you need to load the entire image into memory. Let's take a look at a real world example. My Samsung Galaxy Note has an 8MP camera with a resolution of 3264 by 2448. So in memory that picture assuming ARGB_8888 will be: 3264 pixels x 2448 pixels x 4 bytes/pixel = approximately 30 megabytes Let that sink in, approximately 30 megabytes. Considering that I read somewhere the default heap size for an app running in Dalvik is 48 megabytes you can see how you can quickly run out of memory taking pictures. Fixing the Best Case Scenario I've added some code to detect the best case scenario and not load the image into memory. Here is the getPicture method to call if you want to use the best case all the time. var options = { quality: 100, destinationType : navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.CAMERA, encodingType: navigator.camera.EncodingType.JPEG, } navigator.camera.getPicture(win, fail, options);The important part about the options is that you specify a quality of 100. This along with accepting the default width and height will skip the need to load the image in memory. Reducing Memory when using targetWidth/targetHeight Okay but if you do specify a targetWidth/targetHeight the image has to be loaded into memory. Now we do a bit of math to figure out the smallest multiple of the image that can be loaded that isn't smaller than the requested width and height. You see the Bitmap.createScaledBitmap() method allows you to specify that the bitmap be load at half, quarter, etc. size. Now if you request a 900x900 image from a 2000x2000 original image it will be loaded into memory as 1000x1000 and scaled from that point. It saves about 11 megabytes of memory doing it this way. Respects the saveToPhotoAlbum option Up until 1.9.0 each picture taken automatically gets added to the Android photo album/gallery. As of 1.9.0 if you want that type of behaviour to continue you need to set this option to true as the default is false. Respects the correctOrientation option One of the other big problems with our Camera functionality is that pictures taken in portrait mode were always displayed on their side when you attempted to view them in your app. Remember your app is based off of a WebView and the web view does not care about the exif orientation parameter. Now if correctOrientation is set to true we rotate the image so that it will show up properly in the WebView and we reset the orientation parameter to normal so it'll show up properly in desktop image viewers. If you run into problems using the Camera in 1.9.0 please raise a bug on JIRA and give a detailed reproduction scenario. I want to make sure this functionality is rock solid for the upcoming 2.0.0 release. 118 comments: There's no stopping Simon it seems! :) Well done and thanks. Thanks, but I have problem about display photo and send it to server. path return "" in 1.9 img src="path" cannot display but I can display and send the photo using path in 1.8.1 path return content://media/external/images/media/xxxx in 1.8.1 my problem same as following link: Hi Simon, Hope you are doing well I have a query if you can help me. I am using phonegap 1.3 and created Android plugin with the help of the document given . Now I am trying to update to Phonegap 1.9 but it is giving me an error that import com.phonegap.api.PluginResult.Status; Status in the above statement cant be resolved. I have read the documentation of phonegap 1.9 release and it says that some of the Android plugin will not work properly. Please help me and provide some suggestions why it is not working? Thanks in advance Summved @Summved Jain Just change references to "com.phonegap" to "org.apache.cordova" as the package of the classes has changed. @steve-c Yeah, if you set saveToPhotoAlbum to true in your options it will get back to providing you the content:// type uri. There is no reason why you shouldn't be able to see the image in your own /data/data directory. I've put in a small fix for this issue and I'll post to the PG group thread where you can pick up a jar to test. Thanks Simon, Could you please also let me know what does cordova means here? Is the name has changed from phonegap to Cordova? Summved @Summved Jain Yes, the name has changed. We moved the project to Apache for safe keeping so the package name of the Java classes changed. Great article, but it didn't stop crashing the app with me. Now it doesn't crash when taking a picture, but when choosing a picture from your folders, it still crashes. My settings: quality: 100, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: source, encodingType: navigator.camera.EncodingType.JPEG On success, I put the imageURI to another variable, and then I have another button to send the image. It crashes after choosing the picture, so I think it doesn't have anything to do with the sending etc. This is my full code at the moment. @admins The code you are using looks fine but what I really need to see is the error. Can you run "adb logcat" so I can see what is going on? Thanks for the prompt answer Simon! I pasted the whole LogCat error log there. I hope you can figure out something! @admins O I C You are running into an OutOfMemory error when trying to load the image. I think I can do something about this. Please stand by. I may be able to post a .jar for you to test. in 30 minutes. @admins Please grab a patched jar from: It should fix the out of memory error you are getting. Let me know what you find and then I'll check in the fix. Thank you so much! That completely fixed my problem :) Do you happen to know why the pictures appear sideways when I upload them? This seems to be a usual problem with image uploaders in Android, so I'd like it fixed in my app :P Thanks Simon, That was really helpful. Thanks for your prompt reply. Could you please guide me with some tutorials or books to learn phonegap and JQuery mobile. Kind Regards, Summved @admins I've just checked in the fix. If you are having orientation problems it is probably because you are taking the picture in portrait mode while most phones expect you to take it in landscape more. You can try setting correctOrientation to true when you use getPicture(). @Summved Jain I don't do jQuery Mobile. I haven't found it to be very good on Android. Look at using Sencha Touch or Dojo Mobile instead. To learn more about PhoneGap besides my blog posts there are: Hello Simon, Sorry to bother you again. Could you please help me with the below query? I'm using Phonegap to develop my application and I'm trying to get the app to list files on the sdcard. But only specific files, for example mp3 or my own file format. I've been trying to use the Phonegap API as it seems to have a directory reader action, but I don't know how to use it. Kind Regards, Summved @Summved Jain Take a look at this thread. You'll need to check to see if the name of the file ends with .mp3 but other than that the code is written for you. Thanks so much That was really helpful. Let me test this and will update you. Kind Regards, Summved Hi again, Simon. It seemed that it worked at first, but when I now test to take a picture with camera, it's crashing. This is the error log again. Selecting the image from gallery works fine, but taking a new picture crashes the program. When I first contacted you, selecting a picture crashed, while taking a picture didn't. So this is the opposite of the previous problem. Update to the comment before, it crashes randomly when selecting a image from gallery too :/ @admins It looks like it ran out of memory trying to correct the orientation of the picture. What options are you using when calling getPicture from the camera? Are you taking the picture in portrait mode? How good is the camera resolution? You may want to try the same test with correctiOrientaiton set to false. Basically, I'm trying my hardest to keep memory usage down but Android handles images really poorly. Hey, I know that it's Android problem, but it seems that you're the one and only person I could contact now. I'm glad that you still try to figure the problems, even though it's hard. I'm using Samsung Galaxy S II and camera is 8MP and images 3264x2448. It really seems that it works when I set correctOrientation to false. I'm taking pictures in portrait mode. At the moment, I'm taking pictures with these settings: { quality: 100, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: source, encodingType: navigator.camera.EncodingType.JPEG, correctOrientation: false } Source is user's choice, you can select between navigator.camera.PictureSourceType.PHOTOLIBRARY/CAMERA @admins Yeah, that is the same resolution as my Samsung Note. That means the image in memory is about 31 megabytes and then the secondary image to hold the rotation data is another 31 megabytes and boom! Out of memory error. It looks like we'll need to write our own image manipulation code to get around this issue but that's not going to happen this morning. I wish but other duties call. In the mean time try requesting a smaller targetWidth and targetHeight will save on memory usage. That might not fit the use case for your app but at least it'll get around most crashes for now. Talk to you soon. Hi Simon, Just wondering, do you happen to know of any good way of retaining the exif data once you've resized an image? The ones I seem to lose are, well, all of them, but I'm trying to retain the ones related to the datetime of when the image was created and the gps lang and long co-ordinates...Idea is that someone can upload the image at some point in the future and it'll put itself nicely where they took the picture and when, if you see what I mean. Thanks in advance :) the application crashes when trying to access image from es file explorer in android using phonegap camera photolibrary source. can u suggest some solution. @Duncan The only way for the EXIF info not to be touched is to specify a quality of 100 and a destination of FILE_URI. Don't use any other parameters as that will cause the file to get re-written. I can only keep the following EXIF information as that is what the SDK will allow me to access: GPS and Datetime should stick around. They do on my Samsung phone. @Roshan Chaudhary Use the Gallery app instead. Open an issue on JIRA: and include "adb logcat" so I can see what is going on. Hi simon ... very nice post. I tell you my scenario. Mobile: LG3 with Android 4.0 Using PhoneGap 1.9.0. As you can see I'm using library, no orientation, slow resolution, slow quality ... Any ideas ? THANK YOU in advance Hi Simon, I am using Camera API with Cordova 1.8.1 but not able to make it work. The same code works with phonegap 1.3.0. The API is not returning the base64 of the image. It returns some text that says "content://media/external/images/media/373". The number 373 is changing everytime when camera clicks. Check the code below: - navigator.camera.getPicture(onCameraSuccess, onError, { quality: 50, destinationType: Camera.DestinationType.FILE_URL }); function onCameraSuccess(imagedata) { alert(imagedata); } This alert shows the above text in case of 1.8.1 and shows the base64 in case of 1.3.0 Please help me on this as this is on priority Kind Regards, Summved @Summved Jain You are getting a FILE_URI because that is what you specify in your getPicture command. Change FILE_URI to DATA_URL and you will get a base64 encoded image. Hi Simon, Thank you so much It is working fine. Could you please let me know when I click the picture using the API, it stores in phone sd card but when I try to look at that picture, it doesnt show up. It says preview not available and you can not see that image even when you copy it to your computer. Kind Regards, Summved @Summved Jain Sorry, I don't understand what you are asking. Please provide more details over at: @alex Looking at the stack trace it is an out of memory error. Which I can't do much about. What is the quality of your camera? That is what is the native resolution? Hi, We have implemented the camera capture function in our app with phonegap 1.9 and using it on 30+ device for 30 people. We have specified targetWidth and height of 640 x 800. Most of the time the app works perfectly. But occasionally and randomly we would get thumbnail size photos from the capture function. This is bugging me a lot since we can not reproduce it everytime. We are using Galaxy Tab original with 2.2 and S3 and some Galaxy Notes. And it happens for all the devices on a random basis. Just wanted to find out if anyone experienced any issues like this. Looks to me that the image we get is the thumbnail image. Thanks, Sazzad @Sazzad-Hossain This is the first I've heard of this type of bug. Can you please open an issue on JIRA? Provide as many details as you can and logs are always good. Hi Simon, i am using cordova 2.0,in some phones camera.getPicture() directly opens the image gallery but in some it gives an option either to open image gallery or file explorer, if i open file explorer and select a non image file my app crashes saying application not responding.please help. Thanks, Megha @megha rathore I believe I've fixed all those bugs in 2.1.0 as part of this issue: Hi Simon, Thanks for your prompt reply,by the way when will cordova 2.1.0 be released? as we need to fix this bug asap and send the release to client in three days. Thanks Megha Rathore @megha rathore Well we are going through the voting process of getting from incubator to full fledged Apache project. The whole process has taken much longer than I excepted so I hate to comment on a date but I hope to see it early next week. Hey Simon, in regard with my previous query i updated my phonegap with the latest release(2.1) and found that my app still crashes if i select a non image file (say an audio file or a js file) giving me a message that sorry Unfortunately (my_app_name) has stopped working. :( Megha Rathore @Megha Rathore Okay, what app are you using to select the non-image file? Can you post up the crash in "adb logcat" on gist or pastebin so I can see it? Hi Simon, The app which i am using for selecting a non image file is ES File Explorer (Google market), you can checkout my "adb logcat" here- Thanks Megha @Megha Rathore Cool, I will try to reproduce. @Megha Rathore Cool, I will try to reproduce. @Megha Rathore The normal way works for me but the file way crashes the app. I just checked in a fix to guard against the ES File Explorer returning things the "file way". Honestly looking at your stack trace it appears you are still using the old 2.0.0 jar file. Hey Simon, Thanks again for your quick reply, and yeah i am sorry by mistake i sent you the wrong stack trace(2.0), but anyway the same problem is showing up on 2.1.0 as well. from where can i checkout your fix by the way? Thanks Megha @Megha Rathore Can you show me the stack trace from the 2.1.0 run? It shouldn't be the same at all. If you want to grab the fix it has been checked in to:;a=summary Hey Simon, Thanks a lot for the fix, i will try it out and let you know. :) and here is the error log from cordova 2.1.0 run Thanks Megha Hey Simon, Just wanted to add that for me app crashes either ways( file way as well as normal way), here is the error log from the run of cordova 2.1.0 Thanks Megha @megha rathore Okay, it is the same error. I think I need a more detailed test case as I'm missing out on the problem. So you use ES File Explorer to get the image and it does matter which option you pick from the dialog. I guess it must be something in the options you are sending to getPicture() that I'm not accounting for. Can you send me the line you use for getPicture with all the options you use? Hey Simon, here is what i am using navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 100, destinationType: destinationType.DATA_URL, sourceType: source, targetWidth: 65, targetHeight: 65 }); Thanks Megha @megha rathore Oh, a DATA_URL, never thought to test that. I will give it another try. @megha rathore Wow, don't know why DATA_URL made a difference but it did and I reproduced then fixed the bug. It'll be in 2.2.0. @megha rathore Wow, don't know why DATA_URL made a difference but it did and I reproduced then fixed the bug. It'll be in 2.2.0. Hey Simon, Thanks a lot :) now waiting for cordova 2.2.0 Thanks Megha Hey Simon, Can i ask you for the patch required to solve my problem?(PG crash on using DATA_URL for non image files), need it urgently. Thanks Megha Rathore @megha rathore You can grab the latest source from:;a=summary and build it yourself. Alternatively we are tagging 2.2.0rc1 on Friday so a release candidate binary should be posted on PhoneGap.com early next week. Hi simon, we are having an serious issue that needs to be fixed ASAP.Please do help us.Using cordova 2.1.0, we face the app getting closed when taking a picture from camera and pressing ok button... what is the real problem here? @vivek s Not enough info. What do you see in "adb logcat"? Hi Simon, I'm running out of options with a camera bug. Device: Samsung Galaxy s2 Android: 4.0.4 Phonegap: 2.0.0 The camera crashes the whole application when I click save. I couldn't find a MemoryOutOfBounds error which I had with the 1.8.0, but the behaviour of the camera is the same. call after deviceready: Adb logcat: @Susanna What Camera app are you using? I'm seeing a weird return value for the requestCode. @Simon I'm using the default one, Camera version 1.0 @ Simon and as additional info, the log of a test run with taking only black pictures. I managed to get the crash after 5 pictures. adb logcat: @Susanna I'm at a loss to explain what is going on. When you say it crashes do you mean the application restarts? If so the app may be cleared up by the OS while you are in the Camera app to reduce memory usage. @Simon So the application closes completely. It happens between navigator.camera.getPicture and the success callback. So I get the console logs before and after navigator.camera.getPicture but never the one at the first line of success callback when the app crashes. @ Simon Solved the problem. and it was: adding this to android manifest android:configChanges="orientation|screenSize|keyboardHidden" AND because the application is using backbone I navigate on success to the same page I came from through the router. Before I just saved the image to a model and through a change in the model rendered the view again. I still don't throughly understand why, but hey, it works! and thanks, "If so the app may be cleared up by the OS while you are in the Camera app to reduce memory usage." led me to the right track :D @Susanna ARG!!! Sorry, I should have suggested that earlier. It is a basic step in setting up your PhoneGap app. Without the orientation change Android will restart you app if you switch from portrait to landscape and since you are probably in portrait mode int the app then landscape mode for the camera it all makes sense. Hi Simon, I have an issue when I try to take a picture in my phonegap application. The picture saved in the Camera folder (Nexus 7 or Samsung Galaxy) seems to be corrupted: the file size is equal to 0kb. However I can see the picture browsing the gallery on my phone. I tried a simple project with different options but I didn't find any solution to get a picture saved with its right size. Here is the javascript code used to take the picture: destinationType: Camera.DestinationType.FILE_URI, quality: 100, allowEdit: false, correctOrientation: false, saveToPhotoAlbum: true (sdk 11, 15 or 16) @Simon, no problem. I was the idiot just going android:screenOrientation="portrait" but still, just adding the orientation change was not enough for the problem to be fixed. Something with the models and views. However thanks a million times :) @Julien B Hmmm...can you head over to: and raise an issue? This seems to be a bug but I'd rather collect logs, etc. over there. Hi Simon. I have used getPicture successfully on my Galaxy Note running Cordova 2.0, but it has stopped working and I can't figure out why. The symptoms are 'Camera cancelled.' error. I can't see any memory errors in the logcat output. I have cut it down to a simple test case, and its still failing, here is the code:- And the logcat output:- One thing that caught my eye in the logcat shortly after calling getPicture was the line: W/ActivityManager( 1854): Activity is launching as a new task, so cancelling activity result. I wondered if this could be a project manifest setting that is causing the problem. My activity has the following options set android:name=".RMCv2dev" android:label="@string/title_activity_rmcv2dev" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait" android:alwaysRetainTaskState="true" android:launchMode="singleInstance" android:hardwareAccelerated="true" At the moment I am at a loss as to why the camera code has stopped working. @Simon I resolved my camera issue. I determined that the the problem was in my activity configuration in my manifest, which had android:launchMode="singleInstance" Is there any reason why this should option affect the camera? I had added it because I was sometimes getting multiple instances of my app running, which I don't want either. u r simply awesome Simon,,, Hi Simon! After testing this on Android 4.1.2 with Cordova 2.2.0, I have doubts, that your optimization for the "best case scenario" still works. These are my observations on a Samsung Galaxy SII : (using the options in your post) --> screen freezes ,after 8MP image was taken and control is passed back to my app. Heap grows by 31961104 bytes. (extending your options by targetWidth and targetHeight ; 1000px) --> works as expected. Heap grows by 7990288, then by 3000016 bytes. Now I don't know if anything significant has changed since your post, or if I am doing things wrong. Should I post this as an issue? Post its amazing Simon. Please have a look at my error, im have been trying almost everything its to fix the camera Crash, but nothing works for me. quality: 100, destinationType : navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY, encodingType: navigator.camera.EncodingType.JPEG, correctOrientation: false, targetWidth: 1024, targetHeight: 768 @Sandeep Narwal There is nothing in that log that indicates a crash. I think you may have sent me the wrong link. Hello Simon, Thanks for the great work (blog, plugins, phonegap etc)! I'm having a problem that some others already complain. The camera restarts my app 90% of times. I'm using Phonegap 2.2.0 on android 2.3.4 and 4.0.4. I have the "android:configChanges="orientation|keyboardHidden" on my android manifest. I have tried your tips from this post. Here is a log: I can't identify a memory problem. The app is killed before a took the picture. Can you help me? Thanks! @Hugo Maia Vieira What camera app are you using? I see that there is an error popping up from the C code. Have you tried a different camera app? Hi Simon in certain phones i can access photo but not in other albums get error aS UNDEFINED .Im using photo library option and not savedtophotoalbum.How do i solve this problem in order to access photos @Rahul Mendonca Can you provide me with more details? Simon, I'm using the default camera app. After I install another camera app () the problem stops with both camera apps. But this is happening with some users of my app, with different andoid versions and phones models. There is anything I can do? @Hugo Maia Vieira You didn't really explain what problem you are running into. Also if you've found a solution by installing a 3rd party app that's great news. Hi Simon, I used this code to capture image in my application navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 100, destinationType: navigator.camera.DestinationType.FILE_URI, saveToPhotoAlbum: true, correctOrientation: true,targetWidth: 100, targetHeight: 100 }); its working. but every time i capture the image, my application size increases for 2MB each time.I think it is storing somewhere along with the application. how to solve this? Thanks, @niranjana devi Well each picture is initial saved in your apps temp directory and it is called ".Pic.jpg". The image name is reused each time you take a picture so it shouldn't continue to increase after the first picture taken. hello! , Simon Mac,sorry to troblue you,please take some time look for my questions,i used cordova-2.0.0.js,but when i taked photos,my app progrom will exit,my logcat is: Thank you !!! @Yuguang Zhao There is nothing in your logcat that indicates a crash. When my program crash and then restart eclipse logcat will appear this a hint Could not find method android.webkit.WebView., referenced from method org.apache.cordova.CordovaWebView. @Yuguang Zhao I'm looking for a stack trace. Hi Simon, I'm trying to make camera work on s3, every time i click the save button after capturing the image the app crashes. This is the code i'm using . navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 20, sourceType: navigator.camera.PictureSourceType.CAMERA, mediaType: navigator.camera.MediaType.PICTURE, destinationType: Camera.DestinationType.FILE_URI, targetHeight:1024}); I'm using phonegap 1.9.0. Please help me Thanks! @shruti nair First, check "adb logcat" to see if you are getting an out of memory exception. If that is the case you may need to upgrade to 2.4.0 as the camera on the S3 is very good and creates very large images. @Oliver Krylow Yes, it looks like there was an issue in 2.3.0. It should be resolved in the upcoming 2.4.0. No we are not getting any out of memory exception but can we use any lower cordova version to solve this issue. We have found a solution for that, if we fix the orientation of the application to Landscape mode, the Camera will work in all devices however, our app is only required portrait orientation. Is there a way to fix the orientation on a specific page so we can open camera on landscape orientation and will use the app in portrait on other pages? Thanks @shruti nair If your app is crashing then there is definitely a stack trace. What do you see from the stack trace? Hi Simon Thanks for this post. Not sure whether you are still looking into this. I am stuck with this problem for 1 week. I have tried so many things like using different versions of cordova(2.1, 2.5, 2.7, etc.) and some of the configurations like keeping: quality: 100 Leaving targetWidth, targetHeight so that default values will be taken etc. The issue is that once I take picture and while returning to the app, it crashes. This is happening only in some phones(Samsung Galaxy ACE, Micromax A87). The following is the stacktrace: 05-19 18:21:10.449: W/dalvikvm(9945): threadid=1: thread exiting with uncaught exception (group=0x40142560) 05-19 18:21:10.459: E/AndroidRuntime(9945): FATAL EXCEPTION: main 05-19 18:21:10.459: E/AndroidRuntime(9945): java.lang.RuntimeException: Unable to resume activity {com.eiris/com.eiris.InAppTest}:.performResumeActivity(ActivityThread.java:2120) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.os.Handler.dispatchMessage(Handler.java:99) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.os.Looper.loop(Looper.java:130) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.app.ActivityThread.main(ActivityThread.java:3683) 05-19 18:21:10.459: E/AndroidRuntime(9945): at java.lang.reflect.Method.invokeNative(Native Method) 05-19 18:21:10.459: E/AndroidRuntime(9945): at java.lang.reflect.Method.invoke(Method.java:507) 05-19 18:21:10.459: E/AndroidRuntime(9945): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875) 05-19 18:21:10.459: E/AndroidRuntime(9945): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) 05-19 18:21:10.459: E/AndroidRuntime(9945): at dalvik.system.NativeStart.main(Native Method) 05-19 18:21:10.459: E/AndroidRuntime(9945): Caused by:.deliverResults(ActivityThread.java:2532) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2107) 05-19 18:21:10.459: E/AndroidRuntime(9945): ... 12 more 05-19 18:21:10.459: E/AndroidRuntime(9945): Caused by: java.lang.NullPointerException 05-19 18:21:10.459: E/AndroidRuntime(9945): at org.apache.cordova.DroidGap.onActivityResult(DroidGap.java:849) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.app.Activity.dispatchActivityResult(Activity.java:3908) 05-19 18:21:10.459: E/AndroidRuntime(9945): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528) 05-19 18:21:10.459: E/AndroidRuntime(9945): ... 13 more @ranjjose The stack trace helps but I need to know what version of PhoneGap you are using when you reproduce this issue. Then I can line up the NPE with the line in DroidGap that causes it. @Simon: To follow up, phonegap 2.7.0 also crashed (same stack-trace). With 2.1.0, however, the app was re-starting while coming back to the app after taking a photo. Anyway, I could finally get it working by using foreground camera plugin(). Thanks to them. Ref: Hey Simon I still have this problem can u plz help me @Patchara Lertudomtana Well I've done the best I can to have this issue happen less frequently but there is no way to completely remove it. What are you seeing? Hi Simon, I'm having memory issues with Android 2.3 devices, with PhoneGap 2.8 The error is: java.lang.RuntimeException: Unable to resume activity {com.dansmart.geosight/com.dansmart.geosight.Geosight}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=34, result=-1, data=null} to activity {com.dansmart.geosight/com.dansmart.geosight.Geosight}: java.lang.NullPointerException at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2124) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2139) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1672)) Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=34, result=-1, data=null} to activity {com.dansmart.geosight/com.dansmart.geosight.Geosight}: java.lang.NullPointerException at android.app.ActivityThread.deliverResults(ActivityThread.java:2536) at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2111) ...32) ... 13 more This error appears after having taken a photo when you click the ‘Save/ok’ button to accept the picture before resuming with the app. I have 7 reports of this error, 6 of which are this week, so it's happening regularly now with PhoneGap 2.8 whereas it wasn't happening with our previous release which was 2.1. We're using 100%, JPEG, FILE_URI, and no correction of orientation, as suggested. We also have android:configChanges="orientation|keyboard" Any ideas? Would upgrading to 3.0 help? Best regards, Dan @Dan Smart Upgrading to 3.0.0 probably won't help. The Camera Intent has been problematic in PhoneGap Android since day one and only gets worse as Camera HW gets better. For config changes change it to: android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" and give it a try. Thanks Simon - the strange thing is that the issue is being reported on older devices (Android 2.3), so it shouldn't be due to camera HW. I've sent a release out with the update config, and I'll feedback if we get an improvement. Dan Could Cordova not access the camera directly rather than using the camera activity? Also, with html5 coming along, could cordova use the html5 media capture APIs instead? In my case, I got the application to stop crashing by reducing the target image size to quite a low resolution (1024x768 or something) and also upgrading the the next gen phone, so the issue went away, but we still have some bugzilla's open to consider either direct hardware access, or using html5 media to replace the cordova camera API. @Austin Yes, we could implement our own camera functionality but we are not in the business of writing a Camera app. Personally I wouldn't want to maintain something like that. You can use the ForegroundCamera plugin which provides a simple UI for taking pictures without using an intent. Well, we've already implemented an earlier version of the media capture API but it again uses intents. Personally I can't wait until the browser/web view natively implements more of the HTML5 API's as then PhoneGap can go away. Remember all of us PhoneGap devs are looking forward to the day where PhoneGap is no longer needed for folks to write HTML5/JS apps and get access to the device API's. Hi Simon, Congrats for this great blog and your awesome work. I've been reading all your stuff but I can't find a solution for me :( I've got an app that randomly crashes when selecting a picture from the Gallery. I've got this at manifest.xml: android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" The js to get the picture is this one: function selectPicture() { pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType; // Retrieve image file location from specified source navigator.camera.getPicture( onPhotoURISuccess, onFail, { quality: 25, destinationType: destinationType.FILE_URI, sourceType: pictureSource.PHOTOLIBRARY }); } We are using phonegap 2.7, and the error it randomly throws is this one: java.lang.RuntimeException: Unable to resume activity {com.xmile.events/com.xmile.events.MainActivity}:.performResumeActivity(ActivityThread.java:2765) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2794) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249) at android.app.ActivityThread.access$600(ActivityThread.java:149) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:213) at android.app.ActivityThread.main(ActivityThread.java:5092) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564) at dalvik.system.NativeStart.main(Native Method) Caused by:.deliverResults(ActivityThread.java:3342) at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2752) ... 12 more Caused by: java.lang.NullPointerException at org.apache.cordova.DroidGap.onActivityResult(DroidGap.java:858) at android.app.Activity.dispatchActivityResult(Activity.java:5293) at android.app.ActivityThread.deliverResults(ActivityThread.java:3338) ... 13 more Please, could you help me? :) many thx @donantidees I wish I had a solution for you. What is happening here and has been a problem for quite awhile is that Android is clearing out your application from memory. Then when the Intent to select a picture is done there is no app to return the value to. We've been banging our heads against this for awhile but we've got no solution as of yet. @Simon MacDonald Ok :'( And there is no workaround possible to avoid it? @donantidees Other than pulling in the foreground camera plugin into the code no. Hi Simon, Thank you for this great post! I hope you can help me with pictureSourceType. It working perfectly, but I want to know; if I want the photo taken to be saved in gallery as well as local server, which sourcetype should I use? And I wish you write a tutorial on phonegap+picture+localserver+database+android. I really appreciate your help and intelligent :) @TrialAndError If you want the picture saved in the gallery you set the "saveToPhotoAlbum" option to "true". To save it on a server you'll need to use the FileTransfer.upload method. Hi Simon, I'm using phonegap 2.8.0 and I have some problems when user take a picture from photolibrary. When user select an image sometimes app crash. I use this code: navigator.camera.getPicture(seleccionada2, noseleccionada2, { sourceType: Camera.PictureSourceType.PHOTOLIBRARY, quality: 100, destinationType: Camera.DestinationType.DATA_URI, allowEdit: true, encodingType: Camera.EncodingType.PNG }); The error is: java.lang.RuntimeException: Unable to resume activity {com.perfilempleo.perfil/com.perfilempleo.perfil.Perfilempleo}:.performResumeActivity(ActivityThread.java:2141) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2156) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680) at android.app.ActivityThread.access$1500(ActivityThread.java:121) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.app.ActivityThread.main(ActivityThread.java:3701) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) at dalvik.system.NativeStart.main(Native Method) Caused by:.deliverResults(ActivityThread.java:2553) at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2128) ...49) ... 13 more Thanks in advance Hi simon, Foreground Gallery Plugin is valid for phonegap 2.8.0? Thanks in advance @marcos cuesta Using DATA_URL instead of FILE_URI is a sure way to kill your app. You are either going to run out of memory and crash the app or have the calling app get cleared out to save memory. @Alejo Miguel Hernández García I'm not sure as I did not write it but it should be easy to upgrade if required. Probably just needs a few changes to the Java code to find the right classes. @Simon MacDonald Seems we are quite a few who would like to have the foreground plugin working with newer versions of Phonegap. I've contacted vinicius but seems they have no time to work on it. So, is there any chance to make a call so someone can recode it? :) @donantidees If I could make people do things, I'd be a much richer man than I am now :) Seriously though, it shouldn't be too hard to convert it to 3.0.0. Take a shot at it yourself and let me know if you need help. hi simon i have problem at camera when i use cordova 3.5 and capture pic from camera the image getting rotate 90 degree at left side This is happen only at samsung note 2 and samsung grand at rest devices its working properly. Thanx in advance @Daljeet Singh Are you using the "correctOrientation" parameter in your call to getPicture? IIRC sometimes Samsung puts their own bloatware camera on their devices and it is not coded as well as Google's camera.
http://simonmacdonald.blogspot.com/2012/07/change-to-camera-code-in-phonegap-190.html
CC-MAIN-2017-26
refinedweb
6,972
59.8
Contents - Whence come definitions - Imports from packages - Exposed and hidden packages - The home package - The target set - Star imports - The automatic star - The state of GHCi - Reloading - Overview of commands - Deferring type errors We’ll next look at bringing a file or project into scope in a GHCi session, which we do primarily using the :load and :reload commands. In a Haskell source file, what’s in scope is determined entirely by the list of import statements at the top of the module. We can type import statements into the GHCi prompt too, but GHCi also gives us additional ways to bring code into scope. These features make the scope at the prompt flexible, dynamic, and consequently more complicated. Overall, there are two routes by which things come into scope in GHCi: either you typed them in at the prompt, or they were imported. Understanding the latter is a little tricky, as there are several ways that imports can happen. - The :load, :reload, :add, :unaddcommands that manipulate the target set; - Using importand :moduleto bring modules into and out of scope; - Using the -packageGHC option and :set -packagewithin GHCi to expose hidden packages; and - What *means before a module name.
https://typeclasses.com/ghci/scope
CC-MAIN-2021-43
refinedweb
199
51.41
Are you a developer who finds it easier to read code instead of comments, only to discover how difficult it is to analyse the code and how simple a function/procedure turns out to be? Perhaps you have been in a situation in which you wanted to re-document your code which contains 20-pages (or more) from scratch knowing how tedious it is to remove comments line-by-line. Or maybe you are pondering how to "water down" your code before transmitting it to reduce network transfer times. What happens to comments in your code when you compile your program? This article provides an insight to these and a tool which strips existing comments within an ASCII source code file. Ordinary compilers do not understand comments. It simply skips over them. However, having them in the plain text source will likely cause problems during the compilation process. Hence to overcome this situation, most C-style languages use /* */ or // to denote comments. This will flag to the compiler/intepreter not to "read" what comes after int x; //commentary about an unknown alien x, in one line Or int x; /* Tell me more about the stars and the moon, in an essay */ So ever wonder what what happens to those pesky comments when the moment you hit that compile button? They get dumped! Well, I mean they stay in the source file. Surprised? As mentioned earlier, comments are not for the compiler! Having said that, it may be possible to store comments in a binary's metadata section. (Although I don't know of a compiler that implements this functionality, at much performance trade off) Take this code snippet in Java for example /** * {@link Class#getSimpleName()} is not GWT compatible yet, so we * provide our own implementation. */ @VisibleForTesting static String simpleName(Class<?> clazz) { String name = clazz.getName(); // we want the name of the inner class all by its lonesome int start = name.lastIndexOf('$'); //if this isn't an inner class, just find the start of the // top level class name. if (start == -1) { start = name.lastIndexOf('.'); } return name.substring(start + 1); } When you compile the code the compiler sees it as @VisibleForTesting static String simpleName(Class<?> clazz) { String name = clazz.getName(); int start = name.lastIndexOf('$'); if (start == -1) { start = name.lastIndexOf('.'); } return name.substring(start + 1); } as the comments are striped on the fly. That's all the compiler needs to generate object or/and machine code! The removal of comments is always done prior to compilation and it is very often transparent and invisible to developers. The application I present here today implements this functionality. Given a text source file, it strips of comments, leaving compilable code behind. This come in handy when you wish to redocument someone else's or your code without having to manually remove the code line-by-line. In the example screenshot, all single line, multiline and even Javadoc comments are removed. Likewise, in C#, XML comments are also removed. The basic rule is when a single line(//) comment is found in the line of code, the program should stop reading until a new line is encounted ('\n'), the next line read. When a multiline (/*) token is found, the program should stop processing until a */ is found. A "\n" or a "*/" returns the state to normal. In this implementation, a StreamReader is employed to read our ASCII source code. As code is processes line-by-line using the readLine() method, detecting and handling comment delimeters becomes slightly more difficult. Many compiler implementations written in C such as gcc parses the code on a char-by-char implementation, for performance and optimisation. However what we are developing is nothing close to a full fledged compiler, so line-by-line processing should be adequate. StreamReader readLine() I was able to keep it to a minimum of 2 methods, the main method doUncomment() and an internal method to handle string literals. All methods are implemented as static, so there is no need to create instances. For more information, please refer to the Uncommenter class. doUncomment() static Uncommenter To use the code insert the directive using UcommenterCS; Then simply call the static function to do the work. For example Uncommenter.doUncomment("src.cpp"); //specify full path That's it. If you, however wish to run it standalone "out of the box" or simply like to try it out, I have included a compiled binary which is just as good. It is in the /bin folder. To use it, issue the following command /bin UcommenterCS <source.cpp/c/cs/java/h/js> Comments within string delimeters should be avoided. This application is able to correctly ensure comments are not part of a string! It ignores comments delimeters between " and " blocks. " Future functionality includes detecting and warning against unterminated block comments and string literals with the option of breaking execution should they be found. Because I'm not a compiler linguist, I am not able to think of all the possible scenarios in which the code may fail. However, if you are up for a challenge, you are welcome to attempt to break my code. If that happens, please do let me know. I plan to write a Window Forms version in the not too distant future. Also in the works is a Java version. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) CarriageReturn LineFeed #ifndef _WINDOWS /*lint !e553 */ #pragma long64 #define _LONG64_ 1 #endif #ifndef _WINDOWS #pragma long64 #define _LONG64_ 1 #endif #ifndef _WINDOWS #pragma long64 #define _LONG64_ 1 #endif General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/41810/Source-Code-Uncommentor-in-C
CC-MAIN-2021-39
refinedweb
961
64.3
Step 5: Write Code That Publishes a Platform Event Message Before you publish a custom platform event message, ensure that the platform event is defined in your org. You can view defined platform events in Setup on the Platform Events page. For example, this image shows the definition of Order_Event__e. This event has two fields: Order_Number__c of type Text and Has_Shipped__c of type Checkbox. Create a separate Python file, publish.py, for publishing so that you can run the publisher and subscriber clients independently. Include common code from the subscriber client that you created earlier. Include the import statements, code for creating the channel and stub, and the authentication code to build authmetadata. Also, add this import statement: from datetime import datetime, timedelta Get the topic name for the event you want to publish. The topic format is /event/EventName__e. For example, for Order_Event__ethe topic is /event/Order_Event__e. You use it in the next step. Replace the mypubtopicplaceholder value with your topic. Get the schema ID and schema for the event. To get the schema ID, call the GetTopicmethod and pass the topic name. Next, pass the schema ID to the GetSchemamethod, which returns the schema. Create a function to encode the information that you want to send by using the schema. Create a function that creates a PublishRequest. Construct the payload by adding the event fields and values in the payload variable. Populate the values of the required system fields: CreatedDateand CreatedById. The CreatedByIdvalue isn’t validated. For {event field}: {field value}, list the event fields and values. For example, for Order_Event__e, you can add: The reqvariable contains the encoded payload, which is returned by the encode function. It also contains the schema ID. Make the publish call, and handle any acknowledgements that you get back. Run the client by entering this command on the command line. If the publish request is successful, you receive a PublishResponse message containing the replay ID. If the publish request wasn’t successful, you get an error similar to:
https://developer.salesforce.com/docs/platform/pub-sub-api/guide/qs-publish.html
CC-MAIN-2022-33
refinedweb
336
67.96
-------- Original Message -------- Subject: Re: ant-contrib 1.0b3 broken? From: Jacob Beard <jbeard4@cs.mcgill.ca> To: Ant Users List <user@ant.apache.org> Date: 08.09.2010 04:03 > Thanks for the replies. XML namespace mapping does work fine, as is > written in the docs included with later ant-contrib. For the record, > here's what I have that works: > > <project name="test-antcontrib" basedir="." default="use-antcontrib"> > > <property name="list" value="foo,bar,bat"/> > [...] i had some probs when trying antcontrib 1.0b3, the <assert> task didn't work for me and seems to be broken !? see = Does the example from antcontrib manual work for you ?? Alternatives for antcontrib are = antelope = anxtras = Regards, Gilbert --------------------------------------------------------------------- To unsubscribe, e-mail: user-unsubscribe@ant.apache.org For additional commands, e-mail: user-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-user/201009.mbox/%3C4C87D5C9.4010508@maksimo.de%3E
CC-MAIN-2016-44
refinedweb
135
55.1
As an example of when an interface isn't exactly what you want, use LinkMap and Map. Couldn't use Map because of RemoteException. BootsieIS-A Dog CarIS-AN Automobile OverdraftAccountObject OverdraftAccountIS-AN Account OverdraftAccounthas the same interface and fulfills the same semantic contract as Account OverdraftAccountfulfills the semantic contract differently than Account 1 package com.artima.examples.account.ex * As described in class <code>Account</code>, money is stored in 16 * this account in integral units. Clients 17 * can use this account to store any kind of value, such as money 18 * or points, etc. The meaning of the integral units stored in 19 * this account is a decision of the client that instantiates the 20 * account. The maximum amount of units that can be stored as 21 * the current balance of an <code>Account</code> is Long.MAX_VALUE. 22 */ 23 public class OverdraftAccount extends Account { 24 25 /** 26 * The maximum amount the bank will loan to the client. 27 */ 28 private final long overdraftMax; 29 30 /** 31 * The current amount the bank has loaned to the client 32 * which has not yet been repaid. This must be zero to 33 * overdraftMax. 34 */ 35 private long overdraft; 36 37 /** 38 * Constructs a new <code>OverdraftAccount</code> with the 39 * passed <code>overdraftMax</code>. 40 * 41 * @param overdraftMax the maximum amount the bank will loan 42 * to the client 43 */ 44 public OverdraftAccount(long overdraftMax) { 45 this.overdraftMax = overdraftMax; 46 } 47 48 /** 49 * Returns the current overdraft, the amount the bank has 50 * loaned to the client that has not yet been repaid. 51 * 52 * @returns the current overdraft 53 */ 54 public long getOverdraft() { 55 return overdraft; 56 } 57 58 /** 59 * Returns the overdraft maximum, the maximum amount the 60 * bank will allow the client to owe it. For each instance 61 * of <code>OverdraftAccount</code>, the overdraft maximum 62 * is constant. 63 * 64 * @returns the overdraft maximum 65 */ 66 public long getOverdraftMax() { 67 return overdraftMax; 68 } 69 70 /** 71 * Withdraws exactly the passed amount from the 72 * <code>Account</code>. If the passed amount is 73 * less than or equal to the current balance, all withdrawn 74 * funds will be taken from the balance, and the balance 75 * will be decremented by the passed amount. If the passed amount 76 * exceeds the current balance, the bank may loan the client the 77 * difference. The bank will make the loan only if the difference 78 * between the passed amount and the balance is less than or equal to 79 * the available overdraft. The available overdraft is equal to 80 * the current overdraft (the amount already loaned to the client and 81 * not yet repaid), subtracted from the overdraft maximum, which 82 * is passed to the constructor of any <code>OverdraftAccount</code>. 83 * 84 * <p> 85 * If the passed amount less the current balance is less than or equal 86 * to the available overdraft, the <code>withdraw</code> method returns 87 * the requested amount, sets the current balance to zero, and records 88 * the loan. Otherwise, if the passed amount less the current balance 89 * exceeds the available overdraft, the <code>withdraw</code> method throws 90 * <code>InsufficientFundsException</code>. 91 * 92 * @param amount amount to withdraw 93 * @returns amount withdrawn from the <code>Account</code> 94 * @throws InsufficientFundsException if the <code>Account</code> 95 * contains insufficient funds for the requested withdrawal 96 */ 97 public long withdraw(long amount) 98 throws InsufficientFundsException { 99 100 long balance = getBalance(); 101 if (balance >= amount) { 102 103 // Balance has sufficient funds, just take the 104 // money from the balance. 105 balance -= amount; 106 return amount; 107 } 108 109 long shortfall = amount - balance; 110 long extraAvailable = overdraftMax - overdraft; 111 112 if (shortfall > extraAvailable) { 113 throw new InsufficientFundsException(shortfall - extraAvailable); 114 } 115 overdraft += shortfall; 116 super.withdraw(amount - shortfall); 117 118 return amount; 119 } 120 121 /** 122 * Deposits exactly the passed amount into the <code>Account</code>. 123 * If the current overdraft is zero, the balance will be increased 124 * by the passed amount. Otherwise, the bank will attempt to pay 125 * off the overdraft first, before increasing the current balance 126 * by the amount remaining after the overdraft is repaid, if any. 127 * 128 * <p> 129 * For example, if the balance is 200, the overdraft is 100, and the 130 * <code>deposit</code> method is invoked with a passed <code>amount</code> 131 * of 50, the bank would use all 50 of those monetary units to pay down 132 * the overdraft. The overdraft would be reduced to 50 and the balance would 133 * remain at 200. If subsequently, the client deposits another 100 units, 134 * the bank would use 50 of those units to pay off the overdraft loan and 135 * direct the remaining 50 into the balance. The new overdraft would 136 * be 0 and the new balance would be 250. 137 * 138 * @param amount amount to deposit 139 * @throws ArithmeticException if requested deposit would cause the 140 * balance of this <code>Account</code> to exceed Long.MAX_VALUE. 141 */ 142 public void deposit(long amount) { 143 if (overdraft > 0) { 144 if (amount < overdraft) { 145 overdraft -= amount; 146 } 147 else { 148 long diff = amount - overdraft; 149 overdraft = 0; 150 super.deposit(diff); 151 } 152 } 153 else { 154 super.deposit(amount); 155 } 156 } 157 } OverdraftAccountobject on the heap: ManagerIS-AN Employee PeonIS-AN Employee RedCupIS-A Cup BlueCupIS-A Cup Accountbalance is $5000) OverDraftAccount) StampMachine.Statefamily Accountin the solution. SquareIS-A Rectangle? Wouldn't want to say: Overdraft100Account, Overdraft500Account, and Overdraft1000Account if there were just three legal overdraft maxes. Just use OverdraftAccount that takes a max. And either allow client to establish legal values for overdraft (other than negative), or check at constructor for legal values. Account a = new OverdraftAccount(50000);
http://www.artima.com/interfacedesign/ISA.html
CC-MAIN-2014-35
refinedweb
953
57.3
Template::Manual::Config - Configuration options The ENCODING option specifies the template files' character encoding: my $template = Template->new({ ENCODING => 'utf8', }); A template which starts with a Unicode byte order mark (BOM) will have its encoding detected automatically. The START_TAG and END_TAG options are used to specify character sequences or regular expressions that mark the start and end of inline template directives. OUTLINE_TAG option can be used to enable single-line "outline" directives. my $template = Template->new({ OUTLINE_TAG => '%%', }); This allows you to use both inline and outline tags like so: %% IF user Hello [% user.name %] %% END The OUTLINE_TAG string (or regex) must appear at the start of a line. The directive continues until the end of the line. The newline character at the end of the line is considered to be the invisible end-of-directive marker and is removed.) The outline style uses the default markers for START_TAG and END_TAG ( [% and %] respectively) and additionally defines OUTLINE_TAG to be %%. my $template = Template->new({ TAG_STYLE => 'outline', }); This allows you to use both inline and outline tags like so: %% IF user Hello [% user.name %] %% END Any values specified for START_TAG, END_TAG and/or OUTLINE_TAG will override )---' | `-> Bar With POST_CHOMP set to 1, any whitespace after a directive up to and including the newline will be deleted. This has the effect of joining a line that ends with a directive onto the start of the next line. If PRE_CHOMP or POST_CHOMP is set to 2, all whitespace including any number of newline will be removed and replaced with a single space. This is useful for HTML, where (usually) a contiguous block of whitespace is rendered the same as a single space. With PRE_CHOMP or POST_CHOMP set to 3, all adjacent whitespace (including newlines) will be removed entirely. These values are defined as CHOMP_NONE, CHOMP_ONE, CHOMP_COLLAPSE and CHOMP_GREEDY constants in the Template::Constants module. CHOMP_ALL is also defined as an alias for CHOMP_ONE to provide backwards compatibility with earlier version of the Template Toolkit. Additionally the chomp tag modifiers listed below may also be used for the PRE_CHOMP and POST_CHOMP configuration. my $template = Template->new({ PRE_CHOMP => '~', POST_CHOMP => '-', }); PRE_CHOMP and POST_CHOMP can be activated for individual directives by placing a ' -' immediately at the start and/or end of the directive. [%. The INTERPOLATE flag, when set to any true value will cause variable references in plain text (i.e. not surrounded by START_TAG and END_TAG) to be recognised and interpolated accordingly. my $template = Template- $template = Template->new({ INCLUDE_PATH => '/usr/local/templates', }); my $template = Template->new({ INCLUDE_PATH => '/usr/local/templates:/tmp/my/templates', }); my $template = Template- $template = Template- ' :'. my $template = Template->new({ DELIMITER => '; ', INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN', }); $template = Template- $template = Template->new({ ABSOLUTE => 1, }); # this is why it's disabled by default [% INSERT /etc/passwd %] %] -->' %] $template = Template->new({ CACHE_SIZE => 64, # only cache 64 compiled templates }); my $template = Template- $template = Template- $template = Template->new({ COMPILE_DIR => '/tmp/ttc', }); The COMPILE_EXT option may also be specified to have a consistent file extension added to these files. my $template1 = Template->new({ COMPILE_DIR => '/tmp/ttc', COMPILE_EXT => '.ttc1', }); my $template2 = Template- $template = Template- . The USE directive is used to create plugin objects and does so by calling the plugin() method on the current Template::Context object. If the plugin name is defined in the PLUGINS hash then the corresponding Perl module is loaded via require(). The context then calls the load() class method which should return the class name (default and general case) or a prototype object against which the new() method can be called to instantiate individual plugin objects. If the plugin name is not defined in the PLUGINS hash then the PLUGIN_BASE and/or LOAD_PERL options come into effect. If a plugin is not defined in the PLUGINS hash then the PLUGIN_BASE is used to attempt to construct a correct Perl module name which can be successfully loaded. The PLUGIN_BASE can be specified as a If a plugin cannot be loaded using the PLUGINS or PLUGIN_BASE approaches then the provider can make a final attempt to load the module without prepending any prefix to the module path. This allows regular Perl modules (i.e. those that don't reside in the Template::Plugin or some other such namespace) to be loaded and used as plugins. By default, the LOAD_PERL option is set to 0 and no attempt will be made to load any Perl modules that aren't named explicitly in the PLUGINS hash or reside in a package as named by one of the PLUGIN_BASE components. Plugins loaded using the PLUGINS or PLUGIN_BASE receive a reference to the current context object as the first argument to the new() constructor. Modules loaded using LOAD_PERL are assumed to not conform to the plugin interface. They must provide a new() class method for instantiating objects but it will not receive a reference to the context as the first argument. Plugin modules should provide a load() class method (or inherit the default one from the Template::Plugin base class) which is called the first time the plugin is loaded. Regular Perl modules need not. In all other respects, regular Perl objects and Template Toolkit plugins are identical. If a particular Perl module does not conform to the common, but not unilateral, new() constructor convention then a simple plugin wrapper can be written to interface to it.. $template = Template-. The LOAD_TEMPLATES option can be used to provide a reference to a list of Template::Provider objects or sub-classes thereof which will take responsibility for loading and compiling templates. my $template = Template-.', }, }; $template = Template->new({ PARSER => MyOrg::Template::Parser->new({ ... }), }); The GRAMMAR configuration item can be used to specify an alternate grammar for the parser. This allows a modified or entirely new template language $template = Template->new({ GRAMMAR = MyOrg::Template::Grammar->new(); });
http://search.cpan.org/dist/Template-Toolkit/lib/Template/Manual/Config.pod
CC-MAIN-2016-44
refinedweb
959
51.07
The Firefox UI test suite is an automated testing framework built on top of Marionette for executing ui-level and end-to-end tests for Firefox Desktop. It can be used for tests which cannot be covered in other test suites like browser chrome tests due to restrictions or feature limitations (e.g. requirements for a restart of the browser). Compared to other test suites the Firefox UI tests can also be executed for localized builds of Firefox given that all interactions are done via UI elements retrieved via locale independent DOM properties. To ease the creation and maintainance of tests the Firefox puppeteer POM (page object model) has been created, which contains numerous wrapper classes for the most often used UI elements and API calls. And last but not least the tests are written sequentially, which will drop the complexity of all the asynchronicity in Firefox and allow even newcomers to get started. Running the Firefox UI tests To run the tests, first build Mozilla with your changes; then run ./mach firefox-ui-functional This will launch your build, execute all existing tests, and report the results to stdout. If you don't want to build Firefox yourself or if you want to run the tests against a different build of Firefox, use the --binary option to specify the executable to be used. Keep in mind that you would still have to run at least mach configure to setup the mach environment. It is possible to run specific groups of tests. As with Marionette, testing/firefox-ui/tests/functional/security the command would be: ./mach firefox-ui-functional testing/firefox-ui/tests/functional/security/ Run ./mach help firefox-ui-test for more options. Type of Firefox UI tests Currently the Firefox UI tests are divided into two separate types. This distinction has been made to clearly separate different kinds of tests, which have e.g. completely different requirements or purposes. Functional tests The functional tests, which are the general type of tests and are used for testing the behavior of Firefox as described above. Tests are using local or remote testcase data and are tagged appropriately in the corresponding manifest.ini file. This type of test covers nearly all existing tests and should be used for new tests. Update tests The update tests are a specific subset of the functional tests and are used to properly test the update procedure of Firefox. The tests check what the users are usually doing by upgrading e.g. Firefox 44.0 to Firefox 45.0. So these tests are very important for the release process and the QA signoff for new releases. That also means when comparing the tests with the functional tests two different Firefox builds are involved here. Those builds can also be some versions apart, and would require full backward compatibility. Writing Firefox UI tests Firefox UI tests support test cases written in Python, using Python's unittest framework. Tests are written as a subclass of one of the following testcase classes: MarionetteTestCase(The very basic testcase class which comes via Marionette itself) - FirefoxTestCase (Extended testcase class for the use of firefox-puppeteer) - UpdateTestCase (Extended testcase class on top of FirefoxTestCase for update tests) Whereby individual tests belonging to instance methods that have a name starting with `test`. Additionally, you can provide setUp and tearDown instance methods to execute code before and/or after tests in a particular test class have run, but remember to call setUp/tearDown methods of the base testcase class in your provided function, since the base classes handle setup/teardown between test cases. Because the tests are mainly interacting with the browser and not web pages, all the tests will be executed in chrome scope by default. This test structure is illustrated here: from firefox_puppeteer.testcases import FirefoxTestCase class TestFoobar(FirefoxTestCase): def setUp(self): FirefoxTestCase.setUp(self) # code to execute before any tests are run def tearDown(self): # code to execute before any tests are run FirefoxTestCase.tearDown(self) def test_foo(self): # run test for 'foo' def test_bar(self): # run test for 'bar' Further documentation in how to get started and which rules to obey when contributing to the Firefox UI test suite can be found in the A-Team bootcamp. Adding a new Firefox UI test to the tree To add a new Firefox UI test to the tree, add it to the manifest.ini file in the same folder as the test. Also remember that the test file's name must begin with "test_" for the test to be recognized as a Firefox UI test. If you are adding the first tests in a directory, make sure to also create a new manifest.ini file and include it in the manifest.ini of the parent folder. Resource files Some of the tests make use of local test data as served via a local webserver (we use wptserve). If the new test requires such a file please store it in testing/firefox-ui/resources/. It's URL can then be retrieved in the test via ` self.marionette.absolute_url(%filename%)`. How to disable failing tests If test failures are getting reported to Treeherder the responsible persons of the specific test has to fix the failure. If a patch cannot be done in a short time and the test constantly fails, it has to be disabled aka marked as skipped. This can be done in two ways: - If all test methods within a single test file are failing the complete file has to be marked as disabled via the manifest file of the same folder. This can be done by using the `disabled` key followed by a description which explains why the test has been disabled. It should also contain a bug number for reference: [test_access_locationbar.py]skip-if = true # Bug 1168727 - In case of only one failing test method the above way would not be useful. Instead the one failing test method can be marked as skipped via the `unittest` module, or if available via a Marionette decorator (e.g. `@skip_if_e10s`): import unittest [..] @unittest.skip('Bug 123456') def testCheckAboutPrivateBrowsing(self): from marionette.marionette_test import skip_if_e10s [..] @skip_if_e10s('Bug 123456') def testCheckAboutPrivateBrowsing(self): Other information - Project documentation with current projects, contacts, and tips in how to contribute can be found on wiki.mozilla.org.
https://developer.mozilla.org/en-US/docs/Mozilla/QA/Firefox_UI_tests
CC-MAIN-2017-34
refinedweb
1,048
61.46
DaCHS Reference Documentation¶ Contents - DaCHS Reference Documentation - Resource Descriptor Element Reference - Active Tags - Grammars Available - Cores Available - Predefined Macros - Mixins - Triggers - Renderers Available - Predefined Procedures - Predefined Streams - Data Descriptors - Metadata - Display Hints - Data Model Annotation - DaCHS’ Service Interface - Writing Custom Cores - Regression Testing - Datalink and SODA - Product Previews - Custom UWSes - Custom Pages - Manufacturing Spectra - Echelle Spectra - Supporting getData - Adapting Obscore - Writing Custom Grammars - Functions Available for Row Makers - Scripting - ReStructuredText - Code in DaCHS - System Tables Resource Descriptor Element Reference¶ The following (XML) elements are defined for resource descriptors. Some elements are polymorous (Grammars, Cores). See below for a reference on the respective real elements known to the software. Each element description gives a general introduction to the element’s use (complain if it’s too technical; it’s not unlikely that it is since these texts are actually the defining classes’ docstrings). Within RDs, element properties that can (but need not) be written in XML attributes, i.e., as a single string, are called “atomic”. Their types are given in parentheses after the attribute name along with a default value. In general, items defaulted to Undefined are mandatory. Failing to give a value will result in an error at RD parse time. Within RD XML documents, you can (almost always) give atomic children either as XML attribute ( att="abc") or as child elements ( <att>abc</abc>). Some of the “atomic” attributes actually contain lists of items. For those, you should normally write multiple child elements ( <att>val1</att><att>val2</att>), although sometimes it’s allowed to mash together the individual list items using a variety of separators. Here are some short words about the types you may encounter, together with valid literals: - boolean – these allow quite a number of literals; use Trueand Falseor yesand noand stick to your choice. - unicode string – there may be additional syntactical limitations on those. See the explanation - integer – only decimal integer literals are allowed - id reference – these are references to items within XML documents; all elements within RDs can have an idattribute, which can then be used as an id reference. Additionally, you can reference elements in different RDs using <rd-id>#<id>. Note that DaCHS does not support forward references (i.e., references to items lexically behind the referencing element). - list of id references – Lists of id references. The values could be mashed together with commas, but prefer multiple child elements. There are also “Dict-like” attributes. These are built from XML like: <d key="ab">val1</d> <d key="cd">val2</d> In addition to key, other (possibly more descriptive) attributes for the key within these mappings may also be allowed. In special circumstances (in particular with properties) it may be useful to add to a value: <property key="brokencols">ab,cd</property> <property key="brokencols" cumulative="True">,x</property> will leave ab,cd,x in brokencols. Many elements can also have “structure children”. These correspond to compound things with attributes and possibly children of their own. The name given at the start of each description is irrelevant to the pure user; it’s the attribute name you’d use when you have the corresponding python objects. For authoring XML, you use the name in the following link; thus, the phrase “colRefs (contains Element columnRef…” means you’d write <columnRef...>. Here are some guidelines as to the naming of the attributes: - Attributes giving keys into dictionaries or similar (e.g., column names) should always be named key - Attributes giving references to some source of events or data should always be named source, never “src” or similar - Attributes referencing generic things should always be called ref; of course, references to specific things like tables or services should indicate in their names what they are supposed to reference. Also note that examples for the usage of almost everything mentioned here can be found in in the GAVO datacenter element reference. Grammars Available¶ The following elements are all grammar related. All grammar elements can occur in data descriptors. Cores Available¶ The following elements are related to cores. All cores can only occur toplevel, i.e. as direct children of resource descriptors. Cores are only useful with an id to make them referencable from services using that core. Predefined Macros¶ Macro expansions in DaCHS start with a backslash, arguments are given in curly braces. What macros are available depends on the element doing the expansion; regrettably, not all strings are expanded, and at this point it’s not usually documented which are and which are not (though we hope DaCHS typically behaves “as expected”). If this bites you, complain to the authors and we promise we’ll give fixing this a higher priority. Mixins¶ Mixins ensure a certain functionality on a table. Typically, this is used to provide certain guaranteed fields to particular cores. For many mixins, there are predefined procedures (both rowmaker applys and grammar rowfilters) that should be used in grammars and/or rowmakers feeding the tables mixing in a given mixin. Triggers¶ In DaCHS, triggers are conditions on rows – either the raw rows emitted by grammars if they are used within grammars, or the rows about to be shipped to a table if they are used within tables. Triggers may be used recursively, i.e., triggers may contain more triggers. Child triggers are normally or-ed together. Currently, there is one useful top-level trigger, the `element ignoreOn`_. If an ignoreOn is triggered, the respective row is silently dropped (actually, you ignoreOn has a bail attribute that allows you to raise an error if the trigger is pulled; this is mainly for debugging). The following triggers are defined: Renderers Available¶ The following renderers are available for allowing and URL creation. The parameter style is relevant when adapting condDescs` or table based cores to renderers: - With clear, parameters are just handed through - With form, suitable parameters are turned into vizier-like expressions - With pql, suitable parameters are turned into their PQL counterparts, letting you specify ranges and such. Unchecked renderers can be applied to any service and need not be explicitly allowed by the service. Predefined Procedures¶ Predefined Streams¶ Streams are recorded RD elements that can be replayed into resource descriptors using the FEED active tag. They do, however, support macro expansion; if macros are expanded, you need to given them values in the FEED element (as attributes). What attributes are required should be mentioned in the following descriptions for those predefined streams within DaCHS that are intended for developer consumption. Data Descriptors¶ Most basic information on data descriptors is contained in tutorial.html. The material here just covers some advanced topics. Updating Data Descriptors¶ By default, dachs imp will try to drop all tables made by the data descriptors selected. For “growing” data, that is suboptimal, since typicaly just a few new datasets need to be added to the table, and re-ingesting everything else is just a waste of time and CPU. To accomodate such situations, DaCHS allows to add an updating="True" attribute to a data element; updating DDs will create tables that do not exist but will not drop existing ones. Using fromdb on ignoreSources¶ Updating DDs will still run like normal DDs and thus import everything matching the DD’s sources. Thus, after the second import you would have duplicate records for sources that existed during the first import. To avoid that, you (usually) need to ignore existing sources (see `Element ignoreSources`_). In the typical case, where a dataset’s accref is just the inputs-relative path to the dataset’s source, that is easily accomplished through the fromdb attribute of ignoreSources; its value is a database query that returns the inputs-relative paths of sources to ignore. Hence, unless you are playing games with the accrefs (in which case you are probably smart enough to figure out how to adapt the pattern), the following speficiation will exactly import all FITS files within the data subdirectory of the resdir that haven’t been ingested into the mydata table during the last run, either because they’ve not been there or because there were skipped during an import -c: <data id="import" updating="true"> <sources pattern="data/*.fits"> <ignoreSources fromdb="select accref from \schema.mydata"/> </sources> <fitsProdGrammar> <rowfilter procDef="//products#define"> <bind key="table">"\schema.mydata"</bind> </rowfilter> </fitsProdGrammar> <make table="mydata"> <!-- your rowmaker here --> </make> </data> Note that fromdb can be combined with fromfiles and pattern; whatever is specified in the latter two will always be ignored. To completely re-import such a table – for instance after a table schema change or because the whole data collection has been re-processed –, just run dachs drop on the DD and run import as usual. It is probably a good idea to occasionally run dachs imp -I on tables updated in this way to optimise the indices (a REINDEX <tablename> in a database shell will do, too). Using fromdbUpdating on ignoreSources¶ Sometimes reprocessing happens quite frequently to a small subset of the datasets in a resource. In that case, it would again be a waste to tear down the entire thing just to update a handful of records. For such situations, there is the fromdbUpdating attribute of ignoreSources. As with fromdb, this contains a database query, but in addition to the accref, this query has to return a timestamp. A source is then only ignored if this timestamp is not newer than the disk file’s one. If that timestamp is the mtime of the file in the original import, the net effect is that files that have been modified since that import will be re-ingested. There is a catch, though: You need to make sure that the record ingested previously is removed from the table. Typically, you can do that by defining accref as a primary key (if that’s not possible because you are generating multiple records with the same accref, there is nothing wrong with using a compound primary key). This will, on an attempted overwrite, cause an IntegrityError, and you can configure DaCHS to turn this into an overwrite using the table’s forceUnique and dupePolicy attributes. The following snippet illustrates the technique: <table id="withdate" mixin="//products#table" onDisk="True" primary="accref" forceUnique="True" dupePolicy="overwrite"> <column name="mtime" type="timestamp" ucd="time;meta.file" tablehead="Timestamp" description="Modification date of the source file."/> <!-- your other columns --> </table> <data id="import" updating="True"> <sources pattern="data/*.fits"> <ignoreSources fromdbUpdating="select accref, mtime from \schema.withdate"/> </sources> <fitsProdGrammar> <rowfilter procDef="//products#define"> <bind key="table">"\schema.withdate"</bind> </rowfilter> </fitsProdGrammar> <make table="withdate"> <rowmaker> <map key="mtime">datetime.datetime.utcfromtimestamp( os.path.getmtime(\fullPath))</map> <!-- other rowmaker rules --> </rowmaker> </make> </data> Again, this can be combined with the other attributes of ignoreSources; in effect, whatever is ignored from them is treated as if their modification dates were in the future. Metadata¶ Various elements support the setting of metadata through meta elements. Metadata is used for conveying RMI-style metadata used in the VO registry. See [RMI] for an overview of those. We use the keys given in RMI, but there are some extensions discussed in RMI-style Metadata. The other big use of meta information is for feeding templates. Those “local” keys should all start with an underscore. You are basically free to use those as you like and fetch them from your custom templates. The predefined templates already have some meta items built in, discussed in Template Metadata. So, metadata is a key-value mapping. Keys may be compound like in RMI, i.e., they may consist of period-separated atoms, like publisher.address.email. There may be multiple items for each meta key. Inputing Metadata¶ In RDs, there are two ways to define metadata: Meta elements and meta streams; the latter are also used in defaultmeta.txt. Meta Elements¶ These look like normal XML elements and have a mandatory name attribute, a meta key relative to the element’s root . The text content is taken as the meta value; child meta elements are legal. An optional attribute for all meta elements is format (see Meta Formats). Typed meta elements can have further attributes; these usually can also be given as meta children with the same name. Usually, metadata is additive; add a key twice and you will have a sequence of two meta values. To remove previous content, prefix the meta name with a bang (!). Here is an example: <resource> <!-- a simple piece of metadata --> <meta name="title">A Meta example</meta> <!-- repeat a meta thing for a sequence (caution: not everything is repeatable in all output formats --> <meta name="subject">Examples</meta> <meta name="subject">DaCHS</meta> <!-- Hierarchical meta can be set nested --> <meta name="creator"> <meta name="name">Nations, U.N.</meta> <meta name="logo"></meta> </meta> <meta name="creator"> <meta name="name">Neumann, A.E.</meta> </meta> <!-- @format lets you specify extra markup; make sure you have consistent initial indentation. --> <meta name=description" format="rst"> This resource is used in the `DaCHS reference docs`_ .. _DaCHS reference Docs: </meta> <!-- you can contract "deeper" trees in paths --> <meta name="contact.email">gavo@ari.uni-heidelberg.de</meta> <!-- typed meta elements can have additional attributes --> <meta name="uses" ivoId="ivo://org.gavo.dc/DaCHS" >DaCHS server sortware</meta> <!-- To overwrite a key set before, prefix the name with a bang. --> <meta name="!title">An improved Meta example</meta> </resource> The resulting meta structure is like this: +-- title | +---- "An improved Meta example | +-- subject | +---- "Examples | +---- "DaCHS | +-- creator | +----- name | | +---- "Nations, U.N. | +----- logo | | +---- " +-- creator | +----- name | +---- "Neumann, A.E. | +-- description | +----- [formatted text, "This resource..."] | +-- contact | +----- email | +----- "gavo@ari.uni-heidelberg.de | +-- uses +----- "DaCHS server software +----- ivoId +----- "ivo://org.gavo.dc/DaCHS Stream Metadata¶ In several places, most notably in the defaultmeta.txt file and in meta elements without a name attribute, you can give metadata as a “meta stream”. This is just a sequence of lines containing pairs of <meta key> and <meta value>. In addition, there are comments, empty lines, and continuations. Continuation lines work by ending a line with a backslash. The following line separator and all blanks and tabs following it are then ignored. Thus, the following two meta keys end up having identical values: meta1: A contin\ uation line needs \ a blank if you wan\ t one. meta2: A continuation line needs a blank if you want one Note that whitespace behind a backslash prevents it from being a continuation character. That is, admittedly, a bit of a trap. Other than their use as continuation characters, backslashes have no special meaning within meta streams as such. Within meta elements, however, macros are expanded after continuation line processing if the meta parent knows how to expand macros. This lets you write things like: <meta> creationDate: \metaString{authority.creationDate} managingOrg:ivo://\getConfig{ivoa}{authority} </meta> Comments and empty lines are easy: Empty lines are allowed, and a comment is a line with a hash (#) as its first non-whitespace character. Both constructs are ignored, and you can even continue comments (though you should not). A Pitfall with Sequential Nested Meta¶ The creator.name meta illustrates a pitfall with our metadata definition. Suppose you had more than one creator. What you’d want is a metadata structure like this: +-- creator -- name (Arthur) | +-- creator -- name (Berta) However, if you write: creator.name: Arthur creator.name: Berta or, equivalently: <meta name="creator.name">Arthur</meta> <meta name="creator.name">Berta</meta> by the above rules, you’ll get this: +-- creator -- name (Arthur) | +------ name (Berta) i.e., one creator with two names. To avoid this, make a new creator node in between, i.e., write: creator.name: Arthur creator: creator.name: Berta In the creator.name case, where this is so common, DaCHS provides a shortcut, which you should use as a default; if you set creator directly, DaCHS will expect a string of the form: <author1>, <inits1> {; <authorn>, <initsn>} (i.e., Last, I.-form separated by semicolons, as in “Foo, X.; Bar, Q.; et al”) and split it up into the proper structure. You can mix the two notations, for instance if you want to set a logo on the first creator: <meta name="creator"> <meta name="name">Chandrasekhar, S.</meta> <meta name="logo"></meta> </meta> <meta name="creator">Copernicus, N.; Gallilei, G.</meta> Meta information can have a complex tree structure. With meta streams, you can build trees by referencing dotted meta identifiers. If you specify meta information for an item that already exists, a sibling will be created. Thus, after: creator.name: A. Author creator: creator.name: B. Buthor there are two creator elements, each specifying a name meta. For the way creators are specified within VOResource, the following would be wrong: creator.name: This is wrong. creator.name: and will not work – you would have a single creator meta with two name metas, which is not allowed by VOResource. If you write: contact.address: 7 Miner's Way, Behind the Seven Mountains contact.email: dwarfs@fairytale.fa you have a single contact meta giving address and email. Meta inheritance¶ When you query an element for metadata, it first sees if it has this metadata. If that is not the case, it will ask its meta parent. This usually is the embedding element. It wil again delegate the request to its parent, if it exists. If there is no parent, configured defaults are examined. These are taken from rootDir/etc/defaultmeta, where they are given as colon-separated key-value pairs, e.g., publisher: The GAVO DC team publisherID: ivo://org.gavo.dc contact.name: GAVO Data Center Team contact.address: Moenchhofstrasse 12-14, D-69120 Heidelberg contact.email: gavo@ari.uni-heidelberg.de contact.telephone: ++49 6221 54 1837 creator.name: GAVO Data Center creator.logo: The effect is that you can give global titles, descriptions, etc. in the RD but override them in services, tables, etc. The configured defaults let you specify meta items that are probably constant for everything in your data center, though of course you can override these in your RD elements, too. In HTML templates, missing meta usually is not an error. The corresponding elements are just left empty. In registry documents, missing meta may be an error. Meta formats¶ Metadata must work in registry records as well as in HTML pages and possibly in other places. Thus, it should ideally be given in formats that can be sensibly transformed into the various formats. DaCHS knows four input formats: - literal - The textual content of the element will not be touched. In HTML, it will end up in a div block of class literalmeta. - plain - The textual content of the element will be whitespace-normalized, i.e., whitespace will be stripped from the start and the end, runs of blanks and tabs are replaced by a single blank, and empty lines translate into paragraphs. In HTML, these blocks com in plainmeta div elements. - rst - The textual content of the element is interpreted as ReStructuredText. When requested as plain text, the ReStructuredText itself is returned, in HTML, the standard docutils rendering is returned. - raw - The textual content of the element is not touched. It will be embedded into HTML directly. You can use this, probably together with CDATA sections, to embed HTML – the other formats should not contain anything special to HTML (i.e., they should be PCDATA in XML lingo). While the software does not enforce this, raw content should not be used with RMI-type metadata. Only use it for items that will not be rendered outside of HTML templates. Macros in Meta Elements¶ Macros will be expanded in meta items using the embedding element as macro processors (i.e., you can use the macros defined by this element). Typed Meta Elements¶ While generally the DC software does not care what you put into meta items and views them all as strings, certain keys are treated specially. The following meta keys trigger some special behaviour: Additionally, there is creator, which is really special (at least for now). When you set creator to a string, the string will be split at semicolons, and for each substring a creator item with the respective name is generated. This may sound complicated but really does about what your would expect when you write: <meta name="creator">Last, J; First, B; Middle, I.</meta> Metadata in Standard Renderers¶ Certain meta keys have a data center-internal interpretation, used in renderers or writers of certain formats. These keys should always start with an underscore. Among those are: - _intro – used by the standard HTML template for explanatory text above the seach form. - _bottominfo – used by the standard HTML template for explanatory text below the seach form. - _copyright – used by the standard HTML template for copyright-related information (there’s also copyright in RMI; the one with the underscore is intended to be less formal). - _related – used in the standard HTML template for links to related services. As listed above, this is a link, i.e., you can give a title attribute. - _longdoc – used by the service info renderer for an explanatory piece of text of arbitrary length. This will usually be in ReStructuredText, and we recommend having the whole meta body in a CDATA section. - _news – news on the service. See above at Typed Meta Elements. - _warning – used by both the VOTable and the HTML table renderer. The content is rendered as some kind of warning. Unfortunately, there is no standard how to do this in VOTables. There is no telling if the info elements generated will show anywhere. - _noresultwarning – displayed by the default response template instead of an empty table (use it for things like “No Foobar data for your query”) - _type – on Data instances, used by the VOTable writer to set the typeattribute on RESOURCEelements (to either “results” or “meta”). Probably only useful internally. - _plotOptions – typically set on services, this lets you configure the initial appearance of the javascript-based quick plot. The value must be a javascript dictionary literal (like {"xselIndex": 2}) unless you’re trying CSS deviltry (which you could, using this meta; then again, if you can inject RDs, you probably don’t need CSS attacks). Keys evaluated include: - xselIndex – 0-based index of the column plotted on the x-axis (default: 0) - yselIndex – 0-based index of the column plotted on the y-axis (default: length of the column list; that’s “histogram on y) - usingIndex – 0-based index of the plotting style selector. For now, that’s 0 for points and 1 for lines. RMI-Style Metadata¶ For services (and other things) that are registred in the Registry, you must give certain metadata items (and you can give more), where we take their keys from [RMI]. We provide a explanatory leaflet for data providers. The most common keys – used by the registry interface and in part by HTML and VOTable renderers – include: - title – this should in general be given seperately on the resource, each table, and each service. In simple cases, though, you may get by by just having one global title on the resource and rely on metdata inheritance. - shortName – a string that should indicate what the service is in 16 characters or less. - creationDate – Use ISO format with time, UTC only, like this: 2007-10-04T12:00:00Z - subject – as noted in the explanatory leaflet, these should be taken from the IVOA Vocabulary Explorer. - source – bibcodes will be expanded to ADS links here. - referenceURL – again, a link, so you can give a title for presentation purposes. If you give no referenceURL, the service’s info page will be used. - dateUpdated – an ISO date. Do not set this. This is determined from timestamps in DaCHS’s state directory. There is also datetimeUpdated that you would have to keep in sync with dateUpdated if you were to change it. - creator.name – this should be the name of the “author” of the data set. See below for multiple creators. If you set this, you may want to override creator.logo as well. - type – one of Other, Archive, Bibliography, Catalog, Journal, Library, Simulation, Survey, Transformation, Education, Outreach, EPOResource, Animation, Artwork, Background, BasicData, Historical, Photographic, Press, Organisation, Project, Registry – it’s optional and we doubt its usefulness. - contentLevel – addresse(s) of the data: Research, Amateur, General - facility – no IVOA ids are supported here yet, but probably this should change. - coverage – see the special section - service-specific metadata (for SIA, SCS, etc.) – see the documentation of the respective cores. - utype – tables (and possibly other items) can have utypes to signify their role in specific data models. For tables, this utype gets exported to the tap_schema. - identifier – this is the IVOID of the resource, usually generated by DaCHS. Do not override this unless you know what you are doing (which at least means you know how to make DaCHS declare an authority and claim it). If you do override the identifier of a service that’s already published, make sure you run gavo admin makeDeletedRecord <previous identifier>(before or after the gavo pubon the resource, or the registries will have two copies of your record, one of which will not be updated any more; and that would suck for Registry users. - mirrorURL – add these on publication to declare mirrors for a service. Only do so if you actually manage the other service. If you list the service’s own accessURL here, it will be filtered from this registry record; this is so you can use the same RD on the primary site and the mirror. While you can set any of these in etc/defaultmeta.txt, the following items are usually set there: - publisher - publisherID - contact.name - contact.address - contact.email - contact.telephone Coverage Metadata¶ Coverage metadata lets clients get a quick idea of where in space, time, and electromagnetic spectrum the data within a resource is. Obviously, this information is particularly important for resource discovery in registries. Not all resources have coverages on all axes; a service validator, say, probably has no physical coverage at all, and a theoretical spectral service may just have meaningful spectral coverage. There are two meta keys pertinent to coverage metadata: coverage.waveband– One of Radio, Millimeter, Infrared, Optical, UV, EUV, X-ray, Gamma-ray, and you can have multiple waveband specifications. As this information is quite regularly used in discovery you should make sure to define it if applicable. coverage.regionOfRegard– in essence, the “pixel size” of the service in degrees. If, for example, your service gives data on a lattice of sampling points, the typical distance of such points should be given here. You will not usually specify this unless your „pixel size” is significantly larger than about an arcsec. The legacy coverage.profile meta key should not be used any more. To give proper, numeric STC coverage, use the `Element coverage`_. It has three children, one each for the spatial, spectral, and temporal axes. For spectral and temporal, just add as many intervals as necessary. Do not worry about gaps in the temporal coverage: it is not necessary that the coverage is “tight”; as long as there is a reasonable expectation that data could be there, it’s fine to declare coverage. Hence, for ground-based observations, there is no need to exclude intervals of daylight, bad weather, or even maintenance downtime. Intervals are given as in VOTable tabledata, i.e., as two floating point numbers separated by whitespace. There are no (half-) open intervals – just use insanely small or large numbers if you really think you need them. For spatial coverage, a single spatial element should be given. It has to contain a MOC in ASCII serialisation. Recent versions of Aladin can generate those, or you can write SQL queries to have them computed by sufficiently new versions of pgsphere. Most typically, you will use updater elements to fill spatial coverage (see below). A complete coverage element would thus look like this: <coverage> <spectral>3.8e-07 5.2e-07</spectral> <temporal>18867 27155</temporal> <spatial> 4/2068 5/8263,8268-8269,8271,8280,8323,8326,8329,9376,9378 6/33045-33047,33049,33051,33069,33080-33081,33083,33104-33106, 33112,33124-33126,33128-33130,33287,33289,33291,33297-33299, 33313,33315,33323-33326,33328-33330,37416,37418,37536 </spatial> </coverage> In general computing coverage is a tedious task. Hence, DaCHS has rules to compute it for many common cases (SSAP, SIAP, Obscore, catalogs with usable UCDs). Because coverage calculations can run for a long time, they are not performed online. Instead, DaCHS updates coverage elements when the operator runs dachs limits. In the simplest case, operators add: <coverage> <updater sourceTable="data"/> <spectral/> <temporal/> <spatial/> </coverage> into an RD with a table named data. Currently, this must be lexically below the table element, but if this isn’t fixed to allow the location of the coverage element near the rest of the metadata near the top of the RD, complain fiercely. Operators then run dachs limits q (assuming the RD is called q.rd), and DaCHS will fill out the three coverage elements (in case you want to fix them: the heuristics it uses to do that are in gavo.user.info). In this construction, DaCHS will overwrite any previous content in the coverage child elements. If you want to fill out some coverage items manually and have DaCHS only compute, say, the spatial coverage, don’t give the sourceTable attribute (which essentially says: “grab as much coverage from the referenced table as you can”) but rather the specialised spaceTable. This is particularly useful if you want to annotate ”holes” in your temporal coverage. For instance, if your resource contains two fairly separate campaigns (which DaCHS does not currently realise automatically): <coverage> <updater spaceTable="main"/> <spatial/> <temporal>45201 45409</temporal> <temporal>54888 55056</temporal> </coverage> Due to limitations of pgsphere, DaCHS does not currently take into account the size of the items in a database table. While that is probably all right for spectra and catalogs, for images this might lose significant coverage, as DaCHS only uses the centers of the images and just marks the containing healpix of the selected MOC order. The default MOC order is 6 (a resolution of about a degree). Until we properly deal with polygons, make sure to increase the MOC order to at least the order of magnitude of the images in an image service, like this: <coverage> <updater sourceTable="main" mocOrder="4"/> <spatial/> </coverage> If you know your resource only contains relatively few but compact patches, you may also want to increase mocOrder (spatial resolution doubles when you increase mocOrder by one). Display Hints¶ Display hints use an open vocabulary. As you add value formatters, you can evaluate any display hint you like. Display hints understood by the built-in value formatters include: - displayUnit - use the value of this hint as the unit to display a value in. - nopreview - if this key is present with any value, no HTML code to generate previews when mousing over a link will be generated. - sepChar - a separation character for sexagesimal displays and the like. - sf - “Significant figures” – length of the mantissa for this column. Will probably be replaced by a column attribute analoguous to what VOTable does. - type a key that gives hints what to do with the column. Values currently understood include: - bar - display a numeric value as a bar of length value pixels. - bibcode - display the value as a link to an ADS bibcode query. - checkmark - in HTML tables, render this column as empty or checkmark depending on whether the value is false or true to python. - humanDate - display a timestamp value or a real number in either yr (julian year), d (JD, or MJD if DaCHS guesses it’s mjd; that’s unfortunately arcane still), or s (unix timestamp) as an ISO string. - humanDay - display a timestamp or date value as an ISO string without time. - humanTime - display values as h:m:s. - keephtml - lets you include raw HTML. In VOTables, tags are removed. - product - treats the value as a product key and expands it to a URL for the product (i.e., typically image). This is defined in protocols.products. This display hint is also used by, e.g., the tar format to identify which columns should contribute to the tar file. - dms - format a float as degree, minutes, seconds. - simbadlink - formats a column consisting of alpha and delta as a link to query simbad. You can add a coneMins displayHint to specify the search radius. - hms - force formatting of this column as a time (usually for RA). - url - makes value a link in HTML tables. The anchor text will be the last element of the path part of the URL, or, if given, the value of the anchorText property of the column (which is for cases when you want a constant text like “Details”). If you need more control over the anchor text, use an outputField with a formatter. - imageURL - makes value the src of an image. Add width to force a certain image size. - noxml - if ‘true’ (exactly like this), do not include this column in VOTables. Note that not any combination of display hints is correctly interpreted. The interpretation is greedy, and only one formatter at a time attempts to interpret display hints. Data Model Annotation¶ In the VO, data models are used when simple, more or less linear annotation methods like UCDs do not provide sufficent expressive power. Or well, they should be used. As of early 2017, things are, admittedly, still a mess. DaCHS lets you annotate your data in dm elements; the annotation will then be turned into standard VOTable annotation (when that’s defined). Sometimes, the structured references provided by the DM annotation are useful elsewhere, too – the first actual use of this framework was the geojson serialisation discussed below. We first discuss SIL, then its use in actual data models. At least skim over the next section – it sucks to discover the SIL grammar by trial and error. Old-style STC annotation is not discussed here. If you still want to do it (and for now, you have to if you want any STC annotation – sigh), check out the terse discussion in the tutorial Annotation Using SIL¶ Data model annotation in DaCHS is done using SIL, the Simple Instance Language. It essentially resembles JSON, but all delimiters not really necessary for our use case have been dropped, and type annotation has been added. The elements of SIL are: Atomic Values. For SIL, everything is a string (it’s a problem of DM validation to decide otherwise). When your string consists exclusively of alphanumerics and [._-], you can just write it in SIL. Otherwise, you must use double quotes. as in SQL, write two double quotes to include a literal double quote. So, valid literals in SIL are 2.3e-3 red "white and blue" """Yes,"" the computer said." "could write (type:foo) {bar. baz} here"(elements of SIL are protected in quoted literals) Invalid literals include:(: and / may not occur in literals) red, white and blue(no blanks and commas) 22"(no single quotes) Plain Identifiers. These are C-like identifiers (a letter or an underscore optionally followed by letters, number or underscores). /*...*/). They don’t nest yet, but they probably will at some point, so don’t write /*within a comment. Object annotation. This is like a dictionary; only plain identifiers are allowed as keys. So, an object looks like this: { foo: bar longer: "This is a value with blanks in it" } Note again that no commas or quotes around the keys are necessary (or even allowed). Sequences. This is like a list. Members can be atomic or objects, but they have to be homogenous (SIL doesn’t enforce this by grammatical means, though. Here is an object with two sequences: { seq1: [3 4 5 "You thought these were numbers? They're strings!"] seq2: [ { seq_index: 0 value: 3.3} { seq_index: 1 value: 0.3} ] } References. The point of SIL is to say things about column and param instances. Both of them (and other dm instances, tables, and in principle anything else in RDs) can be referenced from within SIL. A reference starts with an @ and is then a normal DaCHS cross identifier (columns and params within a table can be referenced by name only, columns take precedence on name clashes). If you use odd characters in your RD names or in-RD identifiers, think again: only [._/#-] are allowed in such references. Here is an object with some valid references: { long: @raj2000 /* a column in the enclosing table */ lat: @dej2000 system: @//systems#icrs /* could be a dm instance in a DaCHS-global RD;, this does *not* exist yet */ source: @supercat/q#main /* perhaps a table in another RD */ } Casting. You can (and sometimes have to) give explicit types in the SIL annotation. Types look like C-style casts. The root of a SIL annotation must always have a cast; that allows DaCHS to figure out what it is, which is essential for validation (and possibly inference of defaults and such). You can cast both single objects and sequences. Here’s an example that actually validates for DaCHS’ SIL (which the examples above wouldn’t because they’re missing the root annotation): (testdm:testclass) { /* cast on root: mandatory */ attr1 { /* no cast here; DaCHS can infer attr1's type if necessary */ attr2: val } seq: (testdm:otherclass)[ /* Sequence cast: */ {attr1: a} /* all of these are now treated as testdm:otherclass */ {attr1: b} {attr1: c}]} GeoJSON annotation¶ To produce GeoJSON output (as supported by DaCHS’ TAP implementation), DaCHS needs to know what the “geometry“ in the sense of GeoJSON is. Furthermore, DaCHS keeps supporting declaring reference systems in the crs attribute, as the planetology community uses it. The root class of the geojson DM is geojson:FeatureCollection. It has up to two attributes (crs and feature), closely following the GeoJSON structure itself. The geometry is defined in feature’s geometry attribute. All columns not used for geometry will end up in GeoJSON properties. So, a complete GeoJSON annotation, in this case for an EPN-TAP table, could look like this: <table> <dm> (geojson:FeatureCollection){ crs: (geojson:CRS) { type: name properties: (geojson:CRSProperties) { name: "urn:x-invented:titan"}}}} feature: { geometry: { type: sepsimplex c1min: @c1min c2min: @c2min c1max: @c1max c2max: @c2max }}} </dm> <mixin spatial_frame_type="body"/> </table> Yes, the use type attributes is a bit of an abomination, but we wanted the structure to follow GeoJSON in spirit. The crs attribute could also be of type link, in which case the properties would have attributes href and type; we’re not aware of any applications of this in planetology, though. crs is optional (but standards-compliant GeoJSON clients will interpret your coordinates as WGS84 on Earth if you leave it out). For geometry, several values for type are defined by DaCHS, depending on how the GeoJSON geometry should be constructed from the table. Currently defined types include (complain if you need something else, it’s not hard to add): sepcoo– this is for a spherical point with separate columns for the two axes. This needs latitude and longitude attributes, like this: <dm> (geojson:FeatureCollection){ feature: { geometry: { type: sepcoo latitude: @lat longitude: @long }}} </dm> seppoly– this constructs a spherical polygon out of column references. These have the form c_n_m, where m is 1 or 2, and n is counted from 1 up to the number of points. DaCHS will stop collecting points as soon as it doesn’t find an expected key. If you find yourself using this, check your data model. An example: <dm> (geojson:FeatureCollection){ feature: { geometry: { type: seppoly /* a triangle of some kind */ c1_1: @rb0 c1_2: @rb1 c2_1: @lb0 c2_2: @lb1 c3_1: @t0 c3_2: @t1 }}} </dm> sepsimplex– this constructs a spherical box-like thing from minimum and maximum values. It has c[12](min|max) keys as in EPN-TAP. As a matter of fact, a fairly typical annotation for EPN-TAP would be: <dm> (geojson:FeatureCollection){ feature: { geometry: { type: sepsimplex c1min: @c1min c2min: @c2min c1max: @c1max c2max: @c2max }}} </dm> geometry– this constructs a geometry from a pgsphere column. Since GeoJSON doesn’t have circles, only spoint and spoly columns can be used. They are referenced from the value key. For instance, obscore and friends could use: <dm> (geojson:FeatureCollection) { feature: { geometry: { type: geometry value: @s_region }}} </dm> DaCHS’ Service Interface¶ Even though normal users should rarely be confronted with too many of the technical details of request processing in DaCHS, it helps to have a rough comprehension in order to understand several user-visible details. In DaCHS’ architecture, a service is essentially a combination of a core and a renderer. The core is what actually does the query or the computation, the renderer adapts input and outputs to what a protocol or interface expects. While a service always has exactly one core (could be a nullCore, though), it can support more than one renderer, although the parameters in all renderers are, within reason, about the same, within reason. However, parameters on a form interface will typcially be interpreted differently from a VO interface on the same core. For instance, ranges on the form interface are written as 1 .. 3 (VizieR compliance), on an SSA 1.x interface 1/3 (“PQL” prototype), and on a datalink dlget interface “1 2” (DALI 1.1 style). The extreme of what probably still makes sense is the core search core that replaces SCS’s RA, DEC, and SR with an entirely different set of parameters perhaps better suited for interactive, browser-based usage. Cores communicate their input interface by defining an input table, which is essentially a sequence of input keys, which in turn essentially work like params: in particular, they have all the standard metadata like units, ucds, etc. Input tables, contrary to what their name might suggest, have no rows. They can hold metadata, though, which is sometimes convenient to pass data between parameter parsers and the core. When a request comes in, the service first determines the renderer responsible. It then requests an inputTable for that renderer from the core. The core, in turn, will map each inputKey in its inputTable through a renderer adaptor as returned from svcs.inputdef.getRendererAdaptor; this inspects the renderer.parameterStyle, which must be taken from the svcs.inputdef._RENDERER_ADAPTORS’ keys (currently form, pql, dali). inputKeys have to have the adaptToRenderer property set to True to have them adapted. Most automatically generated inputKeys have that; where you manually define inputKeys, you would have to set the property manually if you want that behaviour (and know that you want it; outside of table-based cores, it is unikely that you do). Core Args¶ The input table, together with the raw arguments coming from the client, is then used to build a svcs.CoreArgs instance, which in turn takes the set of input keys to build a context grammar. The core args have the underlying input table (with the input keys for the metadata) in the inputTD attribute, the parsed arguments in the dictionary args. For each input key args maps its name to a value; context grammars are case-semisensitive, meaning that case in the HTTP parameter names is in general ignored, but if a parameter name matching case is found, it is preferred. Yes, ugly, but unfortunately the VO has started with case-insensitive parameter names. Sigh. The values in args are a bit tricky: - each raw parameter given must parse with a single inputKey’s parse. For instance, if an inputKey is a real[2], it will be parsed as a float array. - if no raw parameter is given for an input key, its value will be None. - when an inputKey specifies multiplicity=”multiple”, the non-None value in the core args is a list. Each list item is something that came out of the inputKey’s parser (i.e., it could be another list for array-valued parameters). - when an inputKey specifies multiplicity=”single”, the value in the core args is a single value of whatever inputKey parses (or None for missing parameters). This is even true when a parameter has been given multiple times; while currently, the last parameter will win, we don’t guarantee that. - when an inputKey specifies multiplicity=”force-single”, DaCHS works as in the single case, except that multiple specification will lead to an error. - when an inputKey does not specify multiplicity, DaCHS will infer the desired multiplicity from various hints; essentially, enumerated parameters (values/options given in some way) have multiplicity multiple, everything else multiplicity single. It is wise not to rely on this behaviour. These rules are independent of the type of core and hold for pythonCores or whatever just as for the normal, table-based cores. For these (and they are what users are mostly concerned with), special rules and shortcuts apply, though. Table-based cores¶ Conddescs and input keys: Defining the input parameters¶ You will usually deal with cores querying database tables – dbCore, ssapCore, etc. For these, you will not normally define an inputTable, as it is being generated by the software from condDescs. To create simple constraints, just buildFrom the columns queried: <condDesc buildFrom="myColumn"/> (the names are resolved in the core’s queried table). DaCHS will automatically adapt the concrete parameter style is adapted to the renderer – in the web interface, there are vizier-like expressions, in protocol interfaces, you get fields understanding expressions, either as in SSAP (for the pql parameter style) or as defined in DALI (the dali parameter style). This will generate query fields that work against data as stored in the database, with some exceptions (columns containing MJDs will, for example, be turned into VizieR-like date expressions for web forms). Since in HTML forms, astronomers often ask for odd units and then want to input them, too, DaCHS will also honor the displayUnit display hint for forms. for instance, if you wrote: <table id="ex1"> <column name="minDist" unit="deg" displayHint="displayUnit=arcsec"/> ... <dbCore queriedTable="ex1"> <condDesc buildFrom="minDist"/> ... then the form renderer would declare the minDist column to take its values in arcsecs and do the necessary conversions, while minDist would properly work with degrees in SCS or TAP. For object lists and similar, it is frequently desirable to give the possible values (unless there are too many of those; these will be translated to option lists in forms and to metadata items for protocol services and hence be user visible). In this case, you need to change the input key itself. You can do this by deriving the input key from the column and assign it to a condDesc, like this: <condDesc> <inputKey original="source"> <values fromdb="source from plc.data"/> </inputKey> </condDesc> Use the showItems="n" attribute of input keys to determine how many items in the selector are shown at one time. If you want your service to fail if a parameter is not given, declare the condDesc as required: <condDesc buildFrom="myColumn" required="True"/> (you can also declare individual an inputKey as required). If, on the other hand, you want DaCHS to fill in a default if the user provides no value, give a default to the input key using the values child: <condDesc> <inputKey original="radius"> <values default="0.5"/> </inputKey> <condDesc> Sometimes a parameter shouldn’t be defaulted in a protocol request (perhaps to satisfy an external contract), while the web interface should pre-fill a sensible choice. In that case, use the defaultForForm property: <condDesc> <inputKey original="radius"> <property key="defaultForForm">0.5</property> </inputKey> <condDesc> DaCHS will also interpret min and max attributes on the input keys (and the columns they are generated from) to generate input hints; that’s a good way to fight the horror vacui users have when there’s an input box and they have no idea what to put there. The best way to deal with this, however, is to not change the input keys but the columns themselves, as in: <table id="ex1"> <column name="mjd" type="double precision" ...> <values min="" max=""/> ... <dbCore queriesTable="ex1"> <condDesc buildFrom="mjd"/> You will typically leave min and max empty and run: dachs limits q#ex when the table contents change; this will make DaCHS update the values in the RD itself. Phrasemakers: Making custom queries¶ CondDescs will generate SQL adapted to the type of their input keys, which; as you can imagine, for cases like the VizieR expressions, that’s not done in a couple of lines. However, there are times when you need custom behaviour. You can then give your conddescs a phraseMaker, a piece of python code generating a query and adding parameters: <condDesc> <inputKey original="confirmed" multiplicity="single"> <property name="adaptToRenderer">False</property> </inputKey> <phraseMaker> <code> if inPars.get(inputKeys[0].name, False): yield "confirmed IS NOT NULL" </code> </phraseMaker> </condDesc> PhraseMakers work like other code embedded in RDs (and thus may have setup). inPars gives a dictionary of the input parameters as parsed by the inputDD according to multiplicity. inputKeys contains a sequence of the conddesc’s inputKeys. By using their names as above, your code will not break if the parameters are renamed. It is usually a good idea to set the property adaptToRenderer to False in such cases – you generally don’t want DaCHS to use its standard rules for input key adaptation as discussion above because that will typically change what ends up in inPars and hence break your code for some renderers. Note again that parameters not given will have the value None throughout. The will be present in inPars, though, so do not try things like "myName" in inPars – that’s always true. Phrase makers must yield zero or more SQL fragments; multiple SQL fragments are joined in conjunctions (i.e., end up in ANDed conditions in the WHERE clause). If you need to OR your fragments, you’ll have to do that yourself. Use the base.joinOperatorExpr(operator, operands) for robustness to construct ORs. Since you are dealing with raw SQL here, never include material from inPars directly in the query strings you return – this would immediately let people do SQL injections at least when the input key’s type is text or similar. Instead, use the getSQLKey function as in this example: <condDesc> <inputKey original="hdwl" multiplicity="single"/> <phraseMaker> <code> ik = inputKeys[0] destRE = "^%s\\.[0-9]*$"%inPars[ik.name] yield "%s ~ (%%(%s)s)"%(ik.name, base.getSQLKey("destRE", destRE, outPars)) </code> </phraseMaker> </condDesc> getSQLKey takes a suggested name, a value and a dictionary, which within phrase makers always is outPars. It will enter value with the suggested name as key into outPars or change the suggested name if there is a name clash. The generated name will be returned, and that is what is entered in the SQL statement. The outPars dictionary is shared between all conddescs entering into a query. Hence, if you do anything with it except passing it to base.getSQLKey, you’re voiding your entire warranty. Here’s how to define a condDesc doing a full text search in a column: <condDesc> <inputKey original="source" description="Words from the catalog description, e.g., author names or title words."> <property name="adaptToRenderer">False</property> </inputKey> <phraseMaker> <code> yield ("to_tsvector('english', source)" " @@ plainto_tsquery('english', %%(%s)s)")%( base.getSQLKey("source", inPars["source"], outPars)) </code> </phraseMaker> </condDesc> Incidentally, this would go with an index definition like: <index columns="source" method="gin" >to_tsvector('english', source)</index> Grouping Input Keys¶ For special effects, you can group inputKeys. This will make them show up under a common label and in a single line in HTML forms. Other renderers currently don’t do anything with the groups. Here’s an example for a simple range selector: <condDesc> <inputKey name="el" type="text" tablehead="Element"/> <inputKey name="mfmin" tablehead="Min. Mass Fraction \item"> <property name="cssClass">a_min</property> </inputKey> <inputKey name="mfmax" tablehead="Max. Mass Fraction \item"> <property name="cssClass">a_max</property> </inputKey> <group name="mf"> <description>Mass fraction of an element. You may leave out either upper or lower bound.</description> <property name="label">Mass Fraction between...</property> <property name="style">compact</property> </group> </condDesc> You will probably want to style the result of this effort using the service element’s customCSS property, maybe like this: <service...> <property name="customCSS"> input.a_min {width: 5em} input.a_max {width: 5em} input.formkey_min {width: 6em!important} input.formkey_max {width: 6em!important} span.a_min:before { content:" between "; } span.a_max:before { content:" and "; } tr.mflegend td { padding-top: 0.5ex; padding-bottom: 0.5ex; border-bottom: 1px solid black; } </property> </service> See also the entries on multi-line input, selecting input fields with a widget, and customizing generated SCS conditions in DaCHS’ howto document. Output tables¶ When determining what columns to include in a response from a table-based core, DaCHS follows relatively complicated rules because displays in the browser and almost anywhere else are subject to somewhat different constraints. In the following, when wie talk about “VOTable”, we refer to all tabular formats produced by DaCHS (FITS binary, CSV, TSV…). The column selection is influenced by: Verbosity. This is controlled by the VERBparameter (1..3) or preferentially verbosity(1..30). Only columns with verbLevelnot exceeding verbosity (or, if not given, VERB*10) are included in the result set. This, in particular, means that columns with verbLevellarger than 30 are never automatically included in output tables (but they can be manually selected for HTML using _ADDITEM). Output Format. While VOTable takes the core’s output table and apply the verbosity filter, HTML uses the service’s output table as the basis from which to filter columns. On the other hand, in HTML output the core output table is used to create the list of potential additional columns. votableRespectsOutputTable. This is a property on services that makes DaCHS use the service’s output table even when generating VOTable output if it is set to True. Write: <property name="votableRespectsOutputTable">True</property> in your service element to enable this behaviour. _ADDITEM. This parameter (used by DaCHS’ web interface) lets users select columns not selected by the current settings or the service’s output table. _ADDITEMis ignored in VOTable unless in HTML mode (which is used in transferring web results via SAMP). noxml. Columns can be furnished with a displayHint="noxml=true", and they will never be included in VOTable output; use this when you use complex formatters to produce HTML displays. _SET. DaCHS supports “column sets”, for instance, to let users select certain kinds of coordinates. See apfs/res/apfs_new.rd` for an example. Essentially, when defining an output table, each output field gets a setsattribute (default: no set; use ALL to have the column included in all outputs). Then, add a _SETservice parameter (use valuesdo declare the avaiable sets). Note that the _SETparameter changes VOTable column selection to votableRespectsOutputTablemode as discussed above. Services that use column sets should therefore set the property manually for consistency whether or not clients actually pass _SET. Sorry for this mess; all this had, and by and large still has, good reasons. Writing Custom Cores¶ While DaCHS provides cores for many common operations – in particular, database queries and wrapped external binaries –, there are of course services that need to do things not covered by what the shipped cores do. A common case is wrapping external binaries. Many such cases still follow the basic premise of services: GET or POST parameters in, something table-like out. You should then use custom cores, which then still let you use normal DaCHS renderers (in particular form and api/ sync). When that doesn’t cut it, you’ll need to use a custom renderer. While a custom core is defined in a separate module – this also helps debugging since you can run it outside of DaCHS –, there’s also the python core that keeps the custom code inside of the RD. This is very similar; Python Cores instead of Custom Cores explains the differences. The following exposition is derived from the times service in the GAVO data center, a service wrapping some FORTRAN code wrapping SOFA (yes, we’re aware that we would directly use SOFA through astropy; that’s not the point here). Check out the sources at; the RD is times.rd. Defining a Custom Core¶ In an RD, a custom core is very typically just written with a reference to a defining module: <customCore module="res/timescore"/> The path is relative to the resdir, and you don’t include the module’s extension (DaCHS uses normal python module resolution, except for temporarily extending the search path with the enclosing directory). You can, in principle, declare the core’s interface in that element, but that’s typically not a good idea (see below). The above declaration means you will find the core itself in res/timescore.py. Ideally, you’ll just use the DaCHS API in the core, since we try fairly hard to keep that api constant. The timescore doesn’t quite follow that rule because it wants to expand VizieR expressions, which normal services probably won’t do. DaCHS expects the custom core under the name Core. Thus, the centerpiece of the module is: from gavo import api class Core(api.Core): The core needs an InputTable and an OutputTable like all cores. You could define it in the resource descriptor like this: <customCore id="createCore" module="bin/create"> <inputTable> <inputKey .../> </inputTable> <outputTable> <column name="itemsAdded" type="integer" tablehead="Items added"/> </outputTable> </customCore> It’s preferable to define at least the input in the code, though, since it’s more likely to be kept in sync with the code in that case. Embedding the definitions is done using the class attribute inputTableXML: class Core(core.Core): <inputKey name="interval" type="integer" multiplicity="single" tablehead="Interval" unit="s" ucd="time.interval" description="Interval between two sets of computed values" >3600</inputKey> </inputTable> """ There is also outputTableXML, which you should use if you were to compute stuff in some lines of Python, since then the fields are directly defined by the core core itself. However, the case of timescore is fairly typical: There is some, essentially external, resource that produces something that needs to be parsed. In that case, it’s a better idea to define the parsing logic in a normal RD data item. Its table then is the output table of the core. In the times example, the output of timescompute is described by the build_result data item in times.rd: <table id="times"> <column name="ut1" type="timestamp" tablehead="UT1" ucd="time.epoch;meta.main" verbLevel="1" description="Time and date (UT1)" displayHint="type=humanDate"/> <column name="gmst" type="time" tablehead="GMST" verbLevel="1" description="Greenwich mean sidereal time" xtype="adql:TIMESTAMP" displayHint="type=humanTime,sf=4"/> <column name="gast" type="time" tablehead="GAST" verbLevel="1" description="Greenwich apparent sidereal time" xtype="adql:TIMESTAMP" displayHint="type=humanTime,sf=4"/> <column name="era" type="double precision" tablehead="ERA" verbLevel="1" description="Earth rotation angle" displayHint="type=dms,sf=3" unit="deg"/> </table> <data id="build_result" auto="False"> <reGrammar> <names>ut1,gmst,gast,era</names> </reGrammar> <make table="times"> <rowmaker> <map dest="gmst">parseWithNull(@gmst, parseTime, "None")</map> ... </rowmaker> </make> </data> So, the core needs to say “my output table has the structure of #times”. As usual with DaCHS structures, you should not override the constructor, as it is defined by a metaclass. Instead, Cores call, immediately after the XML parse (technically, as the first thing of their completeElement method), a method called initialize. This is where you should set the output table. For the times core, this looks like this: def initialize(self): self.outputTable = api.OutputTableDef.fromTableDef( self.rd.getById("times"), None) Of course, you are not limited to setting the output table there; as initialize is only called once while parsing, this is also a good place to perform expensive, one-time operations like reading and parsing larger external resources. Giving the Core Functionality¶ To have the core do something, you have to override the run method, which has to have the following signature: run(service, inputTable, queryMeta) -> stuff The stuff returned will ususally be a Table or Data instance (that need not match the outputTable definition – the latter is targetted at the registry and possibly applications like output field selection). The standard renderers also accept a pair of mime type and a string containing some data and will deliver this as-is. With custom renderers, you could return basically anything you want. Services come up with some idea of the schema of the table they want to return and adapt tables coming out of the core to this. Sometimes, you want to suppress this behaviour, e.g., because the service’s ideas are off. In that case, set a noPostprocess atttribute on the table to any value (the TAP core does this, for instance). In service you get the service using the core; this may make a difference since different services can use the same core and could control details of its operations through properties, their output table, or anything else. The inputTable argument is the CoreArgs instance discussed in Core Args. Essentially, you’ll usually use its args attribute, a dictionary mapping the keys defined by your input table to values or lists of them. The queryMeta argument is discussed in Database Options. In the times example, the parameter interpretation is done in an extra function (which helps testability when there’s a bit more complex things going on): def computeDates(args): """yields datetimes at which to compute times from the ut1/interval inputs in coreArgs args. """ interval = args["interval"] or 3600 if args["ut1"] is None: yield datetime.datetime.utcnow() return try: expr = vizierexprs.parseDateExpr(args["ut1"]) if expr.operator in set([',', '=']): for c in expr.children: yield c elif expr.operator=='..': for c in expandDates(expr.children[0], expr.children[1], interval): yield c elif expr.operator=="+/-": d0, wiggle = expr.children[0], datetime.timedelta( expr.expr.children[1]) for c in expandDates(d0-wiggle, d0+wiggle): yield c else: raise api.ValidationError("This sort of date expression" " does not make sense for this service", colName="ut1") except base.ParseException, msg: raise api.ValidationError( "Invalid date expression (at %s)."%msg.loc, colName="ut1") While the details of the parameter parsing and expansion don’t really matter, note now exceptions are mapped to a ValidationError and give a colName – this lets the form renderer display error messages next to the inputs that caused the failure. The next thing timescore does is build some input, which in this case is fairly trivial: input = "\n".join(utils.formatISODT(date) for date in dates)+"\n" If your input is more complex or you need input files or similar, you want to be a bit more careful. In particular, do not change directory (or, equivalently, use the utils.sandbox context manager); this may confuse the server, and in particular will break the first time two requests are served simultaneously: The core runs within the main process, and that can only have one current directory. Instead, in such situations, make a temporary directory and manually place your inputs in there. The spacecore () shows how this could look like, including tearing the stuff down safely when done (the runSpace function). For the timescore, that is not necessary; you just run the wrapped program using standard subprocess functionality: computer = service.rd.getAbsPath("bin/timescompute") pipe = subprocess.Popen([computer], stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True, cwd=os.path.dirname(computer)) data, errmsg = pipe.communicate(input) if pipe.returncode: raise api.ValidationError("The backend computing program failed" " (exit code %s). Messages may be available as" " hints."%pipe.returncode, "ut1", hint=errmsg) Note that with today’s computers, you shouldn’t need to worry about streaming input or output until they are in the dozens of megabytes (in which case you should probably think hard about a custom UWS and keep the files in the job’s working directories). To turn the program’s output into a table, you use the data item defined in the RD: return api.makeData( self.rd.getById("build_result"), forceSource=StringIO(data)) When the core defines the data itself, you would skip makeData. Just directly produce the rowdicts and make the output table directly from the rows: rows = [{"foo": 3*i, "bar": 8*i} for i in range(30)] return rsc.TableForDef(self.outputTable, rows=rows) Database Options¶ The standard DB cores receive a “table widget” on form generation, including sort and limit options. To make the Form renderer output this for your core as well, define a method wantsTableWidget() and return True from it. The queryMeta that your run method receives has a dbLimit key. It contains the user selection or, as a fallback, the global db/defaultLimit value. These values are integers. So, if you order a table widget, you should do something like: cursor.execute("SELECT .... LIMIT %(queryLimit)s", {"queryLimit": queryMeta["dbLimit"],...}) In general, you should warn people if the query limit was reached; a simple way to do that is: if len(res)==queryLimit: res.addMeta("_warning", "The query limit was reached. Increase it" " to retrieve more matches. Note that unsorted truncated queries" " are not reproducible (i.e., might return a different result set" " at a later time).") where res would be your result table. _warning metadata is displayed in both HTML and VOTable output, though of course VOTable tools will not usually display it. Python Cores instead of Custom Cores¶ If you only have a couple of lines of python, you don’t have to have a separate module. Instead, use a python core. In it, you essentially have the run method as discussed in Giving the Core Functionality in a standard procApp. The advantage is that interface and implementation is nicely bundled together. The following example should illustrate the use of such python cores; note that rsc already is in the procApp’s namespace: <pythonCore> <inputTable> <inputKey name="opre" description="Operand, real part" required="True"/> <inputKey name="opim" description="Operand, imaginary part" required="True"/> <inputKey name="powers" description="Powers to compute" type="integer" multiplicity="multiple"/> </inputTable> <outputTable> <outputField name="re" description="Result, real part"/> <outputField name="im" description="Result, imaginary part"/> <outputField name="log" description="real part of logarithm of result"/> </outputTable> <coreProc> <setup> <code> import cmath </code> </setup> <code> powers = inputTable.args["powers"] if not powers: powers = [1,2] op = complex(inputTable.args["opre"], inputTable.args["opim"]) rows = [] for p in powers: val = op**p rows.append({ "re": val.real, "im": val.imag, "log": cmath.log(val).real}) return rsc.TableForDef(self.outputTable, rows=rows) </code> </coreProc> </pythonCore> As an additional service, DaCHS executes your python cores in a sandbox directory, so you can create temporary files to your heart’s delight; they will be torn down once the core is finished. Regression Testing¶ Introduction¶ Things break – perhaps because someone foolishly dropped a database table, because something happened in your upstream, because you changed something or even because we changed the API (if that’s not mentioned in Changes, we owe you a beverage of your choice). Given that, having regression tests that you can easily run will really help your peace of mind. Therefore, DaCHS contains a framework for embedding regression tests in resource descriptors. Before we tell you how these work, some words of advice, as writing useful regression tests is an art as much as engineering. Don’t overdo it. There’s little point in checking all kinds of functionality that only uses DaCHS code – we’re running our tests before committing into the repository, and of course before making a release. If the services just use condDescs with buildFrom and one of the standard renderers, there’s little point in testing beyond a request that tells you the database table is still there and contains something resembling the data that should be there. Don’t be over-confident. Just because it seems trivial doesn’t mean it cannot fail. Whatever code there is in the service processing of your RD, be it phrase makers, output field formatters, custom render or data functions, not to mention custom renderers and cores, deserves regression testing. Be specific. In choosing the queries you test against, try to find something that won’t change when data is added to your service, when you add input keys or when doing similar maintenance-like this. Change will happen, and it’s annoying to have to fix the regression test every time the output might legitimately change. This helps with the next point. Be pedantic. Do not accept failing regression tests, even if you think you know why they’re failing. The real trick with useful testing is to keep “normal” output minimal. If you have to “manually” ignore diagnostics, you’re doing it wrong. Also, sometimes tests may fail “just once”. That’s usually a sign of a race condition, and you should really try to figure out what’s going on. Make it fail first. It’s surprisingly easy to write no-op tests that run but won’t fail when the assertion you think you’re making is no longer true. So, when developing a test, assert something wrong first, make sure there’s some diagnostics, and only then assert what you really expect. Be terse. While in unit tests it’s good to test for maximally specific properties so failing unit tests lead you on the right track as fast as possible, in regression tests there’s nothing wrong with plastering a number of assertions into one test. Regression tests actually make requests to a web server, and these are comparatively expensive. The important thing here is that regression testing is fast enough to let you run them every time you make a change. Writing Regression Tests¶ DaCHS’ regression testing framework is organized a bit along the lines of python’s unittest and its predecessors, with some differences due to the different scope. So, tests are grouped into suites, where each suite is contained in a regSuite element. These have a (currently unused) title and a boolean attribute sequential intended for when the tests contained must be executed in the sequence specified and not in parallel. It defaults to false, which means the requests are made in random order and in parallel, which speeds up the test runs and, in particular, will help uncover race conditions. On the other hand, if you’re testing some sort of interaction across requests (e.g., make an upload, see if it’s there, remove it again), this wouldn’t work, and you must set sequential=”True”. Keep these sequential suites as short as possible. In tests within such suites (and only there), you can pass information from one test to the following one by adding attributes to self.followUp (which are available as attributes of self in the next test). If you need to manipulate the next URL, it’s at self.followUp.url.content_. For the common case of a redirect to the url in the location header (or a child thereof), there’s the pointNextToLocation(child="") method of regression tests. In the tests that are manipulated like this, the URL given in the RD should conventionally be overridden in the previous test. Of course, additional parameters, httpMethods, etc, are still applied in the manipulated url element. Regression suites contain tests, represented in regTest elements. These are procDefs (just like, e.g., rowmakery apply), so you can have setup code, and you could have a library of parametrizable regTests procDefs that you’d then turn into regTests by setting their parameters. We’ve not found that terribly useful so far, though. You must given them a title, which is used when reporting problems with them. Otherwise, the crucial children of these are url and, as always with procDefs, code. Here are some hints on development: - Give the test you’re just developing an id; at the GAVO DC, we’re usually using cur; that way, we run variations of gavo test rdId#cur, and only the test in question is run. - After defining the url, just put an assert Falseinto the test code. Then run gavo test -Devidence.xml rdId#curor similar. Then investigate evidence.xml(possibly after piping through xmlstarlet fo) for stable and strong indicators that things are working. - If you get a BadCode for a test you’re just writing, the message may not always be terribly helpful. To see what’s actually bugging python, run gavo --debug test ...and check dcInfos. RegTest URLs¶ The url element encapsulates all aspects of building the request. In the simplest case, you just can have a simple URL, in which case it works as an attribute, like this: <regTest title="example" url="svc/form"> ... URLs without a scheme and a leading slash are interpreted relative to the RD’s root URL, so you’d usually just give the service id and the renderer to be applied. You can also specify root-relative and fully specified URLs as described in the documentation of the url element. White space in URLs is removed, which lets you break long URLs as convenient. You could have GET parameters in this URL, but that’s inconvient due to both XML and HTTP escaping. So, if you want to pass parameters, just give them as attributes to the element: <regTest title="example"> <url RA="10" DEC="-42.3" SR="1" parSet="form">svc/form</url> The parSet=form here sets up things such that processing for the form renderer is performed – our form library nevow formal has some hidden parameters that you don’t want to repeat in every URL. To easily translate URLs taken from a browser’s address bar or the form renderer’s result link, you can run gavo totesturl and paste the URLs there. Note that totesturl fails for values with embedded quotes, takes only the first value of repeated parameters and is a over-quick hack all around. Patches are gratefully accepted. The url element hence accepts arbitary attributes, which can be a trap if you think you’ve given values to url’s private attributes and mistyped their names. If uploads or authentication don’t seem to happen, check if your attribute ended up the in the URL (which is displayed with the failure message) and fix the attribute name; most private url attributes start with http. If you really need to pass a parameter named like one of url’s private attributes, pass it in the URL if you can. If you can’t because you’re posting, spank us. After that, we’ll work out something not too abominable . If you have services requiring authentication, use url’s httpAuthKey attribute. We’ve introduced this to avoid having credentials in the RD, which, after all, should reside in a version control system which may be (and in the case of GAVO’s data center is) public. The attribute’s value is a key into the file ~/.gavo/test.creds, which contains, line by line, this key, a username and a password, e.g.: svc1 testuser notASecret svc2 regtest NotASecretEither A test using this would look like this: <regTest title="Authenticated user can see the light"> <url httpAuthKey="svc1">svc1/qp/light.txt</url> <code> self.assertHTTPStatus(200) </code> </regTest> By default, a test will perform a GET request. To change this, set the httpMethod attribute. That’s particularly important with uploads (which must be POSTed). For uploads, the url element offers two facilities. You can set a request payload from a file using the postPayload attribute (the path is interpreted relative to the resource directory), but it’s much more common to do a file upload like browsers do them. Use the httpUpload element for this, as in: <url> <httpUpload name="UPLOAD" fileName="remote.txt">a,b,c</httpUpload> svc1/async </url> (which will work as if the user had selected a file remote.txt containing “a,b,c” in a browser with a file element named UPLOAD), or as in: <url> <httpUpload name="UPLOAD" fileName="remote.vot" source="res/sample.regtest"/> svc1/async </url> (which will upload the file referenced in source, giving the remote server the filename remote.vot). The fileName attribute is optional. Finally, you can pass arbitrary HTTP headers using the httpHeader element. This has an attribute key; the header’s value is taken from the element content, like this: <url postPayload="res/testData.regtest" httpMethod="POST"> <httpHeader key="content-type">image/jpeg</httpHeader> >upload/custom</url> RegTest Tests¶ Since regression tests are just procDefs, the actual assertions are contained in the code child of the regTest. The code in there sees the test itself in self, and it can access self.data (the response content), self.headers (a sequence of header name, value pairs; note that you should match the names case-insensitively here), and self.status (the HTTP response code), as well as the URL actually retrieved in self.url.httpURL (incidentally, that name is right; the regression framework only supports http, and it’s not terribly likely that we’ll change that). You should probably only access those attributes in a pinch and instead use the pre-defined assertions, which are methods on the test objects as in pyunit – conventional assertions are clearer to read and less likely to break if fixes to the regression test API become necessary. If you still want to have custom tests, raise AssertionErrors to indicate a failure. Here’s a list of assertion methods defined right now: All of these are methods, so you would actually write self.assertHasStrings('a', 'b', 'c') in your test code (rather than pass self explicitly). When writing tests, you can, in addition, use assertions from python’s unittest TestCases (e.g., assertEqual and friends). This is provided in particular for use to check values in VOTables coming back from services together with the getFirstVOTableRow method. Also please note that, like all procDef’s bodies, the test code is macro-expanded by DaCHS. This means that every backslash that should be seen by python needs to be escaped itself (i.e., doubled). An escaped backslash in python thus is four backslashes in the RD. Finally, here’s a piece of .vimrc that inserts a regTest skeleton if you type ge in command mode (preferably at the start of a line; you may need to fix the indentation if you’re not indenting with tabs. We’ve thrown in a column skeleton on gn as well: augroup rd au! autocmd BufRead,BufNewFile *.rd set ts=2 tw=79 au BufNewFile,BufRead *.rd map gn i<tab><tab><lt>column<CR><ESC>5kf"a au BufNewFile,BufRead *.rd map ge i<tab><tab><lt>regTest<CR><tab><lt>url><lt>/url><CR><lt>code><CR><lt>/code><CR><BS><lt>/regTest><ESC>4k augroup END Running Tests¶ The first mode to run the regression tests is through gavo val. If you give it a -t flag, it will collect regression tests from all the RDs it touches and run them. It will then output a brief report listing the RDs that had failed tests for closer inspection. It is recommended to run something like: gavo val -tv ALL before committing changes into your inputs repository. That way, regressions should be caught. The tests are ran against the server described through the [web]serverURL config item. In the recommended setup, this would be a server started on your own development machine, which then would actually test the changes you made. There is also a dedicated gavo sub-command test for executing the tests. This is what you should be using for developing tests or investigating failures flagged with gavo val. On its command line, you can give on of an RD id or a cross-rd reference to a test suite, or a cross-rd reference to an individual test. For example, gavo test res1/q gavo test res2/q#suite1 gavo test res2/q#test45 would run all the tests given in the RD res1/q, the tests in the regSuite with the id suite1 in res2/q, and a test with id="test45 in res2/q, respectively. To traverse inputs and run tests from all RDs found there, as well as tests from the built-in RDs, run: gavo test ALL gavo test by default has a very terse output. To see which tests are failing and what they gave as reasons, run it with the ‘-v’ option. To debug failing regression tests (or maybe to come up with good things to test for), use ‘-d’, which dumps the server response of failing tests to stdout. In the recommended setup with a production server and a development machine sharing a checkout of the same inputs, you can exercise production server from the development machine by giving the -u option with what your production server has in its [web]serverURL configuration item. So, gavo test -u ALL is what might help your night’s sleep. Examples¶ Here are some examples how these constructs can be used. First, a simple test for string presence (which is often preferred even when checking XML, as it’s less likely to break on schema changes; these usually count as noise in regression testing). Also note how we have escaped embedded XML fragments; an alternative to this shown below is making the code a CDATA section: <regTest title="Info page looks ok" url="siap/info"> <code> self.assertHasStrings("SIAP Query", "siap.xml", "form", "Other services", "SIZE</td>", "Verb. Level") </code> </regTest> The next is a test with a “rooted” URL that’s spanning lines, has embedded parameters (not recommended), plus an assertion on binary data: <regTest title="NV Maidanak product delivery" url="/getproduct/maidanak/data/Q2237p0305/Johnson_R/ red_kk050001.fits.gz?siap=true"> <code> self.assertHasStrings('\\x1f\\x8b\\x08\\x08') </code> </regTest> This is how parameters should be passed into the request: <regTest title="NV Maidanak SIAP returns accref."> <url POS="340.12,3.3586" SIZE="0.1" INTERSECT="OVERLAPS" _TDENC="True" _DBOPTIONS_LIMIT="10">siap/siap.xml</url> <code> self.assertHasStrings('<TD>AZT 22') </code> </regTest> Here’s an example for a test with URL parameters and xpath assertions: <regTest title="NV Maidanak SIAP metadata query" url="siap/siap.xml?FORMAT=METADATA"> <code> self.assertXpath("//v1:FIELD[@name='wcs_cdmatrix']", { "datatype": "double", "ucd": "VOX:WCS_CDMatrix", "arraysize": "*", "unit": "deg/pix"}) self.assertXpath("//v1:INFO[@name='QUERY_STATUS']", { "value": "OK", None: "OK",}) self.assertXpath("//v1:PARAM[@name='INPUT:POS']", { "datatype": "char", "ucd": "pos.eq", "unit": "deg"}) </code> </regTest> The following is a fairly complex example for a stateful suite doing inline uploads (and simple tests): <regSuite title="GAVO roster publication cycle" sequential="True"> <regTest title="Complete record> <nullCore id="null"/> <service id="run" core="null" allowed="external"> <meta name="shortName">u</meta> <publish render="external" sets="gavo"> <meta name="accessURL"></meta> </publish></service></resource> ]]></httpUpload>upload/form</url> <code><![CDATA[ self.assertHasStrings("#Published</th><td>1</td>") ]]></code> </regTest> <regTest title="Publication leaves traces on GAVO list" url="list/custom"> <code> self.assertHasStrings( '"/gvo/data/testing_ignore/run/external">A test service') </code> </regTest> <regTest title="Unpublication> <service id="run" allowed="external"> <nullCore/> <meta name="shortName">u</meta></service></resource> ]]></httpUpload>upload/form</url> <code><![CDATA[ self.assertHasStrings("#Published</th><td>0</td>") ]]></code> </regTest> <regTest title="Unpublication leaves traces on GAVO list" url="list/custom"> <code> self.assertLacksStrings( '"/gvo/data/testing_ignore/run/external">A test service') </code> </regTest> </regSuite> If you still run SOAP services, here’s one way to test them: <regTest id="soaptest" title="APFS SOAP returns something reasonable"> <url postPayload="res/soapRequest.regtest" httpMethod="POST"> <httpHeader key="SOAPAction">'"useService"'</httpHeader> <httpHeader key="content-type">text/xml</httpHeader >qall/soap/go</url> <code> self.assertHasStrings( '="xsd:date">2008-02-03Z</tns:isodate>', '<tns:raCio xsi:25.35') </code> </regTest> – here, res/soapRequest.regtest would contain the request body that you could, for example, extract from a tcpdump log. Datalink and SODA¶ [Datalink] is an IVOA protocol that allows associating various products and artifacts with a data set id. Think the association of error or mask maps, progenitor datasets, or processed data products, with a data set. It also lets you associate data processing services with datasets, which allows on-the-fly generation of cutouts, format conversions or recalibrations; a particular set of parameters for working with certain kinds of cubes is described in a standard called [SODA] (Serverside Operations for Data Access). Hence, we sometimes call the processing part of datalink SODA. In DaCHS, Datalink is implemented by the dlmeta renderer, SODA by the dlget renderer. In all but fairly exotic cases, both renderers are used on the same service. While in DaCHS, you cannot use SODA without Datalink, there are perfectly sensible datalink services without SODA. In the following, we first treat the generation of “normal” datalinks and discuss processing services later. A central term for datalink is the pubDID, or publisher DID. This is an identifier assigned (essentially) by you that points to a concrete dataset. In DaCHS, datalink services always use pubDIDs as the values of the datalink ID parameter. Unless you arrange things differently (for which you should have good reasons), the pubDIDs used by DaCHS are formed as: <authority>/~?<accref> where the accref usually is the inputsDir-relative path to the file. If you use datalinks of that form, you should at some point run gavo pub //products; this will register the products deliverer as <authority>/~, which means that pubDIDs of this form are compliant with [IVOA Identifiers]_ When developing datalink services, it sometimes is useful to access datalink services directly, in particular because they don’t usually have a useful web interface. Armed with the knowledge about the structure of DaCHS standard PubDIDs, you can easily build the URLs and parameters. For instance, to retrieve the datalink document for mlqso/data/FBQ0951_data.fits on the server dc.g-vo.org using the datalink renderer on the mlqso/q/d service, you’d write: curl -FID=ivo://org.gavo.dc/~?mlqso/data/slits/FBQ0951_data.fits \ | xmlstarlet fo (of course, xmlstarlet isn’t actually necessary, and you can use wget if you want, but you get the idea). Going on, you could pull out what parameters are mentioned somewhat like this: curl -s -FID=ivo://org.gavo.dc/~?mlqso/data/slits/FBQ0951_data.fits \ | \ xmlstarlet sel -N v= -T \ -t -m "//v:PARAM" -v "@name" -nl In the remainder of this section, we first discuss the generation of datalinks and processing services “by example”, which should do for a basic use of the facilities. We continue with a somewhat more in-depth look at the processing of a SODA request, after which we look more closely at the various elements that make up Datalink/SODA services. Integrating Datalink Services¶ You generally declare datalink services on the table(s) that contain the identifiers the datalink service accepts. For that, you include two pieces of metadata: The identifier of the datalink service (which can be a cross-RD id with a hash; use the _associatedDatalinkSvc.serviceId meta key) and the column name within the table (use the _associatedDatalinkSvc.idColumn meta key). Both items will only be checked at run time, and broken links will be reported as warnings. If the following doesn’t give you the datalink resources in results involving the tables, be sure to check the dcInfos log file. The following example is a table that contains two sorts of identifiers that are understood by two different datalink services; one, dlsvc within the same RD, works on values in the accref column, the other, taken from a (hypothetical) doires/q RD, would work on the doi column: <table id="datasets" onDisk="True"> <meta name="_associatedDatalinkSvc"> <meta name="serviceId">dlsvc</meta> <meta name="idColumn">accref</meta> </meta> <meta name="_associatedDatalinkSvc"> <meta name="serviceId">doires/q#doidl</meta> <meta name="idColumn">doi</meta> </meta> <column name="accref" type="text".../> <column name="doi" type="text".../> </table> <service id="dlsvc" allowed="dlmeta,deget"> <meta name="dlget.description">A service for slicing and dicing.</meta> ... </service> Note that forward references, which are generally not allowed in DaCHS, are possible in serviceId and idColumn. An older way to associate datalink services with tables is to give certain services (most notably, SSA ones) a datalink property. This is deprecated now. If you see it in examples, please tell us so we can fix it. Making Datalinks¶ A dataset frequently has associated data, like error or weight maps, derived data, or pieces of provenance. Datalink lets you tie these together algorithmically, using a specialised core (see `element DatalinkCore`_) and `the dlmeta renderer`_. To produce datalinks, the datalink core must be furnished with - exactly one descriptor generator (you can let DaCHS fall back to a default), - one or more meta makers, generating related links. Here is an example, adapted from boydende/q.rd: <datalinkCore> <descriptorGenerator procDef="//soda#fits_genDesc"/> <metaMaker> <code> svc = rd.getById("dl") basename = descriptor.accref.split("/")[-1].split(".")[0] envPath = "data/static/envelopes/{0}.jpg".format(basename) yield descriptor.makeLinkFromFile( envPath, description="Scan of the plate envelope", semantics="#isMetadataFor") </code> </metaMaker> </datalinkCore> A descriptor generator – in the example, one that has additional functionality for FITS files, although the default (`//soda#fromStandardPubDID`_) would work here, too – is passed the pubDID and returns an instance of datalink.ProductDescriptor (or a derived class). If a descriptor generator returns None, the datalink request will be rejected with a 404. Whatever is returned by the descriptor generator is then available as descriptor to the remaining datalink procs (in this case, the meta makers). The columns of the product table (see `dc.products`_) are available as attributes of this object. In addition, subclasses of data.ProductDescriptor may add more attributes; the fits_genDesc used in the example, for instance, provides a hdr attribute containing the primary header as given by pyfits. The descriptor is then passed, in turn, to all meta makers given. These must yield LinkDef instances that describe additional data products; a single meta maker may yield zero or more of these. An example where multiple LinkDef instances are yielded from a single metaMaker can be found in the dl service of cars/q. When the links, as is quite common, correspond to simple files, the easiest way to generate them is through the descriptor’s makeLinkFromFile method, that takes the source path, a description, and semantics (which should be taken from a controlled vocabulary at). File size and media type type, which otherwise should be given when constructing a LinkDef, then default to what’s inferrable from the file (name). makeLinkFromFile will create NotFoundFault error links if the file does not exist, thus alerting the user (and possibly you) that an expected file was not there. When missing files are expectable and should not cause diagnostics, pass a suppressMissing=True to makeLinkFromFile. Another recommended pattern is used in the example: the datalink service itself is used to deliver the static, non-product files. This is effected by declaring the service embedding the core somewhat like this: <service id="dl" allowed="dlget,dlmeta,static"> <property name="staticData">data/static</property> <datalinkCore .../> </service> Note that, of course, exposing directory via the static renderer like this bypasses any access restrictions (e.g., embargos) on the respective data. So, do not expose you primary data in this way if you want to enforce access control. A LinkDef for the product itself (semantics #this) and, if defined in the product table, a preview (semantics #preview) is automatically added by DaCHS unless a suppressAutoLinks attribute is set on the descriptor (you can set that in a meta maker or the descriptor generator). For more information on the elements used here, see below. Embedded Datalink Descriptors¶ For certain renderers (currently, only ssap.xml, but we might do it for SIAP, too), DaCHS will add a direct SODA block if there’s an _associatedDatalinkService meta on the table it serves from and that datalink service has a dlget capability. Here’s how the datalink declarations could look like in such a case: <RESOURCE name="links" type="meta" utype="adhoc:service"> <DESCRIPTION>...</DESCRIPTION> <GROUP name="inputParams"> <PARAM arraysize="*" datatype="char" name="ID" ref="ssa_pubDID" ucd="meta.id;meta.main" value=""/> </GROUP> <PARAM arraysize="*" datatype="char" name="standardID" value="ivo://ivoa.net/std/DataLink#links-1.0"/> <PARAM arraysize="*" datatype="char" name="accessURL" value=""/> </RESOURCE> <RESOURCE ID="proc_svc" name="proc_svc" type="meta" utype="adhoc:service"> <DESCRIPTION>...</DESCRIPTION> <GROUP name="inputParams"> <PARAM arraysize="*" datatype="char" name="ID" ref="ssa_pubDID" ucd="meta.id;meta.main" value=""> <DESCRIPTION>The pubisher DID of the dataset of interest</DESCRIPTION> </PARAM> <PARAM arraysize="*" datatype="char" name="BANDPASS" value=""> <DESCRIPTION>Gaia bandpass to generate the time series for.</DESCRIPTION> <VALUES> <OPTION name="G" value="G"/> <OPTION name="BP" value="BP"/> <OPTION name="RP" value="RP"/> </VALUES> </PARAM> </GROUP> <PARAM arraysize="*" datatype="char" name="accessURL" ucd="meta.ref.url" value=""/> <PARAM arraysize="*" datatype="char" name="standardID" value="ivo://ivoa.net/std/SODA#sync-1.0"/> </RESOURCE> – the first block declares where to obtain full datalink documents by publisher DID from. The second block lets clients take a shortcut and call a processing service directly, without first retrieving the datalink document; it is essentially an anonymised version of the processing declaration fromt the datalink block. To generate these, DaCHS also calls the dlmeta procs, but with pubDID set to None. Whenever you need a concrete pubDID in a dlmeta proc used with SSA, you should therefore add something like: if descriptor.pubDID is None: return Also note that in these cases, a special descriptor type is being used rather than whatever you put into your descriptor generator, and hence you can’t use any special attributes you defined there. On the other hand, you’ll have a limits attribute with a dictionary giving ranges of values within the concrete (SSA) result. This should be used to build Values objects tailored to the specific result. All this is admittedly painful; the shortcut SODA blocks that cause all that pain can probably count as a classic case of premature optimisation. Defining Processing Services¶ In DaCHS data processing services (“SODA services”) use the same datalink cores as the datalink services, and they share the same descriptor. A datalink core does data processing when used by `the dlget renderer`_. To enable data processing, datalink cores additionally need data functions (see `element dataFunction`_) and up to one data formatter (see `element dataFormatter`_). The first data function must add a data attribute to the descriptor and thus plays a somewhat special role. Processing services also use meta makers, but instead of links, these yield parameter definitions in the form of InputKeys (they are used by the datalink services, too, because the datalink documents contain the metadata of the processing services). So, typically, a given piece of SODA functionality comes as a pair of a meta maker and a data function, which then normally are combined in a STREAM (cf. Datalink-related Streams). Processing services usually are a good deal more stereotypical than metadata generation; it is actually beneficial if different services have identical behaviour to facilitate the creation of interoperable clients. SODA itself essentially enumerates what in DaCHS are pre-defined meta makers and data functions. So, most of the time data processing will just re-use STREAMs and procDefs from the //soda RD. The two most common cases are cutouts over FITS cubes and over spectra. Processing services are referenced from the links table. In DaCHS, the description column for the services is empty by default, which you may want to change. Just set a dlget.description meta on the service. In the following example, there is a normal VOResource description that will end up in the Registry and the DaCHS web interface, and a description of the processing service: <service id="dl" allowed="dlmeta,dlget"> <meta name="description">A datalink service for the COOL data collection, giving provenance links, extracted sources, and cutouts</meta> <meta name="dlget.description">Use this interactive service to do cutouts, retrieved scaled images, and choose between FITS and JPEG results.</meta> ... FITS/SODA processing¶ In the first case, the core would like this piece extracted from the dl service in califa/q3: <datalinkCore> <descriptorGenerator procDef="//soda#fits_genDesc" name="genFITSDesc"> <bind key="accrefPrefix">'califa/datadr3'</bind> <bind key="descClass">DLFITSProductDescriptor</bind> </descriptorGenerator> <FEED source="//soda#fits_standardDLFuncs" spectralAxis="3"/> </datalinkCore> Here, we use the `//soda#fits_genDesc`_ descriptor generator with a DLFITSProductDescriptor because CALIFA DR3 stores datalink URLs rather than actual file paths in the product table. You would leave the descClass parameter out when your products are the FITS files themselves. Giving an accrefPrefix to anything using the product table to get accrefs (`//soda#fromStandardPubDID`_ is another example for these) usually is a good idea. If you don’t give it, users can apply the datalink service to any dataset you publish, which might lead to information leaks and hard-to-understand error messages on the user side. accrefPrefix is simply a string that the accref of the product being processed must match. Since in the usual setup, the accref is the inputsDir-relative path of the file, you’re usually fine if you just give the path to the directory containing the products in question. The `//soda#fits_standardDLFuncs`_ STREAM arrange for all general FITS processing functions to be pulled in; these encompass the SODA parameters where applicable (at the time of this writing, there is no support for TIME and POL yet, but if you have such data, we’ll be glad to add it), and some additional ones. If you need extended functionality, it is a good idea to start from this STREAM. Copy it from gavo adm dumpDF //soda and hack from there. SDM processing¶ The other very common sort of SODA-like processing is for spectra. A sketch for these from the sdl service in flashheros/q: > Here, the descriptor generator will in general be `//soda#sdm_genDesc`_. It builds a special descriptor that contains the full metadata from an associated SSA row, which is why you need to give the id of the SSA table in the ssaTD parameter. Since pubDIDs will only be resolved within this table, no accrefPrefix is necessary or supported. The first data function for spectra usually will be `//soda#sdm_genData`_. This will read the entire spectrum into memory using a data item, the id of which is given in the builder parameter. This has to build an SDM-compliant spectrum. Some examples of how to do this can be found in cdfspect/q.rd (reading from half-broken FITS files), c8spect/q.rd (which shows how to create spectra that don’t exist on disk as files), pcslg/q.rd (which nicely uses WCSAxis for parsing spectra that come as 1D-array, “IRAF-style”), or theossa/q.rd (which pulls the source files from a remote server and caches it). For more on generating SDM-compliant spectra, see SDM compliant tables. For large spectra, reading the spectrum in its entirety may incur a significant CPU cost. When that becomes a problem for you, you’ll need to write different data functions, perhaps only parsing a header, and implement, e.g., cutouts directly in a subsequent data function. The two next STREAMs pulled in are just combinations of data functions and meta makers, one for optionally re-calibrating the spectrum (right now, only maximum normalisation is supported), the other for providing a SODA-like cutout. Finally, `//soda#sdm_format`_ pulls in a meta maker defining a FORMAT parameter (letting people order several formats including VOTable, FITS binary table, and CSV) and a formatter that interprets it. General Notes on Processing Services¶ This section contains an overview over how data processing services are built and executed. You should read it if you want to write data processing functions; for just using them, don’t bother. When a request for processed data comes in, the descriptor generator is used to make a product descriptor, and the input keys are adapted to the concrete dataset. This means that, contrary to normal DaCHS services, services with a Datalink core have a variable interface; in particular, the interface on the dlmeta renderer (essentially, just ID) is very different from the one on the dlget renderer (ID plus whatever the meta makers produce). The input key so produced are used to build a context grammar that parses the request. If this succeeds, the data descriptor is passed to the initial data function together with the arguments parsed. This must set the data attribute of the descriptor or raise a ValidationError on the ID parameter; leaving data as None results in a 500 server error. Descriptor.data could an rsc.InMemoryTable (e.g., in SDM processing) or a products.Products instance, but as long as the other data functions and the formatter agree on what it is, anything goes. The remaining data functions can change the data in place or potentially replace descriptor.data. When writing code, be aware, though, that a data function should only do something when the corresponding parameter has actually been used. When you change descriptor.data fundamentally, you’ll probably make the lives of further data functions and the formatter a good deal harder. Finally, the data enters the formatter, which actually generates the output, usually returning a pair of mime type and string to be delivered. It is a design descision of the service creator which manipulations are done in the initial data function, which are in later filters, and which perhaps only in the formatter. The advantage of filters is that they are more flexible and can more easily be reused, while doing it things in the data generator itself will usually be more efficient, sometimes much so (e.g., sums being computed within a database rather than in a filter after all the data had to go through the interface of the database). Descriptor Generators¶ Descriptor generators (see `element descriptorGenerator`_) are procedure applications that, roughly, see a pubDID value and are expected to return a datalink.ProductDescriptor instance, or something derived from it. Simple Product Descriptor Generator¶ In the end, this usually boils down to figuring out the value of accref in the product table and using what’s there to construct the descriptor generator. In the simplest case, the pubDID will be in DaCHS’ “standard” format (see the getStandardPubDID rowmaker function or the `macro standardPubDID`_), in which case the default descriptor generator works and you don’t have to specify anything. You could manually insert that default by saying: <descriptorGenerator procDef="//soda#fromStandardPubDID"/> This happens to be DaCHS’ default if no descriptor generator is given, but as said above that is suboptimal as no accrefPrefix constrains what the service will run on. The easiest way to furnish your descriptors with additional information is to grab that code (use gavo adm dumpDF //soda) and just add attributes to the ProductDescriptor generated in this way. The default ProductDescriptor class exposes as attributes all the columns from the products table. See `dc.products`_ for their names and descriptions. Spectrum Product Descriptor Generators¶ A slightly more interesting example is provided by datalink for SSA, where cutouts and similar is generated from spectra. The actual definition is in //soda#sdm_genDesc, but the gist of it is: <procDef type="descriptorGenerator" id="sdm_genDesc"> <setup> <par key="ssaTD" description="Full reference (like path/rdname#id) to the SSA table the spectrum's PubDID can be found in."/> <par key="descriptorClass" description="The SSA descriptor class to use. You'll need to override this if the dc.products path doesn't actually lead to the file (see `custom generators <#custom-product-descriptor-generators>`_)." late="True">ssap.SSADescriptor</par> <code> from gavo import rscdef from gavo import rsc from gavo import svcs from gavo.protocols import ssap ssaTD = base.resolveCrossId(ssaTD, rscdef.TableDef) </code> </setup> <code> with base.getTableConn() as conn: ssaTable = rsc.TableForDef(ssaTD, connection=conn) matchingRows = list(ssaTable.iterQuery(ssaTable.tableDef, "ssa_pubdid=%(pubdid)s", {"pubdid": pubDID})) if not matchingRows: return DatalinkFault.NotFoundFault(pubDID, "No spectrum with this pubDID known here") # the relevant metadata for all rows with the same PubDID should # be identical, and hence we can blindly take the first result. return descriptorClass.fromSSARow(matchingRows[0], ssaTable.getParamDict()) </code> </procDef> Here, we use ssa.SSADescriptor, derived from ProductDescriptor, rather than monkeypatching the extra ssaRow attribute the former provides; being explicit here may help when debugging. As usual, the descriptor generates encodes how to resolve a pubDID to an accref, in this case using an SSA table. If the product table just lists a datalink URL, you will want to override the accessPath this comes up with. See, for instance, pcslg/q for how to do this. Incidentally, in this case you could stuff the entire code into the main code element, saving on the extra setup element. However, apart from a minor speed benefit, keeping things like function or class definitions in setup allows easier re-use of such definitions in procedure applications and is therefore recommended. FITS Product Descriptor Generators¶ For FITS files, you will usually just use `//soda#fits_genDesc`_, defining the accrefStart as discussed in FITS/SODA processing. This will produce datalink.FITSProductDescriptor instances. As in the SSA/SDM case, you may need different descriptor classes in special situations. Since for large FITS files, just delivering datalink files is a fairly compelling proposition, there is actually a predefined descriptor class to use with datalink access paths, DLFITSProductDescriptor; the dl service in califa/q3 shows how to use it. Meta Makers¶ Meta makers (see `element metaMaker`_) contain code that produces pieces of service metadata from a data descriptor. All meta makers belonging to a service are unconditionally executed, and all must be generator bodies (i.e., contain a yield statement). Link Definitions¶ While meta makers see the LinkDef class itself, too, you should normally use the makeLink or makeLinkFromFile methods of the descriptor (they are available if the descriptor class was derived from datalink.ProductDescriptor, as it usually should). These methods take a link or a path as the first argument, respectively. The rest are keyword arguments corresponding to the datalink columns, viz., - description - A human-readable short information on what’s behind the link - semantics - A term from a controlled-vocabulary describing what’s behind the link (see below) - contentType - An (advisory) media type of whatever this link points to. Please make sure it’s consistent with what the server actually returns if the protocol used by accessURL supports that. - contentLength - The (approximate) size of the resource at accessURL, in bytes (not for makeLinkFromFile, which takes it from the file system) makeLinkFromFile additionally allows an argument service (see below). With the exception of semantics, all auxillary data defaults to None if not given, and it’s legal to leave it at that. Semantics must be non-NULL, even if an error message is generated. To make sure that’s true, DaCHS inserts a non-informational URL, which preferentially shouldn’t escape to the user. Hence, please set semantics on LinkDefs, and if possible choose one of the terms given at You can inspect the definition of the datalinks table active in your system by saying gavo admin dumpDF //datalink | less (the table definition is right at the top). When returning link definitions, the tricky part mostly is to come up with the URLs. Use the makeAbsoluteURL rowmaker function to make them from relative URLs; the rest just depends on your URL scheme. An example could look like this: <metaMaker> <code> yield descriptor.makeLink( makeAbsoluteURL("get/"+descriptor.accref[:-5]+".err.fits"), contentType="image/fits", semantics="#error", description="Errors for this dataset") yield descriptor.makeLink( ""+descriptor.accref.split("/")[-1], contentType="image/fits", semantics="#progenitor", description="Un-flatfielded, uncalibrated source data") </code> </metaMaker> Parameter Definitions¶ To define a datalink service’s processing capabilities, meta makers yield input keys ( InputKey instances). The classes usually required to build input keys return (InputKey, Values, Option) are available to the code as local names. As usual, DaCHS structs should not be constructed directly but only using the MS helper (which is really an alias for base.makeStruct; it takes care that the special postprocessing of DaCHS structures takes place). You should make sure that the input keys have proper annotation as regards minima, maxima, or enumerated values; clients, in general, have to way to guess what is sensible here. The limits can usually be obtained from the descriptor (which, again, is available as descriptor in the meta maker. For instance, the FITS descriptor has a header attribute describing the instance that the core operates on, the SSA descriptor an attribute ssaROW. A meta maker that generates an extra cutout parameter for radio astronomers (note that this is of course a bad idea – unit adaption should be done on the client side) could be: <metaMaker> <setup> <code> from gavo.utils import unitconv </code> </setup> <code> yield MS(InputKey, name="FREQ", unit="MHz", ucd="em.freq", description="Spectral cutout interval", type="double precision[2]" xtype="interval" multiplicity="forced-single" values=MS(Values, min=1e-6*unitconv.LIGHT_C/(descriptor.ssaRow["ssa_specstart"], max=1e-6*unitconv.LIGHT_C/descriptor.ssaRow["ssa_specend"])) </code> </metaMaker> The SODA-compliant version of this is in the //soda#sdm_cutout predefined stream. The main point here is that you should follow section 4.3 for the [SODA] spec, i.e., use interval-xtyped parameters. Also, unless you’re actually prepared to handle multiply-specified parameter values, you should use the forced-single mulitplicity, which makes DaCHS reject requests that contain a parameter more than once. An extra complication occurs when SODA descriptors are generated for DAL responses. Currently, this is only envisaged for SSA. There, the descriptor has an extra limits attribute that gives, for each eligible column, minimum and maximum values or a set of values for enumerated columns. Similar (if possibly less useful) mechanisms are conceivable for, say, partial obscore results or SIAv1. We suggest to keep the attribute name of this sort of collective characterisation as limits. DaCHS does not implement anything of this kind right now, though. Metadata Error Messages¶ Both descriptor generators and meta makers can return (or yield, in the case of meta makers) error messages instead of either a descriptor or a link definition. This allows more fine-tuned control over the messages generated than raising an exception. Error messages are constructed using class functions of DatalinkFault, which is visible to both procedure types. The class function names correspond to the message types defined in the datalink spec and match the semantics given there: - AuthenticationFault - AuthorizationFault - NotFoundFault - UsageFault - TransientFault - FatalFault - Fault Thus, a descriptor generator could look like this: <descriptorGenerator> <code> with base.getTableConn() as conn: matchingRows = list(conn.queryToDicts( "select physPath from schema.myTable where pub_did=%(pubDID)s", locals())) if not matchingRows: return DatalinkFault.NotFoundFault(pubDID, "No dataset with this pubDID known here") return MyCustomDescriptor.fromFile(matchingRows[0]["physPath"]) </code> </descriptorGenerator> Where sensible, you should pass (as a keyword argument) semantics (as for LinkDefs) to the DatalinkFault’s constructor; this would indicate what kind of link you wanted to create. Data Functions¶ Data functions (see `element dataFunction`_) generate or manipulate data. They see the descriptor and the arguments (as args), parsed according to the input keys produced by the meta makers, where the descriptor’s data attribute is filled out by the first data function called (the “initial data function”). As described above, DaCHS does not enforce anything on the data attribute other than that it’s not None after the first data function has run. It is the RD author’s responsibility to make sure that all data functions in a given datalink core agree on what data is. All code in a request for processed data is also passed the input parameters as processed by the context grammar. Hence, the code can rely on whatever contract is implicit in the context grammar, but not more. In particular, a datalink core has no way of knowing what data functions expects which parameters. If no value for a parameter was provided on input, the corresponding value is None but a data function using it still is called. An example for a generating data function is `//soda#generateProduct`_, which may be convenient when the manipulations operate on plain local files; it basically looks like this: <dataFunction> <code> descriptor.data = products.getProductForRAccref(descriptor.accref) </code> </dataFunction> (the actual implementation lets you require certain mime types and is therefore a bit more complicated). You could do whatever you want, however. The following would work perfectly if you make your data functions handle lists of dicts: <dataFunction> <setup> <code> import random </code> </setup> <code> descriptor.data = [{"pix": i, "val": random.random()} for i in range(20000)] </code> </dataFunction> It wouldn’t be hard to come up with a formatter that turns this into a nice VOTable. Filtering data functions should always come with a meta maker declaring their parameters. As an example, continuing the frequency cutout example above, consider this: <dataFunction> <code> if not args.get("FREQ"): return lam_min, lam_max = (unitconv.LIGHT_C/(args[FREQ][0]*1e6) unitconv.LIGHT_C/(args[FREQ][1]*1e6)) from gavo.protocols import sdm sdm.mangle_cutout( descriptor.data.getPrimaryTable(), lam_min, lam_max) </code> </dataFunction> (Ignoring for the moment troubles with half-open intervals). There are situations in which a data function must shortcut, mostly because it is doing something other than just “pushing on” descriptor.data. Examples include preview producers or a data function that should produce the FITS header only. For cases like this, data functions can raise one of DeliverNow (which means descriptor.data must be something servable, see Data Formatters and causes that to be immediately served) or FormatNow (which immediately goes to the data formatter; this is less useful). Here’s an example for DeliverNow; a similar thing is contained in the STREAM //soda#fits_genKindPar: <dataFunction> <setup> <code> from gavo.utils import fitstools </code> </setup> <code> if args["KIND"]=="HEADER": descriptor.data = ("application/fits-header", fitstools.serializeHeader(descriptor.data[0].header)) raise DeliverNow() </code> </dataFunction> When writing data functions, you should raise soda.EmptyData() when a cutout results in empty data (e.g., because the cutout limits are out of range). If you don’t, users of your service might become angry with you when they have to click away many empty windows (say). For further examples of data functions, see the //soda RD coming with the distribution. If you write some, please consider whether they might be interesting for other DaCHS users, too, and submit them for inclusion into //soda. Data Formatters¶ Data formatters (see `element dataFormatter`_) take a descriptor’s data attribute and build something servable out of it. Datalink cores do not absolutely need one; the default is to return descriptor.data (the //soda#trivialFormatter, which might be fine if that data is servable itself). What is servable? The easiest thing to come up with is a pair of content type and data in byte strings; if descriptor.data is a Table or Data instance, the following could work: <dataFormatter> <code> from gavo import formats return "text/plain", formats.getAsText(descriptor.data) </code> </dataFormatter> Another example is an excerpt from //soda#sdm_cutout: <dataFormatter> <code> from gavo.protocols import sdm if len(descriptor.data.getPrimaryTable().rows)==0: raise base.ValidationError("Spectrum is empty.", "(various)") return sdm.formatSDMData(descriptor.data, args["FORMAT"]) </code> </dataFormatter> (this goes together with a metaMaker for an input key describing FORMAT). An alternative is to return something that has a renderHTTP(ctx) method that works in nevow. This is true for the Product instances that //soda#generateProduct generates, for example. You can also write something yourself by inheriting from protocols.products.ProductBase and overriding its iterData method. If you don’t inherit from ProductBase, be aware that this renderHTTP runs in the main server loop. If it blocks, the server blocks, so make sure that this doesn’t happen. The conventional way would be to return, from the renderHTTP method, some twisted producer. Non-Product nevow resources will also not work with asynchronous datalink at this point. Registry Matters¶ You can publish the metadata generating endpoint on your service by saying <publish render="dlmeta" sets="ivo_managed"/>. However, that is not recommended, as it clutters the registry with services that are not really usable after discovery. Datalink services will, however, appear as capabilities of services that publish tables that have associated datalink services. While it might be a good idea to provide some _example meta for all datalink services, when you register them, you really should provide one in any case so validators can pick up IDs and parameters to use when valdiating your service. Here is an example, taken from califa/q3: CALIFA cubes can be cut out along RA, DEC, and spectral axes. CIRCLE and POLYGON cutouts yield bounding boxes. Also note that the coverage of CALIFA cubes is hexagonal in space. This explains the empty area when cutting out :genparam:`CIRCLE(225.5202 1.8486 0.001)` :genparam:`BAND(366e-9 370e-9)` on :dl-id:`ivo://org.gavo.dc/~?califa/datadr3/V1200/UGC9661.V1200.rscube.fits`. Essentially, an identifier to use is given as the dl-id interpreted text role, whereas processing parameters are given as DALI genparams. In DaCHS, they are written as the parameter name and its value in parentheses. Datalinks as Product URLs¶ In particular for larger datasets like cubes, it is rude to put the entire dataset into an obscore table. Although obscore gives expected download sizes, clients nevertheless do not usually expect to have to retrieve several gigabytes or even terabytes of data when dereferencing an obscore access URL. While you could define additional datalink URLs and use these in Obscore – this is what lswscans/res/positions does, and there’s a piece of text on this in the tutorial –, you should in general use datalinks as product URLs throughout with datasets larger than a couple of Megabytes. c8spect/q shows how to do that with completely virtual data, califa/q3 and pcslg/q are examples for what to do with FITS cubes or spectra. This way, of course, without a datalink-enabled client people might be locked out from the dataset entirely. On the other hand, DaCHS comes with a stylesheet that enables datalink operation from a common web brower, so that’s perhaps not too bad. Aladin likes it when columns containing datalink URLs are marked up. DaCHS has two properties that let you add that markup, targetType and targetTitle. On a standalone datalink column that you just add to an output table, this could look like this (the datalink service would have an id of “dl” here; this also assumes you have a column named pub_did): <outputField name="datalink" type="text" id="datalink_output" ucd="meta.ref.url" select="'\getConfig{web}{serverURL}/\rdId/dl/dlmeta?ID=' || gavo_urlescape(pub_did)" tablehead="DL" description="URL of a datalink document for this dataset." displayHint="type=url" verbLevel="1"> <property name="targetType" >application/x-votable+xml;content=datalink</property> <property name="targetTitle">Datalink</property> </outputField> When your product link is a datalink, you have to amend the accref column in your main table. This stereotypically looks like this: <column original="accref"> <property name="targetType" >application/x-votable+xml;content=datalink</property> <property name="targetTitle">Datalink</property> </column>ize">10000</bind> [...] </rowfilter> [...] </fitsProdGrammar> This includes the estimate that the datalink document will have about 10k octets; in that region, there is no need to be precise. Note that the argument to the `macro dlMetaURI`_ is the id of the datalink service; DaCHS has no way to work that out by itself. When you do this, you must use a datalink-aware descriptor generator in SODA. When you use the recommended setup, where the accref is the inputsDir-relative path to the main file, and you’re dealing with FITS, you can use the DLFITSProductDescriptor class.> When not using FITS, you will need to change the descriptor generator’s computation of the local file path yourself, as done, e.g., in pcslg/q. SDM compliant tables¶ A common use for datalink cores in DaCHS is for server-side generation and processing of spectra as discussed in SDM processing . This almost invariably involves defining tables compliant with the spectral data model and filling them. The builder parameter of `//soda#sdm_genData`_ expects a reference to an SDM compliant data element. To define it, you first need to define an instance table. The columns that are in there depend on your data. In the simplest case, the //ssap#sdm-instance mixin is sufficient and adds the columns flux and spectral. Here’s how you’d add flux errors if you needed to: <table id="instance" onDisk="False"> <mixin ssaTable="slitspectra" spectralDescription="Wavelength" fluxDescription="Flux" >//ssap#sdm-instance</mixin> <column name="fluxerror" ucd="stat.error;phot.flux.density;em.wl" unit="m" description="Estimate for error in flux based on the procedure discussed at referenceURL"/> </table> What’s referenced in `//soda#sdm_genData`_ is a data element that builds this table. Here’s one that fills the table from the database: <data id="get_slitcomponent"> <!-- datamaker to pull spectra values out of the database --> <embeddedGrammar> <iterator> <code> obsId = self.sourceToken["accref"].split("/")[-1] with base.getTableConn() as conn: for row in conn.queryToDicts( "SELECT lambda as spectral, flux, error as fluxerror" " WHERE obsId=%(obsid)s ORDER BY lambda"): yield row </code> </iterator> </embeddedGrammar> <make table="instance"> <parmaker> <apply procDef="//ssap#feedSSAToSDM"/> </parmaker> </make> </data> – obviously, you can just as well fill it from a file (e.g., cdfspect/q, which also shows what to do when the metadata that comes with the files is boken). The parmaker with the //ssap#feedSSAToSDM call is generic, i.e., you won’t usually need any more tricks here. Product Previews¶ DaCHS has built-in machinery to generate previews from normal, 2D FITS and JPEG files, where these are versions of the original dataset scaled to be about 200 pixels in width, delivered as JPEG files. These previews are shown on mousing over product links in the web interface, and they turn up as preview links in datalink interfaces. This also generates previews for cutouts. For any other sort of data, DaCHS does not automatically generate previews. To still provide previews – which is highly recommended – there is a framework allowing you to compute and serve out custom previews. This is based on the preview and preview_mime columns which are usually set using parameters in //products#define. You could use external previews by having http (or ftp) URLs, which could look like this: <rowfilter procDef="//products#define"> ... <bind key="preview">("" +"/".join(\inputRelativePath.split("/")[2:]))</bind> <bind key="preview_mime">"image/jpeg"/bind> </rowfilter> (this assumes takes away to path elements from the relative paths, which typically reproduces an external hierachy). If you need to do more complex manipulations, you can have a custom rowfilter, maybe like this if you have both FITS files (for which you want DaCHS’ default behaviour selected with AUTO) and .complex files with some external preview: <rowfilter name="make_preview_paths"> <code> srcName = os.path.basename(rowIter.sourceToken) if srcName.endswith(".fits"): row["preview"] = 'AUTO' row["preview_mime"] = None else: row["preview"] = ('' +os.path.splitext(srcName)[0]+"-preview.jpeg") row["preview_mime"] = 'image/jpeg' yield row </code> </rowfilter> <rowfilter procDef="//products#define"> ... <bind key="preview">@preview</bind> <bind key="preview_mime">@preview_mime</bind> </rowfilter> More commonly, however, you’ll have local previews. If they already exist, use a static renderer and enter full local URLs as above. If you don’t have pre-computed previews, let DaCHS handle them for you. You need to do three things: define where the preview files are. This happens via a previewDirproperty on the importing data descriptor, like this: <data id="import"> <property key="previewDir">previews</property> ... say that the previews are standard DaCHS generated in the //products#definerowfilter. The main thing you have to decide here is the MIME type of the previews you’re generating. You will usually use either the `macro standardPreviewPath`_ (preferable when you have less than a couple of thousand products) or the `macro splitPreviewPath`_ to fill the preview path, but you can really enter whatever paths are convenient for you here: <rowfilter procDef="//products#define"> <bind name="table">"\schema.data"</bind> <bind name="mime">"image/fits"</bind> <bind name="preview_mime">"image/jpeg"</bind> <bind name="preview">\standardPreviewPath</bind> </rowfilter> actually compute the previews. This is usually not defined in the RD but rather using DaCHS’ processing framework. Precomputing previews in the processor documentation covers this in more detail; the upshot is that this can be as simple as: from gavo.helpers import processing class PreviewMaker(processing.SpectralPreviewMaker): sdmId = "build_sdm_data" if __name__=="__main__": processing.procmain(PreviewMaker, "flashheros/q", "import") Custom UWSes¶ Universal Worker Systems (UWSes) allow the asynchronous operation of services, i.e., the server runs a job on behalf of the user without the need for a persistent connection. DaCHS supports async operations of TAP and datalink out of the box. If you want to run async services defined by your own code, there are a few things to keep in mind. (1) You’ll need to prepare your database to keep track of your custom jobs (just once): gavo imp //uws enable_useruws (2) You’ll have to allow the uws.xml renderer on the service in question. (3) Things running within a UWS are fairly hard to debug in DaCHS right now. Until we have good ideas on how to make these things a bit more accessible, it’s a good idea to at least for debugging also allow synchronous renderers, for instance, form or api. If something goes wrong, you can do a sync query that then drops you in a debugger in the usual manner (see the debugging chapter in the tutorial). (4) For now, the usual queryMeta is not pushed into the uws handler (there’s no good reason for that). We do, however, transport on DALI-type RESPONSEFORMAT. To enable that on automatic results (see below), say: <inputKey name="responseformat" description="Preferred output format" type="text"/> in your input table. (5) All UWS parameters are lowercased and only available in lowercased form to server-side code. To allow cores to run in both sync and async without further worries, just have lowercase-only parameters. (6) As usual, the core may return either a pair of (media type, content) or a data item, which then becomes a UWS result named result with the proper media type. You can also return None (which will make the core incompatible with most other renderers). That may be a smart thing to do if you’re producing multiple files to be returned through UWS. To do that, there’s a job attribute on the inputTable that has an addResult(source, mediatype, name) method. Source can be a string (in which case the string will be the result) or a file open for reading (in which case the result will be the file’s content). Input tables of course don’t have that attribute unless they come from the uws rendererer. Hence, a typical pattern to use this would be: if hasattr(inputTable, "job"): with inputTable.job.getWritable() as wjob: wjob.addResult("Hello World.\\n", "text/plain", "aux.txt") or, to take the results from a file that’s already on-disk: if hasattr(inputTable, "job"): with inputTable.job.getWritable() as wjob: with open("other-result.txt") as src: wjob.addResult(src, "text/plain", "output.txt") Right now, there’s no facility for writing directly to UWS result files. Ask if you need that. (7) UWS lets you add arbitrary files using standard DALI-style uploads. This is enabled if there are file-typed inputKeys in the service’s input table. These inputKeys are otherwise ignored right now. See [DALI] for details on how these inputs work. To create an inline upload from a python client (e.g., to write a test), it’s most convenient to use the requests package, like this: import requests requests.post("", {"UPLOAD": "stuff,param:upl"}, files = {"upl": open("zw.py")}) From within your core, use the file name (the name of the input key) and pull the file from the UWS working directory: with open(os.path.join(inputTable.job.getWD(), "mykey")) as f: ... Hint on debugging: gavo uwsrun doesn’t check the state the job is in, it will just try to execute it anyway. So, if your job went into error and you want to investicate why, just take its id and execute something like: gavo --traceback uwsrun i1ypYX Custom Pages¶ While DaCHS isn’t actually intended to be an all-purpose server for web applications, sometimes you want to have some gadget for the browser that doesn’t need VO protocols. For that, there is customPage, which is essentially a bare-bones nevow page. Hence, all (admittedly sparse) nevow documentation applies. Nevertheless, here are some hints on how to write a custom page. First, in the RD, define a service allowing a custom page. These normally have no cores (the customPage renderer will ignore the core): <service id="ui" core="null" allowed="custom" customPage="res/registration.py"> <meta name="shortName">DOI registration</meta> <meta name="title">VOiDOI DOI registration web service</meta> </service> The python module referred to in customPage must define a nevow resource. The recommended pattern is like this: from nevow import tags as T from gavo import web from gavo.imp import formal class MainPage( formal.ResourceMixin, web.CustomTemplateMixin, web.ServiceBasedPage): name = "custom" customTemplate = "res/registration.html" workItems = None @classmethod def isBrowseable(self, service): return True def form_ivoid(self, ctx, data={}): form = formal.Form() form.addField("ivoid", formal.String(required=True), label="IVOID", description="An IVOID for a registred VO resource"), form.addAction(self.submitAction, label="Next") return form def render_workItems(self, ctx, data): if self.workItems: return ctx.tag[T.li[[m for m in self.workItems]]] return "" def submitAction(self, ctx, form, data): self.workItems = ["Working on %s"%data["ivoid"]] return self The formal.ResourceMixin lets you define and interpret forms. The web.ServiceBasedPage does all the interfacing to the DaCHS (e.g., credential checking and the like). The web.CustomTemplateMixin lets you get your template from a DaCHS template (cf. templating guide) from a resdir-relative directory given in the customTemplate attribute. For widely distributed code, you should additionaly provide some embedded stan fallback in the defaultDocFactory attribute – of course, you can also give the template in stan in the first place. On form_invoid and submitAction see below. This template could, for this service, look like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <html xmlns="" xmlns: <head> <title>VOiDOI: Registration</title> <n:invisible n: </head> <body n: <h1>VOiDOI: Register your VO resource</h1> <ul n: <p>VOiDOI lets you obtain DOIs for registered VO services.</p> <p>In the form below, enter the IVOID of the resource you want a DOI for. If the resource is known to our registry but has no DOI yet, the registred contact will be sent an e-mail to confirm DOI creation.</p> <n:invisible n: </body> </html> Most of the details are explained in the templating guide. The exception is the form ivoid. This makes the formal.ResourceMixin call the form_ivoid in in whatever HTML/stan that returns. If nevow detects that the request already results from filling out the form, it will execute what your registred in addAction – in this case, it’s the submitAction method. Important: anything you do within addAction runs within the (cooperative) server thread. If it blocks or performs a long computation, the server is blocked. You will therefore want to do non-trivial things either using asynchronous patterns or using deferToThread. The latter is less desirable but also easier, so here’s how this looks like: def submitAction(self, ctx, form, data): return threads.deferToThread( runRegistrationFor, data["ivoid"] ).addCallback(self._renderResponse ).addErrback(self._renderErrors) def _renderResponse(self, result): # do something to render a success message (or return Redirect) return self def _renderErrors(self, failure): # do something to render an error message, e.g., from # failure.getErrorMessage() return self The embedding RD is available in the custom pages’s global namespace as RD. Thus, the standard pattern for creating a read only table is: with api.getTableConn() as conn: table = api.TableForDef(RD.getById("my_table"), connection=conn) If you need write access, you would write: with api.getWritableAdminConn() as conn: table = api.TableForDef(RD.getById("my_table"), connection=conn) The RD attribute is not avalailable during module import. This is a bit annoying if you want to load resources from an RD-dependent place; this, in particular, applies to importing dependent modules. To provide a workaround, DaCHS calls a method initModule(**kwargs) after so you code doesn’t fail if we find we want to give initModule some further information. The common case of importing a module from some RD-dependent place thus becomes: from gavo import utils def initModule(**kwargs): global oai2datacite modName = RD.getAbsPath("doitransfrom/oai2datacite") oai2datacite, _ = utils.loadPythonModule(modName) Manufacturing Spectra¶ TODO: Update this for Datalink Making SDM Tables¶ Compared to images, the formats situation with spectra is a mess. Therefore, in all likelihood, you will need some sort of conversion service to VOTables compliant to the spectral data model. DaCHS has a facility built in to support you with doing this on the fly, which means you only need to keep a single set of files around while letting users obtain the data in some format convenient to them. The tutorial contains examples on how to generate metadata records for such additional formats. First, you will have to define the “instance table”, i.e., a table definition that will contain a DC-internal representation of the spectrum according to the data model. There’s a mixin for that: <table id="spectrum"> <mixin ssaTable="hcdtest">//ssap#sdm-instance</mixin> </table> In addition to adding lots and lots of params, the mixin also defines two columns, spectral and flux; these have units and ucds as taken from the SSA metadata. You can add additional columns (e.g., a flux error depending on the spectral coordinate) as requried. The actual spectral instances can be built by sdmCores and delivered through DaCHS’ product interface. Note, however, that clients supporting getData wouldn’t need to do this. You’ll still have to define the data item defined below. sdmCores, while potentially useful with common services, are intended to be used by the product renderer for dcc product table paths. They contain a data item that must yield a primary table that is basically sdm compliant. Most of this is done by the //ssap#feedSSAToSDM apply proc, but obviously you need to yield the spectral/flux pairs (plus potentially more stuff like errors, etc, if your spectrum table has more columns. This comes from the data item’s grammar, which probably must always be an embedded grammar, since its sourceToken is an SSA row in a dictionary. Here’s an example: <sdmCore queriedTable="hcdtest" id="mksdm"> <data id="getdata"> <embeddedGrammar> <iterator> <code> labels = ("spectral", "flux") relPath = self.sourceToken["accref"].split("?")[-1] with self.grammar.rd.openRes(relPath) as inF: for ln in inF: yield dict(zip(labels,ln.split())) </code> </iterator> </embeddedGrammar> <make table="spectrum"> <parmaker> <apply procDef="//ssap#feedSSAToSDM"/> </parmaker> </make> </data> </sdmCore> Note: spectral, flux, and possibly further items coming out of the iterator must be in the units units promised by the SSA metadata (fluxSI, spectralSI). Declarations to this effect are generated by the //ssap#sdm-instance mixin for the spectral and flux columns. The sdmCores are always combined with the sdm renderer. It passes an accref into the core that gets turned into an row from queried table; this must be an “ssa” table (i.e., right now something that mixes in //ssap#hcd). This row is the input to the embedded data descriptor. Hence, this has no sources element, and you must have either a custom or embedded grammar to deal with this input. Echelle Spectra¶ Echelle spectrographs “fold” a spectrum into several orders which may be delivered in several independent mappings from spectral to flux coordinate. In this split form, they pose some extra problems, dealt with in an extra system RD, //echelle. For merged Echelle spectra, just use the standard SSA framework. Table¶ Echelle spectra have additional metadata that should end up in their SSA metadata table – these are things like the number of orders, the minimum and maximum (Echelle) order, and the like. To pull these columns into your metadata table, use the ssacols stream, for example like this: <table id="ordersmeta" onDisk="True" adql="True"> <meta name="description">SSA metadata for split-order Flash/Heros Echelle spectra</meta> <mixin [...]//ssap#hcd</mixin> <mixin calibLevel="1">//obscore#publishSSAPHCD</mixin> <column name="localKey" type="text" ucd="meta.id" tablehead="Key" description="Local observation key." verbLevel="1"/> <STREAM source="//echelle#ssacols"/> </table> Supporting getData¶ DaCHS still has support the now-abandoned 2012 getData specification by Demleitner and Skoda. If you think you still want this, contact the authors; meanwhile, you really should be using datalink for whatever you think you need getData for. Adapting Obscore¶ You may want extra, locally-defined columns in your obscore tables. To support this, there are three hooks in obscore that you can exploit. The hooks are in userconfig.rd (see Userconfig RD in the operator’s guide to where it is and how to get started with it) It helps to have a brief look at the //obscore RD (e.g., using gavo admin dumpDF //obscore) to get an idea what these hooks do. Within the template userconfig.rd, there are already three STREAMs with ids starting with obscore.; these are referenced from within the system //obscore RD. Here’s an somewhat more elaborate example: <STREAM id="obscore-extracolumns"> <column name="fill_factor" description="Fill factor of the SED" verbLevel="20"/> </STREAM> <STREAM id="obscore-extrapars"> <mixinPar name="fillFactor" description="The SED's fill factor">NULL</mixinPar> </STREAM> <STREAM id="obscore-extraevents"> <property name="obscoreClause" cumulate="True"> , CAST(\\\\fillFactor AS real) AS fill_factor </property> </STREAM> (to be on the safe side: there need to be four backslashes in front of fillFactor; this is just a backslash doubly-escaped. Sorry about this). The way this is used in an actual mixin would be like this: <table id="specs" onDisk="True"> <mixin ...>//ssap#hcd</mixin> <mixin ... (all the usual parameters)//obscore#publishSSAPMIXC</mixin> </table> What’s going on here? Well, obscore-extracolumns is easy – this material is directly inserted into the definition of the obscore view (see the table with id ObsCore within the //obscore RD). You could abuse it to insert other stuff than columns but probably should not. The tricky part is obscore-extraevents. This goes into the //obscore#_publishCommon STREAM and ends up in all the publish mixins in obscore. Again, you could insert mixinPars and similar at this point, but the only thing you really must do is add lines to the big SQL fragment in the obscoreClause property that the mixin leaves in the table. This is what is made into the table’s contribution to the big obscore union. Just follow the example above and, in particular, always CAST to the type you have in the metadata, since individual tables might have NULLs in the values, and you do not want misguided attempts by postgres to do type inference then. If you actually must know why you need to double-escape fillFactor and what the magic with the cumulate="True" is, ask. Finally, obscore-extrapars directly goes into a core component of obscore, one that all the various publish mixins there use. Hence, all of them grow your functionality. That is also why it is important to give defaults (i.e., element content) to all mixinPars you give in this way – without them, all those other publish mixins would fail unless their applications in the RDs were fixed. If you change %#obscore-extracolumns, all the statement fragments contributed by the obscore-published tables need to be fixed. To spare you the effort of touching a potentially sizeable number of RDs, there’s a data element in //obscore that does that for you; so, after every change just run: gavo imp //obscore refreshAfterSchemaUpdate This may fail if you didn’t clean up properly after deleting a resource that once contributed to ivoa.obscore. In that case you’ll see an error message like: *** Error: table u'whatever.main' could not be located in dc_tables In that case, just tell DaCHS to forget the offending table: gavo purge whatever.main Another problem can arise when a table once was published to obscore but now no longer is while still existing. DaCHS in that case will still have an entry for the table in ivoa._obscoresources, which results in an error like: Table definition of whatever.main> has no property 'obscoreClause' set The fastest way to fix this situation is to drop the offending line in the database manually: psql gavo -c "delete from ivoa._obscoresources where tablename='whatever.main'" Writing Custom Grammars¶ A custom grammar simply is a python module located within a resource directory defining a row iterator class derived from gavo.grammars.customgrammar.CustomRowIterator. This class must be called RowIterator. You want to override the _iterRows method. It will have to yield row dictionaries, i.e., dictionaries mapping string keys to something (preferably strings, but you will usually get away with returning complete values even without fancy rowmakers). So, a custom grammar module could look like this: from gavo.grammars.customgrammar import CustomRowIterator class RowIterator(CustomRowIterator): def _iterRows(self): for i in xrange(int(self.sourceToken)): yield {'index': i, 'square': i**2} This would be used with a data material like: <sources><item>4</item><item>40</item></sources> <customGrammar module="res/sillygrammar"/> – self.sourceToken simply contains whatever the sources produce. One RowIterator will be constructed for each item. It is highly recommended to keep track of the current position so DaCHS can give more useful error messages. When an error occurs, DaCHS will call the iterator’s getLocator method. This returns an arbitrary string, where obviously it’s a good idea if it leads users to somewhere close to where the problem will be. Here’s a custom grammar reading space-separated key-value pairs from a file: class RowIterator(CustomRowIterator): def _iterRows(self): self.lineNumber = 0 with open(self.sourceToken) as f: for self.lineNumber, line in enumerate(f): yield dict(zip(["key", "value"], line.split(" ", 1))) def getLocator(self): return "line %s"%self.lineNumber Note that getLocator doesn’t include the source file name; it will be inserted into the error message by DaCHS. Do not override magic methods, since you may lose row filters, sourceFields, and the like if you do. An exception is the constructor. If you must, you can override it, but you must call the parent constructor, like this: class RowIterator(CustomRowIterator): def __init__(self, grammar, sourceToken, sourceRow=None): CustomRowIterator.__init__(self, grammar, sourceToken, sourceRow) <your code> In practice (i.e., with <sources pattern="*"/>) ``self.sourceToken will be a file name. When you call makeData manually and pass a forceSource argument, its value will show up in self.sourceToken instead. For development, it may be convenient to execute your custom grammar as a python module. To enable that, just append a: if __name__=="__main__": import sys from gavo.grammars.customgrammar import CustomGrammar ri = RowIterator(CustomGrammar(None), sys.argv[1]) for row in ri: print row to your module. You can then run things like: python res/mygrammar.py data/inhabitedplanet.fits and see the rows as they’re generated. A row iterator will be instanciated for each source processed. Thus, you should usually not perform expensive operations in the constructor unless they depend on sourceToken. In general, you should rather define a function makeDataPack in the module. Whatever is returned by this function is available as self.grammar.dataPack in the row iterator. The function receives an instance of the customGrammar as an argument. This means you can access the resource descriptor and properties of the grammar. As an example of how this could be used, consider this RD fragment: <table id="defTable"> ... </table> <customGrammar module="res/grammar"> <property name="targetTable">defTable</property> </customGrammar> Then you could have the following in res/grammar.py: def makeDataPack(grammar): return grammar.rd.getById(grammar.getProperty("targetTable")) and access the table in the row iterator. Also look into EmbeddedGrammar, which may be a more convenient way to achieve the same thing. A fairly complex example for a custom grammar is a provisional Skyglow grammar . Dispatching Grammars¶ With normal grammars, all rows are fed to all rowmakers of all makes within a data object. The rowmakers can then decide to not process a given row by raising IgnoreThisRow or using the trigger mechanism. However, when filling complex data models with potentially dozens of tables, this becomes highly inefficient. When you write your own grammars, you can do better. Instead of just yielding a row from _iterRows, you yield a pair of a role (as specified in the role attribute of a make element) and the row. The machinery will then pass the row only to the feeder for the table in the corresponding make. Currently, the only way to define such a dispatching grammar is to use a custom grammar or an embedded grammar. For these, just change your _iterRows and say isDispatching="True" in the customGrammar element. If you implement getParameters, you can return either pairs of role and row or just the row; in the latter case, the row will be broadcast to all parmakers. Special care needs to be taken when a dispatching grammar parses products, because the product table is fed by a special make inserted from the products mixin. This make of course doesn’t see the rows you are yielding from your dispatching grammar. This means that without further action, your files will not end up in the product table at all. In turn, getproducts will return 404s instead of your products. To fix this, you need to explicitly yield the rows destined for the products table with a products role, from within your grammar. Where the grammar yield rows for the table with metadata (i.e., rows that actually contain the fields with prodtblAccref, prodtblPath, etc), yield to the products table, too, like this: yield ("products", newRow). Functions Available for Row Makers¶ In principle, you can use arbitrary python expressions in var, map and proc elements of row makers. In particular, the namespace in which these expressions are executed contains math, os, re, time, and datetime modules as well as gavo.base, gavo.utils, and gavo.coords. However, much of the time you will get by using the following functions that are immediately accessible in the namespace: Scripting¶ As much as it is desirable to describe tables in a declarative manner, there are quite a few cases in which some imperative code helps a lot during table building or teardown. Resource descriptors let you embed such imperative code using script elements. These are children of the make elements since they are exclusively executed when actually importing into a table. Currently, you can enter scripts in SQL and python, which may be called at various phases during the import. SQL scripts¶ In SQL scripts, you separate statements with semicolons. Note that no statements in an SQL script may fail since that will invalidate the transaction. This is a serious limitation since you must not commit or begin transactions in SQL scripts as long as Postgres does not support nested transactions. You can use table macros in the SQL scripts to parametrize them; the most useful among those probably is \curtable containing the fully qualified name of the table being processed. Python scripts¶ Python scripts can be indented by a constant amount. The table object currently processed is accessible as table. In particular, you can use this to issue queries using table.query(query, arguments) (parallel to dbapi.execute) and to delete rows using table.deleteMatching(condition, pars). The current RD is accessible as table.rd, so you can access items from the RD as table.rd.getById("some_id"), and the recommended way to read stuff from the resource directory is table.rd.openRes("res/some_file). Some types of scripts may have additional names available. Currently: newSourceand sourceDonehave the name sourceToken; this is the sourceToken as passed to the grammar; usually, that’s the file name that’s parsed from, but other constellations are possible. sourceDonehas feeder– that is the DaCHS-internal glue to filling tables. The main use of this is that you can call its flush()method, followed by a table.commit(). This may be interesting in updating grammars where you preserve what’s already imported. Note, however, that this may come with a noticeable performance penalty. Script types¶ The type of a script corresponds to the event triggering its execution. The following types are defined right now: - preImport – before anything is written to the table - preIndex – before the indices on the table are built - preCreation – immediately before the table DDL is executed - postCreation – after the table (incl. indices) is finished - beforeDrop – when the table is about to be dropped - newSource – every time a new source is started - sourceDone – every time a source has been processed Note that preImport, preIndex, and postCreation scripts are not executed when the make’s table is being updated, in particular, in data items with updating="True". The only way to run scripts in such circumstances is to use newSource and sourceDone scripts. Examples¶ This snippet sets a flag when importing some source (in this case, that’s an RD, so we can access sourceToken.sourceId: <script type="newSource" lang="python" id="markDeleted"> table.query("UPDATE %s SET deleted=True" " WHERE sourceRD=%%(sourceRD)s"%id, {"sourceRD": sourceToken.sourceId}) </script> This is a hacked way of ensuring some sort of referential integrity: When a table containing “products” is dropped, the corresponding entries in the products table are deleted: <script type="beforeDrop" lang="SQL" name="clean product table"> DELETE FROM products WHERE sourceTable='\curtable' </script> Note that this is actually quite hazardous because if the table is dropped in any way not using the make element in the RD, this will not be executed. It’s usually much smarter to tell the database to do the housekeeping. Rules are typically set in postCreation scripts: <script type="postCreation" lang="SQL"> CREATE OR REPLACE RULE cleanupProducts AS ON DELETE TO \curtable DO ALSO DELETE FROM products WHERE key=OLD.accref </script> The decision if such arrangements are make before the import, before the indexing or after the table is finished needs to be made based on the script’s purpose. Another use for scripts is SQL function definition: <script type="postCreation" lang="SQL" name="Define USNOB matcher"> CREATE OR REPLACE FUNCTION usnob_getmatch(alpha double precision, delta double precision, windowSecs float ) RETURNS SETOF usnob.data AS $$ DECLARE rec RECORD; BEGIN FOR rec IN (SELECT * FROM usnob.data WHERE q3c_join(alpha, delta, raj2000, dej2000, windowSecs/3600.)) LOOP RETURN NEXT rec; END LOOP; END; $$ LANGUAGE plpgsql; </script> You can also load data, most usefully in preIndex scripts (although beforeImport would work as well here): <script type="preIndex" lang="SQL" name="create USNOB-PPMX crossmatch"> SET work_mem=1000000; INSERT INTO usnob.ppmxcross ( SELECT q3c_ang2ipix(raj2000, dej2000) AS ipix, p.localid FROM ppmx.data AS p, usnob.data AS u WHERE q3c_join(p.alphaFloat, p.deltaFloat, u.raj2000, u.dej2000, 1.5/3600.)) </script> ReStructuredText¶ Text needing some amount of markup within DaCHS is almost always input as ReStructuredText (RST). The source versions of the DaCHS documentation give examples for such markup, and DaCHS users should at least briefly skim the ReStructuredText primer. DaCHS contains some RST extensions. Those specifically targeted at writing DALI-compliant examples of them are discussed with `the examples renderer`_ Generally useful extensions include: - bibcode This text role formats the argument as a link into ADS when rendered as HTML. For technical reasons, this currently ignores the configured ADS mirror and always uses the Heidelberg one. Complain if this bugs you. To use it, you’d write: See also :bibcode:`2011AJ....142....3H`. Extensions for writing DaCHS-related documentation include: - dachsdoc - A text role generating a link into the current DaCHS documentation. The argument is the relative path, e.g., :dachsdoc:`opguide.html#userconfig-rd`. - dachsref - A text role generating a link into the reference documentation. The argument is a section header within the reference documentation, e.g., :dachsref:`//epntap2#populate-2_0`or :dachsref:`the form renderer`. - samplerd - A text role generating a link to an RD used by the GAVO data center (exhibiting some feature). The argument is the relative path to the RD (or, really, anything else in the VCS), e.g., :samplerd:`ppmxl/q.rd`. (if you add anything here, please also amend the document source’s README). Code in DaCHS¶ This section contains a few general points for python code embedded in DaCHS, be it custom pages, cores, or grammars, or even procs. Importing modules¶ To keep the various resources as separate from each other as possible, DaCHS does not manipulate Python’s import path. However, one frequently wants to have library-like modules providing common functionality or configuration in a resdir (the conventional place for these would be in res/). To import these, use api.loadPythonModule(path). Path, here, is the full path to the file containing the python code, but without the .py. When you have the RD, the conventional pattern is: mymod, _ = api.loadPythonModule(rd.getAbsPath("res/mymod")) instead of import mymod. As you can see loadPythonModule returns a tuple; you’re very typically only interested in the first element. Note in particular that for modules loaded in this way, the usual rule that you can just import modules next to you does not apply. To import a modules “next to” you without having to go through the RD, use the special form: siblingmod, _ = api.loadPythonModule("siblingmod", relativeTo=__file__) instead of import siblingmod. This will take the directory part for what’s in relativeTo (here, the module’s own path) and make a full path out of the first argument to pull the modules from there. The DaCHS API¶ User extension code (e.g., custom cores, custom grammars, processors) for DaCHS should only use DaCHS functions from its api as described below. We will try to keep it stable and at any rate warn in the release notes if we change it. For various reasons, the module also contains a few modules. These, and in particular their content, are not part of the API. Note that at this point this is not what is in the namespace of rowmakers, rowfilters, and similar in-RD procedures. We do not, at this point, recommend importing the api. If you do it anyway, we’d appreciate if you told us. Before using non-API DaCHS functions, please inquire on the dachs-support mailing list (cf.). To access DaCHS API functions, say: from gavo import api (perhaps adding an as dachsapi if there is a risk of confusion) and reference symbols with the explicit module name (i.e., api.makeData rather than picking individual names) in order to help others understand what you’ve written. Here is an alphabetical list of the documented API functions: System Tables¶ DaCHS uses a number of tables to manage services and implement protocols. Operators should not normally be concerned with them, but sometimes having a glimpse into them helps with debugging. If you find yourself wanting to change these tables’ content, please post to dachs-support first describing what you’re trying to do. There should really be commands that do what you want, and it’s relatively easy to introduce subtle problems by manipulating system tables without going through those. Having said that, here’s a list of the system tables together with brief descriptions of their role and the columns contained. Note that your installation might not have all of those; some only appear after a gavo imp of the RD they are defined in – which you of course only should do if you know you want to enable the functionality provided. The documentation given here is extracted from the resource descriptors, which, again, you can read in source using gavo admin dumpDF //<rd-name>.
https://dachs-doc.readthedocs.io/refdoc.html
CC-MAIN-2020-29
refinedweb
26,034
54.52
ST. JOHN’S, Newfoundland and Labrador--(BUSINESS WIRE)--Altius Minerals Corporation (“Altius”) (ALS:TSX) is pleased to provide an update on its Project Generation (“PG”) business activities and its public junior equities portfolio. The market value of the junior equities portfolio at June 30, 2018 was $60.3 million, compared to $48.8 million at March 30, 2018. The Altius portfolio value includes new investments in the quarter of $2.6 million while portfolio sales generated $2.4 million. The $60.3 million value does not include the $10 million Champion Iron Ore convertible debenture, various in-the-money share purchase warrants or other equities to be received in exchange for announced, but not yet closed, project transactions. It also does not include 11.2 million shares of Aethon Minerals Corporation (AET: TSX-V) (“Aethon”), which are held within a 49% Altius owned business. An updated list of the public equity holdings has been posted to the Altius website at. Portfolio Additions During the quarter, Aethon began trading after acquiring Mining Equity’s entire mineral property portfolio of Chilean copper-gold projects for 11,200,000 shares or 40% of Aethon. Altius also directly holds a 0.98% gross sales royalty (“GSR”) covering the vended project portfolio. Altius participated in a private placement in Constantine Metals (CEM: TSX-V) that also saw Electrum Strategic Opportunities Fund become a new major shareholder of the company. It also participated in a flow-through private placement in Canstar Resources (ROX: TSX-V), with which it also has a project level equity and royalty agreement that remains subject to final closing. Portfolio Highlights Altius expects that its portfolio companies (in which Altius has >10% equity ownership and/or a project royalty) will carry out in excess of 36 km of exploration drilling during the current year, with five companies having active drill programs underway during the second quarter. Adventus Zinc, in which Altius held a 27% position at quarter end, released ongoing infill drill results from the Curipamba copper-lead-zinc project in Ecuador, which included an intercept of 19.41 meters at a copper equivalent grade of 9.5% (7.0% copper, 1.61 g/t gold, 3.0% zinc, 18.4 g/t silver and 0.14% lead). Adventus also announced a $9.2-million equity financing that included lead order participation by Wheaton Precious Metals Corp. Evrim Resources (EVM:TSX-V) (“Evrim”) announced commencement of a third phase of exploration at its 100%-owned Cuale high-sulphidation epithermal gold project in Mexico. The program will include 3,000 metres of drilling to test the La Gloria zone surface discovery (see Evrim news releases of April 9 and April 16, 2018), from which trench 1 returned 1.67 g/t gold over 263.2 metres and trench 4 returned 13.61 g/t gold over 106.2 metres. In addition to the 11,464,875 common shares of Evrim held by Altius at quarter end, representing approximately 14% of the outstanding shares, the Company holds 2 million warrants priced at $0.50 per share. Altius also holds a 1.5% net smelter return (“NSR”) royalty on precious metals and a 1.0% NSR royalty on base metals covering the Cuale project. On June 25, 2018, Excelsior Mining (MIN:TSX) (“Excelsior”) announced receipt of its Federal Operating Permit from the United States Environmental Protection Agency regarding its Class 3 Underground Injection Control area permit, for the Gunnison copper project, located in Cochise County, southeastern Arizona. The permit was issued with an effective date of August 1, 2018 and is the last permit required to commence production. Altius is a substantial shareholder of Excelsior and also owns a 1% GSR covering the project and an option to acquire a further 0.5% GSR royalty for $5 million CAD once a mine construction decision is formalized. held diversified royalties and streams. It also holds a large portfolio of exploration stage projects which it has generated for deal making with industry partners that results in newly created royalties and equity and minority interests. The Altius exploration team was recently awarded the 2017 Prospector/Explorer Award from the Newfoundland Branch of the CIMM for its recent work on project generation. Altius has 43,215,026 common shares issued and outstanding that are listed on Canada’s Toronto Stock Exchange. It is a member of both the S&P/TSX Small Cap and S&P/TSX Global Mining Indices.
https://www.businesswire.com/news/home/20180710005269/en/Altius-2nd-Quarter-2018-Project-Generation-Update
CC-MAIN-2019-09
refinedweb
741
55.44
15590/what-is-the-function-for-factorial-in-python How do I go about computing a factorial of an integer in Python? Easiest way: math.factorial(x) (available in 2.6 and above). If you want/have to write it yourself, use something like def factorial(n): return reduce(lambda x,y:x*y,[1]+range(1,n+1)) or something more readable: def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) As always, Google is your friend ;) raw_input fuction is no longer available in ...READ MORE Machine Learning is a vast domain. It ...READ MORE The seed method is used to initialize the ...READ MORE Pattern is a web mining tool.
https://www.edureka.co/community/15590/what-is-the-function-for-factorial-in-python
CC-MAIN-2020-40
refinedweb
117
59.8
Building COVID-19 interactive dashboard from Jupyter Notebook | No frontend/backend coding required. [ad_1] Tutorial on creating dashboards simply by using Jupyter Notebooks and Voila package. The dashboard contains all the latest stats/interactive plots and comparisons on COVID-19 confirmed, death and recovered cases. – My featured Medium post on building dashboards: – [Not working at the moment!]GitHub repository: – Use this Colab Notebook as a temporary solution: – Deployed Dashboard: – Refer to this link to deploy your app on heroku: References: – Plotly express examples: – Folium for the global spread on maps: – Voila: – Jupyter: Social Media Links: – Medium where I write: – Twitter: Source [ad_2] Comment List Awesome Videos. Learnt a lot by doing this exercise. How can I deploy this using github? Thanks your lesson I need your help for my thesis… please help me.. can i give your email sir ??? Hi so much of knowledge I got from this session… I tequest you to please come up with a deployment session This is some real encouraging stuff🎉👍 I have been going through a lot of EDA work in recent time, but the static nature made it look bit boring. The amount of interactivity you brought into the jupyter notebook was amazing. Thank you! Awesome tutorial, thank you very much! Is there any way we can prepare a front end to feed data into these visualizations? What I I have business that requires to input data dynamically into this script for the data to be visualized. Awesome 👏 It was amazing!!! so coolllll. ya please go ahead and make a video on how to deploy it. Big thumbs up for this video. Thanks for this good example, Can i use the code in my research topic "spatial data visualization" Whenever I am clicking on Voila tab or running the command : Voila <path of .ipynb>, the link never loads, it shows waiting for local host. Everything is fine with code, it's running fine in jupyter notebook Hi Harshit! I am supposed to create a button and when the button is clicked, an input box should appear that takes the user input. I created button using widgets.button. An then added onclick behavior to invoke another function which shows user text input. This is working fine when running in jupyter notebook but when I open using voila, I am not able to get the user input box when I clicked the button. Any suggestions? Excellent! Thanks for sharing! Thanks for the lesson Harshit, I learnt some cool stuff and thanks for leaving the little errors in, it's nice to see as a beginner that everyone gets errors. Good and nice tutorial. Thanks so much bro. Could you please help in porting Python scrapped data from different source which are plotted with Plotly and i need to create a interactive dashboard using dash and publish on it. Ex. Different Department performing % Hey please help. I'm unable to find the country Dataset Hi Harshit, what is the purpose of defining a blank temp_df? Hey Harshit, can I get your email ID or contact number. Really need help related to some data visualization datasets. Thank you! Is voila supposed to render for a long time? If not, is there a solution to this or do you have a recommended substitute to voila? DO we need to give citation to your github or channel if we put your code on github?Can we put this project on resume? Harshit, your github link is not working. Can you take a look at it. can you post the github link again ? it is not working and showing webpage not found ! Thanks… that's useful. How do you share the voila link? For more interactive and fast development in python without HTML and JavaScript try Streamlit, or Dash Potly, or Justpy. Very nice vedio, i created my notebook and installed Voila. when i run it, it shows an internet page says running and then it goes white. nothing happens..it just stays there on white page forever. Please please suggest. Very nicely explained! time has no attribute named clock after running the interact line I wrote the same code as you for section Slide to check for the worst hit countries IN[106], it build function def plot_cases_of_a_country(country): …. I am getting error AttributeError: 'str' object has no attribute 'iloc' I don't know why, please advise After installing the voila package it shows some errors while running the program. Please help me. Great Video..pls share more videos; a lot of learning I had from your video and best part is dashboard configuration…thanks again.. nice explanation. how to turn a dashboard into a website?? Hi Harshit. i have doubt @video timing 03:57.after data cleaning got done,how to apply data cleaning to all dataframes [short way to select all four datasets].please anyone reply Hi, I am facing an error when deploying into the Heroku I tried with windows and ubuntu I am getting the app builds successfully but shows application error could you please help me, sir, Waiting for your reply! here is the link to the GitHub: pls share video from start to end hands on till deployment This is great stuff! Thank you for the tutorial. I’m going to totally start using this! Cool. Thanks. How to deploy the voila that we made I am repeating the same code visual studio 2019 reading the below data frame is giving ( Error tokenizing data. C error: Expected 1 fields in line 33, saw 2) error death_df = pd.read_csv(''😉 can you please suggest ? Hi, I have an assignment similar to this in my university but the analysis is carried out after merging files into one and as I am a beginner in this field. It would be really appreciated if you can help me to figure out a few things. please let me know asap. Hey please help me, I am getting a parsr error unable to read the csv file I confirmed its documentation as it is from this video but its not working.Please help Harshit bhai this was really good. There are couple of queries i had. if you can address them i would be happy. so we have the data, date wise (day wise). (1) How can we club day and convert it to Week wise and plot, then how can we convert it into month wise and plot? And the main thing which i came here was missing 🙁 (2)i dint find any help with creating dashboards using voila 🙁 🙁 (3)apne direct bana hua web app dikha diya Please make some videos above request (1)(2)(3) as you get time. Please how did you align your HTML format in the center after extracting from the notebook to voila? How can I get the dashboard link to send to others? hi it showing error "interact" is not defined Great video. How did you fix the formatting of your charts when running Voila? Thank for the video.sir How can I put the Jupyter notebook into voila? I am not able to get that Hi Harshit, Great video. However, I was wondering if instead of downloading the data everytime we could web scrape the data and then make the dashboard so that it is live. I was trying to web scrape the covid 29 tracker of India but I am not able to figure out how to go about it. Can you help in this regard. Thanks a ton heroku deployment ? plese give me some resource. Can I host this in my website ?
https://openbootcamps.com/building-covid-19-interactive-dashboard-from-jupyter-notebook-no-frontend-backend-coding-required/
CC-MAIN-2021-10
refinedweb
1,263
73.88
VSTO extends the Word and Excel object models in several ways. Although it is possible to use these features without understanding what is actually happening "behind the scenes," it is helpful to take a look back there. This section explains by what mechanisms host items and host controls extend the Word and Excel programming models. Then the discussion focuses on exactly which new features are available. Aggregation, Inheritance, and Implementation If you create a Word project in Visual Studio and open the Object Browser window, you will see several assemblies listed. Two are of particular interest. You already know that the Microsoft.Office.Interop.Word assembly is the primary interop assembly (PIA), containing the definitions for the interfaces that allow managed code to call the unmanaged Word object model. Similarly, the Microsoft.Office.Interop.Excel assembly is the PIA for the unmanaged Excel object model. You can find the VSTO extensions to the Word and Excel object models in the Microsoft.Office.Tools.Word and Microsoft.Office.Tools.Excel assemblies; each contains a namespace of the same name. From a VSTO Word document project, open the Object Browser and take a look at the Document host item class in the Tools namespace, as shown in Figure 13-2. Figure 13-2. Examining the Document host item class in the Object Browser. Notice that the host item class implements the properties, methods, and events defined by the Document interface from the PIA, and extends the BindableComponent base class. Chapter 17 gets into the details of how data-bindable components work; for now, the fact that this class implements the properties, methods, and events from the PIA interface rather than extends a base class is important. It is important to notice that even though the Document host item class has all the methods, properties, and events of the Document interface from the PIA, the type definition does not actually say that it implements the Document interface itself. This is a subtle distinction that we will discuss in more detail later. Conceptually, the difference between extending a base class and implementing the properties, methods, and events from an interface is that the former describes an "is a" relationship, whereas the latter describes a "can act like" relationship. A Microsoft.Office.Tools.Word.Document object really is a bindable component; it actually shares functionalitycodewith its base class. But it merely looks like and acts like a Word Document object; it is not a Word document object as far as Word is concerned. For example, the Sheet1 class in Excel has your event handlers and host controls. It extends the Microsoft.Office.Tools.Excel.Worksheet base class and implements the properties, methods, and events defined by the Microsoft.Office.Interop.Excel.Worksheet interface. Hooking Up the Aggregates VSTO's host item and host control objects aggregate some of the underlying Word and Excel document objects (such as the Document and Bookmark objects in Word, or the Worksheet and NamedRange objects in Excel). You have already seen how you can call methods on the document object in a VSTO customization. Suppose, for instance, that you call the CheckGrammar method on the document. If this is not really a Word Document object but merely looks like one, how does it work? The aggregating object's implementation of that method checks to see whether it has obtained the aggregated Document object already. If it has not, it makes a call into Word to obtain it (and caches away the object so that it will be available immediately when you make a second method call). After it has the reference to the aggregated object, the aggregating object calls CheckGrammar on the aggregated object. The great majority of the properties and methods on the aggregating objects do nothing more than just pass the arguments along to the PIA code, which then passes them along to the unmanaged object model. Events work in the analogous way; if your code listens to an event exposed by an aggregating object, the aggregating object listens to the event on the aggregated object on your behalf. When the event is raised by the aggregated object, the aggregating object's delegate is called, which then raises the aggregating object's event and calls your event handling delegate. All the host controls are hooked up in a similar manner as the host items. For instance, if you have a NamedRange host control member of a worksheet, the aggregating Worksheet object itself creates an aggregating NamedRange object. The first time you call a method on the host control, the aggregating class obtains the underlying "real" object from Excel and passes the call along. This might seem like a whole lot of rigmarole to go through just to add new functionality to the Word and Excel object models. The key benefit that this system of aggregates affords is that each host item class in each project can be customized. One spreadsheet can have an InvoiceSheet class with a CustomerNameRange property, another can have a MedicalHistorySheet class with a CholesterolLevelChart property, and so on. In short, VSTO extends the Word and Excel object models by aggregating the unmanaged object models with managed objects. VSTO enables developers to further customize and extend some of those objectsthose representing the workbook, worksheet, chart sheet, and documentthrough subclassing. Obtaining the Aggregated Object Much of the time, the foregoing details about how the aggregation model works are just that: implementation details. Whether the host item "is a" worksheet or merely "looks like" one seems to be an academic point. However, in some rare scenarios, it does matter. Word's and Excel's object models were not written with the expectation that managed aggregates would implement their interfaces; when you call a method that takes a range, Excel expects that you are passing it a real range, not an aggregated range that acts like a range. For instance, suppose you have a customized worksheet with two host controls: a NamedRange member called InvoiceTotals and a Chart object called InvoiceChart. You might want to write code something like this snippet: this.InvoiceChart.SetSourceData(this.InvoiceTotals, Excel.XlRowCol.xlColumns); This code will not compile because the SetSourceData method on the chart aggregate must be passed an object that implements the Range interface. It looks like at runtime the InvoiceChart aggregate will pass InvoiceTotals, an aggregated range, to the "real" aggregated chart. But Excel will expect that the object passed to SetSourceData is a range, whereas in fact it is the VSTO aggregate; it merely looks like an Excel range. When just calling methods, reading or writing properties, and listening to events, the aggregate is more or less transparent; you can just use the object as though it really were the thing it is aggregating. If for any reason you need to pass the aggregate to an Excel object model method that requires the real Excel object, you can obtain the real Excel object via the InnerObject property. The code above will compile and work properly if you rewrite it to look like this: this.InvoiceChart.SetSourceData(this.InvoiceTotals.InnerObject, Excel.XlRowCol.xlColumns); Aggregation and Windows Forms Controls If you drag and drop a Windows Forms button onto a worksheet or document, the button control is also aggregated. However, Windows Forms controls are aggregated slightly differently than the NamedRange, Bookmark, ListObject, and other controls built in to Word and Excel. There are two relevant differences between Windows Forms controls and Office's controls. First, Windows Forms controls are implemented by extensible managed classes, unlike the unmanaged Office controls, which only expose interfaces in their PIAs. Second, Word and Excel controls inherently know how they are situated in relation to their containing document or worksheet; non-Office controls on a worksheet do not know that they are in a worksheet. Word and Excel overcome the second difference by aggregating an extender onto a control sited on a document or worksheet. Word's extender implements the properties, methods, and events of the _OLEControl interface that can be found in the Word PIA (but as with other aggregated VSTO controls, the type definition does not actually claim to implement the _OLEControl interface). It has five methods, all of which take no arguments and return no result: Activate, Copy, Cut, Delete, and Select. It also exposes floating-point read-write properties Top, Left, Height, and Width, string properties Name and AltHTML, and an Automation object. Excel's extender implements the properties, methods, and events of the _OLEObject interface that can be found in the Excel PIA. When you drop a button onto a document or worksheet, the project system adds a new field to the host item class, but types it as Microsoft.Office.Tools.Word.-Controls.Button or Excel.Controls.Button, respectively. Because the underlying System.Windows.Forms.Button class is extensible, this time the aggregate actually is a subclass of the Windows Forms control. However, it still must aggregate the unmanaged extender interface provided by Word or Excel. As a further convenience, the managed objects representing embedded Windows Forms controls also have read-only Right and Bottom properties aggregated onto them. Improving C# Interoperability The Word and Excel object models were originally designed with VBA in mind. Unfortunately, there are some language features which VBA and VB.NET support but C# does not, such as parameterized properties. In VBA, you could do something like this: Set Up = ThisWorkbook.Names.Item("MyRange").RefersToRange.End(xlUp) End is a read-only property that takes an argument, but C# does not support passing arguments to property getters; arguments can only be passed to methods and indexers in C#. Therefore, the PIA exposes the property getter as a function. You could talk to the PIA like this in C#: Up = ThisWorkbook.Names.Item("MyRange", System.Type.Missing, System.Type.Missing).RefersToRange.get_End( Microsoft.Office.Interop.Excel.XlDirection.xlUp) Note that the PIA interface calls out that this is a "getter" function; for writable properties there would be a corresponding set_ function that took the parameters and new value as arguments. C# does, however, support something similar to parameterized property accessors: parameterized indexers. In a VSTO project with a host item or host item control that has been extended, you can accomplish the same task like this: Up = MyRange.End[Excel.XlDirection.xlUp]; The get_End accessor function is implemented by the aggregate, so you can still use it if you want to. However, because it is no longer necessary and there is a more elegant solution, it is not displayed in the IntelliSense drop-down. In several places in the VSTO object model, parameterized indexers have replaced parameterized properties; you will find a list of them all along with the rest of the changes to the object model at the end of this chapter. The "Tag" Field Every host item and host control now has a field called Tag, which can be set to any value. This field is entirely for you to use as you see fit; it is neither read nor written by any code other than your customization code. It is included because it is very common for developers to have auxiliary data associated with a particular control, but no field on the control itself in which to store the data. Having the object keep track of its own auxiliary data is, in many cases, more straightforward than building an external table mapping controls onto data. Event Model Improvements Like VBA, VSTO encourages an event-driven programming style. In traditional VBA programming, relatively few of the objects source events, which can make writing event-driven code cumbersome. For instance, in Word, the only way to detect when the user double-clicks a bookmark using the standard VBA object model is to declare an "events" class module with a member referring to the application: Public WithEvents WordApp As Word.Application Then sink the event and detect whether the clicked range overlaps the bookmark: Private Sub App_WindowBeforeDoubleClick(ByVal Sel As Selection, _ Cancel As Boolean) If Sel.Range.InRange(ThisDocument.Bookmarks(1).Range) Then MsgBox "Customer Clicked" End If End Sub And initialize the event module: Dim WordEvents As New WordEventsModule Sub InitializeEventHandlers Set WordEvents.WordApp = Word.Application End Sub And then add code that calls the initialization method. In short, this process requires a fair amount of work to detect when an application-level event refers to a specific document or control. The VSTO extensions to the Word and Excel object models were designed to mitigate difficulties in some tasks, such as sinking events on specific controls. In VSTO, the bookmark object itself sources events, so you can start listening to it as you would sink any other event: MyBookmark.BeforeDoubleClick += new ClickEventHandler(OnDoubleClick); In Chapter 2, you saw some of the new VSTO extensions to the view object model in action. You also read about events added by VSTO in Chapters 4, "Working with Excel Events," and 7, "Working with Word Events." At the end of this chapter, we describe all the additions to the event model in
https://flylib.com/books/en/2.53.1/vsto_extensions_to_word_and_excel_objects.html
CC-MAIN-2021-39
refinedweb
2,175
50.46
Multiprocessing in Python is a built-in package that allows the system to run multiple processes simultaneously. It will enable the breaking of applications into smaller threads that can run independently. The operating system can then allocate all these threads or processes to the processor to run them parallelly, thus improving the overall performance and efficiency. Why Use Multiprocessing In Python? Performing multiple operations for a single processor becomes challenging. As the number of processes keeps increasing, the processor will have to halt the current process and move to the next, to keep them going. Thus, it will have to interrupt each task, thereby hampering the performance. You can think of it as an employee in an organization tasked to perform jobs in multiple departments. If the employee has to manage the sales, accounts, and even the backend, he will have to stop sales when he is into accounts and vice versa. Suppose there are different employees, each to perform a specific task. It becomes simpler, right? That’s why multiprocessing in Python becomes essential. The smaller task threads act like different employees, making it easier to handle and manage various processes. A multiprocessing system can be represented as: - A system with more than a single central processor - A multi-core processor, i.e., a single computing unit with multiple independent core processing units In multiprocessing, the system can divide and assign tasks to different processors. What Is the Multiprocessing Module? The Python multiprocessing module provides multiple classes that allow us to build parallel programs to implement multiprocessing in Python. It offers an easy-to-use API for dividing processes between many processors, thereby fully leveraging multiprocessing. It overcomes the limitations of Global Interpreter Lock (GIL) by using sub-processes instead of threads. The primary classes of the Python multiprocessing module are: - Process - Queue - Lock Let’s use an example to better understand the use of the multiprocessing module in Python. Example - Using the Process Class to Implement Multiprocessing in Python # importing Python multiprocessing module import multiprocessing def prnt_cu(n): print("Cube: {}".format(n * n * n)) def prnt_squ(n): print("Square: {}".format(n * n)) if __name__ == "__main__": # creating multiple processes proc1 = multiprocessing.Process(target=prnt_squ, args=(5, )) proc2 = multiprocessing.Process(target=prnt_cu, args=(5, )) # Initiating process 1 proc1.start() # Initiating process 2 proc2.start() # Waiting until proc1 finishes proc1.join() # Waiting until proc2 finishes proc2.join() # Processes finished print("Both Processes Completed!") Output Now, it’s time to understand the above code and see how the multiprocessing module and process class help build parallel programs. - You first used the “import multiprocessing” command to import the module. - Next, you created the Process class objects: proc1 and proc2. The arguments passed in these objects were: - After the object construction, you must use the start() method to start the processes. - Lastly, you used the join() method to stop the current program’s execution until it executes the processes. Thus, the program will first run proc1 and proc2. It will then move back to the following statements of the running program. What Are Pipes Used For In Multiprocessing In Python? While using multiprocessing in Python, Pipes acts as the communication channel. Pipes are helpful when you want to initiate communication between multiple processes. They return two connection objects, one for each end of the Pipe, and use the send() & recv() methods to communicate. Let’s look at an example for a clear understanding. In the below code, you will use a Pipe to send some info from the child to the parent connection. import multiprocessing from multiprocessing import Process, Pipe def exm_function(c): c.send(['Hi! This is child info']) c.close() if __name__ == '__main__': par_c, chi_c = Pipe() mp1 = multiprocessing.Process(target=exm_function, args=(chi_c,)) mp1.start() print (par_c.recv() ) mp1.join() Output What Are the Queues Used For In Multiprocessing In Python? The Queue in Python is a data structure based on the FIFO (First-In-First-Out) concept. Like the Pipe, even a queue helps in communication between different processes in multiprocessing in Python. It provides the put() and get() methods to add and receive data from the queue. Here’s an example to show the use of queue for multiprocessing in Python. This code will create a function to check if a number is even or odd and insert it in the queue. You will then initiate the process and print the numbers. import multiprocessing def even_no(num, n): for i in num: if i % 2 == 0: n.put(i) if __name__ == "__main__": n = multiprocessing.Queue() p = multiprocessing.Process(target=even_no, args=(range(10), n)) p.start() p.join() while n: print(n.get()) Output What Are The Locks Used For In Multiprocessing In Python? The lock is used for locking the processes while using multiprocessing in Python. With its acquire() and release() methods, you can lock and resume processes. Thus, it allows you to execute specific tasks based on priority while stopping the other processes. The below code uses the lock mechanism on an ATM-like system. import multiprocessing # Withdrawal function def wthdrw(bal, lock): for _ in range(10000): lock.acquire() bal.value = bal.value - 1 lock.release() # Deposit function def dpst(bal, lock): for _ in range(10000): lock.acquire() bal.value = bal.value + 1 lock.release() def transact(): # initial balance bal = multiprocessing.Value('i', 100) # creating lock object lock = multiprocessing.Lock() # creating processes proc1 = multiprocessing.Process(target=wthdrw, args=(bal,lock)) proc2 = multiprocessing.Process(target=dpst, args=(bal,lock)) # starting processes proc1.start() proc2.start() # waiting for processes to finish proc1.join() proc2.join() # printing final balance print("Final balance = {}".format(bal.value)) if __name__ == "__main__": for _ in range(10): # performing transaction process transact() Output Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer Conclusion In this article, you learned about what is multiprocessing in Python and how to use it. The most practical use of multiprocessing is sharing CPU resources and ATM operations, as you have seen in the last example. Because of the ease it provides to manage multiple processes, the concept of multiprocessing in Python will undoubtedly get a lot of traction. It will be a wise move to get a firm understanding and hands-on practice. If you are a newbie and this is too hard to digest, you can begin learning the basics first. You can refer to Simplilearn’s Python Tutorial for Beginners to get acquainted with the basic Python concepts. Once you are clear with the basics, you can opt for our Online Python Certification Course to excel in Python development. Do you have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, ASAP. Happy learning!
https://www.simplilearn.com/tutorials/python-tutorial/multiprocessing-in-python?source=frs_recommended_resource_clicked
CC-MAIN-2021-49
refinedweb
1,137
50.73
Following my series from less known features of Modern C++. In Modern C++, you can also use and, or and not as boolean operators which means &&, || and ! respectively which is identical to languages like Python. They were in C but as macros but Modern C++ introduced them as keywords. #include <iostream> int main() { std::cout << true and true << std::endl; std::cout << true or false << std::endl; std::cout << not true << std::endl; return 0; } This is exactly identical to. #include <iostream> int main() { std::cout << true && true << std::endl; std::cout << true || false << std::endl; std::cout << !true << std::endl; return 0; } You can probably use any one of the styles depending on your codebase. Discussion Why would they even do that? Even if you are not a pedantic preacher of the only-one-way-to-do-it philosophy, there should at least be a reason for having multiple ways to do it... It's really disingenuous to label this "Modern" C++. It's a legacy C feature to support keyboards that didn't have all the previously accepted symbols (en.wikipedia.org/wiki/Digraphs_and...) or to make it more accessible for people with trouble inputting all the symbols. Heh, that's funny. One of my colleagues once went on an angry tirade about how "modern" C++ was ruining programming by allowing you to have a one statement if block without any surrounding curly braces... I didn't have the heart to tell him... Interesting, I knew about trigraphs but apparently they went away in C++17. andisn't strictly a C language feature: it's a language keyword in C++ but is a macro in C. Here's more docs on the and/ or/ notalternative operators: en.cppreference.com/w/cpp/language...
https://dev.to/delta456/modern-c-and-or-and-not-as-boolean-operators-2jgf
CC-MAIN-2020-29
refinedweb
294
65.32
adding existing domain as a child domain I have two companies at two different sites, separate domains, we will call them abc.local and cba.local. There is also a domain controller for each domain offsite in a data center. there are site to site vpn's from the Data center dc to the onsite dc for each domain. (all server 2008 r2 x64) These two companies are merging, there is currently a two way trust between them. They would like a single place to share files. Origianlly i wanted to setup DFS namespace and setup replication groups betweenthe offices. A DFS namespace can be setup and namespace servers setup in different domain .....only if they are inthe same forest. with this limitation i could have one office access the namespace across the wan, but no files would be replicated locally. Is it possible to setup a new domain and make the two offces child domains under the new parent domain under one happy forest? If yes can you point me the direction of any documentation to set it up. 5 Replies Jan 31, 2013 at 4:05 UTC This is possible, since you have a trust setup already between the forest, your almost halfway there. You need to use ADMT to migrate the domain over http:/ Jan 31, 2013 at 4:08 UTC In a sense it's not "moving" the domain, and the name can't be the same name as the old domain when you do it. It basically copies all of the pertinent information that it can, to the new domain that you create under the forest where you want it, and whatever name you want it. Jan 31, 2013 at 7:03 UTC A secondary goal, other than seamless file sharing would be not having to re setup user computer profiles. I did a quick scan of the article and it looks like an intra forest migration might work. It sounds like user profiles would stay the same. It would make the one domain a child of the other, correct? With there being mabye 10 people at the one office, I am wondering if it would be faster/easier to demote their DC and join it to the other domain. Jan 31, 2013 at 9:47 UTC You should use AD Sites not Child Domains, Site's are the correct way to implement different sites of the same company (Merge) depending on what services are running on each site you can place your Global Catalogue's strategically. Child Domain provide a degree of Administrative separation, unless you have a dying need for child domains i would use AD SItes. Jan 31, 2013 at 9:54 UTC Whatever will be simplest to get them in the same forest. This discussion has been inactive for over a year. You may get a better answer to your question by starting a new discussion.
http://community.spiceworks.com/topic/297532-adding-existing-domain-as-a-child-domain
CC-MAIN-2014-10
refinedweb
485
69.21
I posted a brief article with some preliminary benchmarks for the new merge/join infrastructure that I've built in pandas. I compared the performance with base::merge in R which, as various folks in the R community have pointed out, is fairly slow. There are a few other more intelligently-implemented functions available in CRAN, in particular plyr::join in plyr and the merge implemented for data.table objects in the data.table package. Lastly, Sean Taylor contributed a benchmark for SQLite3, by accounts the most widely deployed SQL engine. So anyway, here are the two benchmarks I'm interested in to get a sense of the large-ish data runtime of these algorithms: Many-to-one joins. In these benchmarks I have a 80,000 row table with 10 copies of 8,000 key pairs and an 8,000 row table with a single copy of another 8,000 key pairs, only 6,000 of which are found in the larger table. The result of a left join between these tables should have 80,000 rows, an inner join 60,000, and an outer join 82,000. Many-to-many joins. To keep things simple I use the same tables as above except the right able is the table above stacked on itself. You can do the combinatorics here, but the outer join between these two tables has 144,000 rows. Note: that plyr::joindoes not implement (or least I've been told to avoid) many-to-many joins so I only run the many-to-one benchmarks for that. I've normalized the results by the minimum runtime (which is pandas in all cases): UPDATE (1/6/2012): Jared Lander pointed out that data.table is capable of much faster left and right joins by using the syntax left[right] instead of merge(left, right, all.y=True). I updated the benchmarks below and added the right join results which shows data.table performing very admirably. SQLite3 Benchmarks A bit of care needs to be taken with SQLite3 benchmarks because the time to fetch the table from the database cursor (even though this is an in-memory SQLite database) is very significant. The performance as you can imagine is also quite different with and without indexes. Here is the basic code to insert the data into SQLite: import sqlite3 create_sql_indexes = False conn = sqlite3.connect(':memory:') conn.execute('create table left( key varchar(10), key2 varchar(10), value int);') conn.execute('create table right( key varchar(10), key2 varchar(10), value2 int);') conn.executemany('insert into left values (?, ?, ?)', zip(key, key2, left['value'])) conn.executemany('insert into right values (?, ?, ?)', zip(right['key'], right['key2'], right['value2'])) # Create Indices if create_sql_indexes: conn.execute('create index left_ix on left(key, key2)') conn.execute('create index right_ix on right(key, key2)') With no indexes, here is a comparison of just the SQL execution time vs. the total pandas execution time for the many-to-one case described above:
https://wesmckinney.com/blog/high-performance-database-joins-with-pandas-dataframe-more-benchmarks/
CC-MAIN-2021-31
refinedweb
497
63.7
BerMucBAN USER Simple Java private static String stripSpaces(String input) { String output = ""; if (input == null || input.isEmpty()) { return output; } for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == ' ' && i + 1 < input.length() && input.charAt(i+1) == ' ') { continue; } output += input.charAt(i); } return output; } Here a possible solution in Swift: func randomizer(num:Int, addNum: Int) -> Int { if num > 0 { var tmp:Int = NSDate.timeIntervalSinceReferenceDate().bridgeToObjectiveC().integerValue; return (tmp % num) + addNum; } else { return 0; } } // range 100-199 println(randomizer(100,100)); Here a solution in Swift: func shrinkString(var string: String, substrings: String[]) -> String { for substring in substrings { if !string.rangeOfString(substring).isEmpty { string = string.stringByReplacingOccurrencesOfString(substring, withString: "") string = shrinkString(string, substrings); } } return string; } jacobghester2, Accountant at ASAPInfosystemsPvtLtd I'm an artist at heart. I went from print design to web development and lots of server administration professionally ... Shastri Ji is well known hindi and tamil vashikaran specialist. He will give you effective and simple totke to control ... verarfurman, Problem Setter at Cerberus Capital I am Vera from Bullard USA, I am working as a Violin repairer in a Handyman company. My interest in ... kellydbrown23, Jr. Software Engineer at Auto NInja I live in College Park USA with my family, and my current job is clerk in Luria’s company. I ... brandysolsen, Area Sales Manager at AMD I am a Social butterflies who enjoy travel.Have fun doing this job and project an atmosphere that reflects Amazon ... mitadwilson, Scientific Officer at Cleartrip.com Hello, I am Mita from Dayton, I am working as a Systems programmer in Evans company, I have Experience of ... Huge collection of cheap ammo for Rifle, Handgun, Shotgun & Rimfire from top brands you are looking for. rubyperezj, Backend Developer at A9 My name is Ruby Perez and I live in Lyndonville and it would be my honor and privilege to be ... - BerMuc June 11, 2014
https://careercup.com/user?id=5679641926828032
CC-MAIN-2020-34
refinedweb
311
50.12
From: Paul A. Bristow (boost_at_[hidden]) Date: 2003-06-24 04:24:26 I have now been able to try your suggestions using MSVC 7.1 (rather than the undoubtedly better Intel 7.1 version (was KAI?)) cout << (float) math::pi etc are OK (though does this imply that every use of pi need to include the cast? This would NOT be at all popular because it would obscure the meaning of equations :-( With Kenniston's namespace one can simply declare "I'm only using doubles" with using namespace boost::math::double_constants; Alas, the area example doesn't work because MSVC 7.1 does not resolve the ambiguity in std::cout << "Area (float) = " << area(1.0F) << std::endl; // <<<< Note float argument Sletteboe_constants1.cpp(35) : error C2593: 'operator *' is ambiguous could be 'built-in C++ operator*(float, float)' or 'built-in C++ operator*(int, float)' or 'built-in C++ operator*(double, float)' or 'built-in C++ operator*(long double, float)' while trying to match the argument list '(const boost::math::pi_type, float)' Sletteboe_constants1.cpp(40) : see reference to function template instantiation 'T area<float>(T)' being compiled with [ T=float ] Should it? Suggestions?] | -----Original Message----- | From: boost-bounces_at_[hidden] | [mailto:boost-bounces_at_[hidden]]On Behalf Of Terje Slettebø | Sent: Sunday, June 22, 2003 2:33 AM | To: Boost mailing list | Subject: Re: [boost] Math Constants Formal Review | This is tested on Intel C++ 7.1, but it should work on most compilers, | especially if workarounds are applied, if needed. | | As shown, this works well with generic code, like the "area()" function. | | My question is: Is there any reason why it can't be done this simple? | | Note that there are no extra classes or functions needed. There's only the | class representing the constant, and the templated conversion operator, and | any specialisations of it. This should be trivial for a compiler to inline, | and should also be easy to examine with a debugger (an issue that also has | come up). | | This is very easy to extend with new constants and types. It's an open-ended | system. | | It uses macros for easy definition of constants and their values for | different types, for easy definition (just like Kenniston's and Daniel's | approach). | | The above addresses the presentation of the constants (their interface), as | identified by Paul as one of the primary objectives. What values that are | used in the definitions is orthogonal to this. | | | Regards, | | Terje | Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2003/06/49298.php
CC-MAIN-2019-18
refinedweb
427
56.96
Katherine J. Wu | The Atlantic 2021 by The Atlantic Monthly Group. All Rights Reserved.tag:theatlantic.com,2021:50-619137<p>The best immune systems thrive on a healthy dose of paranoia. The instant that defensive cells spot something unfamiliar in their midst—be it a living microbe or a harmless mote of schmutz—they will whip themselves into a frenzy, detonating microscopic bombs, sparking bouts of inflammation, even engaging in <a href="">some casual cannibalism</a> until they are certain that the threat has passed. This system is built on alarmism, but it very often pays off: Most of our encounters with pathogens end before we ever notice them.</p><p></p><p>The agents of immunity are so<i> </i>risk-averse that even the dread<i> </i>of facing off with a pathogen can sometimes prompt them to gird their little loins. Ashley Love, a biologist at the University of Connecticut, has seen this happen in birds. A few years ago, she stationed healthy canaries within eyeshot of sick ones, infected with a bacterium that left the birds sluggish and visibly unwell. The healthy canaries weren’t close enough to catch the infection themselves. But the mere sight of their symptomatic peers revved up their immune systems all the same, Love and her colleagues <a href="">report today in <i>Biology Letters</i></a>.</p><p></p><p>Love, who did the research as a graduate student at Oklahoma State University, had an inkling that the experiment would work before she did it. In 2010, the psychologist Mark Schaller, at the University of British Columbia, and his colleagues <a href="">described a similar reaction in humans</a> looking through photos of people who were sneezing or covered in rashes. The study subjects’ immune cells then reacted aggressively when exposed to bits of bacteria, a hint that the pictures had somehow whipped the body into fighting form, Schaller told me.</p><p>That 2010 study, Love told me, “sort of blew my mind,” because it didn’t follow the typical trajectory of the immune system <i>reacting</i> to an ongoing assault. Instead, the cells were internalizing visual cues and buttressing themselves <i>preemptively</i>—raising shields against an attack that hadn’t yet happened, and perhaps never would. It was what you might call bystander immunity, and it was totally bizarre.</p><p></p><p>Love decided to try her own version in domestic canaries, among the many bird species susceptible to a pathogen called <i>Mycoplasma gallisepticum. </i>She infected 10 canaries with <i>Mycoplasma, </i>then placed them in sight of microbe-free birds. In parallel, she had two other cadres of healthy canaries scope each other out, as a symptomless point of comparison.</p><p></p><p>Throughout the 24-day experiment, the uninfected canaries acted as most songbirds do, feeding, chirping, and bopping cheerily around their cages. But about a week in, the birds dosed with <i>Mycoplasma </i>became mopey and lethargic, and developed a nasty form of pink eye. “I could approach the cage and just pick them up,” Love told me. (Some <i>Mycoplasma</i> species can cause disease in humans; this one doesn’t.)</p><p></p> <a href="">how they would in the presence of <i>Mycoplasma</i></a>, Love said. The birds’ blood was also rife with so-called complement molecules, which can shred bacterial cells, or flag them for other types of destruction.</p><p></p><p.</p><p></p><p>To confirm that idea, Love would have needed to expose the onlooker birds to <i>Mycoplasma </i.</p><p></p> <i>negative</i> for the witness, wasting precious bodily resources or unnecessarily damaging healthy tissues. Heterophils and complement molecules also comprise just a small subset of the immune system’s arsenal, much more of which would be marshaled into quelling a <i>Mycoplasma </i>invasion. Letícia Soares, a disease ecologist at Western University who wasn’t involved in the study, told me she wished she’d been able to see how well the observer birds’ immune responses simulate what happens in infected birds who eventually recover.</p><p></p><p.</p><p></p><p>The connective tissue that links visual cues to immune activation is still scientifically foggy. At first, “it all seems kind of magical,” Schaller, the University of British Columbia psychologist, told me. But it’s also sensible (literally) for animals to glean information from their environment and <a href="">react accordingly</a>. “We’re stimulus-response devices,” he said. “We perceive something in some way, and our body responds.” Several experts told me that they wouldn’t be surprised if nonvisual signals—including the sounds, sensations, or even <a href="">smells</a> of a <a href="">stranger’s sickness</a>—could clue animals into the risks of infection as well. Love told me she hopes to figure out whether animals can tune their immune responses to the severity of the disease symptoms they see.</p><p></p><p>The paper speaks to the strange appeal of visible disease, says Cécile Sarabian, an expert in sickness behaviors at the Kyoto University Primate Research Institute who wasn’t involved in the study. The signs and symptoms of infection are often a pain for the individual who experiences them. But they also “alert others, and prepare other potential hosts,” she told me.</p><p></p><p>Spotting symptoms alone isn’t good enough. In the past year and a half, SARS-CoV-2 has benefited from its ability to spread silently from person to person. Humans have also taken a multitude of other measures—masking, distancing, and the like—to keep the coronavirus at bay, acts of avoidance that Schaller says count as a kind of <a href="">behavioral immunity</a>. Still, Schaller and others think it’s interesting to consider what sorts of infections count as truly “asymptomatic.” Even if an infected person isn’t feeling outright ill, they might be beaming out slight signals that betray their status, and influencing those around them. “We’re pretty sensitive to some pretty subtle stuff,” Schaller said. “It could be that we are able to pick up on other people’s sicknesses, even if those people are not yet aware.”</p><p></p><p>If an infection is to persist in a population long term, it must become communal; perhaps the experience of it is as well, in ways we don’t yet appreciate. Soares, who’s had <a href="">long</a> <a href="">COVID</a> for <a href="">more than a year</a>,.</p><p></p>Katherine J. Wu Cells Are More Paranoid Than We Thought2021-06-08T19:00:00-04:002021-06-08T19:00:56-04:00Healthy birds watched their friends get sick with a bacterial disease. Their immune cells freaked out.tag:theatlantic.com,2021:50-619112<p>Any diagnostic test worth its salt has precision on its side. It can pinpoint the presence of <i>this </i>condition, but not <i>that </i>one; it can, when used for an infectious disease, distinguish between microbes that look very much the same.</p><p>For most of the pandemic, that exactness has been a major asset for the <a href="">hundreds of tests</a> that detect SARS-CoV-2. But the discerning nature of most tests has also opened up a weak point for the coronavirus to exploit. With the virus mutating into <a href="">new and concerning variants</a>, a few of the tests designed to recognize its original iteration are now getting duped. What was once a singular target has split itself off into many, many bull’s-eyes, each a little different from the next, and we’re having trouble taking aim.</p><p>This isn’t yet a crisis, and perhaps it never will be. Most<i> </i <a href="">continue to rejigger its genes</a>, which means that test manufacturers will need to closely track the virus’s movements and tailor their products to follow it. More than a year out from the time when experts first got eyes on the virus, tests are in need of a touch-up.</p><hr class="c-section-divider">.</p><p><a href="">According to the FDA</a>, almost none of these tests is actually pinging back variant-related<i> </i>false negatives, with perhaps the exception of the <a href="">Accula</a>, made by Mesa Biotech. A <a href="">document</a> <a href="">two</a> <a href="">more</a> recently identified by researchers may soon join the list of tests whose detective powers are weakened, but not obliterated, by variants.)</p><p data-<i>[<a href="">Read: Fewer Americans are getting COVID-19 tests</a>]</i></p><p>One test on the FDA’s list, Thermo Fisher Scientific’s <a href="">TaqPath</a>, targets a segment of the S coronavirus gene (which encodes the spike protein). A snippet of that segment is missing from several variants of concern—including the very contagious <a href="">Alpha</a> (B.1.1.7), the <a href="">dominant form of the coronavirus in the U.S.</a>—rendering S <a href="">effectively invisible</a> to the TaqPath. But most molecular tests, including the TaqPath, have a <a href="">de facto insurance policy</a>: They generally scan the genome for <i>multiple</i> RNA segments at a time—<a href="">two, three, sometimes more</a>—making it nearly impossible for the virus to elude the test’s scrutiny entirely. The TaqPath, for instance, detects two additional gene segments outside of S, both of which are intact in Alpha<i>, </i>and will still spit out a positive result.</p><p>A slightly different set of issues is now playing out with antigen tests—a type of rapid test that can usually be done outside a lab—which detect coronavirus <i>proteins</i>..</p><p>In a recent <a href="">paper</a>, not yet published in a scientific journal, Greninger and his colleagues found that a common nucleocapsid-hunting antigen test called the <a href="">Sofia</a>, made by Quidel, might not recognize a very small fraction of coronavirus variants, incorrectly marking infected samples as virus-free. Greninger told me that the test-confounding mutation is present in <a href="">less than 0.5 percent of SARS-CoV-2 genomes</a> cataloged to date, so the test itself is fine for now. But the mistake it’s making isn’t necessarily an anomaly. Another recent <a href="">study</a>, also not yet peer-reviewed, claims a similar issue with a test called the <a href="">PanBio</a>, made by Abbott. The PanBio isn’t available in the U.S., but it’s similar to another test made by Abbott, the <a href="">BinaxNOW</a>, that has been authorized by the FDA.</p><p>.”)</p><p>Even if they’re rare, false negatives due to variants can have a ripple effect on our ability to contain the virus. Antigen tests have already stirred controversy because they <a href="">aren’t as good as molecular tests at identifying infections</a>, especially in people who <a href="">don’t have symptoms or in whom the virus is somewhat scarce</a>..</p><p data-<i>[<a href="">Read: The black hole in America’s COVID-19 data</a>]</i></p><i> </i <a href="">tests</a> that can tell Alpha<i> </i>from Beta<i> </i>(B.1.351) and Gamma<i> </i>(P.1). A few companies, including Thermo Fisher, are <a href="">marketing products</a> that can do the same.</p><p <i>new</i> variants that might otherwise be mistaken for others or escape notice entirely. Testing and genome surveillance are inextricably linked: We can’t find variants if we’re not looking for them; we can’t design tests compatible with variants that we’re not aware of.</p><hr class="c-section-divider"><p>The arms race between virus and test isn’t a new story. The mutational capers of SARS-CoV-2 are actually pretty mild compared with the wild rides pathogens have taken us on before. The rise of the H1N1 flu virus in 2009 <a href="">bamboozled several tests</a>,.”</p><p>More tests are already on their way, and molecular- and antigen-test manufacturers are intent on designing them to be long-lasting. For one, they’re focusing on bits of the virus’s genome that are less likely to mutate. Now that <a href="">millions of SARS-CoV-2 genomes</a> <a href="">have been sequenced</a>, <a href="">listed by the FDA as “impacted by SARS-CoV-2 mutations,”</a> is adding a third target to its product to make it a bit more variant-proof, according to David Persing, the company’s chief medical and technology officer.</p><p data-<i>[<a href="">Read: One vaccine to rule them all</a>]</i></p><p>Still, it’s hard to ignore the game of whack-a-mole we’ve locked ourselves into. No test can be <i>completely </i <i>after </i>they’ve invaded the body—forces their design to be reactionary. The virus barrels on; tests give chase.</p><p.</p>Katherine J. Wu Kon / Getty / Katie Martin / The AtlanticCoronavirus Variants Have Nowhere to Hide2021-06-07T07:00:00-04:002021-06-07T09:25:02-04:00Our tests will need frequent touch-ups to make sure that no mutations get past them.tag:theatlantic.com,2021:50-619067<div class="oembed" data- <p>The trunk of an African elephant is an evolutionary marvel. Clocking in at weights well over 200 pounds, it ripples with thousands of individual muscles that help the superlong schnoz <a href="">lift barbells</a>, <a href="">uproot trees</a>, and <a href="">fling bothersome lions into the air</a>.</p> <p.</p> <p>And yet a union between chip and trunk is not as impossible as it might seem. Andrew Schulz, an engineer at Georgia Tech, and his colleagues have <a href="">caught such an improbable pair on camera</a>, reconciling the absurd imbalance between them, and described it in a <a href="">paper</a> published today in the <i>Journal of the Royal Society Interface</i>. When offered a tortilla chip, they found, an elephant will use its trunk to deftly suction<i> </i>the salty treat into its grip. The chip stays intact (at least until it’s deposited into the elephant’s mouth); in the video, you can hear the researchers cheer.</p> <p>Elephants don’t encounter many chips in the wild, or even that often in captivity. But that’s not necessarily the point. The tortilla-chip experiment, along with several others conducted by Schulz’s team, helps illustrate the biomechanical properties of trunks, which vacuum up foods the animals can’t otherwise easily reach. African-elephant noses, the team found, can inhale air at speeds of more than 335 miles per hour, faster than a Bugatti, faster than most bullet trains, faster than a dive-bombing peregrine falcon. Elephants are kind of, sort of, accomplishing a type of <a href="">airbending</a>—using air as a tool to manipulate their surroundings, a rare skill among land animals. “It’s a way for an animal to move food toward its body without even touching it,” Rita Mehta, an evolutionary biologist at UC Santa Cruz who wasn’t involved in the study, told me.</p> <p><iframe frameborder="0" height="351" src="" width="568"></iframe></p> <p>Researchers were tabulating the talents of trunks long before their encounters with tortilla chips were captured on camera. (A quick note: The paper refers to its corn-based experimental fodder as “tortilla chips,” but technically they were small tostadas, according to Schulz.) Trunks are über-extended noses that allow elephants to breathe, call, fight, grasp, sense, and smell, all with the same piece of anatomy. They’re tipped with fingers deft enough to <a href="">pinch individual blades of grass</a>; the olfactory machinery they contain is so sensitive that it <a href="">detects TNT</a> better than most bomb-sniffing dogs. The <a href="">Elephant Ethogram</a>, an archive of African-elephant behaviors hosted by the organization Elephant Voices, documents no fewer than 250 separate trunk-related actions that elephants engage in, from signaling to <a href="">snorkeling</a> to <a href="">pinching parents’ genitals to get their attention</a>. “The trunk is a magnificent apparatus,” Joyce Poole, a co-founder and co-director of Elephant Voices, told me. Elephant trunks were already one of the strangest and most accomplished limbs in the annals of biology; the calculations from Schulz’s team now confirm that they also suck real hard.</p> <p>Some of that suckage isn’t necessarily news. Researchers have known for many years that elephants’ tubelike snoots can siphon up water, then deposit it into the mouth or spray it across the back. And at least as far back as the 1800s, naturalists such as Charles Darwin were suggesting that elephants could blow air to push objects just beyond their reach; a 2016 study confirmed that the animals could use the tactic to <a href="">nudge food around their enclosures</a>. But the mechanical <i>how </i>of these behaviors, Schulz told me, has remained mostly mysterious. And although there had been some chatter about air going out<i>, </i>few people were asking how it came <i>in. </i></p> <p>The Georgia Tech team decided to investigate with the help of keepers at Zoo Atlanta and a now-38-year-old African elephant named Kelly. When offered frustratingly flat objects such as chips, Kelly reliably used suction to get an easier grip on them. But she was judicious with other snacks, and would vacuum up small cubes of rutabaga only when there were too many for her to easily pluck them up one by one with her fingers.</p> <p><iframe frameborder="0" height="351" src="" width="568"></iframe></p> <p>To measure the strength of Kelly’s inhales, the researchers filmed her slurping up a slurry of chia seeds mixed into water. By tracking the movements of the seeds frame by frame, Schulz and his colleagues could visualize how quickly water was entering her nostrils. Kelly’s six-foot-long trunk, they found, could expand to comfortably fit more than 5.5 liters of liquid at once, enough to account for every drop of blood in an average adult human’s body. Kelly sucked up that volume in about a second and a half.</p> <p>The researchers crunched the numbers to approximate how air, rather than water, would flow into the same structure. Their estimate of 150 meters per second, or 335 miles per hour, is about 30 times as fast as a typical <a href="">human</a> <a href="">sneeze</a>. Elephant air expulsion, Schulz suspects, might be even faster, though he’s not sure by how much. (It would also, he pointed out, produce a <i>lot </i>of snot.)</p> <p>Poole, who wasn’t involved in the study, said that food suctioning might be somewhat uncommon in the wild, where snuffing up vegetation off the ground could ferry all manner of dirt and crud into the airway as well. (Consider also just how difficult it would be to pick a six-foot-long nose.) But elephants are capable<i> </i>of executing this strategy, and it probably gets more play in zoos, where their meals are carefully cut and portioned. “All these little bits are given to them in captivity, for convenience,” Caitlin O’Connell, an elephant researcher at Harvard who wasn’t involved in the study, told me.</p> <p>Schulz’s team argues that the sucking shenanigans of elephant trunks count as a form of suction feeding—a technique that many fish use to vacuum up their meals. Some of the experts I talked with were less sure. An originalist interpretation of suction feeding might hold that an animal must suck and swallow with the same orifice, as many fish do: They can expand the highly mobile bones in their skull, generating a pressure gradient that draws water—and the stuff living in it—into their waiting mouth in as little as six milliseconds. Suction feeding is also a staple among certain marine mammals, such as <a href="">whales</a> and and <a href="">seals</a>, and, arguably, all animals that <a href="">suckle from their mother</a> after birth. Even <a href="">some seabirds</a> seem to have some liquid-vacuuming prowess.</p> <p>Elephants and their trunks are outliers. Their noses are middlemen, and suctioners of convenience; elephants are lucky enough to do most of their feeding on land, where simply reaching out and grabbing a morsel of food is easy. (Animals that hunt or forage in the sticky, viscous fluid that is water often end up pushing their meals <i>away </i>when they move toward them.) The elephant approach to suctioning is “definitely different than everything else,” Mehta said.</p> <p>But these unconventional quirks might make trunks all the more remarkable. And the exclusive club of suck doesn’t have to be anatomically strict: Ariel Camp, a fish suction-feeding expert at the University of Liverpool who wasn’t involved in the study, points out that some of the world’s most impressive suction feeders are carnivorous plants called <a href="">bladderworts</a>, which suction their prey into traps at blistering speeds, even though they don’t share the vertebrate body plan.</p> <p>Schulz, who said he personally “cannot eat a tortilla chip without breaking it,” isn’t agonizing over the differences. (He admitted that he has yet to try suctioning up a chip with his nose.) His next goal is to more thoroughly map the internal structure of the elephant trunk, and to put more mathematical weight behind all that the appendage can accomplish. “It’s a muscular multi-tool,” Schulz said. “It pushes all of the extremes of what we understand animals to be able to do.”</p> </div>Katherine J. Wu / GettyOne More Reason to Admire Elephant Trunks2021-06-01T19:00:00-04:002021-06-02T16:03:46-04:00New research confirms that elephant trunks don’t just blow—they can also suck.tag:theatlantic.com,2021:50-619027<p>With <a href="">165 million people and counting</a> inoculated in the United States, vaccines have, at long last, tamped the pandemic’s blaze down to a relative smolder in this part of the world. But the protection that vaccines offer is more like a coat of flame retardant than an impenetrable firewall. SARS-CoV-2 can, very rarely, still set up shop in people who are <a href="">more than two weeks out from their last COVID-19 shot</a>.</p><p>These rare breakthroughs, <a href="">as I’ve written before</a>,.</p><p>Breakthroughs can offer a unique wellspring of data. Ferreting them out will help researchers confirm the effectiveness of COVID-19 vaccines, detect coronavirus <a href="">variants</a> that could evade our immune defenses, and estimate when we might need <a href="">our next round of shots</a>.</p><p>But testing too <i>often </i>can sometimes cause as much damage as testing too <i>little. </i>The nation has yet to settle into its late-pandemic testing patterns, and decide which types of breakthroughs warrant the most attention. On May 1, after weeks of reporting <a href="">all post-vaccination infections, regardless of whether they were linked to symptoms</a>, the CDC narrowed its focus to cases involving hospitalization or death—a move that prioritizes investigations of “cases that have the most public-health significance,” Tom Clark, who leads the agency’s vaccine-evaluation unit, told me.</p><p></p>.</p><hr class="c-section-divider"><p>This early in our relationship with SARS-CoV-2, the perks of testing for breakthrough cases are clear.</p><p></p><p, <a href="">particularly in people who weren’t well represented in the vaccine makers’ studies</a>..</p><p></p><p>It’s <i>because </i>of breakthroughs—and how few of them we’re finding—that we know that the vaccines are <a href="">performing</a> <a href="">well</a> <a href="">in</a> a <a href="">broad range of people</a>, knocking back <a href="">both disease and infection</a>, even as the number of <a href="">coronavirus variants</a> carrying antibody-dodging mutations continues to rise. By the end of April, when more than 100 million Americans had finished their shots, the CDC had received <a href="">documentation of 10,262 post-vaccination infections</a> of all severities, according to a report published this week. (That’s a definite undercount of the true number, but breakthroughs are still a tiny fraction of the <a href=""><i>millions </i>of SARS-CoV-2 infections that have been reported to the agency since the vaccine rollout began</a>.) Breakthroughs could also eventually clue researchers in to how well the vaccines thwart very rare or late-appearing consequences of infection, including <a href="">long COVID</a>. And the future of COVID-19 booster shots hinges on carefully archiving breakthroughs. Clusters of these post-vaccination infections compelled public-health officials to alter the dosing schedules for <a href="">measles</a> and <a href="">chicken-pox</a> vaccines, for example.</p><p></p><p>A subset of the test samples collected from breakthrough cases can also be <a href="">sequenced</a>, as part of the search for unusual mutations in a pathogen’s genome. Genetic surveillance has, for months, been the pandemic’s bellwether for variants; more than 1.6 million SARS-CoV-2 genomes from around the world have been cataloged in an <a href="">ever-growing database</a>. Of those 10,000 breakthrough cases, 555—roughly 5 percent—came with sequencing data. Although that’s not a highly representative sample, dozens of those sequences turned up as coronavirus <a href="">variants</a> that can bypass certain immune defenders.</p><p></p><p>Across the country, the news on variants and vaccines seems mixed, experts told me. One recent <a href="">study</a>,.</p><hr class="c-section-divider"><p>If a variant <i>were </i.</p><p></p><b>. </b>“Now states are scrambling, trying to sort it out.” Some states, such as <a href="">Illinois</a> and <a href="">Tennessee</a>, quickly followed the CDC’s lead. Others are hesitant. For now, “we’re not changing what we’ll be sequencing,” Myra Kunas, the director of Minnesota’s state public-health laboratory, told me.</p><p></p><p>Some of the same vaccine attributes that make breakthroughs rare also make them difficult to unearth and sequence. When sparks of virus <i>do </i>take hold in a vaccinated person, their fire still seems to <a href="">burn extremely low</a>—though infected, these people simply don’t carry much virus. That’s great news from a clinical standpoint, but not for someone hoping to identify a virus variant<b>. </b>Proper sequencing requires rounds of shredding and scanning pieces of the coronavirus’s genome, then cobbling them back together into a readable format. Sometimes, the samples from vaccinated people are barely enough to prompt a positive from a test, let alone yield a decent sequence.</p><p></p><p <i>all</i> post-vaccination infections in this way isn’t a reasonable expectation.</p><p></p><p>Fervor for testing has also waned nationwide since the vaccine rollout began. Most vaccinated people don’t need to regularly seek out tests, especially if they’re not feeling sick. The CDC has <a href="">loosened guidelines about quarantine</a> <a href="">cutting</a> <a href="">back</a> on <a href="">screening</a> for the immunized.</p><p></p><p>Programs like these might have otherwise revealed some breakthroughs. But hunting for these cases has other drawbacks. Earlier this month, the New York Yankees, a team that <a href="">continued to regularly test</a> its fully vaccinated personnel, <a href="">recently reported nine positive tests</a>—most connected to asymptomatic cases. Many experts framed the detection of mostly symptomless infections as proof that the shots were doing their job, but worried about rote reliance on testing as a security blanket, and wondered about <a href="">the possibility</a> of <a href="">false positives</a>. Vaccinated people are so unlikely to catch the virus that administering a bunch of tests wastes resources and <a href="">increases the likelihood for errors</a>,?”</p><p></p><p>Vaccinated people in high-risk settings, such as <a href="">health-care workers</a> and long-term-care-facility residents, might have more reason to test going forward, especially in areas where caseloads are high. Collecting data from these populations will lend itself to studies of real-world vaccine effectiveness—an endeavor <a href="">the CDC is still engaged in</a>. But “there’s no recommendation that you get tested randomly” if you’re vaccinated, says Kristen Ehresmann, the director of infectious-disease epidemiology, prevention, and control at Minnesota’s Department of Health.</p><p></p><p.</p><hr class="c-section-divider"> <i>caused </i>by COVID-19, but simply involved a positive post-vaccination test.)</p><p></p><p>“With viruses, and with any infectious disease, there’s no end to how much work you can do,” Robin Patel, the director of the Infectious Diseases Research Laboratory at Mayo Clinic, told me. “You have to stop somewhere.”</p><p></p><p>The agency’s decision to shunt attention away from quieter breakthroughs could also help <i>normalize</i> <a href="">remind our dormant immune cells to stay on guard</a>.</p><p></p><p.</p><p></p><p>I asked Meyer when she thinks her job will get easier. She laughed. “If you figure that out,” she said, “can you let us know?”</p><p></p><p <a href="">done for the flu</a>, with labs regularly soliciting specimens from around the nation and sequencing them<b>.</b> We will approach a reality in which our relationship with the virus settles into a tense but sustainable truce, in which small fires flare up every once in a while. We’ll be able to see many of them coming, because we’ll know where to look.</p><p></p><p></p><p></p>Katherine J. Wu Maree Williams / GettyWhat Breakthrough Infections Can Tell Us2021-05-27T15:20:34-04:002021-05-27T16:52:00-04:00Post-vaccination infections reveal how effective vaccines are—and which variants are sneaking past our defenses.tag:theatlantic.com,2021:50-618993<p>In many, many ways, fish of the species <i>Brienomyrus brachyistius </i<i>. </i>“It’s even simpler than Morse code,” Bruce Carlson, a biologist at Washington University in St. Louis who studies <i>Brienomyrus</i> fish, told me.</p><p>In at least one significant way, though, fish of the species <i>Brienomyrus brachyistius</i> do speak a little bit like Barack Obama. When they want to send an important message …</p><p>They stop, just for a moment.</p><p>Those gaps tend to occur in very particular patterns, right before fishy phrases and sentences with “high-information content” about property, say, or courtship, Carlson said. Electric fish have, like the former president, <a href="">mastered the art of the dramatic pause</a>—a rhetorical trick that can help listeners cue in more strongly to what speakers have to say next, Carlson and his colleagues report in a <a href="">study</a> published today in <i>Current Biology</i>.</p><p>“Fish can’t yell,” Kate Allen, a neuroscientist at Johns Hopkins University who wasn’t involved in the study, told me. But titrating the amount of time that passes between the signals they send might be the next best thing. (<i>Brienomyrus</i>,<i> </i>she said, seems to be deploying a version of the <a href="">polarizing “emphasis clap”</a> that’s found its way into so many tweets.)</p><p>These pauses might be especially useful for fish with such a limited repertoire of oratory tools. Each individual fish says just one word—its own signature electric wave, as distinctive as the way a person says their name: <i>Barack. </i>That voiciness alone can reveal the speaker’s age, sex, or even social status. But one special wave is all a fish gets, and it looks roughly the same every time: <i>Barack Barack Barack</i>. (A <i>Barack</i> fish cannot, sadly, even say <i>Michelle.</i>) To communicate a more context-dependent message, such as “Get away from me”<i> </i>or “Let’s mate,”<i> </i>fish have to tinker with the frequency at which the waves pulse out: <i>Barack---Barack--BarackBarack--Barack---Barack </i>says something different than <i>Barack----Barack--Barack-BarackBarackBarackBarack.</i> It’s pretty typical for several <i>Barack</i>s<i> </i>to <a href="">cluster together in rapid succession</a>; the fish can’t speak in phrases or sentences, per se, but these wildly intricate trains come pretty close.</p><p>You can listen here to get a sense of these patterns, which have been passed into an audio speaker:</p><p><iframe allow="autoplay" frameborder="no" height="166" scrolling="no" src="" width="100%"></iframe></p><div style=="" style="color: #cccccc; text-decoration: none;" target="_blank" title="TheAtlantic">TheAtlantic</a> · <a href="" style="color: #cccccc; text-decoration: none;" target="_blank" title="The Sounds of Electric Fish - Courtesy of Bruce Carlson">The Sounds of Electric Fish - Courtesy of Bruce Carlson</a></div><p>From the listener’s perspective, the onslaught of <i>Barack</i>s means receiving and processing the exact same signal over and over and over. A few years ago, Tsunehiko Kohashi, then a postdoctoral fellow in Carlson’s lab, was sifting through old data when he noticed that this glut of identical electric waves seemed to be exhausting<i> </i>the listener’s brain cells. When these cells operate at full capacity, they’ll spark out a “message-received”<i> </i>signal (<i>!!!!!</i>) upon registering an inbound wave. But the longer the cells are stimulated with the same signals, the less enthusiastic their responses become (<i>!!</i>). The weary cells, Kohashi soon discovered, need a sensory palate cleanser—a pause of about a second or more—to recover and reset. “That allows the animal to better understand and interpret the signal,” Kory Evans, a fish biologist at Rice University who wasn’t involved in the study, told me.</p><p>Kohashi and his colleagues decided to confirm the findings by observing a fresh batch of live laboratory fish. They set up pairs of animals in adjacent tanks and linked the watery chambers with electrodes so that the fish could discourse. Then, they selectively muted segments of each fish’s speech for two seconds apiece. The team found that when speaker fish spewed signals at a blistering rate, the listeners’ noggins quickly zonked out. A carefully placed pause, however, whipped their brains back into shape—and prompted the listeners to send out their own burst of electric signals in return (<i>MichelleMichelleMichelle</i>), a sort of “Okay, okay, you’ve got my attention” response.</p><p>Fish intentions are difficult to assess. (The electric fish did not respond intelligibly to requests for comment.) But the <i>Brienomyrus </i>species does seem to be actively punctuating its conversations with pauses, the team found—the piscine equivalent of “on purpose.” When the researchers pasted electrodes onto fish tanks to record the conversations within, they found that the animals paused more frequently while cohabiting with a roommate than when they were housed alone. The positions of the pauses also seemed to precede big bursts of speech—signals that Carlson suspects were helping fish court each other, or stake out a piece of real estate. A pause, he said, is a message in and of itself, a silent way of saying “It’s time to take me seriously.”</p><hr class="c-section-divider"><p>Plugging a pause into human language is, for the most part, pretty trivial—a matter of taking a breath or a beat, or a keystroke or two that slightly lengthens a page. Short silences pepper monologues and dialogues, even in writing (hello, em dashes, semicolons, ellipses). But for an electric fish, the difference between</p><p><i>Barack---Barack--BarackBarack--Barack---Barack</i></p><p><i>Barack----Barack--Barack-BarackBarackBarackBarack</i></p><p>and</p><p><i>Barack---Barack--BarackBarack--Barack---Barack</i></p><p><i>…</i></p><p><i>…</i></p><p><i>…</i></p><p><i>…</i></p><p><i>Barack----Barack--Barack-BarackBarackBarackBarack</i></p><p>can be much more fraught.</p><p>Electric fish use signals to interact not just with one another but with the watery world around them. The waves they produce help them sense their surroundings, a process called electrolocation. To maintain their bearings, fish will hum out signals almost constantly; when they pause, “it’s like they’re closing their eyes for a period of time,” Allen, of Johns Hopkins, told me. Verbal hiatuses, so to speak, don’t happen willy-nilly.</p><p>Scientists have long known that electric fish that lose fights will deliberately go mum for many seconds at a time and slink away in silence, like an attempt to evade detection by their electrically sensitive rivals. The findings from Carlson’s team represent a new kind of pause—a shorter one that can keep a dialogue going, rather than grind it to a halt. “This is a pause that’s attention-grabbing,” Sophie Picq, an electric-fish biologist at Michigan State University who wasn’t involved in the study, told me.</p><p>Humans have yet to fully crack the fish’s electric<i> </i>code. Still unclear are the contexts in which <i>Brienomyrus</i> most often uses pauses, or how these conversational gaps shake out when animals are gabbing in groups. Researchers also can’t be certain how deep the parallels between fish and human go. <a href="">Among people</a>, pauses can be moving and memorable. They create contrast between signal and noise; they capture focus and build anticipation—the perfect strategy for a politician teeing up sound bites. When <a href="">people hear pauses</a>, studies have shown, they better internalize the information that comes next. But pauses can also reflect nervousness or confusion, or an utter lack of knowledge—the manifestation of a person who’s desperately grasping for words. Pauses can be ambiguous or manipulative, leaving the listener on tenterhooks. They can … perhaps … be—much like adverbs, adjectives, and florid language—really, truly, egregiously overused; no one wants to wait forever for a simple statement, conveying a single and uncomplicated idea, to just come to a close.</p><p>It’s hard to imagine an electric fish cavorting with this much complexity. But years of research have taught Kohashi that <i>Brienomyrus </i>is a lot more human than some might like to think. When the fish communicate, whether through pulses or body language, they’re constantly asserting themselves. (Electric animals are, unsurprisingly, keen on showing one another who’s in charge.)<i> </i>Kohashi has seen fish be selfish and arrogant. He’s seen fish be bullied, and get downright depressed. The fish clearly make one another feel. “Some fish are,” he said, pausing, “assholes.”</p><p>But Kohashi thinks the fish have plenty to teach us about decorum as well, and the importance of hitting the reset button from time to time. (Since performing these experiments, he thinks he’s become a better public speaker.) The babble of <i>Brienomyrus </i>also delightfully claps back against the common misconception that fish are just “simple-minded creatures that blub about in bowls,” Evans, of Rice, told me. “They’re far more complex than we give them credit for.”</p>Katherine J. Wu Lewis / IT Catalysts, Inc.Can Electric Fish Talk Like Obama?2021-05-26T11:00:00-04:002021-05-26T13:37:15-04:00Yes, they can.tag:theatlantic.com,2021:50-618954<p.</p><p></p><p>In recent months, though, it’s become clear that the coronavirus is a <a href="">slippery, shape-shifting foe</a>.</p><p></p><p>To be clear, setting our sights on spike has served us well. The vaccines we’ve built against the coronavirus continue to be astoundingly effective shields against disease largely <em>because <.</p><p data-<i>[<a href="">Read: Why the coronavirus has been so successful</a>]</i></p><p>Vaccines that teach the immune system to recognize the spike will, in all likelihood, be vaccines that teach the immune system to act effectively, and <em>fast—</em>quickly enough, perhaps, to waylay an invading virus before it even has a chance to break into cells. This process, called neutralization, is carried out by specific types of antibodies, and it holds a <a href="">venerated status in the field of vaccinology</a>, David Martinez, a vaccine expert at the University of North Carolina at Chapel Hill, told me. Once a vaccinated person produces <a href="">enough neutralizing antibodies</a>, so the theory goes, they need little else to stave off sickness. And the spike protein appears to be <a href="">top-notch antibody bait</a>. “Spike is here to stay—it is absolutely necessary,” Smita Iyer, an immunologist at UC Davis, told me.</p><p></p> <a href="">now appeared in several countries</a>, including South Africa, Brazil, India, and the United States; more will certainly follow.</p><p data-<i>[<a href="">Read: One vaccine to rule them all.</a>]</i></p><p>None of our current vaccines has yet been completely nullified by a coronavirus variant, and vaccine makers such as <a href="">Moderna</a> and <a href="">Pfizer</a>.</p><p></p><p>There’s another solution. We could simply give the immune system more hunks of the virus to target. Several vaccines containing whole coronavirus particles—which have been chemically incapacitated so they can’t cause true infections—have <a href="">already been authorized</a>, including <a href="">a couple made by the Chinese company Sinopharm</a>. Whole-virus vaccines, however, can be a pain to produce, and have delivered mixed results in the past.</p><p></p><p><a href="">Several</a> <a href="">companies</a>, <a href="">two proteins that the coronavirus keeps in its interior</a>: one called nucleocapsid, which helps the pathogen package its genetic material, and another called ORF3a, which helps newly formed coronavirus particles mosey out of cells.</p><p data-<i>[<a href="">Read: Post-vaccine inertia is real</a>]</i></p><p.</p><p></p><p>T cells are already an essential part of the immune response our bodies mount to our current vaccines, because they react very strongly to spike.<strong> </strong>But Andrew Allen, Gritstone’s CEO, told me that the T cells in our bodies could be doing <em>more, </em>if given the chance. T cells in people who have been infected by the coronavirus can home in on <a href="">many parts of the virus</a> that aren’t packaged into most vaccines. Some of these immune targets, encouragingly, have mutated more slowly than spike, raising hopes of protection that’s both potent and long-lived. Early studies suggest that new coronavirus variants that bamboozle certain antibodies are still <a href="">nowhere near stumping the body’s diverse cavalry of T cells</a>.</p><p data-<i>[<a href="">Read: The body is far from helpless against coronavirus variants.</a>]</i></p><p><a href=".">Strong and versatile T-cell responses</a> may, on occasion, be powerful enough to <a href="">fend off the coronavirus</a> largely on their own. That could make spike-plus vaccines a huge boon for people who are on drugs <a href="">that blunt the ability of immune cells called B cells to produce antibodies</a>,—<a href="">curbed the severity of COVID-19 in laboratory hamsters and mice</a>. The rodents still got sick, “but the T cells are coming in and doing cleanup and preventing more disease from occurring,” he said.</p><p></p><p>The experiment was just proof of concept: A spike-free vaccine probably isn’t in the cards. But a shot that <em>includes </em>nucleocapsid makes for a pretty good insurance policy. What vaccine makers are after is “more layers of protection,” on top of the successful foundation the current vaccines have laid, Padmini Pillai, an immunologist at MIT, told me.</p><p></p><p>Another company, California-based <a href="">ImmunityBio</a>, plans to push the pro-T-cell paradigm even further. It has several versions of a <a href="">spike-nucleocapsid combo vaccine</a> <a href="">hunker down in and around the lungs</a>, where they can head off the virus immediately, something that <a href="">doesn’t happen as efficiently</a>.</p><p data-<i>[<a href="">Read: The J&J rescue mission starts with a choice</a>]</i></p><p>The spike-plus approach isn’t foolproof. Stuffing too many triggers into a vaccine could backfire if, for instance, an extraneous protein ended up <em>distracting </em>cells from spike. A poorly designed vaccine could also rev up T cells, but sap resources away from the B cells that might otherwise pump out neutralizing antibodies to stop the virus <em>before </em>it infects our tissues. “We need to make sure we have balance,” Pillai told me.</p><p></p><p>Worse still would be a vaccine candidate that inadvertently drives an overzealous immune response, burning up healthy tissues alongside the sick. There’s <a href="">even</a> <a href="">precedent</a> for this with the coronavirus that caused the 2002 SARS epidemic: Lab mice fared <em>worse </em>with the pathogen after taking a vaccine that included nucleocapsid. “I wouldn’t necessarily rule [nucleocapsid] out as a target yet,” Martinez, of UNC, told me. “But we have to proceed with a lot of caution.”</p><p></p><p.</p><p data-<i>[<a href="">Read: A simple rule of thumb for knowing when the pandemic is over</a>]</i></p><p>To accelerate that truce, our approaches to vaccination might need to become less <em>reactive—</em>responding to the virus after it alters itself—and more <em>proactive, </em>anticipating its next moves. Surveillance centers around the world have, in recent months, begun to sequence samples of the virus <a href="">at an accelerated pace</a>, cataloging every tweak in its genome, while researchers work to <a href="">model the ways viral genes and proteins might change</a>. SARS-CoV-2 has learned the strength of its costume changes and won’t be easy to put down. But perhaps our next round of vaccines will move us closer to the possibility of one-shot-fits-all.</p><p></p><p></p>Katherine J. Wu Zilinsky / Andriy Onufriyenko / Getty / Katie Martin / The AtlanticCOVID-19 Vaccine Makers Are Looking Beyond the Spike Protein2021-05-21T13:06:37-04:002021-05-21T14:34:59-04:00It’s time for more weapons in the shots-versus-virus arms race.tag:theatlantic.com,2021:50-618919<p.</p><p></p><p>They are Temnothorax ants, and their elixirs of life are the tapeworms that teem within their bellies—parasites that paradoxically prolong the life of their host at a strange and terrible cost.</p><p></p><p>A few such life-lengthening <a href="">partnerships</a> have been documented between microbes and insects such as <a href="">wasps</a>, <a href="">beetles</a>, and <a href="">mosquitoes</a>. <a href="">study</a> published today in <i>Royal Society Open Science</i>. No one is yet sure when the insects’ longevity tops out, but the answer is probably in excess of a decade, approaching or even matching that of ant queens, who can survive up to 20 years.</p><p></p><p>“Some other parasites do extend life spans,” Shelley Adamo, a parasite expert at Dalhousie University, in Nova Scotia, who was not involved in the study, told me. “But not like this.”</p><p></p>.</p><p></p>.</p><p data-<i>[<a href="">Read: How the zombie fungus takes over ants’ bodies to control their minds.</a>]</i></p><p.</p><p></p><p.</p><p></p><p.</p><p></p><p>Only when the researchers took a closer look did that tapestry begin to unravel. The <i>uninfected </i.</p><p data-<i>[<a href="">Read: Life is tough for teenage parasites.</a>]</i></p> <i>react; </i <a href="">puppeteering the entire society</a>.</p><p></p><p, <i>Oh, what’s going on?</i>”</p><p></p> <a href="">futz with the ant’s core physiology</a>, likely impacting their host’s hormones, <a href="">immune system</a>,.</p><p></p>.</p><p></p><p></p>Katherine J. Wu Foitzik / Johannes Gutenberg University MainzThe Never-Aging Ants With a Terrible Secret2021-05-18T19:00:00-04:002021-05-19T12:54:10-04:00A parasite gives its hosts the appearance of youth, and an unmatched social power in the colony.tag:theatlantic.com,2021:50-618915<figure><img alt="A cat in rear view" height="896" src="" width="672"> <figcaption class="credit">Arne Svenson, Stray #55</figcaption> </figure><p></p><p>To peer into the soul of a sea cucumber, don’t look to its face; it doesn’t have one. Gently turn that blobby body around, and gaze deep into its marvelous, multifunctional anus.</p><p></p><p>The sea cucumber's posterior is so much more than an exit hole for digestive waste. It is also a makeshift mouth that <a href="">gobbles up bits of algae</a>; a faux lung, latticed with tubes that <a href="">exchange gas with the surrounding water</a>; and a weapon that, in the presence of danger, can <a href="">launch a sticky, stringy web of internal organs</a> to entangle predators. It can even, on occasion, be a <a href="">home for shimmering pearlfish</a>, which wriggle inside the bum when it billows open to breathe. It would not be inaccurate to describe a sea cucumber as an extraordinary anus that just so happens to have a body around it. As Rebecca Helm, a jellyfish biologist at the University of North Carolina at Asheville, told me, “It is just a really great butt.”</p><p></p><p>But the sea cucumber’s anus does not receive the recognition it deserves. “The moment you say ‘anus,’ you can hear a pin drop in the room,” Helm said. Bodily taboos have turned anuses across the tree of life into cultural underdogs, and scientific ones too: Not many researchers vocally count themselves among the world’s anus enthusiasts, which, according to the proud few, creates a bit of a blind spot—one that keeps us from understanding a fundamental aspect of our own biology.</p><p></p><p>The appearance of the anus was <a href="">momentous in animal evolution</a>, turning a one-hole digestive sac into an open-ended tunnel. Creatures with an anus could physically segregate the acts of eating and defecating, reducing the risk of sullying a snack with scat; they no longer had to finish processing one meal before ingesting another, allowing their tubelike body to harvest more energy and balloon in size. Nowadays, anuses take many forms. Several animals, such as the sea cucumber, have morphed their out-hole into a Swiss Army knife of versatility; others thought that gastrointestinal back doors were so nice, they sprouted them at least twice. “There’s been a lot of evolutionary freedom to play around with that part of the body plan,” Armita Manafzadeh, a vertebrate morphology expert at Brown University, told me.</p><p></p><p>But anuses are also shrouded in scientific intrigue, and a fair bit of squabbling. Researchers <a href="">still hotly debate</a> how and when exactly the anus first arose, and the number of times the orifice was acquired or lost across different species. To tap into our origins, we’ll need to take a squarer look at our ends.</p><hr class="c-section-divider"><p>In the beginning, there was nothing. The back ends of our animal ancestors that swam the seas hundreds of millions of years ago were blank, relegating the entry and exit of all foodstuffs to a single, multipurpose hole. Evolutionary echoes of these life-forms still exist in corals, sea anemone, jellyfish, and a legion of marine worms whose digestive tract takes the form of a loose sac. These animals are serially monogamous with their meals, taking food in one glob at a time, then expelling the scraps through the same hole. (Contrary to what you might have read, not <a href="">everyone poops</a>.) These creatures’ guts operate much like parking lots, subject to strict vacancy quotas that restrict the flow of traffic.</p><p></p><p>The emergence of a back door transformed those parking lots into highways—the linear “through-guts” that dominate body plans today. Suddenly, animals had the luxury of downing multiple meals without needing to fuss with disposal in between; digestive tracts lengthened and regionalized, partitioning into chambers that could extract different nutrients and host their own communities of microbes. The compartmentalization made it easier for animals to get more out of their meals, Andreas Hejnol, a developmental biologist at the University of Bergen, in Norway, told me. With the lengthening and uncorking of the end of the gut, he said, many creatures grew into longer and larger body forms, and started to move in new ways. (It would take several more eons for true buttocks<i>—</i>the fleshy, fatty accoutrements that flank the anuses of some animals, such as humans—to evolve. Some researchers I talked with are comfortable using <i>butt</i> to mean any anal or anus-adjacent structure; others are purists, and consider the term strict shorthand for <i>buttocks</i> and <i>buttocks</i> alone.)</p><p></p><p>The benefits of bottoming out the gut are clear; how the back door was excavated isn’t. Soft, squishy, bone-free holes aren’t exactly fixtures of the fossil record, making just about <i>any </i>anus-heritage theory tough to prove. <a href="">One of the oldest hypotheses</a> holds that the anus and the mouth originated from the same solo opening, which elongated, then caved in at the center and split itself in two. The newly formed anus then moseyed to the animal’s posterior. Claus Nielsen, a developmental biologist at the Natural History Museum of Denmark, is a fan of this theory. It’s both reasonably parsimonious and evolutionarily equitable: In this scenario, neither the mouth nor the anus technically arose first; they emerged as perfect developmental twins.</p><p></p><p>Hejnol and others favor a different idea, in which the <a href="">mouth formally preceded the anus</a>, which spontaneously burst through the other end of the body. “It’s a secondary breakthrough,” Hejnol said. “The gut forms, then [makes] a connection to the outer world.” Punching an extra hole in the body is not so difficult: Some worms have managed the feat dozens of times over. One unusually aerated specimen, a type of polyclad flatworm, sports multiple anuses that speckle its backside like feces-spewing freckles. Two others, a pair of sponge parasites called <i>Syllis ramosa</i> and <i>Ramisyllis</i> <i>multicaudata,</i> will <a href="">twine their body</a> through host tissues like a tapestry of tree roots, with each tip terminating in its own proprietary butthole; they have hundreds, <a href="">perhaps thousands</a>, in total. (It’s not totally clear why these animals and others spawned an embarrassment of anuses, but in at least some cases, Hejnol thinks it’s a logical outcome of a branched digestive system, which can more easily transport nutrients to a body’s every nook and cranny.)</p><p></p><p>Hejnol and his colleagues are still amassing support for their hypothesis, but he said there’s already some argument against the hole-splitting idea: Animals don’t generally express the same <a href="">genes around their mouth and anus</a>, a knock against the notion that the two openings are cut from the same developmental cloth. A better backstory for the orifice, he said, might involve a body plan stolen from the reproductive tract, which already naturally terminates at the animalian posterior.</p><p></p><p>If that theory pans out, though, it won’t necessarily close the case on the anus’s evolutionary start. A cursory glance at the animal tree of life <a href="">might at first suggest</a> that anal openings appeared about 550 million years ago, around the time our own bloblike ancestors straightened out into tubes. But Hejnol and many others think that the anus was so useful that animals independently evolved it at least half a dozen times, perhaps many more, and not necessarily in the same way. This timeline has other snags: Some creatures have since lost their anal opening—and some might have made theirs even further back in history.</p><hr class="c-section-divider"><p>One of the largest potential wrinkles in the smooth anus narrative takes the shape of a comb jelly—a gelatinous animal that vaguely resembles a translucent Darth Vader helmet and is thought to be at least 700 million years old. As far back as the 1800s, scientists have been puzzling over comb jellies’ back end, and whether they were excreting formal feces from a set of strange-looking pores. More than a century passed before their acts of defecation were finally caught on camera, by the biologist William Browne of the University of Miami and his colleagues, who filmed one of the amorphous creatures taking a big fishy dump in the lab. When the clip debuted at a 2016 conference, “everyone in the hall audibly gasped,” Helm, who attended the lecture, told me. If comb jellies were pooping, that poop had to be coming out of some sort of rear hole. Perhaps, some said, the history of the anus ran far deeper in time than many had thought.</p><p></p><p>In the months after Browne’s team <a href="">published its findings</a>, scientists sparred repeatedly over their significance. Some hailed the discovery as revolutionary. But <a href="">others</a>, Hejnol among them, argued that the <a href="">now-infamous video</a> didn’t signify all that much dogmatic change, and may not be hard to reconcile with what’s long been known. Comb jellies probably cooked up their anuses independently of other animals, and happened upon a similar blueprint by chance; there’s no telling when exactly that might have occurred. Such a scenario would leave the chronology of our own<i> </i>anus, which emerged out of a different line of creatures at a separate point in time, intact.</p><p></p><p>The various possibilities aren’t easy to prove or disprove. Just as new apertures can rupture into being, useless ones can disappear, as seems to have been the case with <a href="">brittle stars</a> and <a href="">mites</a>, which stitched their ancestral anuses shut. Some <a href="">ambivalent</a> creatures might even gouge out <i>transient</i> anuses—holes that come and go on an as-needed basis. (A <a href="">2019 study</a> by the biologist Sidney Tamm suggested that some comb-jelly anuses could fall into this category of “sometimes-butts,” as Manafzadeh calls them.)</p><p></p><p>Many of the animals that have managed to keep some version of the anus embellished upon it, and now harbor an organ of immense extravagance. Turtles, like sea cucumbers, <a href="">breathe</a> through their butt. Young dragonflies suck water into theirs, then spew it out to <a href="">propel themselves forward</a>. Scorpions jettison their posterior when attacked from behind, evading capture but tragically <a href="">losing their ability to poop</a> (and eventually dying with their abdomen full of excrement). Lacewing larvae incapacitate termite prey with the <a href="">toxic flatulence</a> they emit from their end—“they literally KO their enemies with death farts,” Ainsley Seago, an entomologist at the Carnegie Museum of Natural History, told me.</p><p></p><p>Some of the most intriguing (and NSFW) back ends are all-purpose anus analogues called cloacae, which merge the terminal parts of the digestive, urinary, and reproductive tracts into a single opening—essentially an evacuation foyer for outbound feces, urine, eggs, and sperm. Cloacae are fixtures among birds, reptiles, and amphibians, and although they tend to get a bad rap, their internal architecture is actually quite sophisticated, Patricia Brennan, a cloaca expert at Mount Holyoke College, in Massachusetts, told me. They can also be quite convenient: When female birds mate with <a href="">unsatisfactory males</a>, they can simply <a href="">eject the subpar sperm</a> and begin the process anew. Cloacae have been around for so long, Hejnol added, that they could even represent the evolutionary bridge between the reproductive and digestive tracts that helped lead to some of the first anuses.</p><p></p><p>Still, cloacae come with risks: “You have all your digestive waste pretty much in direct contact with genitalia,” basically a gnarly infection just waiting to happen, Brennan said. Any live young who pass through the reproductive tract could also be imperiled by the proximity to poop-borne pathogens. Perhaps that’s why human anuses ventured off on their own.</p><hr class="c-section-divider"><p>Whatever the reason behind it, the partitioning that did away with the cloaca made human anuses, as Manafzadeh said, “completely boring.” As far as exit holes go, ours are standard-issue, capable of little more than extruding waste from the gut, with no frills to speak of.</p><p></p><p>The only redeeming quality of humans’ humdrum posterior hole is the feature we evolved to cushion it: our infamous buttocks, the most voluminous one documented to date, thanks to our bizarre tendency to strut around on our two primate legs. “Our bipedalism is obligate; it’s special; it’s the only way we get around,” Darcy Shapiro, an anthropologist, told me. That pattern of locomotion reshaped the pelvis, which in turn <a href="">reoriented our muscles</a>. The gluteus maximus—the hefty muscle that powers our ability to run and climb—swelled in lockstep, and blanketed itself in a cozy layer of fat that some scientists think serves as an energy reserve. Anuses aside, “our buttocks are the real innovation here,” Manafzadeh said.</p><p></p><p>Evolution blew the human butt out of proportion; our cultural norms quickly followed suit. We regard one another’s bums with lust, disgust, and guilty fascination. We shrink them, we sculpt them; we sexualize them. We <a href="">rap about them</a> with abandon. They, in return, make it much easier to sprint, but much harder to keep our rear ends clean. Our anus is a sheep dressed in a very fabulous wolf’s clothing, and we simply cannot deal.</p><p></p><p>Maybe that’s part of why humans are so often embarrassed of their posteriors, and, by extension, so many others. We even opt for <i>butt </i>as a euphemism for <i>anus</i> in casual conversation. Buttocks aren’t anuses, but they do cloak them, physically and perhaps figuratively. They obscure the idea that, from its very start, our digestive end has been a wonder. It cracked open our ancestors’ evolutionary path, and made our own existence possible. Maybe it’s time we made like a pearlfish, and got comfortable with what’s between those cheeks.</p>Katherine J. Wu SvensonThe Body’s Most Embarrassing Organ Is an Evolutionary Marvel2021-05-18T15:34:04-04:002021-05-19T11:41:30-04:00And yet we have very little idea where anuses come from.tag:theatlantic.com,2021:50-618858<p>On Monday morning, my partner laid a carry-on suitcase down on the floor, preparing to pack for his first post-vaccination trip to visit his parents. The moment he unzipped the bag, our cat Calvin promptly clambered inside.</p><p>A piece of me would like to think that Calvin was attempting to covertly join my partner on his trip, or perhaps thwart his inevitable attempt to spirit away. But I’m pretty sure #OccupyLuggage was less a heart-wrenching bid to tag along on a flight, and more a textbook example of a central scientific tenet: Cats are absolute suckers for boxes. And sinks, and vases, and grocery bags, and shoes, and Pringles cans, and the nooks and crannies between furniture and walls, and <a href="">just about any other space they deem cozy, confining, and swaddly</a>. (Cats, in case you were wondering, are a non-Newtonian liquid.) It’s the one thing about which our pointy-eared companions are not terribly picky: <a href="">If it fits, they sits</a>. And when they do, we humans can’t help but obsess over them.</p><p>Across the internet, felines’ beguiling fluidity and vaguely <a href="">psychopathic tendencies</a> spark a mixture of adulation and fear. Internet cats <a href="">vibe</a><a href="">, </a><a href="">LOL</a><a href="">, </a><a href="">lust after cheeseburgers</a>, and <a href="">vaguely resemble the Führer</a>. But it’s perhaps cat booty, and the spaces it parks itself in, that commands one of the most interesting and best publicized cultural memes of all. In April 2017, the phenomenon of cats moseying into boxes <a href="">took over Twitter</a> with the hashtag #CatSquare. And last week, a new <a href="">study</a> plumbing the depths of the cat-box phenomenon <a href="">went viral</a>, spawning thousands of likes and a stream of cat-stanning coverage. “I can’t believe how much attention this is getting,” Gabriella Smith, a behavioral biologist who led the study at Hunter College, told me. The allure of the boxed cat is perhaps a kind of entrapment in its own right—time out of <em>our </em>days, space taken up in <em>our </em>brains, while the felines are none the wiser. Humans have cohabited with cats for <a href="">thousands of years</a>. But we still can’t tell exactly who is domesticating whom.</p><p data-<i>[<a href="">Read: How cats used humans to conquer the world</a>]</i></p><p>For all the hype that box-cats command, scientists still don’t fully understand why felines both <a href="">big</a> and small so fervidly flop their keisters into anything and everything. And because cats are generally uncooperative study subjects, humans have had a hell of a time trying to suss it all out. “We can’t get into those little brains,” Mikel Delgado, a cat-behavior expert at Feline Minds, a cat-behavior consulting group, told me.</p><p>But at least a handful of theories have been tossed around. One posits that cats squish themselves into small spaces in search of solace. The world is a legitimately terrifying place, and grocery bags, drawers, and Amazon packages might be the best analogue to a cave that a house cat can find. “To a cat who’s nervous, a box represents shelter and safety,” Delgado said. Certain containers might also provide an insulating effect—a sort of crude cardboard hug. Some animal behaviorists think that being squeezed by enclosures might even remind cats of being <a href="">snuggled by their mothers and littermates</a>. Whatever the exact source of the comfort, having a hidey hole to retreat into seems to embolden cats: <a href="">One 2014 study</a> found that shelter cats who were gifted boxes in their new home were less stressed than their boxless housemates, and adjusted to their surroundings faster.</p><p>Another idea holds that cats aren’t retreating<em> into</em> receptacles, but strategizing <em>from </em>them like the <a href="">ruthless assassins</a> they are. “A box provides cover for a predator,” Delgado told me. Enclosed spaces, it turns out, are excellent vantage points from which to stalk and ambush prey, be it a mouse, a feathery wand toy, or a hapless human foot.</p><p>But none of these explanations can really account for why the mere <em>shape </em>of a box is so beguiling to some cats, who have been documented planting their butts down on mouse pads, letters, place mats, baking sheets, even rectangles demarcated by tape. Calvin is one of the weirdos for whom wall-lessness is no barrier: He will commandeer any vaguely polygonal object in sight. “It’s truly mystifying,” says Gita Gnanadesikan, an animal-behavior researcher at the University of Arizona who fosters undersocialized cats. “They have the whole floor to choose from, and they sit on a sheet of paper.”</p><p>It’s possible that cats are just extending their impulse from high-sided containers to shallow ones. They might even be gambling on the off chance that something that appears to be flat is deceptively deep, Delgado told me: “I’m going to err on the side of, <em>It’s a box</em>.” But another big driver, she said, is almost certainly the classic cat Achilles’ heel: curiosity. The appearance of an unfamiliar object is a surefire way to pique a cat’s interest, perhaps even enough for your pet to try to ensconce themselves in it.</p><p>Even a box without any true borders seems enough to trip cats’ shape-seeking senses. Smith tested this notion in her new study using the <a href="">Kanizsa-square illusion</a>—a visual trick in which strategically placed Pac-Man shapes evoke the perception of a square that’s not actually there. A small number of lab-trained cats had been <a href="">documented falling for the illusion before</a>, but Smith and her colleagues were keen on finding out whether pet felines would instinctively spring for the faux squares. Just 30 cats saw the experiment through to the end, most of whom expressed no interest in any floor shapes at all, illusory or not. But the felines who did were about as likely to sit on a Kanizsa square as a definitively outlined one. It’s a small group of cats, Gnanadesikan told me, but the trend the team observed isn’t terribly surprising, given that researchers already knew that cats covet flattened shapes with obvious perimeters. “This is just one more step in that direction,” she said.</p><p data-<i>[<a href="">Read: Why we think that cats are psychopaths</a>]</i></p><p>The last variable in the cat-box equation is, well, <em>us</em>. We’re the agents of chaos who built our environments to be amenable to cats. Cats sit in boxes because we provide them. Their videos go viral because we film them and share them. Some cats, left to their own devices, might not go gaga for boxes at all, if not for the fact that the humans they love lavish attention on them when they oblige. Perhaps we so desperately and doggedly document cats because we’re finally trying to tame them for good. But in the end, it’s almost always we humans who end up boxed in.</p><p>Something about the box behavior is almost certainly ancient and ingrained, written deep into the DNA that cats and humans share. A year into the pandemic, people can certainly relate to a craving for security and a desire to define our own boundaries, made up though they might sometimes be. But Delgado, who has made a career out of assessing cat behavior, says there’s merit to giving in to the mystery. Cats are, above all else, inscrutable creatures. In a particularly cheesy demonstration of the box phenomenon, one of Delgado’s own pet felines once plopped his tush into a pan of lasagna. (Warm? Check. Secure? No. Stealthy? Depends on where he was headed next.)</p><p>On Monday, after Calvin relinquished the suitcase, I tried a version of Smith’s Kanizsa experiment on him by cutting out four Pac-Man shapes and arranging them to hint at a square. Calvin strode confidently over to the configuration and parked his booty not inside the square, but <em>onto one of the illusory cutouts. </em>It was a moment enshrined in tragedy: He could not squeeze the entirety of his substantial rump into a three-quarter circle. In the end, he had fallen prey to the greatest deception of them all—the true size of his own bum.</p>Katherine J. Wu No Attention to That Cat Inside a Box2021-05-12T07:00:00-04:002021-05-12T12:11:27-04:00Seriously, stop it.tag:theatlantic.com,2021:50-618829<p>Had Johnson & Johnson’s COVID-19 vaccine been the first to get the FDA’s green light, it might have been hailed from the get-go for what it actually is: a scientific and technological marvel. It requires just one injection to confer full immunity—a boon for needlephobes and tough-to-reach populations who can’t easily access a second dose. It’s relatively cheap and has forgiving refrigeration requirements, making it a breeze to ship and store. And clinical trials showed that it’s a <a href="">knockout at guarding against hospitalization and death</a>, and <a href="">66 percent</a> effective at preventing moderate to severe cases of COVID-19, even amid the rise of antibody-dodging coronavirus variants. Johnson & Johnson accomplished all this in <a href="">less than a year</a>, granting the world a <a href="">safe and effective vaccine</a> crucial to hastening the pandemic’s eventual end.</p><p>That’s not how the J&J story played out.</p><p>By the time the authorization for the J&J vaccine went through, its mRNA-based counterparts, boasting clinical-trial efficacies of roughly 95 percent, had been in the field for months. Experts cautioned that differences in trial design and timing made the trio of vaccines impossible to accurately compare. But people pitted them against one another all the same, and time and time again, J&J appeared to lose out. The shot was labeled “<a href="">second class</a>” just as it surged into some of the disadvantaged populations hit hardest by the pandemic, raising discomfiting questions about whether the rich and privileged were hoarding the top-tier vaccines for themselves. Manufacturing snafus that <a href="">compromised millions of doses</a> quickly <a href="">added to the ire</a>. Last month’s <a href="">10-day hiatus</a>, when the CDC and FDA linked the vaccine to a rare and unusual blood-clotting disorder, dealt the shot yet another blow, <a href="">spurring a noticeable dip</a> in confidence in the J&J formulation.</p><p>As vaccine <a href="">supply starts to exceed demand</a>.</p><p>“I think it’s going to be hard to dig our way out,” Abraar Karan, an internal-medicine physician at Brigham and Women’s Hospital in Boston, told me.</p><p>What the J&J shot now faces is a sort of branded vaccine reluctance, <a href="">largely specific to one company’s product</a>. But the reputation of other vaccines also hinge on this one, experts told me, making rehabilitation key. An important first step, they said, might be giving people the option not to take it at all.</p><hr class="c-section-divider"><p>The Johnson & Johnson vaccine is not, experts repeatedly told me, a “worse” vaccine. Among the three options available to Americans—Pfizer-BioNTech, Moderna, and J&J—“the best vaccine you can get is the one you can get in your arm as soon as possible,” Chrissie Juliano, the executive director of the Big Cities Health Coalition, told me.</p><p></p><p>But J&J’s vaccine is <a href="">undeniably <i>different</i></a>, and its portability and convenience have <a href="">prompted health departments</a> to shuttle it into distinct populations, such as incarcerated individuals and people experiencing homelessness. In practice, this may be contributing to some unintended stratifications. David Lazer, a computer scientist at Northeastern University, told me his team has collected data showing that Black people are almost twice as likely to have received the J&J vaccine than white people, a disparity that doesn’t seem to be accounted for by preferences alone.</p><p></p><p>The hustle to allocate J&J immediately raised questions about whether America’s “problematic” vaccine was being earmarked for communities who are already distanced from medical resources and disproportionately pummeled by the virus, says Rachel Hardeman, a health-equity expert at the University of Minnesota. That stigma rapidly began to reinforce itself. In early March, Detroit Mayor Mike Duggan <a href="">rejected a batch</a> of J&J doses, saying that he wished to provide his residents with only “the best” vaccines. One physician told me that she’d received calls from reporters asking her to comment on J&J “being the poor person’s vaccine.” “There’s this undercurrent of tension,” Taison Bell, a critical-care physician at the University of Virginia Health System, told me. Many of the populations described as good J&J candidates “feel, rightfully so, that they receive second-rate care.”</p><p></p><p>This challenge, even if it has more to do with public perception than the vaccine’s intrinsic quality, can’t be dismissed: If people <i>believe </i>the vaccine is inferior, “that’s just as important as reality when people try to make healthy decisions for themselves,” Bell said.</p><p></p><p>Rehabilitating the Johnson & Johnson vaccine, experts told me, will require honest acknowledgments of its shortcomings, and validating, not combatting, people’s concerns. The rare blood clots that have been tied to the vaccine are serious, they said, but extraordinarily uncommon—a risk that’s far outweighed by the benefits of immunity.</p><p></p><p>The pause clearly did shake things up. Willie Bodrick II, a senior pastor of Twelfth Baptist Church in Boston, who’s heavily engaged in vaccine outreach to the city’s Black community, told me that, even before the pause, he had been fielding questions about the J&J shot for weeks. Some people who were unwilling to take a second dose, whether because of work constraints or wariness of side effects, saw the single injection as an ideal option; others “were really worried they would be receiving a subpar vaccine,” he said. Just days before the J&J halt, Bodrick felt he’d made progress. But news of the rare blood clots “resurfaced a hurdle I thought we were doing a good job moving beyond,” he said. Van Yu, a physician at the Center for Urban Community Services in New York City, where he is working to bring J&J vaccines to people experiencing homelessness, told me that, before the pause, many of his patients explicitly requested “the single-shot thing.” Now that J&J is available again, he and his colleagues have noticed that some people are citing the halt as a reason to turn it down.</p><p></p><p>The risk of clots has persuaded a few people to forgo vaccination entirely. Earl Potts, a 60-year-old IT-security specialist in Maryland, told me that he’s been skeptical of receiving <i>any </i>vaccines for decades. Although constant coaxing from family initially nudged him and his wife, Lori Renee Potts, toward getting J&J “because it was just one shot,” the pause reignited their fear that the vaccine-making process had been rushed. “I need more data; I need more time,” he said.</p><p></p><p>In many parts of the country, however, a simple message is still encouraging people to roll up their sleeves: Johnson & Johnson’s vaccine is “one of three excellent choices for protection against COVID-19,” as Hardeman puts it. In Columbus, Ohio, the health department’s on-site clinic vaccinates about 130 to 140 people each day, more than a third of whom are still queueing up for the one-and-done shot, Health Commissioner Mysheika Roberts told me. At another large site, where Pfizer and J&J doses are alternated throughout the week, “the J&J days are just as busy.”</p><p></p><p>Still, the pause prompted Roberts and her team to switch up their outreach tactics. Before the halt, city officials had brought only one brand at a time when inoculating off-site, prioritizing J&J allocations for the residents of homeless shelters and homebound individuals. When the vaccine returned with <a href="">a warning label</a>, “we thought it was appropriate to offer a choice,” Roberts told me, so no one felt cornered. Porting mRNA vaccines around requires a mobile freezer, which is “tedious to maintain,” she said, but removes a barrier. “Now when we go out to any location, it’s, ‘Which do you want, Pfizer or J&J?’”</p><hr class="c-section-divider"><p>This smorgasbord-of-shots strategy, experts told me, could be key to the next stage of the American rollout, especially as vaccine delivery moves past inoculating enthusiasts, and starts pointedly targeting those with reservations. The idea is to meet the unimmunized where they are, both literally and figuratively. And sending different brands of vaccines to different communities isn’t going to work in a culture set on believing one shot is “worse” than the rest. Biased allocation also puts the vaccination campaign as a whole at risk, Bell told me: If something should derail a shot that’s been doing most of the heavy lifting for certain demographics, those populations could be put in a sudden and irreversible bind.</p><p></p><p>“There should be no community without a choice of vaccines available to it,” Camara Phyllis Jones, a family physician and epidemiologist based in Atlanta, told me. “Giving options is another way of signaling we value people equally.” Sending J&J to places that lack the infrastructure to store and administer Moderna and Pfizer, for instance, might seem easier or more expedient in the short term. But it sidesteps the actual inequities at play, she said. And she doesn’t consider a lack of a freezer a good excuse for snubbing an mRNA vaccine: “Bring a freezer.”</p><p></p><p>An infrastructure of choice is now supporting the vaccine rollout among people experiencing homelessness in Los Angeles County, where <a href="">close to 70,000 people</a> are without stable housing. Heidi Behforouz, the medical director of Housing for Health, told me that her team has delivered doses to more than 3,500 people living in shelters or on the streets in the past three months. Most received the Moderna vaccine. The shot is cumbersome to trek into encampments, but with the help of specialized coolers and a vigilant follow-up protocol, “our second-dose return rate is about 93 percent,” she said. (The national average, meanwhile, is <a href="">about 92 percent</a>.) The team added J&J to its repertoire in early April, just days before the pause, and plans on offering both brands to all of its patients.</p><p></p><p>Two of Housing for Health’s recent recipients, Candy Acuña Rodriguez and Daniel Gilbert Trujillo, told me they gladly selected the one-and-done shots last Friday, after health workers assuaged their concerns about the pause. “Why would we want to have to go back and take two doses?” Rodriguez told me. “It should be all in one.”</p><p></p><p>None of these discussions are intended to erase the fact that the J&J vaccine may be well suited to, or preferred by, certain groups of people. Making <i>assumptions</i> about who those individuals are is what imperils a rollout. Roberts, in Columbus, told me that one of her region’s first outreach clinics brought J&J to a predominantly African American church, whose members rallied for the brand because it was familiar to them. “They said, ‘It’s a company we’ve heard of,’” she told me. In Los Angeles, however, Behforouz told me that some Black women regard J&J with reproach, citing concerns that the company had, in prior years, <a href="">aggressively marketed baby powder to their demographic</a>, even amid accusations of asbestos contamination. “It’s hard to predict which patients will want which vaccines,” Josh Banerjee, a physician working with the Street Medicine Program at USC, told me. As Yu, the New York physician, said: “It’s not like I can take a look at you and just guess.”</p><p></p><p>A big asterisk still hangs on this discussion. While millions of Americans quibble over their glut of three spectacular shots, residents of other countries are wrapped into a far worse conundrum: <a href="">a paucity of any vaccines at all</a>. High-income countries have already laid claim to <a href="">more than half the globe’s available doses</a>. As things stand, the rest of the world doesn’t have the luxury of choice. The U.S. has taken some limited steps in rectifying global disparities, by <a href="">shipping out doses of the AstraZeneca vaccine</a> (which resembles J&J in formulation but has yet to be cleared by American regulators), and moving toward <a href="">waiving intellectual-property protections</a> on the vaccines.</p><p></p><p>After failing to protect people for months, U.S. policies are finally reversing that trend with a <a href="">successful vaccination campaign</a>. The country now has another opportunity for global leadership: collectively opting back into a lifesaving shot. Choosing a J&J vaccine here doesn’t just benefit the person who receives it; it sends a reverberating message, Karan, of Brigham and Women’s, told me. “It highlights that perhaps this is not a worse vaccine at all.”</p>Katherine J. Wu Atlantic / Flavio Coelho / GettyThe J&J Rescue Mission Starts With a Choice2021-05-07T07:32:10-04:002021-05-07T12:59:02-04:00The reputation of all COVID-19 vaccines hinges on improving perceptions of the Johnson & Johnson shot.tag:theatlantic.com,2021:50-618798<p>In preparation for birth, some expectant human parents will build IKEA cribs or down prenatal vitamins. Female hoopoes douse their eggs in a pungent postcoital goo.</p><p>Shortly after laying their eggs, these delightfully zebra-striped birds will begin to paint the clutch with their beak. The pigment they use is made in-house—a brown, oily substance secreted by the uropygial gland, located at the base of the female’s tail. The eggshells start out cerulean, but with each coat of fluid, they transform into a mucked-up greenish-gray. Though subtle in appearance, the secretions are rank: Thanks to the bonanza of bacteria within, they reek like “a very strong and smelly cheese,” tinged with a putrid <em>je ne sais quoi</em>, Juan José Soler, a biologist at the Experimental Station of Arid Zones, in Spain, who has spent years working with the birds, told me. The first time Soler grew the malodorous microbes in the lab, they stank up his entire department.</p><p>Humans might recoil, but hoopoes don’t mind the stuff. They dollop it liberally into their eggs’ <a href="">sponge-like pores</a>, imbuing them with friendly microbes that protect the eventual hatchlings from pathogens—<a href="">a sort of living antibiotic</a>. The grodier and grayer the shell, the more likely the embryo within is to survive—a trend that male birds appear to have picked up on. In a <a href="">paper</a> published today in <em>Proceedings of the Royal Society B</em>, Soler and his colleagues at the University of Granada report that male hoopoes will bring more food to females tending less color-saturated eggs, an apparent attempt to invest in higher-quality chicks. It’s a heartwarming display of fatherhood, spurred on by the intergenerational application of a stinky cosmetic.</p><p>The behavior, which has never before been observed in birds, is as notable as it is bizarre. Most documented signals exchanged between male and female birds center on hot-to-trot bachelors flashing their most appealing traits, such as <a href="">dazzling plumage</a> or nest-building prowess, to coax lady birds into having sex with them. This newly discovered hoopoe trick turns that narrative on its head. Here, females are doing the advertising, after the copulatory deed has already been done. Sexual scrutiny, it seems, <a href="">doesn’t stop even after birds couple up</a>.</p><p>“Mate choice is a multistep process,” Sahas Barve, an evolutionary ecologist at the Smithsonian National Museum of Natural History, who wasn’t involved in the study, told me. “Just like humans, birds are constantly judging their partners to make sure they made the best choice.”</p><p>The strange amorous antics of hoopoes—named for their distinctive whooping cry—have long been known to science. During their unusually long breeding season, which roughly spans from February to July, males adopt a variety of strategies to woo potential mates, including seductive serenades and mid-flight beak jousts with competitors that can <a href="">leave losers blinded</a>. Eventually, males and females pair up, mostly monogamously, spawning about half a dozen eggs that mothers incubate while their mates ferry in insect meals. For a couple of weeks or so, the female sits tirelessly on her clutch; what the male brings her is pretty much the only food she gets.</p><p>Raising kids is hard, and after hoopoe chicks hatch, things can get a little nasty in the nest. Within days of emerging, nestlings learn to defend themselves by hoisting their butts skyward and <a href="">squirting liquid streams of feces</a> at potential intruders. Silvia Díaz Lora, one of the study’s authors, calls this behavior “shooting the shit,” and has learned to open hoopoe nest boxes only while armed with plastic bags to catch the initial spray.</p><p>What residue gets left behind isn’t always cleaned up by mom. But the females’ uropygial secretions might constitute a preemptive counteraction to domestic slovenliness. Within hours of laying their first eggs, the birds will start dribbling the fluids over the shells with their needlelike beaks, one painstaking droplet at a time. They repeat the process over days, until the shells’ pores have been filled and the eggs’ color is largely uniform. (Most birds use similar fluids to keep their feathers clean and healthy; the mom’s preened bellies might also help work the oils onto the eggs’ surface.) This labor of love buoys the eggs’ shot at successfully hatching. But not all shells will end up looking the same, inviting some sharp-eyed judgments from males.</p><p>In 2014, a team led by Soler and Manuel Martín Vivaldi, also of the University of Granada, found a link <a href="">between the color of uropygially painted eggs and antimicrobial activity</a>. Eggs that were grayer—that is, less intensely colored—boasted more beneficial bacteria, and were thus better guarded from infection. This pattern of microbial protection is hard to discern with crummy human eyes. But bird vision is keen, capable of distinguishing “very subtle differences between colors,” Javier Medel Hidalgo, a visual ecologist at the University of Exeter, in England, told me. The University of Granada scientists hypothesized that male hoopoes might be scoping out the eggs to see which ones were über-sanitized, and spent the next several years trying to prove it.</p><p>Their latest study, which followed the egg-smearing shenanigans of hoopoes tending 61 nests, seems to nail the connection. Díaz Lora and her colleagues waited for females to paint their newly laid eggs in a variety of hues, then switched the contents of several clutches to help ensure that the team was measuring males’ response to color alone. Having rejiggered the nests, they tracked how much food males trucked in to each female. As the researchers expected, grayer sets of eggs, on average, garnered more grub for mom. The differences in the amount of food weren’t massive, and an oddly colored clutch probably wouldn’t turn a doting father into a deadbeat dad. But during this crucial time, egg painting might help make life cushier for certain hoopoes.</p><p>As far as the researchers can tell, the color-coded system is an honest one: A female hoopoe can’t paint her eggs deceptively to cheat extra attention out of her mate. But egg color might act both as confirmation that the males’ choice of partner was a good one, and incentive to up their commitment further. If male hoopoes are actually cluing in to this signal, and acting accordingly, they’ll increase their chances of yielding big, successful clutches and passing on their genes, Julie Hagelin, an ornithologist and a behavioral ecologist at the University of Alaska Fairbanks, who wasn’t involved in the study, told me. In evolutionary terms, that’s akin to “winning the lottery.”</p><p><a href="">Other birds</a>, including <a href="">robins</a> and <a href="">starlings</a>, have been spotted <a href="">titrating</a> their <a href="">investment</a> in their kids <a href="">based on egg colors</a>. But egg complexion is usually an inborn trait; hoopoes are unusual in their ability to alter those hues after the shell’s taken shape. Martín Vivaldi told me that these findings mark the first time cosmetically colored eggs—wearing the avian equivalent of makeup—have been shown to goad males into stepping up their parenting game.</p><p>Given the unmistakable odor of hoopoe secretions, Hagelin told me she can’t help but wonder whether males are using their <a href=";2.full">sense of smell</a> to gauge antimicrobial potency as well. In Germany, it’s considered an insult to “<em>stinken wie ein Wiedehopf</em>”—to stink like a hoopoe. But every species has its own way of sniffing out a good mate.</p>Katherine J. Wu López / EyeEm / GettyA Bird’s Stinky Egg Is Actually a Humblebrag2021-05-04T19:00:00-04:002021-05-05T09:08:24-04:00Female hoopoes will paint their eggs with a brownish goo, in a bid for greater male attention.tag:theatlantic.com,2021:50-618751<p><small><em>Updated at 4:39 p.m. ET on April 29, 2021.</em></small></p><p>On my kitchen wall hangs a very small and very adorable cat calendar, with May 23 circled in Sharpie. It’s the day my Pfizer vaccine will, at long last, blossom into “<a href="">full vaccination</a>,” as <a href="">sanctioned by the CDC</a>. I’ll be able to <a href="">safely venture outdoors unmasked</a> and skip post-exposure quarantines. I’ll be able to schmooze with other immunized people indoors—perhaps even travel across state lines to visit family members I haven’t hugged since last spring.</p><p>In a matter of weeks, social life as I know it will crack open. And a pretty big part of me is <a href="">flat-out terrified</a> of what lies within that widening maw.</p><p>The world is a long way from vaccinating most of the human population. But here in the United States, <a href="">nearly a third of Americans<.</p><p>As <a href="">enthused as I am about immunity and vaccines</a>,, <a href="">Team Couch</a>,.</p><p> <a href="">massive flip</a> from a year of calls for near-ubiquitous shielding. Some people have already easily, <a href="">almost intuitively</a>, made the hop; others have <a href="">been there for months</a>. But plenty are having trouble toggling their brain from masking modesty to face-exhibiting exuberance.</p><p <i>weird</i>. Carter’s brain has intellectually squared his change in circumstance, he said, “but <i>knowing</i> something is safe and <i>feeling</i> safe are very different things”—a sentiment my colleague Amanda Mull <a href="">captured in the fall</a>.</p><p data-<i>[<a href="">Read: The difference between feeling safe and being safe</a>]</i></p><p>.</p><p.</p><p <i>more </i>people than usual this past year, and since his shots, which <a href="">took hold more than two months ago</a>, he has slipped almost seamlessly back into regular hangouts with his vaccinated friends and co-workers. They want me to join them as soon as I feel ready. I don’t know when that will be.</p><p data-<i>[<a href="">Read: Two competing impulses will drive post-pandemic social life</a>]</i></p><p>Experts told me that some of my molasses-y feelings can be traced back to just how much ambiguity we’re all being asked to deal with right now. Vaccinations are up, but <a href="">so are infection rates in many parts of the country</a>. The virus is still evolving and, on occasion, sprouting new versions of itself that <a href="">could continue to trouble us</a>..</p><p.</p><p>The risk calculus is especially tricky for people in mixed-vaccination households. <a href="">Most kids can’t yet get their shots</a>; certain people, such as those taking <a href="">immunosuppressive drugs</a>,.”</p><p data-<i>[<a href="">Read: We’re turning COVID-19 into a young person’s disease</a>]</i></p><p <i>some </i>control over. But local circumstances, including ongoing outbreaks and community vaccination rates, are also crucial to consider. Vaccines offer a layer of protection, but <a href="">aren’t impermeable</a>;.</p>.</p><p>Inevitably, people’s social expectations will misalign, and we’ll all need to exercise some patience, with ourselves and others, and clearly communicate our ground rules. “Say what you need and what you feel comfortable with,” Carter said. The activities we <i>can </i>safely do after vaccination should not necessarily be seen as the behaviors we <i>should </i>engage in; they are options, not obligations.</p><p.</p><p>The way to quash that fear is, of course, to flex the mingling muscles that have atrophied, and to remind myself that, as misanthropic as I can be, I <i>do </i.</p>.</p>Katherine J. Wu / The AtlanticPost-vaccination Inertia Is Real2021-04-29T12:44:26-04:002021-04-29T16:50:06-04:00Readjusting our ideas about what’s safe is going to take time.tag:theatlantic.com,2021:50-618731<p>In the summer of 2009, when Diana was three and a half years old, her health took a tumble. She began to run high fevers and vomit, and gain weight at a baffling pace. She made several trips to the emergency room over the course of two months before doctors finally diagnosed her with two rare, life-threatening conditions. The first, atypical hemolytic uremic syndrome, went after her kidneys, “and really messed them up,” Diana told me. The other, secondary hemophagocytic lymphohistiocytosis, sparked waves of inflammation, and walloped just about everything else. Diana spent months receiving chemotherapy, immunosuppression, and dialysis treatments, and about five years on a low-sodium, low-potassium diet. Sometime during the acute phase of Diana’s illness, Jo noticed that her daughter was holding her books too close to her face. Her optic nerve had been damaged, leaving her legally blind.</p><p>Diana is now 15, and her two conditions are in remission. (<i>The Atlantic</i> agreed to use only her and her mother’s first names to keep her health status private.) When the pandemic began, she was a straight-A student closing out her freshman year at a competitive magnet school in Manhattan. She was learning bass guitar to start a band with her friends. She used a white cane, took a fistful of medications morning and night, and was still cycling through the offices of about half a dozen doctors each year. But her medical visits and treatments had, for years, felt routine—background noise to her vibrant life.</p><p>Then the coronavirus crash-landed in New York, relegating Diana and her parents to their three-bedroom home in the Bronx. Last March, her classes went entirely virtual, lashing her to a computer for most of her day. By the beginning of April, Diana was dealing with a trio of new symptoms. Within minutes of turning on a screen, she’d be flooded with a wave of nausea—rocking, jolting sensations that made her feel like she was trapped in a zigzagging car. Pain would intermittently grip the sides of her head. And for about 80 percent of her day, she told me, her eyes ached as though “someone had been holding them open for a really long time,” making it nearly impossible to find and focus on the words and numbers that flashed in front of her.</p><p>She’s had little respite in the year since, as her doctors have struggled to diagnose her symptoms and rein them in. It’s a bad spot to be in, Diana told me, while her classes are still taught mostly on Zoom, and her social relationships are tethered by virtual lifelines. Early last fall, she decided to permanently log out of the Discord platform that her friends have been using to exchange messages, despite knowing how severely it would deepen her isolation. “I’ve missed half a year of inside jokes,” she told me. “It’s hell.”</p><p>The triad of neurological symptoms has been so consuming that the threat of the coronavirus itself blipped almost entirely off Diana’s radar. Despite following all precautions, she got a mild case of COVID-19 a couple of months ago—likely during a trip to the optometrist, and within days of both her parents’ second shots. She took the virus seriously, holing up in her room and leaving only to make masked trips to the bathroom. A year into battling her mystery illness, getting COVID-19 was “almost a relief,” she said. This time, at least, “I knew exactly what was wrong with me.”</p><hr class="c-section-divider"><p>Diana is, in some ways, an exceptional case. At 15, she is on the cusp of being eligible for Pfizer’s vaccine, but <a href="">can’t yet receive the lifesaving shot</a>. She is African American and Asian American—two groups that have experienced heightened discrimination in recent months—though she and her mom say race hasn’t been a huge factor in their pandemic experience. Her chronic health issues are an additional stressor; in the pandemic’s early months, Jo worried that her daughter’s weakened kidneys would <a href="">put her in the coronavirus’s crosshairs</a>. In a time of chaos, Diana has had to seek more medical care, not less, upping her exposure to others. The changes the global crisis has wrought seem to have broken the tenuous truce she had with her health.</p><p>“The quarantine, the isolation, the remote learning, that has been tragic—that has hit everybody,” Carolina Pombar, Diana’s pediatrician at Mount Sinai, told me. “In her case, I think it has been even worse.”</p><p>But within Diana’s pandemic experience are echoes of many others’. Diana is one of millions of Americans living with a chronic health condition—many of whom have had to chart their own course through the pandemic. She is also among the many young adults who have been driven into hiding at a time when social development matters most, and have felt their optimism and self-worth diminish as a result. Around the world, teenagers are reporting <a href="">serious</a> <a href="">declines</a> in mental health—an alarming trend experts have called a “crisis” that will likely ripple throughout the rest of adolescence and beyond. Much of COVID-19’s health fallout, they told me, will have nothing to do with the coronavirus itself, but everything to do with the pandemic it has caused.</p><p>The stress, solitude, and interminable parade of screens have certainly eroded Diana’s mental and physical well-being. Since last spring, when the headaches, nausea, and eye pain started, she’s roughly quadrupled her trips to doctors, in specialties as wide-ranging as neurology, ophthalmology, allergy, gastroenterology, and otolaryngology. Even after a year of tests and dozens of appointments, Diana’s doctors aren’t completely sure what’s at the root of her symptoms. The latest theory revolves around a potentially deviated septum, which not only would provide the relief of a clear diagnosis but could be fixed with a same-day surgery. But that could still turn out to be a dead end. “I excel at stumping the medical community,” Diana told me.</p><p>Remote learning—a hurdle that’s placed millions of children in front of screens this past year, and heightened their sense of solitude—likely bears at least some of the blame, a sort of collateral damage from the coronavirus. “It’s the fallout of the fallout,” as Diana puts it. She jokes darkly that she’s only now starting to hear her teachers and classmates complain openly of serious Zoom fatigue. “It took a year for this to catch up with y’all,” she said. “And it took me a month.”</p><p>If the symptoms don’t let up soon, Diana could be in for a few more rough months. Her school is back to hybrid learning, with students on campus two days a week. But most of Diana’s classroom time, whether in person or not, remains dependent on Zoom; she still spends more than six hours of her day staring at screens. Although prescription lenses have given her back a decent bit of her vision, scrolling dizzies her; moving text strains her eyes. When she scans over a page, not all the letters register right away. She often has to skim words and guess what they are based on the context. Science and math are even tougher: “I can’t look at the beginning of a number and guess what the rest is going to be,” she told me. “My nightmare is asking me to read, letter for letter, a paragraph of gibberish.”</p><p>Diana has to put far more energy into her education to maintain her top-notch GPA this year, and she’s exhausted all the time. She hasn’t always felt that the staff at her school understand the toll remote learning has taken on her health. She recalled telling one teacher that the lecture slides in class were too small to parse—a complaint that was met with a shrug: <i>Well, I can’t make them any bigger.</i></p><p>Even before the pandemic, Diana’s parents had repeatedly entertained the idea of moving her to a school that might make more accommodations for her visual impairments. But Diana loves her friends. She feels appropriately challenged by her classes; she has designs on a career in patent law. Now, the headaches, nausea, and fatigue are chipping away at her mental health. And many social interactions—the psychological bandages that once held her education together—have atrophied and disappeared. “If we’re not mostly in person, without having to be on Zoom, by next year,” Diana told me, “I think I’m going to lose it.”</p><hr class="c-section-divider"><p>Pombar, Diana’s pediatrician, told me that most of her patients have had an absolutely miserable year. Some kids have been <a href="">skipping routine immunizations</a>. Others have retreated into unhealthy habits, spending eight to 10 hours a day playing <a href="">video games</a>. Many, like Diana, have seen their mental health begin to crack and crumble; Pombar has had to send several patients <a href="">to the emergency room</a> as a last resort. A few of her patients gained 30 to 50 pounds in just a couple of months, and are now teetering on the edge of morbid obesity. “That’s something that will <a href="">kill kids silently</a>,” she said. “An obese child is a very sick child, but nobody’s talking about that.”</p><p>The power of being a pediatrician, Pombar told me, is being able to intervene early—to prevent health problems before they appear. That all fell to the wayside while the country descended into crisis. “It felt like you were at war and you had to choose which battles to fight,” Pombar said. “We’re now paying the price of all the things we pushed.”</p><p>The psychological losses are even harder to nail down. Allison Agwu, a pediatrician at Johns Hopkins, told me that it will take a long time for researchers to fully capture what America’s youth have lost to the pandemic. It’s been a year “devoid of normalcy,” she said, and adding up chaos during a crisis isn’t easy: “Which part is the virus? Which part is society?”</p><p>Diana, like many others, can’t pin her problems to a single inflection point. The entirety of the pandemic, this extended interruption to normalcy, is catching up to her in bursts.</p><p>An only child, Diana is close with her parents. Their home is spacious enough that it easily accommodated her brief isolation when she tested positive for the coronavirus at the end of February. She practiced her bass, binge-watched <i>Criminal Minds</i>, and took her meals on trays.</p><p>But even now that her tussle with the coronavirus is over, Diana doesn’t feel terribly liberated. Her world remains shrunken: Her home has, for more than a year, been her classroom, her entertainment center, her all-purpose nexus for existence. There is nowhere to escape to. She misses taking trips to Chinatown, and singing Disney songs with her friends. She misses sitting on her school’s campus with her classmates, filching grapes and crackers from their lunches.</p><p>Diana is young for her grade, so many of her friends have already signed up for their COVID-19 vaccines; she’s not yet old enough. “I am forever salty about this,” she told me. (The Pfizer-BioNTech vaccine, which is currently cleared for people age 16 and up, <a href="">will likely soon be green-lit for kids as young as 12</a>, almost certainly before Diana’s birthday in November.)</p><p>I asked Diana how long the pandemic will stay with her. Years, she predicted. The 13 months that COVID-19 has consumed represent most of her high-school experience so far, and nearly a tenth of her life. She’s still processing the emotional toll, she told me—the misery, the exhaustion, and what the past year will mean for her future. “I’m very tired,” she said. “I don’t know. It has genuinely messed me up.”</p>Katherine J. Wu ImagesThe Pandemic Made Her Sick, Even Before She Caught COVID-192021-04-27T14:41:12-04:002021-04-27T17:27:33-04:00Headaches, eye pain, nausea—her symptoms began last spring. No one knows exactly why, except that the pandemic is to blame.tag:theatlantic.com,2021:50-618726<p>Once, we had a wide world of socializing opportunities: crowded bars and intimate dinner parties, stadiums full of strangers and weddings full of everyone we loved most. The coronavirus pandemic made many of those things dangerous or impossible, and shrank our social worlds dramatically.</p><p>Now, as vaccination rates go up, the floodgates of social life are poised to reopen. But not everyone will want to use this newfound freedom in the same way. Even before the pandemic, introverts and extroverts disagreed on the optimal size and frequency of gatherings. <em>be</em>.</p><p data-<i>[<a href="">Read: 2 competing impulses will drive post-pandemic social life</a>]</i></p><p>To get a sense of how these personality types are planning to approach life after the pandemic, I had a chat with two of my colleagues—<a href="">Amanda Mull</a>, an extrovert, and <a href="">Katherine Wu</a>, an introvert.</p><p>We talked about what they are and aren’t looking forward to, how they would design the new normal if it were up to them, and how we can be kind to our friends who aren’t ’verted the same way we are.</p><p>This conversation has been edited for length and clarity.</p><hr class="c-section-divider"><p><strong>Julie Beck:</strong> If we had an imaginary scale of introversion and extroversion with <em>extreme introvert</em> being negative 10, and <em>extreme extrovert</em> being positive 10, and zero being true neutral, where would you place yourselves along the scale? And why?</p><p><strong>Katie Wu:</strong> I don’t appreciate the connotation that I’m the negative one. I think I’m a negative six.</p><p><strong>Amanda Mull:</strong> I would say that I’m a positive seven.</p><p><strong>Wu:</strong> Amanda, I’m really curious why you consider yourself an extrovert and why you picked seven.</p><p><strong>Mull:</strong> The difference between being energized or drained by being around other people and being energized or drained by being by yourself seems like the most reasonable way to think about that. I just really like being around other people.. And it doesn’t mean that I dislike being by myself at home. There are definitely times for that.</p><p>Before the pandemic, I would spend a couple of hours at home, and then I would just get bored and want to go walk around or sit at the coffee shop or see if a friend wanted to get a drink. It would just start to psychologically wear on me if I was alone for too long. It seems I pretty classically fit the idea of an extrovert in that way. I picked seven because I think I am a more ardent extrovert than the average person who fits that mold.</p><p><strong>Beck:</strong> Katie, why did you pick six?</p><p><strong>Wu: </strong>Amanda, when you were rattling off all those things that give you energy, I felt my heart rate go up, which was a big flag for me that I have identified my correct allegiance. I see myself as an introvert not because I’m a complete agoraphobe or don’t like people, but because I don’t derive any energy from being around other people. It drains me. I recuperate and gain energy from being alone.</p><p.</p><p><strong>Beck:</strong> Damn. That was real.</p><p><strong>Wu:</strong> Yeah, I can’t do it. Honestly, I really need a haircut right now. And half of the reason I haven’t gone is because I want to wait until I’m fully vaccinated, but also because I’m really dreading getting asked a lot of questions by my hairdresser.</p><p><strong>Mull:</strong> I used to have a hairdresser who I really loved talking to, and sometimes on Friday afternoons if work was slow and nobody was in the salon, I would go get a blowout just because I wanted to chat with him for half an hour.</p><p><strong>Beck:</strong> Do you think that the pandemic has changed where you fall along that scale or made you reassess your number?</p><p><strong>Mull:</strong> I have realized that I’m even more of an extrovert than I originally thought. Before, there were times when I would get overscheduled and think, <em>It would be nice to have some more time to spend at home. </em>And then I got a lot of time to spend at home, around no one, and I realized that I was scheduled like that because that is genuinely what I like.</p><p><strong>Wu:</strong> I miss social interaction, but I’ve been very fine this year. I really miss hugging, like, five other people, but I have no desire to see all of them at once and no desire to go to a bar or a party. I could do this for a while.</p><p><strong>Beck:</strong> What did you most hate about pre-pandemic life, and what did you most love?</p><p><strong>Mull:</strong> I hate scheduling things. I like to be able to call my own shots. If I want to go do something for dinner, then I’m going to go do that. Having to keep appointments and dates straight is hard for me. That’s probably not related to me being an extrovert; that’s probably related to me having ADHD. So I like the simplicity of things now.</p><p>The thing I liked best about pre-pandemic life was being able to go sit in a bar on a Saturday night, and it’s just full of people. You’re with your friends, and you’re gossiping, just catching up on the Sturm und Drang of everybody’s lives. I want to go sit in a bar when it’s cold outside and it’s warm inside, and the front window gets clouded up. And everybody’s having a good time, and there’s good music. I really, really miss the energy of that situation.</p><p><strong>Wu:</strong> So many things had become background noise to me. I never really enjoyed being in crowded places or waiting in lines. But they’re not things that really bugged me on a daily basis. I do feel like there was a decent bit of social shaming of people who didn’t want to rally and go out all the time. I would feel guilty about that. And that’s something I don’t miss a ton.</p><p><strong>Beck:</strong> What have you most hated about pandemic life? And what do you most love? Setting aside the virus and the possibilities of illness and death, which we all hate.</p><p><strong>Wu:</strong> Yeah, I definitely hate those things. I really do hate not being able to touch and see other people. I actually didn’t live with my partner during the pandemic until a few months ago, because we got married and then he moved away to do his medical residency. For the first six or so months of the pandemic, I was alone in my apartment with my cats. That was a huge bummer. And now I’m so grateful I have him, but I have only him pretty much. I miss my friends. I miss my family.</p><p><strong>Mull:</strong> Something I really appreciated about the last year is that I really like to cook, which is not a great extrovert activity. This time has given me the space and opportunity to explore that hobby a little bit more, and I don’t feel like I’m sacrificing experiences that I enjoy in order to do it.</p><p>The thing I hated about the past year the most is how cut off I’ve felt, not just from my friends and family but from the community as a whole. I live in New York, where the community life is—you’re sort of cheek by jowl with everybody. I was a regular at lots of places around my apartment. I saw lots of people I knew just walking around, going about my day. I really, really miss the serendipitous bump of energy I was constantly getting off of that. I can’t wait to see the people I used to see whose names I don’t know. I want those people back.</p><p><strong>Beck: </strong>If you were the boss of everything, how would you design life as we emerge from the pandemic?</p><p><strong>Mull:</strong> I think we had built a lot of unnecessary structures and expectations before the pandemic. What would be nice for everybody is to have some more flexibility and self-determination—flexibility in how people interact with work, flexibility around how people choose to navigate their social lives. If somebody finds it draining to go to the office every day, or if somebody has a particularly long commute, we know how to navigate around those things to make life more humane for more people. So why don’t we just do that? That is the big thing for me: Why would we discard the flexibility we found in the past year? We should keep it.</p><p><strong>Wu:</strong> I agree with that. I surprised myself by realizing how much I actually did miss having an office to go to this past year. I would love to meet my co-workers in person; I haven’t done that yet. But it’s not just about that. I really liked having separation, for work-life balance. And it’s going to be tricky to navigate that post-pandemic because now we’re all in this blurred state. But I hope conversations about that continue.</p><p data-<i>[<a href="">Read: The pandemic is changing work friendships</a>]</i></p><p><strong>Beck:</strong> What do you think the norms should be as we’re getting back into socializing—norms around how we make plans, or norms around how and whether we rekindle the relationships that got back-burnered during the pandemic?</p><p><strong>Mull:</strong> Something that has been valuable about the past year is that we have talked more explicitly about boundaries. My friends have been forgiving of one another when somebody has a concern that means they choose not to participate, or when someone is just not feeling up for something. We have all learned to be more generous with one another and more mindful of one another’s psychological needs. Why not be just as mindful of one another in the future?</p><p><strong>Wu:</strong> I think this is more specific to me than necessarily an introvert thing, but I don’t do super well with people who just want to play plans by ear. Like, “Let’s meet up later.” I can’t put “later” in my calendar. Communication is super key.</p><p>I also think a lot about what crowded gatherings are going to look like after this. I genuinely wonder if people are going to have trouble shaking the fear of, <em>Am I actually standing six feet away from this person?</em> I’m curious to see how that plays out in all the public spaces I inhabit.</p><p><strong>Beck:</strong> You guys are both very considerate and thoughtful. But in a broader sense, do you think there might be any conflict between introverts and extroverts in how they want to approach post-pandemic life?</p><p><strong>Wu:</strong> I have a lot of friends who are now planning their post-pandemic hooplas—weddings that were postponed or canceled, super-belated birthday parties, graduation parties, all these things that we missed—and I want them to be able to celebrate those things. But I’m also slightly panicking about the 15 weddings I’m going to get invited to in the span of four months. It’s a lot of pressure. I love all these people. But I personally need space between events to recharge.</p><p>I always think of—this is so nerdy. I played a lot of Pokémon when I was little. There were those very evolved Pokémon who would do a really big move and had to spend the next couple of turns recharging. They couldn’t make another move. That’s me. I can’t do it!</p><p><strong>Beck:</strong> You’re just super-evolved.</p><p><strong>Wu: </strong>It feels like people are going to try to make up for all the lost social time, and I don’t think I’m equipped for that emotionally.</p><p><strong>Mull:</strong> Definitely in my mind, I’m like, <em>Can I go on vacation? Can I go see my parents? Maybe I should have a party.</em> I can see that people in my position who are really excited to be able to do those things might feel like people who are reluctant to do them, for non-safety reasons, are maybe being a little bit rude. I could see those miscommunications happening.</p><p><strong>Beck:</strong> Let’s do a lightning round of: Are you looking forward to these things?</p><p>Working in an office. Yes or no?</p><p><strong>Wu: </strong>Yes.</p><p><strong>Mull:</strong> Yes. A couple of days a week. I don’t want to go back every day.</p><p><strong>Beck:</strong> Eating at restaurants?</p><p><strong>Mull:</strong> Yes.</p><p><strong>Wu:</strong> Yes.</p><p><strong>Beck:</strong> Travel?</p><p><strong>Mull:</strong> Yes.</p><p><strong>Wu:</strong> I hate travel. And now everyone’s gonna hate me.</p><p><strong>Mull:</strong> I will say that it gives me a ton of anxiety to have to plan a trip. I like being there. But I really dislike the logistics aspect of it. So I can agree with you on that.</p><p><strong>Wu:</strong> If I love you, I will travel to see you, hands down. That is always worth it to me. But I find travel stressful a lot of the time. I think it’s largely because of the ambiguity and too much novelty.</p><p><strong>Beck:</strong> Public transit?</p><p><strong>Wu:</strong> No. I was a staunch biker before the pandemic.</p><p><strong>Mull:</strong> Yes. I took the subway yesterday for the first time in more than a year to go get a root canal. And I was genuinely so glad to be on the subway.</p><p><strong>Beck: </strong>Parties?</p><p><strong>Wu: </strong>Nope.</p><p><strong>Mull: </strong>Yes.</p><p><strong>Beck:</strong> What about visiting other people inside their homes, not necessarily in a party situation?</p><p><strong>Wu:</strong> Yeah.</p><p><strong>Mull:</strong> Yes.</p><p><strong>Beck:</strong> What about big gatherings, like concerts or sports games?</p><p><strong>Wu:</strong> No, no, no.</p><p><strong>Mull:</strong> Sports, yes. There’s too much standing at concerts.</p><p><strong>Wu:</strong> Concerts are the few big, moshy-type things that I have enjoyed going to in the past. But I can’t do more than a couple a year.</p><p><strong>Beck:</strong> Are you looking forward to the end of Zoom meetings, or the great decrease in Zoom meetings?</p><p><strong>Wu:</strong> This one I feel kind of conflicted about. This is terrible, because I’m a reporter, but phone calls and video calls do scare me. I always have to psych myself up for them. I would much rather see someone in person than over Zoom. But Zoom is also super convenient sometimes; I’ve liked having the flexibility.</p><p><strong>Mull:</strong> I have not used Zoom that much. I have probably two Zooms a week. I really like talking on the phone. I appreciate Zoom as the tool it is, but I am glad that we won’t have to rely on it as much.</p><p><strong>Beck:</strong> Are you looking forward to the end, or decline, of Zoom happy hours?</p><p><strong>Wu: </strong>Yeah, it is really hard to have a happy hour on Zoom. I’ve been to a lot of awkward ones. But I super-appreciate the effort. Is it better than no happy hour at all? Probably yes.</p><p><strong>Beck:</strong> But only just.</p><p><strong>Mull:</strong> I have not been to a purely social Zoom happy hour since May 2020, I think. As soon as my friends were able to go sit in a park or sit outside of a bar or something, we started doing that instead. I cannot imagine a scenario in which I will opt into a purely social Zoom happy hour ever again. Unless there’s another pandemic. I think that they are a poor excuse for the real thing.</p><p><strong>Wu: </strong>If I come to a happy hour, there’s a 99 percent chance I came primarily for the free food. Can’t do that over Zoom.</p><p><strong>Beck:</strong> You can’t. That’s true.</p><p><strong>Mull:</strong> Gotta provide your own snacks.</p><p><strong>Beck:</strong> Okay, great lightning round. Do you have closing thoughts on how we can bridge the introvert-extrovert divide as we emerge into the sun again?</p><p><strong>Wu: </strong>I have been slightly sad to see the stereotype that all introverts want quarantine to last forever. That seems oversimplified to me. I think we all want the pandemic to end and to see one another. I love my extroverted friends.</p><p><strong>Mull:</strong> I think that to bridge the gap, what has worked so well, at least among my friends, is just being really explicit and direct with our needs and our concerns. I could imagine a future in which, if I had an introverted friend and they needed to cancel something because they just needed to recharge—if they told me that, it would be totally fine. I hope that we can continue to be really explicit with each other about our needs and our boundaries.</p>Julie Beck Mull J. Wu Vintage Stock / Corbis / GettyThe Coming Conflict Between Introverts and Extroverts2021-04-27T10:51:18-04:002021-04-27T12:52:01-04:00When the social floodgates open, not everyone will want to use their newfound freedom in the same way.tag:theatlantic.com,2021:50-618668<p></p><p>If the immune system ran its own version of <i>The Bachelor</i>, antibodies would, hands down, get this season’s final rose.</p><p>These Y-shaped molecules have acquired some star-caliber celebrity in the past year, due in no small part to COVID-19. For months, their potentially protective powers have made headlines around the globe; we <a href="">test for them with abandon</a>, and anxiously await the results. Many people have come to equate antibodies, perhaps not entirely accurately, with near imperviousness to the coronavirus and its effects. Antibodies are, in many ways, the heartthrobs of the immune system—and some 15 months deep into immunological infatuation, the world is still swooning hard.</p><p>Frankly, it’s all getting to be a little too much.</p><p>Don’t get me wrong: Antibodies have served me well, and thanks to my recent dalliance with the Pfizer vaccine, the anti-coronavirus variety will be receiving an extra dose of my admiration for a good while yet. I am, above all else, eager for the rest of the global population to nab the safeguards they offer, ideally for keeps.</p><p>But antibodies are simply <a href="">not the only immune-system singles worthy of our love</a>. A multitude of cells and molecules are crucial to <a href="">building a protective immune response</a> against this virus and many others. It’s time we took a break from antibodies, and embarked on a brief Rumspringa with the rest of the body’s great defenders.</p><p>What follows isn’t even close to a comprehensive overview of the immune system, because I am not a masochist, and because no one wants to read a 75,000-word story. Instead, I asked a few immunologists to chat with me about some of their favorite immune cells and molecules, and imagine what these disease fighters might be like if they truly were single and ready to mingle.</p><hr class="c-section-divider"><p>As it were, everyone needs someone to be their starter bae.</p><p>Some good candidates might be found among the members of the innate immune system, a fast-acting fleet of cells that are the first to contend with an infection. (Antibodies belong to another branch, called the adaptive immune system; more on that later.) They’re a lot like adolescent lovers: dogged and earnest, but impulsive and, on occasion, woefully imprecise. Unlike antibodies, which can zero in on specific pathogens, innate immune cells are built to clobber just about anything that doesn’t resemble their human host. Perhaps it’s no surprise that these underdog cells are often forgotten or outright snubbed in conversations about immune protection.</p><p>But the all-purpose approach of innate immune cells has its charms. They’ll try anything at least once, and they’re admirably selfless. When pathogens come knocking, innate cells are the first to volunteer to fight, and often <a href="">the first to die</a> (RIP, <b>neutrophils</b>). Some ambush invading microbes directly, snarfing them down or bathing them with deadly toxins, while others blow up infected cells—tactics reminiscent of guerrilla warfare. Although antibodies take many days to appear, innate cells will immediately be “by your side when you have a problem,” Ashton Trotman-Grant, an immunologist at the University of Toronto, told me.</p><p>These acts of martyrdom buy the rest of the immune system time to prepare a more targeted attack. And in many cases, innate immune cells act so quickly and decisively that they can subdue an invasive microbe on their own—a level of self-sufficiency that most other defenders can’t match.</p><p>Some innate immune cells are also just plain adorable. Among the fan favorites are <b>macrophages</b> (“big eaters” in Greek), aptly named for their <a href="">round-boi</a> physique and insatiable appetite. Their goal in life is to chow down for the greater good. “They’ll never make you feel like you’re eating too much, and they’re open to trying new foods,” Juliet Morrison, a virologist and immunologist at UC Riverside, told me. They’re also endearingly unselfish: If a microbe crosses their path, they’ll gobble it up, then belch up bits to wave at adaptive immune cells as a warning of potential danger. It’s a great gift-giving strategy, Morrison said, especially if weird microscopic puke is what makes your heart go <i>pitter-patter</i>.</p><p><b>Dendritic cells</b> have a similar modus operandi. Like macrophages, they specialize in regurgitating gunk for other immune cells. But they are much more social than macrophages, which prefer to gorge and digest in solitude. Dendritic cells are sentinels and gregarious gossips; their primary imperative is to “talk and hang out with other cells,” and they’ll flit from tissue to tissue to do it, David Martinez, an immunologist at the University of North Carolina at Chapel Hill, told me. If you’ve recently caught word of a new and dangerous infection, you probably heard about it from a dendritic cell.</p><p>A few weeks ago, Trotman-Grant put together <a href="">a March Madness–style bracket</a> to choose the “best” immune cell; after a couple of grueling weeks of voting, dendritic cells won. They’re almost certainly the cells you’d want to take to prom. But Trotman-Grant warned that their social-butterfly tendencies could be a double-edged sword: Dendritic cells just aren’t the type to settle down.</p><hr class="c-section-divider"><p>Innate immune cells might be convenient dates, for a time. But while they’re great at first impressions, they can also be commitment-phobes, as likely to ghost you as they are to come on strong. (Besides, who wants to date someone who’s always arriving on the early side?)</p><p>The real keepers belong to the adaptive branch of the immune system: B cells—the makers of antibodies—and T cells, which, among many other tasks, kill virus-infected cells. Adaptives are slow-moving specialists. They take down microbial invaders that innate cells can’t handle on their own, relying heavily on intel from macrophages, dendritic cells, and other early defenders. They won’t be the first to make a move, but they’re sharp and sophisticated, capable of singling out individual pathogens and zapping them with precision. B and T cells are self-assured enough to know what they want. Unlike innate cells, they’re also capable of remembering<i> </i>the things they’ve encountered before, ensuring that most pathogens can’t trouble the same person twice; that capacity is the conceptual basis of vaccines. “They do a great job at committing things to memory,” Ryan McNamara, a virologist at UNC Chapel Hill, told me. That also means no missed birthdays or anniversaries—and no chance they’ll ever forget that time you were wrong.</p><p>If you’re a fan of antibodies, you have <b>B cells</b> to thank: They are the glorious wellsprings whence these molecules hail. (On Mother’s Day, antibodies call their B cells.) Unfortunately, B cells are often overlooked; as living, dividing cells that hide away in tissues, they’re harder to isolate and study than the proteins they produce. But the antibodies they deploy can be powerful enough to quash microbes <i>before</i> they break into cells, potentially halting infections in their tracks. And even after antibodies disappear, B cells persist, ready to produce more.</p><p>Martinez stans the B cells he studies. But he’s wary of their romantic potential. B cells, he said, are almost <i>too </i>good at their job, and will compete aggressively among themselves. Their crime-fighting careers consume them, leaving little room for a fulfilling personal life. “I would say B cells are selfish,” he told me. In the cold light of morning, it turns out a lot of them are just self-involved snobs.</p><p>T cells play a far more subtle game. Their career choices range from demolishing virus-killed cells to corralling and coordinating other immune cells. As several researchers have pointed out, T cells might be some of the <a href="">most underappreciated cells</a> in the war against COVID-19, especially when it comes to vaccines. Some evidence even suggests that, in the absence of decent antibodies, T cells can <a href="">clean up the coronavirus</a> mostly on their own.</p><p>Certain T cells are <b>killers</b><i>. </i>As their name suggests, they operate with devilish flair: When they happen upon virus-infected cells, they force them to self-destruct. Killers’ excellent memories also give them a predilection for grudges—enemies that trouble them twice should expect to be trounced with extra gusto. Thrill seekers might be drawn to killers, but Avery August, an immunologist at Cornell University, points out that these cells, also called cytotoxic T cells, might be all take and no give. Scientifically, they’re full of intrigue; romantically, he told me, “not so much”—at least for him.</p><p>Then there are the <b>helpers</b>—the benign Jekyll to the killers’ bellicose Hyde. Helper Ts are some of the most loyal partners you’ll find in the immune system, nurturing almost to a fault and versatile to boot. They coax B cells into maturing into antibody factories. They cheer killers along their murderous paths. They even goad innate immune cells into becoming the most ferocious fighters (and feeders) they can be. Effectively, helpers are “badass multitaskers that coordinate every level of immunity,” Marion Pepper, an immunologist at the University of Washington, told me. They’re about as supportive as they come—as long as you don’t mind being micromanaged from time to time.</p><hr class="c-section-divider"><p>It’s easy to see the appeal of antibodies. They’re among the few immune-system soldiers that can annihilate viruses before they enter cells, and they’re thought to be crucial to most vaccines. They can also be team players, throwing up red flags around microbes in order to alert other defenders to their presence. Transferred from animal to animal, or <a href="">human to human</a>, antibodies can <a href="">confer protection</a> against COVID-19; synthetic versions of the molecules are also relatively straightforward to manufacture en masse. Scoring a date with an antibody is a bit like finally getting together with the most popular person in school.</p><p>But counting on antibodies, and only antibodies, for protection is like shacking up with the first eligible suitor you meet—a risky and perhaps close-minded gamble. In the same way that our immune systems can guard against multiple pathogens at once, we could stand to be a bit less monogamous with our affections.</p><p>Besides, the choice might not ultimately be ours to make. Love is a two-way street, and antibodies are incorrigibly picky. Their sole mission is to glom on to a very specific microbe and cling to it, ignoring everything else along the way; it’s largely <i>them </i>doing the picking and choosing. And if you’re not the soul mate they imagined, there’s little you can do to change their minds—they’re proteins, and they don’t have one.</p><p>Really, it’s not them. It’s you.</p>Katherine J. Wu / Adam Maida / The AtlanticShow Your Immune System Some Love2021-04-22T15:31:18-04:002021-04-22T17:09:35-04:00Antibodies are great and all, but macrophages, B cells, and helper T cells deserve some attention too.tag:theatlantic.com,2021:50-618627<p>The Johnson & Johnson shot is teetering on the precipice of becoming America’s <a href="">“dudes only”</a> vaccine. On Tuesday, the CDC and FDA advised <a href="">halting the vaccine’s nationwide rollout</a> to investigate six cases of <a href="">a rare blood-clotting disorder</a> that’s occurred in people within about two weeks of receiving the vaccine—all of them women under the age of 50. In an emergency meeting convened Wednesday by the CDC, experts raised the possibility of <a href="">limiting its future use to males</a>, reserving Johnson & Johnson’s vaccine, <a href="">as some have unfortunately put it</a>, for johnsons alone.</p><p>That idea, crude though it may be, has something to it. The demographic pattern that’s emerged is striking, and many of the experts I talked with this week told me they suspect that, if the vaccine is ultimately linked to these clots, the relationship will come with a clear-cut sex or gender difference too. (These questions are also being <a href="">debated</a> with regard to the <a href="">AstraZeneca vaccine</a>, which contains comparable ingredients and might very rarely cause a similar or identical type of <a href="">clotting disorder</a>.)</p><p>But health officials have strongly cautioned that it’s too early to tell for certain whether a specific subset of the population is at increased risk of this clotting disorder; scientists haven’t even definitively pinpointed the J&J shot as its cause. Prematurely masculinizing the J&J vaccine could not only reinforce <a href="">biases that compromise health care</a>, but also run counter to one of the most important goals of the ongoing pause: identifying what factors, if any, <i>do </i>contribute to these unusual clots, and protecting the people they affect.</p><p data-<i>[<a href="">Read: The blood-clot problem is multiplying</a>]</i></p><p>The post-vaccination clots under investigation belong to a class called cerebral venous sinus thrombosis (CVST), and they seem to manifest when antibodies, perhaps produced in response to the shots, inadvertently rile up platelets in the blood. Platelets exist to keep wounds from bleeding indefinitely: They clump blood cells and proteins together to plug up leaks. But in CVST, they seem to spark a clotting cascade that can clog veins in dangerous places, including the brain, and lead platelet levels to plunge. The disorder is a collision between a powerful immune response and a naturally clot-prone environment; a potentially simple explanation for why they might show up more in women is that the hormone estrogen can amp up both of these factors.</p><p>Estrogen has many jobs in the body, and in a lot of contexts, it’s an instigator: It can boost a person’s propensity to clot, and it can goad immune cells into <a href="">responding</a> <a href="">more vigorously</a> to pathogens and vaccines. (There’s also some evidence that <a href="">having two X chromosomes</a> can make immune systems <a href="">more reactive</a>.) CVSTs are rare among the general population, but are <a href="">more common in women</a>. Menaka Pai, a hematologist who specializes in blood clots at McMaster University, in Ontario, likens clotting to falling off a cliff; estrogen, among other things, “pushes us closer to the edge.”</p><p><iframe frameborder="0" height="200" scrolling="no" src="" width="100%"></iframe></p><p>Estrogen and chromosomes aren’t the only variables here, though. Physiology undoubtedly influences a person’s responses to diseases, treatments, and vaccines, but <a href="">behavior</a> and social factors can, too. In recent weeks, <a href="">dozens of similar CVST cases</a> have cropped up amid millions of doses of the AstraZeneca shot (which hasn’t yet been green-lit in the United States). As with the J&J effect, most of these cases involved younger women. But in certain countries, women also <a href="">made up the majority of people</a> who were inoculated early on, weakening the clots’ link with gender. Some experts I talked with also noted that women tend to stay in more frequent contact with their health-care providers than do men, and might feel less wary about reporting unusual side effects or symptoms after getting a vaccine.</p><p data-<i>[<a href="">Read: The rural pandemic isn’t ending</a>]</i></p><p>If researchers confirm that these two vaccines are operating in similar ways, “being older, being a man—that’s not going to protect you,” Pai told me. In addition to the six cases in women, researchers are now reevaluating a potentially similar CVST case that was <a href="">identified in a young man who had received J&J’s vaccine during the company’s late-stage clinical trials</a>. Still, the extreme gender trend in the early J&J reports has been hard to ignore. Prior to the pause, <a href="">roughly equal numbers</a> of men and women had received the company’s shot, according to the CDC. I asked Alfred Lee, a hematologist at Yale New Haven Hospital, how often his discussions with colleagues about the clotting disorder had turned to the topic of sex or gender since Tuesday’s news broke. “Literally almost every single one,” he told me. Lee and his team are now being particularly vigilant about monitoring their recently vaccinated female patients, especially those taking estrogen-containing oral contraceptive pills—the group of people they’ve deemed to be “high-risk right now,” he said.</p><p>It’s heartening, several people told me, to see the possibility of sex and gender differences in vaccine side effects being openly acknowledged and addressed. For years, gender norms have <a href="">influenced health-care providers</a> in ways that haven’t served patients well—by dismissing women’s “hysterical” complaints of pain, for instance, or accusing them of falsifying their symptoms. But grabbing onto a still-tenuous link between sex and certain side effects could create problems, too. The seemingly obvious culprit of estrogen, for example, could end up obscuring some more obtuse cause. Sarah Richardson, the director of the Harvard GenderSci Lab, pointed me to the case of the sleep aid zolpidem, also known by its brand name Ambien. In 2013, the FDA <a href="">recommended</a> that women should receive a lower dose of the drug than men. The agency claimed that women’s bodies were more sluggish at clearing Ambien, leaving female users more cognitively impaired eight hours after ingesting it. That analysis later turned out to be <a href="">flawed and incomplete</a>, in part because the agency hadn’t properly accounted for differences in body weight; the drug wasn’t leaving all women worse off. “There isn’t any scientific evidence supporting sex-based dosage for zolpidem,” Richardson wrote in a <a href="">2019 op-ed</a> for <i>The Washington Post</i>. Ambien, once hailed as a “flagship example of how sex differences can influence health,” she wrote, has morphed into a cautionary tale.</p><p>To truly home in on what’s at play with the Johnson & Johnson vaccine, Richardson told me, researchers will need to consider factors such as age, sex, gender, race, ethnicity, medical history, even <a href="">social norms around how unusual symptoms are reported</a> to health-care providers, and figure out how these variables intersect. That work is extraordinarily hard to do with just a handful of people, a likely reason the vaccine’s pause has been prolonged—so more data could be collected and analyzed. “People are really interested in the gender thing,” Lee, of Yale, told me. “But we can’t prove it yet.” That’s in part why a universal halt—one that didn’t segregate by gender, age, or any other demographic—was probably “the right approach” for now, Janna Shapiro, who studies sex differences in immune responses at Johns Hopkins University, told me.</p><p>Categorizing these clotting events incorrectly or too early also comes with dangers. The repetitive association of <i>women </i>and <i>clots </i>could stoke vaccine hesitancy in skewed ways. One recent poll showed that public confidence in the safety of the J&J vaccine <a href="">plunged after the pause</a>, and Elaine Hernandez, a medical sociologist at Indiana University, told me she’s concerned that reluctance about vaccines might concentrate among certain subgroups of women. She and her colleagues have found that young women who are Black and Latinx—groups that already have more limited access to vaccines—are more wary of getting immunized than their white peers.</p><p>Pushing this association too hard and too quickly could also skew data collection. Health workers could narrow their clinical lens; women might scour themselves for symptoms, while men and other people who don’t identify as women “may not take the symptoms [of CVST] seriously,” Krutika Kuppalli, an infectious-disease physician and vaccine expert at the Medical University of South Carolina, told me. That bell could be especially tough to un-ring in a culture where masculinity is so often considered incompatible with sickness. “People want to appear strong and tough, men in particular,” Hernandez told me. “There are already social pressures to not complain.” Casting the clotting condition as a “female problem” too early means donning blinders. “That’s troubling for the objectivity of the investigation going forward,” Richardson, of Harvard, said. (There’s still a paucity of data on whether transgender, intersex, or nonbinary people, especially those who are on hormonal therapies, might be vulnerable to unique vaccine side effects.)</p><p data-<i>[<a href="">Read: The pandemic broke America’s health-care workers</a>]</i></p><p>If a clear sex or gender difference <i>does </i>emerge, nuanced messaging will be necessary. As coronavirus cases surge, the risk of taking the vaccine might still be relatively low, especially in parts of the country where the fragile Pfizer and Moderna vaccines are harder to store and administer. Restricting the vaccine to certain age or gender groups could seed equity issues, both in the U.S. and internationally, or trigger repeated rounds of sociopolitical fallout. Shapiro pointed to the HPV vaccine, which was initially targeted to adolescent girls. The shots are now recommended for children of all genders, but misperceptions of the early rollout stigmatized the mostly female <a href="">preteens</a> who signed up for the shots as promiscuous, and the sole bearers of disease.</p><p>The goal in the coming days and weeks, Pai told me, is to appropriately titrate expectations of risk—to address concerns, but also avoid sensationalizing them. Our understanding of the clots’ danger could shift quickly as more data are collected. The dangers implied by six cases of a rare clotting disorder out of the roughly 7 million Americans who have received the J&J shot is much lower than the risk implied by six cases within the smaller population of the <a href="">1.4 million vaccinees who are women<i> </i>under 50</a>. But now that physicians know what to look for, the numerator in that ratio will likely change as well. More cases will certainly appear, spanning a wider range of genders, ages, races, and ethnicities. These shifting odds will be easier to communicate if our lens isn’t unnecessarily narrowed: Expanding<i> </i>the definition of an at-risk population is harder than paring it down.</p><p>The suspension might already seem frustratingly long to some; plenty of people have called it out as cowardly and unwise, and questioned why federal officials prolonged it. But nearly everyone I’ve spoken with this week has praised the move as prudent, during a time of great uncertainty about who’s most at risk. “Ideally, we find out over time which vaccines are best for which groups, and why,” Leana Wen, an emergency physician affiliated with George Washington University, told me. “That’s the positive way of seeing this—this is in part the kind of information we’re getting here.”</p>Katherine J. Wu Martin / The AtlanticThe Danger of a ‘Dudes Only’ Vaccine2021-04-16T16:32:09-04:002021-04-16T19:16:46-04:00We still don’t know who’s most at risk of getting the Johnson & Johnson vaccine blood clots.tag:theatlantic.com,2021:50-618596<p <em>act</em> as though he is. “I personally remain scared to death,” he told me.</p>.</p><p>Vaccines have promised, to the rest of the world, a return to a semblance of normal life; the ones currently cleared for use against the coronavirus are, by all accounts, extraordinary. But they were not designed for, or <a href="">tested</a> <a href="">extensively</a> <a href="">on</a>, immunocompromised or immunosuppressed individuals, whose immune systems have been subdued by underlying conditions, environmental exposures, drugs, or viruses such as HIV. With their defenses down, many of these people can’t yet count on what the rest of us can: that the new shots will protect them from the coronavirus.</p><p>The benefits of vaccination still far outweigh the risks: Experts told me they had <a href="">no safety concerns</a> about vaccinating people with weakened immune systems, who are often at <a href="">higher risk of getting severe COVID-19</a>. And in signing up for their shots, Rick and others like him can also help fill the data void that the <a href="">clinical</a> <a href="">trials</a> <a href="">left</a>,.</p><p>But inoculating the immunocompromised remains, in some ways, fraught. As the vaccine rollout continues, many people with weakened immune systems are unsure of how to navigate their post-vaccination existence. The milestone they must wait for isn’t their <em>own</em> vaccination, but <em>everyone else’s</em>—when society reaches an immunological tipping point that will shield the still-vulnerable from the disease.</p><hr class="c-section-divider"><p>There is no single way to build a well-functioning immune system. But there are countless ways to derail one.</p><p>A typical immune system, if such a thing exists, relies heavily on precision and coordination. The body must first accurately distinguish an assailant from its own healthy tissue, then launch a series of well-timed attacks without marshaling extraneous fighters to the fore. The what, when, and where of these immunological assaults are all crucial to the body’s ability to waylay disease; any perturbation threatens to set the whole system askew.</p><p data-<i>[<a href="">Read: The body is far from helpless against coronavirus variants</a>]</i></p><p>Some people are born with genetic mutations that hamstring immune cells’ abilities to recognize and thwart infections; others struggle to mount strong responses because of environmental causes, such as poor nutrition, cancers, or chemotherapies and pathogens that attack some of the body’s most potent defenders. Immunosuppression can also be an intentional, lifesaving tactic. Drugs that deliberately muzzle immune cells can help people with autoimmune conditions, such as rheumatoid arthritis, lupus, multiple sclerosis, and inflammatory bowel disease; organ-transplant recipients must take them, typically for the rest of their lives, to boost tolerance for unfamiliar tissue.</p><p>Overlaying vaccines onto this inherent diversity becomes a complex tangle. Vaccines are intel-packed training regimens designed for well-functioning immune cells—rookie soldiers who can sponge up info, strategize with their peers, and prepare for an upcoming encounter with a dangerous microbe. But the protection calculus changes when the contents of the shots are met by fighters who have been restrained.</p><p>Some medications are expected to present a slight setback, but <a href="">aren’t necessarily disastrous</a> for COVID-19 immunization, because they suppress just a sliver of the immune system’s typical operations. One example is ustekinumab (Stelara), a common treatment for Crohn’s disease, which zaps the signals that immune cells send one another—an intervention akin to temporarily putting a military’s radio system on the fritz. Many of these treatments <a href="">can continue on schedule</a> during vaccination, under the advisement of a physician.</p><p>Other drugs, however, are far blunter tools, <a href="">clobbering large swaths of the immune system</a>. Among them is Rick Phillips’ drug, rituximab (Rituxin), which is used to treat rheumatoid arthritis, multiple sclerosis, lupus, and white-blood-cell cancers such as leukemia and lymphoma. It destroys entire populations of B cells—on par with blitzing a fleet of naval forces. B cells are antibody factories, and without them the immune system has <a href="">more difficulty</a> committing new viruses to memory. “We’ve pharmacologically made a hole in the immune system,” Erin Longbrake, a neurologist at Yale New Haven Hospital who is studying COVID-19 vaccine responses in multiple-sclerosis patients, told me. After a rituximab infusion, B cells can take six months or more to bounce back.</p><p>The lasting impacts of B-cell-depleting therapies have prompted many physicians to recommend that such drugs be administered <a href="">with careful timing</a> <a href="">around a COVID-19 shot</a>. “It’s the medication I worry about the most,” Anna Helena Jonsson, a rheumatologist at Brigham and Women’s Hospital, in Boston, told me. Rick Phillips was three months out from his most recent infusion of rituximab when he received his first dose of Pfizer’s vaccine, in February. He pushed back his next infusion until mid-April—a month later than usual—in hopes of giving his COVID-19 shots’ protective powers time to take hold.</p><p data-<i>[<a href="">Read: Immunology is where intuition goes to die</a>]</i></p><p>People who have an autoimmune disease that’s poorly controlled, though, could risk a symptom flare by delaying their medications; others who have received organ transplants, or who are at the beginning or middle of a chemotherapy course, can’t simply flip their medications off. Some people will need to prioritize their existing treatment, “then just get the vaccine when you can,” Chaitra Ujjani, an oncologist at the Seattle Cancer Care Alliance who is studying COVID-19 vaccine responses in people with blood cancers, told me.</p><p>People living with HIV are facing a different type of immune deficit. The virus <a href="">annihilates immune cells called helper T cells</a>, which coax young B cells into churning out antibodies and spur other T cells, called killers, to assassinate infected cells. Without helper T cells, the body’s coordinated defenses against disease very often crumble. “We know from other vaccines that people with very low [helper T-cell] counts <a href="">do not mount a good response</a>,” Boghuma Kabisen Titanji, an infectious-disease physician who works with HIV patients at Emory University, told me. Potent antiretroviral therapies can buoy helper T-cell counts, but they don’t work for everyone. Titanji’s strategy with her patients has been to manage expectations about vaccination: “You will get some protection, but I can’t tell you for certain you’ll have the same degree of protection as others.”</p><p>“We’re still telling them to use full precautions and social distance” after vaccination, Ujjani told me of her own patients. Some people might benefit from the most conservative approach of all, she said: “It’s almost as if the vaccines didn’t exist.”</p><hr class="c-section-divider"><p>Laboratory immunology is often a game of subtractions and additions. Scientists will snuff out certain genes, or monitor the health of animals with faulty immune cells, and see how they react to a bevy of infections. Translating those results to humans is inevitably messy; researchers can’t tinker with the health of people in the same invasive ways. But vaccinating real, diverse patient populations could offer a similar set of immunological hints. Multiple sclerosis and other autoimmune diseases, for example, can be treated with a multitude of drugs, each targeting a slightly different branch of the immune system. John Wherry, an immunologist at the University of Pennsylvania, told me that he and his colleagues hope to suss out which of these medications most often punches holes in vaccine-induced protection: If one group of patients is unusually vulnerable after vaccination, that distinction might then clue scientists into which cells and molecules are most crucial for protection. “The composite picture can really tell you a lot,” Wherry said. Data like these could help tailor future vaccines to immune systems that have been altered by drugs or disease, or that have simply aged out of maximal protection.</p><p>In early results, researchers are already seeing how different groups of immunocompromised people are varying in their response to the shots. Ghady Haidar, a transplant infectious-disease physician at the University of Pittsburgh, told me that his team did not detect antibodies in <a href="">about 46 percent</a> of blood-cancer patients who had received both doses of the Pfizer or Moderna vaccine. Two studies out of Johns Hopkins University found no evidence of antibodies in <a href="">26 percent</a> of people with rheumatic or musculoskeletal disease (a group that includes rheumatoid arthritis and lupus), and <a href="">83 percent</a> of organ-transplant recipients, after their first dose of the Pfizer or Moderna vaccine. Dorry Segev, a transplant surgeon and an author of both studies, told me that his team will soon publish data that show those percentages do drop after the second vaccine dose, down to below 50 percent or so in the transplant group. Still, across studies, even patients who did produce antibodies seemed to mount a somewhat muted response.</p><p>For many people in these studies, negative antibody results have been a source of anxiety, especially while vaccinated friends and family are presumably antibody-rich and beginning to venture back into public. Rick Phillips, who is participating in Johns Hopkins’s research, told me he was “very stressed” to discover that he had not produced detectable antibodies in response to his first vaccine dose; he’ll be taking another test tomorrow to see if the second shot made a difference. But these early antibody data have big caveats. Measuring antibody levels captures only a small subset of the immune system’s protective potential, which includes <a href="">a dizzying array of other cells</a>. In some cases, antibodies might be almost entirely dispensable, as long as there are other immune defenders to fill the void. “The immune system doesn’t put all its eggs in one basket,” Wherry said.</p><p data-<i>[<a href="">Read: Leave your antibodies alone</a>]</i></p><p>Researchers also don’t yet know the quantity or quality of antibodies necessary to guard against the coronavirus or the symptoms it can cause. The vaccines available in the United States all tickle typical immune systems into making gobs and gobs of antibodies—very possibly more than is absolutely necessary to guard against the coronavirus. People with ostensibly healthy immune systems exhibit an enormous range of antibody responses to vaccines. So for individuals, low antibody levels shouldn’t be cause for panic, Robin Avery, one of the authors on the Johns Hopkins transplant study, told me. Even if antibody levels fall below the as-yet-undefined threshold of complete protection, the molecules might still be abundant and potent enough to <a href="">curb the severity of symptoms</a>, as they often do when the <a href="">flu vaccine</a> is given to people who are immunocompromised. (For these reasons and more, nearly every expert I spoke with advised extreme caution against, or actively discouraged, seeking out commercial antibody tests—many of which <a href="">don’t even look for the antibodies that will be produced after a vaccine</a>—as a way to test whether a shot was “successful.”)</p><p>If certain people are confirmed to be less protected by current vaccine regimens, they’ll likely have other options for protection. Haidar, of the University of Pittsburgh, noted that people who don’t produce antibodies in response to the hepatitis B vaccine, for example, will sometimes be <a href="">administered a second three-dose series of the vaccine</a>. Avery, of Johns Hopkins, also noted that older people, whose immune systems tend to be a little sluggish, are given <a href="">higher doses of flu vaccines</a>, which might have a better shot at jump-starting their cells. And early trials in nursing homes have hinted that monoclonal-antibody treatments can be administered as a preventive to keep coronavirus infections at bay—a sort of temporary pseudo-vaccine. None of these options has yet been rigorously tested, though. For now, there’s a clear approach for immunocompromised people, Dorlan Kimbrough, a neurologist who treats people with multiple sclerosis at Duke University, told me. As one of his colleagues put it: “Get vaccinated, but behave as though you’re not."</p><p>In some ways, the habits many people adopted during the pandemic are familiar for immunocompromised people. “We don’t spend a lot of time out and about in crowds,” Toni Grimes, a 48-year-old retired Army major in Phoenix, Arizona, who takes rituximab for lupus, told me. “The way everything felt with the pandemic—masks, hand sanitizing, staying away from people who are sick—we already do that every day.” But as vaccinated friends and family loosen up on masking and distancing, some people, like Patty Adair, 74, of Newton, Massachusetts, have felt left behind. Adair takes a heavily immunosuppressive drug called mycophenolate, which subdues both B cells and T cells, to treat her autoimmune hepatitis, and worries that the treatment hampered her ability to respond to the Moderna vaccine, which she completed in early March. “I feel almost as vulnerable as before I had the vaccine,” she told me. “I have done so much to keep safe over this past year. I would not change any of it. But I’d just like to feel a little safer.”</p><p data-<i>[<a href="">Read: Pregnant? The vaccine may protect you and your baby</a>]</i></p><p>For now, immunocompromised people will have to rely on those who <em>can </em>confidently derive protection from vaccines, such as household members, health-care providers, and other close contacts. That puts some of the onus on the rest of the world: “Every vaccine that goes into an arm is protection for these people,” Longbrake, of Yale, said.</p><p>The cost of neglecting the health of immunocompromised people can be staggeringly high. It will be far harder to stop the coronavirus from spreading if entire swaths of people remain unprotected. Those who struggle to clear the virus may also end up harboring it for months at a time, allowing it to mutate before it hops to another host. “This is how some variants emerged,” Ali Ellebedy, an immunologist at Washington University in St. Louis, who is studying vaccine responses in immunocompromised patients, told me. It’s a clear reason, he and many others noted, to ensure the needs of these individuals are understood and met, for their sake and everyone else’s.At home in Indianapolis, Rick Phillips remains hunkered down. Sheryl, his wife, is becoming “more adventurous” by the day, Rick told me. It’s painful, he said, to have to keep turning down lunch invitations from old work colleagues and friends, and to still not know when he’ll next see his grandchildren. He is already seeing the world inch forward without him. But Rick plans to stay the course; he can’t risk making any other choice. “We’re too close to the end,” he said. Slip up now, “and you don’t get a second chance.”</p><p></p>Katherine J. Wu R. Shamal / GallerystockCOVID-19 Vaccines Are Entering Uncharted Immune Territory2021-04-15T10:19:12-04:002021-04-16T15:49:41-04:00Some people’s bodies aren’t set up for vaccines.tag:theatlantic.com,2021:50-618578<p.</p><p <a href="">that kind</a>)..</p><p>The consequences of these tiny tussles range from the sociopolitical to the molecular. In earning the title of gamergate (pronounced <i>gamm</i>.</p><p>In perhaps the most astounding change of all, the ants’ brain <a href=""><i>shrinks</i> by about 20</a> to <a href="">25 percent</a>.</p><p.”</p><p>And for any gamergate that’s not vibing her new digs, there is, under certain circumstances, an out. In a new paper published today in <i>Proceedings of the Royal Society B</i>, Penick, Liebig, and their colleagues report that the gamergate transformation is entirely reversible, <a href="">down to the mind-boggling changes the ants’ brain tissue undergoes<.</p><p data-<i>[<a href="">Read: How the zombie fungus takes over ants’ bodies to control their minds</a>]</i></p><p. <a href="">Songbirds</a> will bloat their brain ahead of breeding season to help them learn sexy tunes for their mates, only to pare away the excess tissue once the deed is done; <a href="">hamsters</a> and <a href="">shrews</a> will cull brain tissue to help conserve energy during hibernation, then restore the lost matter when they awaken in the spring. But reversible changes are unprecedented among insects, which were previously known to <a href="">add</a> <i>or </i><a href="">subtract</a>, but not both, in a single individual. In the insect realm, “I’ve never heard of something [like] a brain shrinking, and then reverting back to a bigger size,” Lopes told me. “That’s a lot of change.”</p><p>There’s probably a good reason reversible brain shrinkage isn’t terribly common. The act of pruning and then <i>regrowing</i> <i>has </i <i>or </i>reproduce. Penick tells me that other ants don’t take kindly to ants that temporarily enter this hybrid state, and will chomp at them until they flip back to worker status—an act called “policing.”)</p><p.</p><p>Among ants, females always rule the nest. (Generally speaking, males exist solely to manufacture sperm, then promptly drop dead after sex.) Even in this company, the Indian jumping ants’ fluidity is especially empowering and delightfully unpredictable. Among these ants, every little girl actually <i>can</i> grow up to be a queen. But thrones can always be usurped.</p>Katherine J. Wu Penick / Kennesaw State UniversityIndian jumping ants "police" a female to force her to revert to worker status.A Tiny Ant Brain Is Still Too Big for Reproduction2021-04-13T19:00:00-04:002021-04-14T12:18:47-04:00Disturbingly light is the head that wears the crown.tag:theatlantic.com,2021:50-618591<p>The Johnson & Johnson vaccine has entered regulatory purgatory. This morning, the CDC and FDA jointly recommended, “out of an abundance of caution,” a nationwide halt to the single shot’s rollout. The two agencies are investigating a rare blood-clotting disorder: In the <a href="">six cases reported so far</a>, all in the United States, women ages 18 to 48 developed an unusual type of blood clot within about two weeks of receiving the company’s inoculation.</p><p>Experts haven’t yet conclusively determined whether J&J’s vaccine is directly causing these strange clots, or how frequently the condition might be occurring, because they’re relying largely on people reporting their health conditions to federal agencies. <a href="">Roughly 7 million doses</a>.”</p><p.</p><p, <a href="">other</a> <a href="">vaccines</a> have been subject to the same scrutiny; it’s not that uncommon for products to hit roadblocks <i>after </i>initial clearance. “I’m somewhat concerned, but I’m not freaking out,” Omer said. With the right monitoring systems in place, investigations like this can<i> </i>and should<i> </i>happen, with transparency. “This is the system working as intended,” Natalie Dean, a biostatistician at the University of Florida who studies vaccine trials, told me. “We’re paying close attention to even these exceedingly rare outcomes.”</p><p>People who have already gotten the J&J vaccine absolutely shouldn’t panic, especially if more than a month has passed since they received their dose. So far, the incidents documented seem to be occurring with the first couple of weeks post-vaccination. The CDC and FDA <a href="">recommend</a> that recent recipients should contact their health-care provider if they develop severe headaches, abdominal pain, leg pain, or shortness of breath within three weeks of their injection. (Those worrisome symptoms shouldn’t be confused with the mild headaches, aches, and other flulike symptoms that <a href="">commonly arise</a> as <a href="">side effects</a> within the first couple of days of <i>any </i>COVID-19 vaccine.) Adverse effects also don’t detract from a vaccine’s effectiveness at preventing COVID-19, so there’s no need to seek out another vaccine to supplant J&J’s.</p>.</p><p>Blood-clotting disorders, should they ultimately be tied to this vaccine, won’t necessarily end Johnson & Johnson’s current efforts at COVID-19 immunization. <a href="">Certain types</a> of estrogen-containing <a href="">oral contraceptives</a> and hormone therapies carry similar concerns, but have yet to be pulled from the market. (Rasmussen told me that those potential side effects didn’t stop her from using oral birth control for the better part of 20 years.)</p><p>The clots reported after J&J immunization—called cerebral venous sinus thromboses—<i>are</i> in an unusual class. A very similar clotting problem has been reported after injections of AstraZeneca’s COVID-19 vaccine, which strongly resembles the J&J shot in formulation; several European countries have <a href="">restricted the AstraZeneca shot</a>.</p> <a href="">compromised up to 15 million doses</a>..</p><p.</p><p>“Hopefully one outcome would be that we develop a better understanding of this issue, and who’s specifically at risk,” Dean told me.</p><p>If researchers establish that there <i>is </i, <a href="">by some estimates</a>,.</p><p>A Johnson & Johnson recall would be “a disaster,” Rasmussen told me. “We need all the doses we can get.”</p><p.</p><p>Johnson & Johnson’s vaccine still <a href="">has immense appeal</a>. Unlike its two-dose Moderna and Pfizer counterparts, it’s a one-and-done shot—a potentially big boon for people who can’t easily travel to and from inoculation sites, or otherwise access the injections. Vials can also be stored at <a href="">refrigerator temperatures</a> for months, making the shots easier to ship to parts of the world with few resources. “We were really counting on these to help vaccinate the world,” Gounder told me, referring to J&J, AstraZeneca, and other shots with similar recipes.</p><p.</p><p>If the J&J vaccine does return with the FDA’s blessing, we’ll need to rehabilitate it with clear and nuanced messaging, Gounder and many others told me. A vaccine can be excellent. A vaccine can also carry risks. Both can be true; both <i>have </i>been true, for other shots we’ve used. In this case, the gamble could be very small—and still be well worth it.</p><hr><p><small>The Atlantic<em>’s COVID-19 coverage is supported by a grant from the Chan Zuckerberg Initiative.</em></small></p>Katherine J. Wu Ciaglo / Getty3 Different Futures for the Johnson & Johnson Vaccine2021-04-13T18:21:49-04:002021-04-16T15:04:29-04:00A pause is just that—a pause—in which health officials can reevaluate the data at hand.tag:theatlantic.com,2021:50-618506<p>A lot can change in 17 years. The last time the cicadas were here, the virus behind the SARS outbreak had finally retreated. George W. Bush was campaigning for his second presidential term, and Myspace had <a href="">commenced its meteoric rise</a>. Tobey Maguire was still the reigning Spider-Man. The year was 2004, and a roaring mass of red-eyed, black-bodied insects had just mated and died—and left behind billions of baby bugs, heirs of the hallowed Brood X, to burrow into the soil for <a href="">a lonely stint underground</a>.</p><p></p><p>Now, as the world attempts to trounce a new SARS-like virus, these orphaned insects are resurfacing for their first taste of sunlight in nearly two decades. By mid-May or so, a dozen states in the Mid-Atlantic, South, and Midwest will be bombarded with teenage bugs, creaking out choruses of come-hither calls—some as loud as lawn mowers—and jonesing for sex. For a few short, glorious weeks, the newly liberated bugs will gather in clouds as dense as 1.5 million per acre, blanketing trees and roadways, filling buildings and buses and the bellies of dogs. They will mate, and then they will die, dropping a legion of eggs to hatch another generation of cicadas into the dirt, beginning the cycle anew. It is an X-rated <em>rumspringa</em> on steroids, the ultimate last hurrah.</p><p></p><p>When cicadas emerge, it’s hard for humans to look away. “Like ’em or hate ’em, you cannot ignore them,” John Cooley, a biologist at the University of Connecticut, told me. Cicada chasers are already getting calls about these up-and-comers, weeks ahead of schedule. (One expert I talked with informed me that I was his sixth cicada call of the day.) After the year we’ve had, Brood X’s arrival is a joyous, zany distraction, one of the few things about 2021 that still feels predictable—and the cicada stans are coming in hot.</p><p></p><p>Something else could be behind our obsession with Cicadafest 2021. For the first time in a long time, maybe ever, a lot of us are vibing hard with these bugs. Call it cicada envy: We’ve gotten a year-long taste of their solitary adolescence, and are now craving the raucous springtime orgy that inevitably follows. The bugs’ subterranean seclusion might be extended, but at least it has a definite expiration date. And the cicadas’ coming debauchery—the gathering of a lifetime—could be a tantalizing foreshadow of the end of our own isolation, when we can shed our inhibitions like so much exoskeletal molt.</p><p data-<i>[<a href="">Read: Watch a cicada metamorphose</a>]</i></p><p>In a pandemic, humans face the most danger from crowds. But among cicadas, the more bodies, the better. “They have this safety-in-numbers strategy, in order to survive,” Chris Simon, a biologist at the University of Connecticut, told me. Not all cicadas synchronize their emergence. Those that do, called periodical cicadas, engage in a self-sacrificial strategy: So many come out at once that even the most gluttonous predators can’t nom the bugs into extinction. Of the <a href="">15 broods of periodical cicadas in the U.S.</a>, 12, including Brood X (that’s X as in “10,” from the Roman numeral), pop up every 17 years. The rest appear every 13.</p><p></p><p>This system must be perfectly timed and tuned. Cicadas that surface too early are quickly snarfed up by predators, and have no partner to woo. Those that are sluggish “miss the party,” Cooley told me. In both cases, they usually die alone and unsexed.</p><p></p><p>Avoiding such a sad end requires careful arithmetic, which, remarkably, cicadas seem to carry out by <a href="">tracking the seasonal pulses of nutrients</a> in the underground vegetation they sup on. Each passing year adds another tick to their mental log, until they hit the magic threshold of 17 (or 13, as the case may be). The long wait time probably provides some cushion, giving late bloomers time to catch up to their more precocious kin. “They’re able to do all this without cellphones, without talking to cicadas in the vicinity,” Samuel Ramsey, an entomologist at the U.S. Department of Agriculture in Maryland, told me—an impressive system of coordination without apparent communication. Finally, in the throes of spring, late-stage nymphs climb back upward to wait near the soil’s surface until it reaches 64 degrees Fahrenheit—the final signal for them to burst free. Would that we, too, could be freed from our pandemic prison by a simple change in the weather.</p><p data-<i>[<a href="">Read: Before eating cicadas, pause</a>]</i></p><p>Many humans fixate on the cicadas’ debut. But their time in purgatory is at least as beguiling. Seventeen years ago, the bugs of Brood X were little nymphs, white and fragile and smaller than apple seeds, dropping from the branches of trees where the eggs that held them had been laid. Their pale, squishy bodies fell to the dirt and began to carve out solitary burrows several inches underground, where they sucked a watery substance called xylem from plant roots. In the 17 years since, they have undergone four developmental transitions, during which the young cicadas had only three chief responsibilities: drink, grow, and wait.</p><p></p><p>We’ve logged just one year in this pandemic, engaging in our own mammalian version of drinking, growing, and waiting; God willing, we won’t log 16 more. But it takes a lot more than time and food for humans to truly transform. If anything, I’ve metamorphosed in reverse over the past few months, devolving from a fully fledged adult into a feeble, soft-bodied nymph.</p><p></p><p>Pandemic or no, Brood X will rise—an immutable imperative of nature, human crisis be damned. Many of us can’t help but get swept up. Gene Kritsky, a cicada expert at Mount St. Joseph University, in Ohio, told me he’s helped more than 80 couples time their wedding ceremonies around the arrival of various cicada broods. Others, like Louie Yang, an entomologist at UC Davis, have tracked their life in cicada units. Yang, who’s 43, has been alive for two Brood X eruptions, and hopes he’ll get to see two more after this one. “So much has happened aboveground,” he told me. “Below the ground, the clock is slower.” That time warp is something we might have a better appreciation for now.</p><p></p><p>Periodical cicadas offer a lesson in temperance, but also a cautionary tale. Their time spent underground is predictable, methodical. When they surface, all hell breaks loose. <a href="">A fraction of the brood will die to fill the bellies of predators</a>, so their brethren might fly free. Others might be lost to a devastating fungus that <a href="">drugs the bugs with mind-altering psychedelics and makes their butts fall off</a>. Even the lucky cicadas, who manage to couple up in their few good days aboveground, “die in horrible and gratuitous ways,” Cooley told me.</p><p data-<i>[<a href="">Read: This parasite drugs its hosts with the psychedelic chemical in shrooms</a>]</i></p><p>Human timelines are hazier than cicadas’. We can’t guarantee when we’ll be able to safely break free of our confines and mingle unchecked. But when we do, we won’t have to flame out in a matter of weeks; we won’t have to die from a butt-munching fungus. And unlike insects, we can endure our time in isolation <em>knowing</em> just how much the wait will pay off, then reflect on the lessons we have learned—about ourselves, about what matters most in life, about how to stop outbreaks from spiraling out of control. A lot can change in 17 years. The next time the cicadas are here, perhaps we’ll have grown up, too.</p><p></p><p></p>Katherine J. Wu Heilman / AlamyThe Biggest Party of 2021 Is About to Start2021-04-05T13:43:06-04:002021-04-05T16:21:42-04:00Billions of bugs will soon burst out of the ground to begin the mass gathering of a lifetime. It’s hard not to feel jealous.tag:theatlantic.com,2021:50-618500<p>A few weeks ago, my partially vaccinated partner and my wholly unvaccinated self got an invitation to a group dinner, held unmasked and indoors. There’d be Thai food for 10, we were promised, and two über-immunized hosts, <a href="">more than two weeks out</a> from their last Moderna doses. <em>And what about everyone else?</em> I asked.<em> Would they be fully vaccinated, too?</em></p><p><em>Well</em>, came the response. <em>Not really.</em> Some would be, some wouldn’t. But it had been so long—weren’t we close enough?</p><p>The answer was of course <em>no</em>, <a href="">Americans’ vigilance about distancing and avoiding public places</a> seems to be slackening, regardless of their immunization status. Slowly but surely, we’re losing our grip.</p><p>To be clear, we have reason for optimism. Vaccination rates are also rising, and according to the latest estimates, the currently cleared shots are extraordinarily effective at preventing not just symptomatic disease, <a href="">but asymptomatic infections</a>—key to slowing the virus’s often-silent spread. In recent weeks, the CDC has <a href="">green-lit fully vaccinated people</a> to skip post-exposure quarantines; mingle with one another in small groups, indoors and unmasked; visit unvaccinated, low-risk people under limited circumstances; and, now, travel safely within the United States. With <a href="">less than 20 percent of the country fully vaccinated</a>, the agency is quite understandably moving with caution, and hasn’t yet changed its stance on whether vaccinated people should wear masks in public (yes) or gather in medium- and large-size groups (no).</p><p>But across the country, states are <a href="">rushing to lift mask mandates</a>, <a href="">two-week period</a> that the CDC advises waiting after the final shot, so that immunity can mature. “What difference is a few days going to make?” a friend asked me the other day.</p><p data-<i>[<a href="">Read: The false dilemma of post-vaccination risk</a>]</i></p><p>Amid all the fudging, that sentiment is starting to become a constant refrain: <em>Really, what’s the harm?</em></p><p>The harm is, frankly, mathematical. Over time, our vaccine cheat days start to add up. It might truly be innocuous for a few people to cut a couple of corners on occasion. But eventually, a series of flubs will allow exposures, which will in turn beget disease. Our shortcuts also signal to others that it’s okay to chill out when it is very much not.</p><p>Now is not the time to relax—quite the opposite. “We’re so close to the end that we should be <em>extra </em>careful right now,” Julie Downs, a psychologist and behavioral scientist at Carnegie Mellon University, told me. The problem is, our lapses don’t just slow us down. They set us <em>back</em>, in the same way that repeatedly opening an oven door will prolong the time it takes to bake a cake (and, at worst, make your delicious dessert collapse). Having made so much progress, we risk a lot with our impatience. And right now, we’re in serious danger of botching our grand pandemic finale.</p><p <a href="">how effectively inoculations thwart infection</a> and the <a href="">risks of post-vaccination travel</a>.</p><p, <em>If I can get together with another household that’s unvaccinated, why can’t we do large meetings?</em>”</p><p <em>this</em>.</p><p>The post-vaccination cohort might also be subtly signaling to others that behavioral change is expected, and good. Having a ton of vaccinated friends who are starting to hang out and shed their masks might be renormalizing old habits for those who expect their shots soon.</p><p, <em>It’s not fair,</em>” she said. “<em>If no one else is being good, why am I at home?</em>”</p><p.</p><p data-<i>[<a href="">Read: Vaccinated people are going to hug each other.</a>]</i></p><p.”)</p><p <em>down </em>from our baseline of “normal.” Now we’re getting signals that things are improving. The vaccines have injected hope into the conversation; they’re a tool that is <em>raising </em.”</p><p.</p><p.’”</p>Katherine J. Wu Images / Designer 29 / Getty / Katie Martin / The AtlanticVaccine Cheat Days Are Adding Up2021-04-04T08:00:00-04:002021-04-16T14:59:06-04:00Vaccinated <em>and</em> unvaccinated people are getting more lax with behavior at a time when vigilance really matters.tag:theatlantic.com,2021:50-618465<p><em><small>Updated at 3:21 p.m. on April 1, 2021.</small></em></p><p>One year ago, around the end of March, Carly Taylor received a positive result for two tests in two consecutive weeks. The first was a test for the new coronavirus. The second was a pregnancy test.</p><p>Her daughter, Ophelia, arrived on December 22, within days of the public debut of the first COVID-19 vaccines in the United States. In the weeks after, Taylor, a 20-year-old former day-care worker who lives in Alabama—a state she describes as “a cesspit of anti-vax rhetoric”—waffled on whether to get her shots. The clinical trials run by Moderna or Pfizer-BioNTech hadn’t included anyone who was pregnant or breastfeeding; the CDC was <a href="">treading carefully</a> in its official, and the World Health Organization had even<a href=""> discouraged pregnant women</a><b> </b>from getting <a href="">certain shots</a>. Taylor’s social-media feed had been flooded with speculation about the shots’ effects on fertility and infant health. Even her father and stepmother had doubts, citing QAnon conspiracy theories about the vaccine’s dubious contents. “At first,” she told me, “I thought, <i>I don’t know.</i>”</p><p>Three months later, Taylor’s thinking had changed. On March 21, she received her first dose of the Pfizer vaccine, a decision she made for both herself and her daughter, who has been nursing since she was born. Taylor can’t yet get Ophelia a vaccine. But with breast milk as a conduit, she might be able to offer some of her own immunity instead.</p><p>Like Taylor,<b> </b>many others who might once have hesitated to get a vaccine because they’re pregnant or breastfeeding are lining up for their shots. In doing so, they’re helping provide much-needed data on whether vaccines can safely guard them from the virus, and hints that some of that protection might, through the placenta or breast milk, trickle down to their children. Baseless concerns about the vaccines’ risks to fetuses and infants are being replaced with talk of their benefits; the narrative is evolving from “<i>No, I don’t think so, I’ll wait on this,</i> to <i>When is it my turn to receive this vaccine?</i>” Ifeyinwa Asiodu, a nurse and breastfeeding researcher at the University of California, San Francisco, told me. After months in limbo, pregnant and lactating people<b> </b>are now seeking out inoculations not in spite of their children but <i>because</i> of them.</p><p data-<i>[<a href="">Read: A pandemic pregnancy is a more dangerous pregnancy</a>]</i></p><p>Any protection that passes to children through the placenta and breast milk will be temporary, “passive” immunity. As caregivers await the arrival of pediatric vaccines, and as collective immunity to the coronavirus mounts, these short-term transfers can function as a sort of immunological bridge. Pandemic babies, born or conceived amid this global crisis, might not need to navigate their earliest days entirely unguarded—one of the few windfalls new parents have gotten this year.</p><hr class="c-section-divider"><p>There’s good reason to wonder if vaccines will work differently during and directly after pregnancy. To ensure that an embryo—a wad of unfamiliar tissue—will be tolerated, pregnancy must muzzle parts of the immune system, which then rebound after the baby is born. Pregnancy also alters how the body metabolizes drugs, some of which can move across the placenta or into breastmilk. Many of the bodily changes that bookend birth remain poorly understood.</p><p>Despite these questions—and because of them—pregnant and lactating people have largely been left out of trials for COVID-19 treatments and immunizations, allowing<a href=""> misinformation</a> to fill the data void. Conspiracy theorists argued that the shots were part of a plot to<a href=""> render people infertile</a>, trigger miscarriages, or deliver dangerous lab-made toxins to newborns. None of these ideas was based in fact. But by the time the first vaccines were authorized, serious damage had been done.</p><p>Kelly Nolan, a 35-year-old business owner in San Diego, flip-flopped over the decision to vaccinate while she and her husband were trying to conceive their second child in the fall. “I didn’t have a lot of faith in the last administration when it came to science,” she told me. When a pregnancy test came back positive for Nolan in December, “I thought I wasn’t going to be the first in line to get this vaccine,” she said.</p><p>But Nolan was soon heartened to see pregnant friends and colleagues signing up for their shots. Among them was Toluwalaṣé Ajayi, a pediatrician and palliative-care physician, who received her first shot of the Pfizer vaccine when she was midway through her third trimester. Ajayi, too, had her worries. “It was pretty nerve-wracking,” she told me. “We didn’t know much about how the vaccine would affect pregnant women.” What Ajayi <i>was </i>certain of, however, was the threat<a href=""> the virus posed to pregnant people</a>,<a href=""> who are more likely to become severely ill after infection</a>—a threat that was likely multiplied by her frequent exposures to the virus as a health-care worker. Fully vaccinated, Ajayi delivered her new daughter, Ayokárí, on March 4; two weeks later, Nolan got her first shot.</p><p data-<i>[<a href="">Read: Why the coronavirus hits kids and adults so differently</a>]</i></p><p>Nolan told me that building evidence of the shots’ safety and effectiveness during pregnancy, shared in a bevy of online support groups, also helped clinch her choice to immunize. Most states are now prioritizing<b> </b>pregnancy in the vaccination queue. As of March 29,<a href=""> more than 69,000 pregnant Americans</a> have reported receiving their shots, according to a CDC registry, and so far, “the data seems to suggest there<a href=""> has not been a safety signal</a>” in this population, Kathryn Gray, an expert in maternal-fetal medicine at Brigham and Women’s Hospital in Boston, told me. In a<a href=""> study</a> published last week, Gray and her colleagues found that the Pfizer and Moderna vaccines did not seem to trigger more<a href=""> side effects</a> in<b> </b>pregnant or lactating people, and still roused an impressively robust immune response, comparable to what’s been seen in other populations. That makes the risk calculus for pregnant people<b> </b>simpler. “It’s indisputable that the mom will gain protection against COVID-19 from being immunized in pregnancy,” Andrea Edlow, a maternal-fetal-medicine specialist at Massachusetts General Hospital in Boston and a co-author on the study, told me.*</p><p>These results haven’t yet been backed by clear-cut proof from clinical trials, which are<a href=""> now in the works for this population</a>. And certain vaccine side effects, including intense fevers, which can be dangerous during pregnancy, are still important to keep tabs on. But watching the number of safely immunized individuals grow is “incredibly reassuring,” Geeta Swamy, an expert in maternal immunization at Duke University, told me.</p><p>There’s also nothing to support the notion that certain vaccine ingredients (which have not yet been specifically vetted in clinical trials for infants) might be inadvertently shuttled to a fetus or a nursing newborn. mRNA, the active agent in the Pfizer and Moderna vaccines, is extraordinarily fragile, and would have a hard time traversing the placenta or entering breast milk intact. (Even if a shred or two of the molecule did meander into milk, it would stand no chance of surviving the infant gut.) One very<a href=""> small study</a>, not yet peer reviewed, found no traces of mRNA in samples of breast milk from six lactating individuals who had gotten the Pfizer or Moderna vaccine. “Some people have been told to ‘pump and dump’” in the hours or days after getting their shots, Stephanie Gaw, a UCSF researcher who led the study, told me. “But there is no evidence whatsoever for discarding breast milk after a vaccine.”</p><p data-<i>[<a href="">Read: Here comes the COVID-19 baby bust</a>]</i></p><p>Researchers do, however, expect something <i>else </i>to pass to fetuses and infants after vaccination:<a href=""> antibodies</a>, Y-shaped immune molecules that can block viruses from entering human cells. Gray and Edlow’s team found that antibodies generated in response to the vaccine are detectable in umbilical-cord blood and breastmilk—a strong sign that they’re being transported to fetuses and infants, potentially raising a temporary neonatal shield against the coronavirus.</p><hr class="c-section-divider"><p>Immunity is one of the first heirlooms that kids inherit from their parents. Antibodies naturally cross the placenta into the fetus, then persist throughout the first six or so months of the baby’s life, as the infant’s own immune system begins to churn out homemade batches of microbe-vanquishing molecules. Some vaccines, like those that work against<a href=""> whooping cough</a>, leverage antibodies’ wayfaring tendencies and are recommended for all pregnant people specifically to keep newborns safe. But researchers still don’t know the amount or type of antibody necessary to reliably insulate <i>adults</i> from the coronavirus, let alone infants, says Galit Alter, an immunologist at the Ragon Institute in Boston and a co-author on Gray’s recent study. For this reason, Gaw, of UCSF, prefers to compare the COVID-19 vaccines to flu vaccines, which the CDC<a href=""> recommends primarily for the protection of pregnant women themselves</a>. Any benefits passed on to the fetus are “kind of a bonus,” she told me.</p><p>Some of the same fogginess shrouds breast milk. Human milk has long been known to teem with immunity-promoting ingredients that can shore up a baby’s defenses against many pathogens, but whether the new coronavirus is definitely among them remains to be seen. Also unclear is how long antibodies capable of thwarting the coronavirus persist even in the adult body, or whether they reliably travel to fetuses or infants after the pathogen vacates the premises.</p><p data-<i>[<a href="">Read: Immunology is where intuition goes to die</a>]</i></p><p>On top of that, vaccines might not induce the same types of antibodies that a natural infection would, or push the same subsets of them into breast milk. The biggest player in milk is<a href=""> typically an antibody class called Immunoglobulin A</a>, or IgA, which is tailor-made to guard mucus-lined parts of the body, including the airway, where the coronavirus likes to set up shop. At least some COVID-19 shots seem to<a href=""> prompt the production of breast milk that’s richer in another antibody called IgG</a>, the same type that’s shuttled across the placenta and into fetal blood, but is typically somewhat scarcer in milk, says Rebecca Powell, a human-milk immunologist at Mount Sinai in New York. That’s not necessarily a bad thing, Powell told me. But this skew could indicate that vaccines delivered directly to the airway, such as nasal sprays, might eventually be a better option for sharing immunity through breast milk.</p><p>Still, talk of <i>any</i> protection for babies is a dramatic shift from the early days of the vaccine rollout, when official recommendations seemed to signal “that I had to make a choice between getting vaccinated or nursing,” says Liz Johnson, a 34-year-old microbiologist and infant-nutrition researcher at Cornell University, who is breastfeeding her son, Lucas. Knowing that those two goals aren’t at odds “definitely helps get over that hesitation,” she told me. Some parents are now even considering delaying weaning in their infants to prolong the potential protection. (Unlike placentally transferred antibodies, which persist for months in a baby’s body, most milk antibodies last just hours or days after they move from parent to child.)</p><p>Kelsey Linn, a 33-year-old pharmacist in Pittsburgh, decided to keep breastfeeding her 13-month-old, Michael, past her planned weaning date after she received her second dose of Moderna’s vaccine on February 14—her son’s birthday. Michael is attending day care three days a week, and since August, his classroom has been shut down twice due to suspected coronavirus exposures. Ajayi, the pediatrician in San Diego, plans to breastfeed newborn Ayokárí for about a year, and is stirring some of her milk into oatmeal and cereal for her older daughter, Tiwalọlà, who is three and a half, just in case it gives her body a boost.</p><p data-<i>[<a href="">Read: A bold and controversial idea for making breast milk</a>]</i></p><p>In Virginia, Jeanel Little, a vaccinated nurse practitioner at UVA Health, sought out donor milk for her now-ten-month-old daughter, Ruby, after discovering that she had low supply last summer. Little and her husband figured that, odds are, some of their donors have been vaccinated or were infected, and might be providing some coronavirus-fighting antibodies in their milk. As the pandemic wears on, and Ruby remains unvaccinated, “the breast milk has helped to subside some of [our] fears,” Little told me.</p><hr class="c-section-divider"><p>It’s hard to quantify the increasing optimism about getting vaccinated while pregnant or breastfeeding, or how influential such changes in perspective might be. More of these individuals are certainly signing up for shots—but shots are also more available now. Still, “I definitely think shifting attitudes could be a factor,” Kristen Nordlund, a CDC spokesperson, told me.</p><p>Recent data hints that this encouraging trend will continue. Asiodu, at UCSF, began surveying lactating and breastfeeding people about the new vaccines in February. Of the 110 or so people now enrolled in her study, she told me, most haven’t yet had the chance to get a shot. But a majority of them want to. Edlow, who works with patients in Massachusetts, echoes the sentiment: “To me, it seems people are feeling only more positive.”</p><p>The intense polarization regarding vaccines, and the<a href=""> public scrutiny over eligibility</a>, has also intensified certain debates over pre- and postpartum health, fetal health, and breastfeeding—topics that were charged long before the pandemic began. Early on, “there was real shaming of pregnant and breastfeeding women on social media” who signed up for their shots, Swamy, of Duke University, told me.</p><p data-<i>[<a href="">Read: Becoming a parent during the pandemic was the hardest thing I’ve ever done</a>]</i></p><p>Now there’s danger of stigmatizing vaccinated parents who are unable to, or choose not to, nurse their infants. “These parents aren’t ‘failing’ their children,” Stephanie Langel, an immunologist at Duke, told me. Distancing, hygiene, masking, and vaccinating the adults who interact with the baby will still confer indirect protection, like a cocoon, Edlow, of Massachusetts General Hospital, said. And soon enough, vaccines for infants as young as six months of age will likely be available as well, after going through their own clinical trials.Taylor, the former day-care worker in Alabama, spent a good part of her first trimester battling COVID-19 symptoms that sapped strength from her lungs, brain, and heart. A year later, she’s close to<a href=""> full vaccination</a>, and eager to spare both herself and her daughter from a similar rash of sickness. In addition to breastfeeding, Taylor plans to seek out a pediatric vaccine once the option is available. She hopes the immunity she shares with Ophelia now will tide the baby over, she told me, until she gets a shot—one that’s been vetted for kids her age, and gives her protection that’s long-lasting and entirely her own.</p><hr><p><small>The Atlantic’</small><em><small>s COVID-19 coverage is supported by a grant from the Chan Zuckerberg Initiative.</small></em></p><hr><p><small><i><a href="#updated">*</a> <a id="update" name="update"></a>This article originally quoted Andrea Edlow describing the risk calculus of vaccines for expectant parents as "indisputable." It has been updated to clarify that she was discussing the vaccines' protection of pregnant people.</i></small></p>Katherine J. Wu Chikwendiu / The Washington Post / GettyPregnant? Breastfeeding? The Vaccine Might Protect You and Your Baby2021-03-31T13:25:05-04:002021-04-01T15:24:36-04:00Antibodies that cross the placenta or end up in milk could give infants temporary immunity to COVID-19.tag:theatlantic.com,2021:50-618407<p>Among the vegetable world’s most incorrigible villains, the whitefly ranks high. Pale, squishy, and smaller than a sesame seed, these sap-sucking bugs terrorize more than 600 plant species, infecting them with deadly viruses and smearing their leaves with sweet, sticky liquids that encourage the growth of molds. Whiteflies <a href="">resist pesticides</a>. They <a href="">dupe plants into mounting the wrong defenses</a>. They can overtake greenhouses by the millions and sicken entire fields of crops; their dastardly deeds grace the pages of many an agricultural guide, and perhaps a horticulturist’s burn book or two.</p><p>Against such an enemy, plants deploy poisons powerful enough to stunt insect growth or bring about the bugs’ untimely demise. But whiteflies (which aren’t flies, but cousins of aphids) have found a work-around for this obstacle, too, through thievery. To protect themselves against toxins called <a href="">phenolic glycosides</a>, a common botanical defense, whiteflies imported a stolen good: a gene that encodes a kind of antidote, likely pilfered from an ancient poisonous plant, according to <a href="">a study published today in <i>Cell</i></a>. The plant had probably created the chemical cure to protect its own tissues. In doing so, it revealed a vulnerability for the sticky-fingered whitefly to exploit.</p><p>“It’s so clever,” says Naomi Pierce, an entomologist and evolutionary biologist at Harvard who wasn’t involved in the study. “It’s taking advantage of a defense that has been carefully honed by plants … I’m just contemplating how incredible it is.”</p><p>Genetic theft is very difficult to prove, and by all accounts, it appears to be somewhat rare. The evidence is generally circumstantial, and by the time scientists clue in, millions of years may have passed. “There’s really no way to know—none of us were there,” says Seemay Chou, a biochemist at UC San Francisco, who led the discovery of <a href="">a similar phenomenon in ticks</a> but wasn’t involved in the new study.</p><p data-<i>[<a href="">Read: The wild experiment that showed evolution in real time</a>]</i></p><p><span>When grand genetic heists do occur, they can create evolutionary shortcuts, and blur the boundaries between organisms. The tree of life is often presented as full of discrete branches, spaced farther and farther apart. Every so often, however, two organisms come close enough to intersect, and leave relics of their intimacy in their genetic codes. In abducting its enemy’s antidote, the whitefly may have rapidly armed itself with a new weapon, skipping over the chore of creating the gene itself, and becoming a touch plantier in the process. The study’s authors think the insect may have even carried out its felony with an accomplice: a microbial smuggler ferrying bits of genetic material between multicellular hosts.</span></p><p>Typically, genes can be traced back in time, because ancestors tend to pass them down like heirlooms to the generations that follow. But the new study’s researchers, led by Youjun Zhang, a plant biologist at the Chinese Academy of Agricultural Sciences, noticed that this one didn’t follow the usual pattern. They found the gene that protects these bugs from poison in the genomes of only one close-knit group of species on the whitefly family tree, as if it had appeared out of nowhere. Curious about the gene’s origins, the researchers searched its sequence in a massive database. They found that no other insect genomes encode the gene, or anything that even vaguely resembles it.</p><p>But a version of the gene appears to be a fixture of many plant species—a hint that it might have hopped from one organism into an entirely different one.</p><p>These genome-jumping events are known as <a href="">horizontal gene transfers</a>. They’re common among bacteria, which swap genetic material willy-nilly, often as a sort of primitive pantomime of sex. Among eukaryotes such as plants and animals, though, they’re relatively rare. For another organism’s genes to integrate, foreign DNA must make its way through a creature’s complex body, and into a cell. It must breach the barriers of the nucleus, where genetic material is cloistered. It must assimilate itself into a new molecular context in a usable form, without diminishing the integrity of the genome that’s already there. It must accomplish all of this without being nuked or jettisoned by the host’s many defenses against unfamiliar matter.</p><p>After all that, the stolen genes must then find their way into an egg or a sperm cell, perhaps carrying some sort of benefit that will make offspring more fit.</p><p data-<i>[<a href="">Read: This is a truly lousy experiment about evolution</a>]</i></p><p>The chances of all those pieces falling into place are low, to say the least. But in recent years, as genetic-sequencing technologies have become more advanced, scientists have discovered more and more examples of gene hopping. Microbes, they found, can punt genes not just to one another, but to more complex creatures as well. Bacterial <a href="">genomes are gold mines</a>: They’re where <a href="">ticks</a> got the genes to manufacture defensive antimicrobial compounds, and where <a href="">beetles</a> acquired the ability to destroy coffee plants. <a href="">Parasitic wasps</a> have weaponized the genes of viruses. Tiny freshwater creatures called <a href="">rotifers</a> seem to be career criminals, habitually lifting genes from bacteria, fungi, and plants. In perhaps the closest parallels to whiteflies, <a href="">aphids</a> snatched DNA from fungi to paint themselves in a rosy red hue, and <a href="">caterpillars</a> burglarized bacteria to protect themselves from the cyanides in certain plants. Humans, too, have likely <a href="">plundered a few microbial genomes</a>.</p><p>There can also be red herrings—strange sequences of DNA that appear to point to horizontal gene transfer, but are actually the result of something else, such as laboratory contamination. That seems to have been the case with <a href="">a study examining the genomes of tardigrades</a>, and the <a href="">original draft of the human genome</a>.</p><p>But several outside experts told me that the new study by Zhang’s team seems solid. “It’s convincing to me,” Nancy Moran, an entomologist at the University of Texas who pioneered work showing <a href="">horizontal gene transfer in aphids</a>, said. “My skeptical radar is usually raised with horizontal gene transfer,” said Harmit Malik, a geneticist at the Fred Hutchinson Cancer Research Center who collaborated with Chou on the tick study. But a whitefly pinching the gene from a plant is “the most parsimonious hypothesis.”</p><p>Still unclear, though, is exactly how, when, or from whom the whiteflies filched the gene. Ted Turlings, a chemical ecologist at the University of Neuchâtel in Switzerland and an author on the new study, told me that the event must have occurred at least 35 million years ago. Back then, plants looked a bit different.</p><p>Most cases of horizontal gene transfer seem to have involved prolonged close contact between donor and recipient. It’s certainly possible that plant DNA, adrift in the whitefly’s digestive tract, somehow meandered its way over to a reproductive cell. But Turlings said he and his colleagues think the whitefly had help from a virus with privileged access to parts of the insect’s body. Viruses, after all, are used all the time in labs to deliver genetic intel to cells; this superpower has even been leveraged in <a href="">some COVID-19 vaccines</a>. Perhaps what the researchers found is not a direct plant-to-insect dispatch, but a protracted relay that could have taken place over many years—a molecular drug trade, with microbes acting as the mules.</p><p>Julie Dunning Hotopp, a microbiologist and <a href="">horizontal-gene-transfer expert</a> at the University of Maryland who wasn’t involved in the study, told me she favors the idea of a bacterial intermediary. A bacterium could even have been the original source of the detoxifying gene<i>, </i>she noted, doling it out first to a very early plant, then again to whiteflies further down the road.</p><p>Details aside, it’s clear that whiteflies somehow gained a serious wing up on the plants that try to poison them. That might sound like bad news for plant lovers. “It’s an endless problem for us,” Pierce, of Harvard, told me. “We’re constantly fighting against whiteflies.”</p><p>But the world’s vegetation isn’t doomed. Evolution trudges on; perhaps some plants have wised up to the whiteflies’ tactics, and are already plotting their next toxic move. Humans, too, could help by engineering crops that turn the whitefly’s gene off, making the insect vulnerable once again. Pierce delights in this possibility. Watching whiteflies over the years, “you wonder, <i>How do they do it?</i>” she told me. “Now I look at them and I think,<i> Aha—we’ll get you in the end</i>.”</p>Katherine J. Wu Cattlin / AlamyA Pesky Insect Took an Evolutionary Shortcut2021-03-25T11:49:15-04:002021-03-25T15:22:55-04:00Millions of years ago, whiteflies pilfered a plant defense, and they have been benefiting ever since.tag:theatlantic.com,2021:50-618406<p?”</p><p.”</p><p>Many long-haulers are still lining up for vaccination, in hope of guarding against a future tussle with the coronavirus and a more severe bout of disease. (Early evidence hints that COVID-19 survivors do produce <a href="">a strong immune response to the virus</a>, but <a href="">might need the extra jolt</a> offered by vaccines to keep their defenses high.) Now, as more shots roll out, a second potential perk has emerged: A scattering of long-haulers report that their COVID-19 symptoms have mysteriously <i>faded </i>after their shots—an astounding and unexpected pattern that’s captured the attention of experts worldwide.</p><p <i>worse.</i></p><p>Long COVID, with its constellation of debilitating, life-altering symptoms, is one of the most serious outcomes of a coronavirus infection. But it remains <a href="">one of the least understood parts of the pandemic. </a>A year into the greatest global health crisis in a century, scientists still <a href="">have not settled on a consensus definition</a> for long COVID, let alone a standard set of tests or <a href="">treatments</a>. Now long-haulers are tackling one of the biggest data vacuums yet: the collision of their condition with vaccines.</p><p.</p><hr class="c-section-divider"><p>My colleague Ed Yong was <a href="">one of the first to report on long COVID, in June</a>. In the nine months since, the condition has gained international recognition and sparked a small but growing number of efforts to scientifically suss out its causes, including several that will <a href="">be funded by the National Institutes of Health</a>. Without firm answers, progress on palliatives and preventives for the disease will be halting and patchwork; in many trials studying treatments for coronavirus infections, long-COVID patients have simply been left out.</p>.</p><p>That oversight may have opened up a big gap in the armor that vaccines are meant to offer. Recent studies suggest that <a href="">10</a> to <a href="">30 percent of people</a> with documented coronavirus cases have experienced long-term consequences. Some lingering impacts are the products of <a href="">severe coronavirus infections</a>, which can leave organs riddled with damage that <a href="">lasts months</a>.. <a href="">Many</a> long-haulers <a href="">never became sick enough to be hospitalized</a>; some even started out with <a href="">mild or symptomless infections</a> that <a href="">only later blossomed bafflingly into debilitating disease</a>.</p><p data-<i>[<a href="">Read: Don’t be surprised when vaccinated people get infected.</a>]</i></p><p>Akiko Iwasaki, an immunologist at Yale, has <a href="">proposed three explanations</a>.</p><p.</p><p.”</p><p>The vaccines have also been linked with a bevy of side effects that, <a href="">while not inherently unsafe</a>, echo the fevers, aches, and fatigue that long-haulers often experience. People who have already encountered the virus also seem more likely to have an <a href="">initially rough go with their shots</a>..</p><p.</p><p.</p><p><a href="">One small study</a>,.</p><hr class="c-section-divider"> <i>relief</i> from their symptoms. For some, the improvements have already endured for weeks or months—the most extended calm some of them have had since their sickness began.</p><p>I’ve been so sick for a year. What if this makes me really bad again?</i>” But two days after receiving her first dose of the Pfizer vaccine on March 12, Wills-Rinaldi awoke and found that almost all of her symptoms had vanished. “For me, this is like a miracle,” she said.</p><p <a href="">HIV</a> and <a href="">certain cancers</a>, in the hope that they will rev up immune cells to purge roaming pathogens, or destroy aberrant or infected cells. If typical vaccines are study guides given to students before big exams, therapeutic vaccines are a next-best resource—open-book tests.</p><p>Still, speculating on what soothes long COVID layers the theoretical on top of the theoretical. In a <a href="">recent blog post on Medium</a>, Iwasaki, the Yale immunologist, expanded on her three original hypotheses, appending<b> </b>explanations of how the vaccine might tackle each of them.</p><p.”</p><p.</p><p.</p><hr class="c-section-divider"><p.</p><p>One patient-led <a href="">survey</a>,.</p><p.</p><p data-<i>[<a href="">Read: Unlocking the mysteries of long COVID</a>]</i></p><p.</p> <i>without </i.</p><p>Nevertheless, “there’s something kind of consistent in these reports,” Iwasaki told me. “I’m hopeful that there is something real underneath.” In the coming weeks, months, and years, researchers will try to home in on what that something is.</p>.</p><p.</p><p.”</p>Katherine J. Wu Kai Chen / The New York Times / ReduxLong-Haulers Are Pushing the Limits of COVID-19 Vaccines2021-03-25T07:10:37-04:002021-04-16T16:34:26-04:00People with long COVID were left out of vaccine trials. They are now navigating the new shots on their own.tag:theatlantic.com,2021:50-618330<p>It’s hard to know when exactly the first cases appeared. But certainly by January’s end, a slow trickle of post-vaccination infections had begun in the United States. They arose in the West, making headlines in <a href="">Oregon</a>; they sprouted in the <a href="">Midwest</a> and the <a href="">South</a>. Some of the latest reports have come out of <a href="">Florida</a>, <a href="">Texas</a>, and <a href="">Hawaii</a>. These breakthrough cases—discovered in people more than two weeks after they received their final COVID-19 shot—will continue to grow in number, everywhere. And that’s absolutely no cause for concern.</p><p>Breakthrough infections, which occur when fully vaccinated people are infected by the pathogen that their shots were designed to protect against, are an entirely expected part of any vaccination process. They’re the data points that keep vaccines from reaching 100 percent efficacy in trials; they’re simple proof that no inoculation is a perfect preventative. And so far, the ones found after COVID-19 vaccination seem to be unextraordinary.</p><p>Since mid-December, when the rollout of the newly authorized vaccines began, <a href="">nearly 40 million Americans</a> have received the jabs they need for <a href="">full immunization</a>. A vanishingly small percentage of those people have gone on to test positive for the coronavirus. The post-shot sicknesses documented so far seem to be mostly mild, reaffirming the idea that inoculations are powerful weapons against serious disease, hospitalization, and death. This smattering of cases is a hazy portent of our future: Coronavirus infections will continue to occur, even as the masses join the ranks of the inoculated. The goal of vaccination isn’t eradication, but a détente in which humans and viruses coexist, with the risk of disease at a tolerable low.</p><p <i>any </i>version of the coronavirus will also make a difference. If vaccinated people are spending time with groups of unvaccinated people in places where the virus is running rampant, that still raises their chance of getting sick. Large doses of the virus<b> </b>can overwhelm the sturdiest of immune defenses, if given the chance.</p><p>The human side of the equation matters, too. Immunity is not a monolith, and the degree of defense roused by an infection or a vaccine will differ from person to person, <a href="">even between identical twins</a>. Some people might have underlying conditions that hamstring their immune system’s response to vaccination; others might simply, by chance, churn out fewer or less potent antibodies and T cells that can nip a coronavirus infection in the bud.</p><p data-<i>[<a href="">Read: You’re not fully vaccinated on the day of your last dose</a>]</i></p><p told me. The pathogen rushes to copy itself, and the immune system recruits more defenders. The longer the tussle drags on, the more likely the disease is to manifest.</p><p>The <a href="">range of vaccine responses</a> “isn’t a variation of two- to threefold; it’s thousands,” Ellebedy told me. “Being vaccinated doesn’t mean you are immune. It means you have a better <i>chance</i> of protection.”</p><p>For these reasons and more, Viviana Simon, a virologist at the Icahn School of Medicine at Mount Sinai, in New York, dislikes the term <i>breakthrough case</i>, which evokes a barrier walling humans off from disease. “It’s very misleading,” she told me. “It’s like the virus ‘punches’ through our defenses.”</p><p>Vaccination is actually more like a single variable in a dynamic playing field—a <i>layer</i> circumstances, vaccines are still best paired with safeguards such as masks and distancing—just as rain boots and jackets would help buffer someone in a storm.</p><p data-<i>[<a href="">Read: People are keeping their vaccines secret</a>]</i></p><p>In some ways, the shots’ <a href="">staggering</a> <a href="">success</a> <a href="">in trials</a>—where breakthrough cases were <i>also </i>observed, causing appropriately minimal stir—may have papered over the inevitability of post-vaccination infections in more natural settings. “The vaccines exceeded expectations,” Luciana Borio, a former acting chief scientist at the FDA, told me. Now, as we exit what Borio calls the “honeymoon phase” of our relationship with the jabs, we need to temper our enthusiasm with the right amount of realism, especially as more data on the shots’ strength and longevity accumulate. Even excellent vaccines aren’t foolproof, and they shouldn’t be criticized when they’re not. “We can’t expect it’s going to be perfect, on day one, always,” Borio said.</p><p>Breakthrough cases also include asymptomatic infections, according to the CDC's current definition—which is different from the criteria on which the vaccines were originally judged. In clinical trials, the three vaccines cleared for emergency use in the United States were evaluated for their ability to <a href="">prevent <i>symptomatic </i>cases of COVID-19</a>, which they each do to a remarkably high extent. The Moderna and Pfizer-BioNTech jabs reduce, on a population scale, the risk of disease by about 95 percent; Johnson & Johnson’s clocked in at 72 percent among Americans.</p><p>The <a href="">numbers for asymptomatic infections</a> are <a href="">still crystallizing</a>, but they’re likely to be lower. Purging a virus before sickness sets in is a higher bar for the immune system to clear. “The trick is to distinguish between infection and disease,” Simon told me. “Whenever someone tests positive, the real question is, are they sick, and how sick are they? That’s a big difference.”</p><p>Efficacy, a figure specific to clinical trials, also doesn’t always translate perfectly to the messiness of the real world, where there’s immense variability in how, when, where, by whom, and to whom shots are administered. The vaccine’s performance under these conditions is tracked by a separate measure, called <a href="">effectiveness</a>. Studies rigorously examining vaccine <i>effectiveness</i> are challenging, but <a href="">early</a> <a href="">data</a> <a href="">suggest</a> that the Pfizer-BioNTech and Moderna shots are <a href="">living up to their initial hype</a>.</p><p data-<i>[<a href="">Read: The second COVID-19 vaccine is a rude reawakening for immune cells</a>]</i></p><p>The number of post-vaccination infections is also contingent on “the ongoing transmission situation,” Omer told me. “It depends on how much people are mixing.” A vaccine with a recorded efficacy of 95 percent, for example, doesn’t give everyone who’s vaccinated a 5 percent chance of getting sick. Not all of those people will even encounter the virus. The key is how vaccination changes the outcome for those who <i>are </i>meaningfully exposed: Among 100 individuals who might have fallen ill without the vaccine, just five symptomatic cases might appear.</p><p>A team at the CDC is tracking breakthroughs and will soon start reporting case counts, as well as any patterns related to where, or in whom, these infections are occurring, Martha Sharan, a CDC spokesperson, told me. Details like those matter. They can help experts figure out why post-vaccination infections happen, and how they might be stopped. “The reassuring part is, these cases will not go unnoticed,” Omer told me.</p><p>Most of the time, vaccines are far more likely to offer some help than none. Serious disease, hospitalization, and even death <a href="">will still occur</a>, as will less well-studied outcomes, such as the long-term symptoms that often arise from less severe disease. But should post-vaccination infections climb to unexpectedly high rates, backup plans will quickly kick into gear. Some shot recipients might get second or third shots to bolster their immune response; others might be administered a tweaked vaccine recipe to account for a new viral variant.</p><p>There’s something a touch counterintuitive about breakthrough cases: The more people we vaccinate, the more such cases there will be, in absolute numbers. But the rate at which they appear will also decline, as rising levels of population immunity cut the conduits that the virus needs to travel. People with lackluster responses to vaccines—as well as those who can’t get their jabs—will receive protection from the many millions in whom the shots <i>did </i>work. In a crowd of people holding umbrellas, even those who are empty-handed will stay more dry.</p>Katherine J. Wu Green / Bloomberg / GettyDon’t Be Surprised When Vaccinated People Get Infected2021-03-19T07:04:29-04:002021-03-19T10:37:36-04:00Post-immunization cases, sometimes called “breakthroughs,” are very rare and very expected.
https://www.theatlantic.com/feed/author/katherine-j-wu/
CC-MAIN-2021-25
refinedweb
38,737
51.28
I’m doing a test drive of the Berryboot Fedora install today. So far, I like it. It is a MATE desktop, that is in many ways comfortable. It didn’t ‘balk’ when I hand edited the /etc/passwd file to add the user “pi” with the same user id and group id as on Debian. I mounted my (now living on external disk) pi home directory and then logged in a ‘pi’. There’s all my stuff, and it works nicely. Launched FireFox. It is a faster browser than the IceWeasel and IceApe clones on Debian. No idea why. Using IceWeasel on Debian (the newer) had slow spots and was just “an issue”. Even with squid running. With the IceAgeNow page open, it tends to consume most of a CPU (likely the way ads are done on that site. I have seen this on several browsers with them, so now I use them as a test case.) At present, I have my site, WUWT, and IceAgeNow all open AND I’m puting in a posting. No type ahead. CPU is at 53% of one core. That’s a significant gain. I did install Squid on it, and found that it installs with a different user ID, so I can’t just point it at the same cache directory on the external disk drive. No big deal, I’m just leaving it with the defaults for now. Overall the system is clean and fast. It does have that “slightly stuffy” feeling of all things Red Hat. Crisp, but in a “you WILL do it my way” sort of way. Yet it works, and from a first look, rather well. I suspect that the new Debian (Jessie) is having “issues” from trying to integrate systemd and message bus processes. Fedora was where it was developed and integrated from the start (only one of the reasons I’m not fond of systemd… it forces change in so much other stuff, all of which will take a good bit of tuning and debugging to get back to where they were prior to the conversion…) But “it is what it is” and Fedora looks to be using those basics better, for now. It looks like some other folks like it too: [fedora-arm] New Raspberry Pi 2 with ARM v7 processor User Digital user0007 at yahoo.com Sun Feb 22 17:40:19 UTC 2015 […] Fedora is running indeed on RPI2 – you may use Berryboot – Boot menu / OS installer for ARM devices (). The Berryboot web site is It is needed to download 32.8MB zip file and to copy the unzipped files to a FAT or FAT32 formated microSD card. Then you may add to the Berryboot main menu the existing Fedora ARM 21 OS with MATE desktop. It is running very well, the desktop is nice and fast, Firefox v.33.1 is already pre-installed (Raspbian OS has only old Firefox version Iceweasel). Audio hardware should be added. The previous version included in Berryboot was Fedora 18 with xfce desktop – it was running very well too on RPI2. I’ll be “living on Fedora” for a few days now. Mostly to see how it does with a wider range of things. See what the “build script” for it would need to be to get “all my usual tools” in place. It isn’t all that big a deal to do: yum install squid instead of apt-get squid install but knowing what is already in, and out, is the longer part of the process. I’ve been using CentOS on the Antek/ASUS box, and it is just a slightly older Fedora with bit more QA and a package set more aimed at large data centers. The two are more alike than different. But what I care about is the browser performance, mostly. This one is significantly smoother. (Hey, they both can be nearly identical, but if one is using 1.5 X the CPU, it hits 100% and bogs while the other doesn’t. As of now, I’ve not seen this Firefox hit 100%…) I did mount a ‘real swap’ on it, and with just the browser and 2 terminal windows open I’ve got 16,052 blocks of swap already used. It’s a bit of a memory hog build. That may be where the extra speed comes from, a willingness to put more stuff in memory to save some cycles. On an all SD card system this would likely mean more SD card wear. As I really like having “real swap” this isn’t an issue for me. And as SD cards are cheap, just be ready to restore a backup if you run on an SD card for a year or two. Ah! On clicking “save” during the draft of this article: the CPU usage for FireFox went to 117%, so more than one core. It is both ‘multicore aware” and efficient. Nice. IIRC, IceApe is not multicore aware yet, limiting on one core. In Conclusion So that’s the update from this posting. If you are a Fedora / RedHat fan, or just like MATE, it seems to be an industrial strength ‘re-mix’ for the ARM chip set. So far. (this is still early in the test drive). Oh, and I’m running from a Class 4 card, so it is a reasonable speed chip, but not like a Class 10 Ultra at 30 MB/second. It’s not the chip that lets this be fast. Now that my home directory is external, a lot of the ‘issues’ of living on another OS for a while go away. All must current stuff and projects come with me. That makes ‘variety testing’ easier. Don’t be surprised if I’m bouncing between distributions for a while. But, with that said, the ease of making postings on a real FireFox without pauses is likely to keep me here when posting. At least for now. There is a reasonable selection of ‘the usual suspects’ installed. Libre Office and gparted and transmission all already in place. Didn’t see Gimp, though. So until I’m installing it now. “yum install gimp”. I’ve also not yet tested sound. That will be later today. It ought to work, though. We’ll see what happens on a youtube video… All in all, it is looking like a decent release. Just for grins, I swapped over to the Ubuntu MATE on the Pi. It is themed with a particularly pond slime green color. It also uses ‘squid3’ when you install squid… that then will not start due to ‘directory not found’. Moving a terminal window up to the top of the desktop causes it to ‘auto zoom’ to fill the entire window. I’ve found no way to make it go back to normal. I can minimize it to the tab at the bottom. You can close / kill it. But just “go back to normal” is not obvious. Very annoying. It does have a Very Nice system monitor with a ‘wiggly line’ for each CPU, each it it’s own color. Opening 3 tabs in FireFox it is using 4080 kb of swap (so glad I mounted it) but Ubuntu has always been a bit of a memory hog. It also has another interesting “feature”, at least I think it is a feature… maybe: At login, if you select “guest”, it just lets anyone log it. It looks like it is making a “disposible user” and it claims nothing is saved, warning that if you want to save anything, it needs to be copied off to somewhere else. IFF that is really true, it is a risk in that you are depending on their code to prevent malicious code insertion; but a benefit in that you have an incognito login on demand. It does also mean that I can’t let Ubuntu just be laying around as an alternat boot on any SD card where I’m seriously interested in security. Having a “powerfail, reboot, login for just anyone” is not a security feature. So: “Note to self: No Ubuntu as alternate boot choice on secure cards”. (Why I do these test drives… to find stuff like that which is not obvious when you just “install it in case I want to play with it some day”… It might be a Fine and Secure disposible user… but any time you let a person have a login and a USB port there is just sooo much potential… ) The Firefox seems the same as on Fedora, and it claims to have working audio ( I already had a video ad run on one page). So likely it is a very nice home user option. For me, I find enough anoying that I’m unlikely to do more than make sure it works and doesn’t do anything bad. With the pond scum color theme, the blow-up windows, and squid that doesn’t work (and I’m not interested in debugging) it is not a place I’ll be hanging out much. I might make a decidated very small chip with just Ubuntu on it for a ‘disposible system’ where it is 100% generic and all I ever do is log in as ‘guest’. With that, back to the bit mine ;-) Ah, if you grab the title bar with the mouse and pull down, the window goes back to normal… just don’t expect any wigits or controls to do that and don’t expect any clue anywhere to do it… Just an FYI… unlikely to bite folks unless they do a lot of the OS du jour like I do… With my home directory on /Diskname/home/pi it gets mounted on each operating system. That way all my ‘stuff’ comes with me. Well, that includes some config files that the operating system and its services and parts like to use. Things you don’t normally think about. One of them is the stuff that lets X-Windows work. In particular, there is a file named .Xauthority (note that it starts with a dot – that says “don’t show this file in a normal file listing with the ls command. You must use the -a for “all” option to see it, so do a: in your home directory to see it. When you do the ‘startx’ command to start the x-windows system (to get all that graphical interface stuff) it spawns an Xauth command that looks at that file. All well and good. Except… Ubuntu did something to it that causes it to be incompatible at least with the older Debian. I went to boot “my usual” system, and when doing ‘startx’, it just sat there ‘hung’. Not doing anything. Well, I did a CTRL-z to put it in the packground and looked around. Eventually figuring out it was the .Xauthority file that was having Xauth hang on it. I copied the last one from the old home directory default /home/pi/.Xauthority back in to /Diskname/home/pi and after issuing a “kill -9 {process ID number}” on the startx process, doing startx then worked. Thus my being able to make this comment using this chip. The point of it all? 1) This is why I leave the old defaults laying around when I do things. If I’m going to change a config file, I do “cp whatever.config whatever.config.DEFAULT” or something similar before I edit the original. I also leave the old default home directory in place (and even leave a symbolic link to it from the new mount point) when mounting a new home directory from another disk. 2) When you share things between systems, sometimes the problem does not show up on the system that caused it. 3) I’m documenting “how to fix it” if someone else runs into it. 4) This may be an example of how dbus and systemd can cause issues of compatibility. In the .xsession-errors file I found: which looks like maybe dbus was having issues. As this Debian release has not moved to systemd, I suspect that “something” was set in the .Xauthority file to say ‘expect systemd stuff’ and when it wasn’t there, this Xauth hung, hanging the whole thing. Maybe… that’s my debug speculation anyway. So just “be advised” that moving between non-systemd operating systems and those that are well into it may cause your X-Windows system to hang if you ever regress to the prior system. (And why on God’s Earth a program intended to do ‘initialization’ at boot time has its fingers into the X-Windows system is anyone’s guess… part of that whole “all your binaries are belong to us!” behaviour of DBus and systemd and why many ‘old hands’ don’t like it…) Hmmm the common refrain of “new and improved” what could possibly go wrong if we do this? But wait! There’s More!! …. I rebooted back into Fedora (after moving the image onto a very small 4 GB mini-SD chip) and noticed it was running about 1/2 my network bandwidth in the very nice 4 color CPU monitor… Why?…. I pondered. I have 3 terminal windows open, but I’m not using the network…. Then it shifted as the network usage fell, and CPU pegged…. Why?…. I pondered. I’m not using the CPU… A process named “dnf” was using my machine… Cutting to the chase. The dnf command replaces ‘yum’ (but keeps all the command syntax intact… so why change it? ) “Why? Don’t ask why. Down that path lies insanity and ruin. -E.M.Smith” So at every boot up this thing auto-launches an update process. That’s gonna get real old if I’m using a system that is launched from a static binary each time… and I scrub it back to clean after each use… It is also a ‘beacon’ to Red Hat and who knows who all else that this particular system has booted up. Hardly “incognito”. (Has Red Hat joined the Prism prison?… maybe… maybe not… have to look into it… but Systemd and DBus would be a great way to root around in what different programs on your computer might be doing… “Back Doors R Us NSA” folks would love that access… but it is only unproven paranoia at this point. You know, the normal expected part of the job of the security guy doing sysadmin kind of worries…) No worries, thinks I… I’ll just pull down ‘preferences’ and shut off automatic update… Uh, no… Doing a web search turns up dozens of folks trying to turn off auto-update from various bad things, one being an update of a package that killed 20 machines at one guy’s site. (Why I always turn off auto-update… Nobody but ME gets to decide when to put my machines at risk and nobody but ME gets to kill them and take the blame ;-) First off, due to the swap from Yum to dnf, there’s several different recipes. Second, it isn’t easy and I’m not sure you can ‘get them all’ in one place. At least one page had a discussion of how non-privileged users could update gnome from a popup request(!) and why can’t the sysadmin shut that off… Just ghastly… But here’s what I found: This first one talks about yum, that I think no longer applies to the Fedora release on the Pi. and a second answer: Now doing a systemctl command is not hard, but certainly not what a typical user of a Pi is going to be familiar with. Also note that this will not be persistent over reboots from a base Berryboot image. (It lets you ‘reset’ to the base image if desired to purge your changed data – i.e. make it amnesiac to some degree). So FIRST you have to configure it to not update, THEN save (‘backup’) the image with the changes from Berryboot, THEN remake your chip with that ‘modified’ image… Sheesh. All to stop it from constantly sucking down “only” 50 MB just for the metadata about packages. Lord help you if pakage updates happen too. From the first time they moved from being Red Hat to being Fedora the general direction of Red Hat Linux releases has been antithetical to my basic attitudes as a sysadmin. I’ve used it for decades (from the beginning, actually…) and it just keeps getting more “me hostile’ with each release. This one runs nice and looks good, but man, making it a locked down system I can trust is getting more an more difficult. BTW, automatic software updates sounds like a good idea, but it can crash and brick your system by surprise any time it happens, and it can be subjected to ‘man in the middle’ attacks. Also, since Prism means the ‘man in the middle’ might be your software vendor… for any system that you want to have be secure from that mode of attack, ALL automatic updates need to be firmly and undeniably OFF. You have an ongoing limited exposure to ‘zero day’ and recent hacks as you don’t have ‘the latest bug patches’, but as of the Prism Program I think that less of an issue for me than Big Brother, given the typical exploits found against Linux. (It isn’t that easy to crack it and I’m not much of a target anyway). At any rate, you can see that the general direction of Red Hat continues toward the Central Authority model with them deciding how you will run your shop… Oh Well… If I can’t get this sucker locked down in a reasonable chunk of time it will go back on the ‘never mind’ list… Oh, and this link about an earlier way to do it on an earlier system using yum has an interesting example of why I (and many many others) do not turn on auto-updates: And in comments it has the reference to the self-updating-users-problem: So while it feels like a smooth and somewhat faster system, I’m getting that same old “not for me” feeling again… I don’t need 50 MB of downloads on every reboot… In 1999 Red Hat had a share price of ~$80 per share that put the value of the company ahead of most North Carolina corporations including Lowe’s and Duke Power. Back then I paid $20 for a Red Hat disk. I failed to install Red Hat’s version of Linux because it was not “User Friendly” enough for semi-computer-literate people like this camel. I got stuck on the disk partitioning and never managed to get to a log in prompt. Later I tried Knoppix. I was able to log in but my screen resolution was lousy and I could not get rid of green lines at the top and bottom of my screen. Ubuntu turned out to be a distro that ordinary mortals could handle so I was able to break away from the tyranny of Bill Gates and his dreadful Windows operating systems in 2007. Compared to Windows, Ubuntu is compact so everything happens faster. It is also far more secure so there is no need to combat viruses, malware etc. A few years ago Ubuntu introduced the “Unity” GUI that I found totally obnoxious. It featured large disappearing icons and many of the Ubuntu “Apps” I liked stopped working. Fortunately, I found Linux “Mint” which is essentially Ubuntu prior to the Unity interface so now I run Mint. Rightly or wrongly I equate Fedora with “Red Hat”. While someone like Chiefio can play tunes on every distro imaginable I am not the least bit tempted to try Fedora. Once bitten, twice shy. Once you have a Linux operating system all the basic software needed for everyday business applications is available for free. Email, word processor, spreadsheet, data base, and much much more. All these basic applications work better than they ever will in Windoze. I still use Windoze compatible file formats so I can share my files with Windoze users. My problem with Linux is specialized software, such as the following: ACCOUNTING SOFTWARE I used Quicken’s “Quick Books” for my sub-chapter “S” corporation. Then Quicken demanded that I upgrade with the threat that my on-line banking feature would stop working. It turned out that they were not bluffing. I don’t respond well to coercion so instead of upgrading I installed “Gnucash” which is a free Linux program. While Gnucash is not as slick as Quickbooks nobody is trying to force me to pay again for software I already bought. TAX SOFTWARE In 2006 I was using TurboTax and was very pleased with it. Unfortunately it did not work well with Linux so I looked for an alternative and found “TaxAct”. IMHO TaxAct is superior to TurboTax and it is free if you don’t have to submit a state return (I live in Florida with no state income tax). IMAGE PROCESSING I use “Photoshop” and don’t like the Linux GIMP photo editor. Fortunately Photoshop works really well in Linux if you install WINE. WEB SITE EDITING I have not been able to find a decent Linux web site editor “App” buit it does not matter as my version of Adobe “Dreamweaver” and associated tools (Fireworks etc) works well in Mint 17. Today, only two of my applications still require a Windoze operating system: OPTICAL TIME DOMAIN REFLECTOMETER My OTDR is a uOTR204 from AFS (Advanced Fiber Solutions). While the “Post Processor” runs well in Linux, this OTDR uses a proprietary (Closed Source) USB driver. FINITE ELEMENT ANALYSIS I use the student version of “Quickfield” to solve differential equations. It requires a Windoze OS: EM, yes, automatic updates on Mint 17 Quiana have broken not only Firefox and seamonkey, but Opera browser as well. The browsers crash at random times — unacceptable. Tried all the “solutions” on the Mint forums (a fair number of people there seem to have browser problems) — no joy. Thing is, I ran Firefox for six months on Mint w/o any issue, then after a Mint automatic update, the problems began. I’m exhausted from dealing w/the problem, so pretty much given up on Mint for now & get my linux-fix from puppy linux which uses seamonkey. @Beng35: Sorry to hear of your “tale of woe”. It there no easy “roll back” method available? Or was this more of a major update rather than an incremental browser update? FWIW I’ve noticed that the ‘systemd’ release of Debian (Jessie) is a little faster, but also seems a little ‘quirkier’ to me. Nothing fatal, just little things. Like make a terminal window taller, your text goes to the top with that bar, and sits with 1/2 a blank page below it. Until…. Type something it it, the text is re-flowed all the way to the bottom, and rather abruptly. It ought to reflow as you stretch the window… smoothly. Oddly enough, CentOS (that is basically Fedora with more stability and some different settings and default packages) comes with automatic updates disabled by default. Data Center guys don’t like auto-update-break-by-whole-data-center-by-surprise…. It’s not just me ;-) That is likely also why I tend to pack-rat a collection of old releases. So when some surprise Aw-Shit shows up, I can roll back to older release levels if needed FWIW, since CentOS also runs a few levels back from Fedora (guess who gets to do the free QA work for CentOS ?…) you could likely install a CentOS release and find happiness again. I’m running 6.4 and 6.5 (last release pre-Systemd) and I’m happy with it. Firefox works fine. @GallopingCamel: The green lines are changed with the ‘overscan’ setting at boot time. BerryBoot does a nice job of asking if you have them, or not, and then doing the right thing. I’ve looked at the BerryBoot process and nothing at all prevents porting it to a non-Raspberry Pi box. I’ve gotten fond of it as it does several very nice things (more in a posting ‘later’) and would not mind having it on my Intel box… Then again, there may be enough variations in PC hardware to make a port complex… Fedora was just a marketing re-name of the Red Hat releases. They (Red Hat company) decided to use Red Hat for only the company, and divide the software releases into a Paid Support version and a Free-Don’t-Bug-Me-Kid version. To support the idea that one was worth paying for, they changed the names to be different. Red Hat Enterprise Linux (RHEL) was the one you paid money to get (and got to keep the Red Hat name) while the “freebee” was renamed Fedora. CentOS is made by a bunch of “folks like me” – data center junkies who work on big iron or buildings full of racks of small iron – who take Fedora and basically turn it into a free RHEL clone, but without the name or the price tag… Ubuntu is basically just a Debian with some “look and feel” added (that a lot of folks liked… right up to Unity ;-) and some eye-candy and a bit more Q.A. Debian has been known to occasionally have an update that causes ‘issues’… but you can back out things modestly easily (as long as it didn’t ‘brick’ on you). Ubuntu tends to hold back a bit more on release of new code and issue a more stable base. Most of the time ;-) My complaint about Ubuntu is that they, too, have an “all your system are belong to us!” mentality with it being “chatty” back to their site. I don’t know that there is any risk in it, as ordinary “keep me up to date with patches and such” does cause a certain degree of “I have / send me” chatter. I just don’t like the idea of my system: 1) Beacon Broadcasting: Here I am, I have THIS operating system with THIS code and you can look up all my exposures in your database. I run THESE applications, so you can know what I do, and I have exactly THAT configuration so you can ‘finger me’ based on those details. 2) Auto-Updating: Covered above. In a company, you do NOT want an auto update just before year end close of the books, quarter end financial reporting, month end, payroll, peak sales, etc. etc. so why do I want it just any old time at home? ( I have been known to get contracts at any old time that expect me to have a working workstation…) 3) Giving me loads of ‘eye candy’ and not so much core function. I hate to say it, but it’s true. I’d rather have the entire “build suite” pre-installed ( including not just the C compiler, but all the other software devo tools and add FORTRAN) than have a really cool to desktop look with the latest Cool Stuff and animated dancing crapletts that gets in the way of my doing things. 4) Suddenly changing my compute paradigm under me. Ubuntu with Unity, Red Hat with systemd (now infecting Debian, through it Ubuntu, Arch, and a few more). Not wanting to rehash the systemd wars, ‘init’ lost and I ‘get that’, but I don’t have to go willingly. It is just conceptually wrong to any long time Unix guy. Violates the core principle of “many small parts each doing one job very well” with one giant binary blob that is too dense to be provably secure and provably stable; with a ‘finger in every pie’ so if it DOES have an issue, the whole world is broken at once and you can’t shut off that part or backlevel it. In a year or two, if ANY security hole is found in systemd, then nearly 100% of those major distributions will all be exposed at the same time. Impossible to fix and close in time to be anything less than a disaster. (It is the Microsoft paradigm of design, IMHO. It is “the registry” in a way. Binary Blob From Hell stuck in the middle of everything.) Oh, CallopingCamel: Do note that Ubuntu Mint is on Berryboot for the Raspberry Pi. You might want to give it a whirl and let folks know what you think of it. Re-skinned in a nicer color ( I’m not fond of ‘pond scum’ as a color theme…) it’s a decent package for the average person, IMHO. Debian with a lot of the wrinkles taken out. Just not quite for me… You might want to look at: I count 23 packages in the ‘free’ listing alone, then there is the ‘pay for it’ listing… @All: FWIW, I’ve become a bit ‘smitten’ with Berryboot. It’s just a well thought out bit of code that does a few things very very well. I’ve found directions for ‘sucking in’ the operating system of your choice, for example. Want to make you own OS for the R.Pi and not get bogged down in the whole boot process? No problem. It’s about 5 lines of commands… I’m also increasingly fond of it as a platform for a secure computing platform. It stores your base OS as a squashfs file system (rather like I did with /usr /sbin and such in an earlier posting) and layers a writable layer over that. So at the end of any session you can choose to ‘reset’ to where you started. Incognito on the cheap. (Not quite perfect as some bits will still be on the SC card, but unless you have NSA on your back, good enough). You can, by default, encrypt the Linux part of the card. It is trivially easy to do and works well and efficiently. The kicker, though, is that you can clone any one OS on the card and you can back it up to other media and restore it again to that card or to another (just hold down the “Add OS” button and the choice pops up). Now “put it together”: Install a basic OS like Debian. Do you “build script” to get all the stuff on it you want. Pull out any bits that you don’t like. Customize whatever you want. Now ‘backup’ (really a kind of export) that image. It gives you a choice of ‘base image’ (that first installed bit) or the whole thing including your customized bits. This essentially merges your customized layer with the base layer into one squashfs image that is stored off on USB drive. Now, build a new card. Tick the ‘encrypt’ box. Hold down the add OS button, and pull in your custom image. Now your ‘base image’ has all the things you want in it. At this point, you can reboot on it, and go browsing or ‘whatever’. When done, at the next boot click the ‘reset’ to base button and all that history of where you browsed and what you did goes away. Also any virus or other malware along with cookies and all gets nuked too. You are back to your clean installed base. Or you can not do that and pick up where you left off. To me, this is a happy 1/2 house between wide open remember everything normal systems, and Tails that is forced amnesiac and a bit of a PITA to use. IFF you are a journalist working with secret sources or one of those secret sources, by all means, use TAILS. But for “folks like me” who just need a bit of privacy and some comfort too, this is a nice mix. It isn’t “NSA proof”, but likely good enough to beat the local gendarmes It will be strongly malware resistant at only a small penalty in comfort, by being ‘amnesiac enough’ and on my schedule of when to forget. At this point my intent is to make a Debian base release, with my ‘build script’ bits in it, and see if I can get tor working on it. It’s not quite Tails, but more than I need. Having that as a base OS choice, and right next to it a ‘regular’ build, lets me choose with one click which world to boot. I’m good with that. EM, I removed FF from updated Mint & installed an earlier version (the version on the original Mint installation DVD which had no issues) & it crashed quickly. So pretty much attribute it to Mint updates. And Opera also crashing supports the Mint origins of the issue. I guess I could reinstall the original Mint & update only FF, but that’s getting to be a bit too many issues. @Beng135: As Mint is just a look and feel layer of the basic OS, I’d be more inclined to think it was a general release issue. That could be checked by seeing if FF on Ubuntu non-Mint also has issues. But at this point it looks like your interest has likely moved on… I didn’t have any issues with FF on Ubuntu Mint on the RaspberryPi (Berryboot edition), but I also didn’t give it a big shakeout. For $60 and a weekend putting it together it might be an easier solution 8-) Then again, maybe not everyone likes to spend a nice All Saints Day hacking computers ;-) FWIW, this kind of ‘mysteriously a bunch of things stop working quite right’ is exactly the kind of issues I’d expect to manifest as folks go through the “teething” of moving from init based systems to systemd / message bus based. Part of why I’m not so interested in ‘living that dream’… The fundamental way processes communicate with each other and with the kernel is being replaced. The potential for Aw Shits (IMHO) is just too high. It might just be paranoia on my part (having lots of burned fingers from far less wide reaching ‘improvements’…) or it might be valid “visioning the future”. Time will tell. In a couple of years it will all be ironed out and stabilized in either case. I’m happy to live “back level” until then. But that’s just me :-] Classic reason why I stay 1 or 2 releases behind in windows versions. Why should I be the beta tester? I remember one urgent update in windows broke my network adapter. Had to physically remove the network card, install another crappy network card, then remove it and put back in the Intel Pro / 100+ card which had been working flawlessly for a long time, to get windows to install the proper old driver for the card which had never skipped a beat until windows “improved things”. I like the simplicity of the RC scripts myself, and from the sound of it systemd has its fingers in a few too many pies. I will stick with the non-systemd OS releases as well when I finally get the time to build up the new R Pi 2’s. @Chiefio, Thanks for explaining what I was perceiving “through a glass darkly”. I don’t have the smarts to “boldly go where Chiefio has gone before” so I will stick with Mint with the auto-update turned off. Currently my general purpose browser (Firefox) is behaving itself and so is Chrome that I use for Netflix on my old (Sony Bravia) HDTV that lacks direct access to the Internet. I hope the faithful here have noticed how much money you save by getting rid of your cable TV company. I bought two “4K’ TVs for $800 each and recouped the expense in less than a year. From here on I am saving $150 per month as my TVs no longer need set top boxes ($7 per month) or DVRs ($19 per month). Instead of paying the cable company for 100 channels that I never watch or $3 per VoD movie, I pay Netflix $9/month and watch what I want when I want. For sports lovers it won’t be long before you can buy sports programming direct from the source. That way you will soon be able to cut out the middle man (your cable company) and have direct access to the stuff you really want. For example I want to watch the ACC in general and the UNC Tarheels in particular. I live in Florida where there is nothing but the SEC and the ugly Gators. In a year or two you will be able to follow your favorite team no matter where you live. My wife insists on watching the local news and “Good Morning America”. Instead of paying the cable company to provide this kind of programming I bought an antenna from HD Frequency that pulls in about 50 channels. OK, most of those channels are about as interesting as watching paint dry but my wife can now watch the “Main Stream Media” (ABC, CBS, FOX etc) for free. While watching local TV broadcasts is free you are stuck with the advertising. In the run up to a presidential election the political advertising will be utterly obnoxious and now I don’t have a DVR I can no longer “Fast Forward” over the ads. There has to be a solution to this problem. Well, so as not to be a quitter and also waste hard-earned Mint experience, I reformatted the partition & reinstalled from the original DVD. Will not update ANYTHING, including Firefox & see how it pans out. If it crashes, then I’ll call it quits for Mint. Posting from it now, but sometimes the crash would not happen for several hrs of browsing (sometimes instantly). @G.C: You could always turn a Raspberry Pi into a DVR … Personally, I’d likely go the Model 2 route for the extra speed, but hey, buy them both, they’re cheep enough ;-) @Beng35: FWIW, I usually accumulate “images” of systems. Starting at “fresh install”, next at “just finished my usual configs”, then at “installed all my other stuff and moved in” and then at any other “update” point. I toss out the very oldest of the “incremental” parts (keeping the “fresh install” and “just finished my usual”) when I run out of disk space on the TB sized USB drive ;-) Takes the fear out of “Heck, I’m going to just reformat the sucker and try again” 8=} @Chiefio, A few years ago I built my own DVR using Hauppauge TV receiver cards installed in spare slots on my PC. It worked but packaged DVRs by Scientific Atlanta, Motorola and others worked better so I abandoned “Home Brew” and paid tribute to my cable company. Now I have jumped ship from the “Cable Company” I am once again open to a “Home Brew” solution to killing the advertising on the programs my wife watches. That Raspberry Pi approach you linked above is a fraction of the cost of my earlier Hauppauge solution. I will have to try it. Thanks, EM. Couldn’t sleep, so stress-testing Firefox 28.0 on freshly installed Mint — good so far w/a dozen opened tabs. Not sure how to image Linux. Do you image on a thumbdrive? Or can you do it on the linux partition itself, or another HD partition? I have plenty of room. Question. Instead of a separate partition, I just typically make a swap file at the partition root. Made it (2 Gigs) & turned it on. To get it going at boot-up, appended /etc/fstab with: none /mintswap.swp swap sw 0 0 Rebooted — “free” command reports it didn’t work? Remembering similar issue from previous Mint installs, changed to: /mintswap.swp none swap sw 0 0 Rebooted, and: bee@daisy ~/Desktop $ free total used free shared buffers cached Mem: 8176448 1672360 6504088 18716 136028 663988 -/+ buffers/cache: 872344 7304104 Swap: 2097148 0 2097148 and: bee@daisy ~/Desktop $ swapon -s Filename Type Size Used Priority /mintswap.swp file 2097148 0 -1 But: bee@daisy ~/Desktop $ cat /etc/mtab /dev/sda6 / ext4 rw,relatime,errors=remount-ro 0 0 proc /proc proc rw,noexec,nosuid,nodev 0 0 sysfs /sys sysfs rw,noexec,nosuid,nodev 0 0 none /sys/fs/cgroup tmpfs rw 0 0 none /sys/fs/fuse/connections fusectl rw 0 0 none /sys/kernel/debug debugfs rw 0 0 none /sys/kernel/security securityfs rw 0 0 etc, etc. The swap file doesn’t show on mtab. Anyways, doesn’t figure — mtab shows the “form” for miscellaneous entries to be like my original append (“none” first), not the later append that worked??? Tried the sequence again to confirm, and the same thing happened. Confusing. Oh, EM, you prb’ly know, but a tip I came across — appending vm.swappiness=10 to /etc/sysctl.conf is much better than the default value of 60. Supposely 5 is even better for a low-memory box. @Beng135: The best two ways of monitoring swap use, IMHO, are just to have ‘top’ running in a window as it reports swap size and use, and to do a ‘swapon -s’ that reports how much on which partition or file. It doesn’t really matter at all if you use a real partition or a swap file, IMHO. I usually have one of each ;-) As “swap” isn’t a mounted file system, it ought not to show up in mtab, IIRC. Swap is ‘special’ ;-) I think I have ‘swappiness’ set to 1 or some such. I’ve not done much with it and don’t really know what it does, other than making it more / less prone to swapping…. but part of me thinks “either you need to swap or you don’t”, so I’m not grokking the idea at some level… @Beng135: An “image” of a system is just a backup copy at a particular state. Preferably in an easy to recover and fairly fast way that preserves ALL the bits. An “archive copy”. I used the word “image” as many of the other words imply a particular tool to use. There are many… In The Beginning, when God (Dennis and Richie) created Unix, there was the “dump” command. It had nice options for doing ‘towers of Hanoi’ dump levels with 0 being the lowest level or ‘full dump’. Widely used for incrementals with three levels of incremental 9 (daily incremental) 5 (end of week) 3 (month end) and 0 quarterly full dump. Now it isn’t even showing up on my system when I do a “man dump”. Doing an apt-get install dump got and installed it, so it is still around, just no longer installed by default. So you could use dump to get an image. Then there was “tar”, the TApe Archiver. With it, you write to the tape drive by default. It has options for ‘append’ for incrementals. So you can do a full dump by default with something like: tar cv / Though looking at the Debian man page it looks like the ‘default to tape device’ is not stated any more, so it might have ‘issues’ on that ‘whole name space’ thing. There are a few dozen more options (or so it seems…) for just about anything you would like to do. A common one being to send the output to somewhere other than the default /dev/tape (especially now that many folks don’t have a tape drive…) One I commonly use is: tar cvf /Output/Filename.tar /DirectoryTo/StartWith You can also use this to move a directory and all it’s contents from one place to another. Decades back, that was hard to do as the ‘cp’ (CoPy) command only copied files. It can also be a tiny bit tricky to keep all the ownership and permissions settings right with copies and moves so I set those bits in tar as well. From memory it was something like: (cd /FromDir; tar cvf – .) | (cd /ToDir; tar xf – ) but with a couple of more tar settings for ownership and permissions preserving. Oh, and the FromDir and ToDir were usually $1 and $2 so they could be passed in with an argument like: cpdir /from/this/dir /to/that/directory (I had named my scriptlette ‘cpdir’) Now you might think you could clone a whole system with: cpdir / /archive/place but that ends up in a recursive copy problem when most of the system is in /archive/place and tar starts to copy it, too… BTW, now ‘cp’ has been made smarter and you can just do: cp -a /fromdir /todir “way back when” there was ‘cp -r’ to copy directories, but it didn’t keep timestamps and such quite right… With the arrival of AT&T Profit Motive we got the gratuitously changed System V consider it all the property of AT&T and send us money… It came with “cpio” that stands for “copy in / copy out”. It had slightly more convenient preservation of metadata and a few other more flexible things (like easier to do non-tape devices) along with enough flexibility and other options to choke a large horse. I’ve used it to backup and image whole systems too. Oddly, Raspbian has cpio installed by default. (but no ‘dump’… how odd…) The “cpio” command handles some things better than tar. IIRC it did the whole crossing file systems control and metadata handling a bit better. It has a zoo of options and I’ve used it to copy whole systems. About 20 years ago… The “grandaddy” way to image a disk (and with it, presumably the whole Unix / Linux on it) was the “dd”command (that stands for “Convert and Copy”, but ‘cc’ was already taken by the C Compiler so they went with dd instead). It has very nice options for things like turning ASCII into EBCDIC and vice versa… along with all kinds of block padding and other things that only really matter down in the land of raw blocks. I’ve often imaged a disk or copied a system with dd. To or from disks. To or from tape. All sorts of ways. You see this one still listed on the ‘how to set up your Raspberry Pi’ pages for a quick ‘back up your SD card’ via something like: dd bs=4M if=/dev/sdXN of=/usbBUPdir/sysemFromDate Where bs is block size of 4 Meg, ‘if’ is input file and ‘of’ is output file. The X is the drive letter and the N is the partition number. To take the whole SD card, one leaves off the N. For example, putting my SD card into a card reader on another Linux machine it might mount it at, say /dev/sdc1 and /dev/sdc3 (not mounting my swap partition at /dev/sdc2). To ‘grab the whole image’ I do: dd bs=4M if=/dev/sdc of=/usbBUPdir/dd_Secure_System_date This will grab every single block on the card and ‘image’ it onto that destination disk as the file “dd_Secure_System_date including all the encrypted blobs, any bit errors, the exact layout of the bytes even if files are heavily fragmented, etc. It will even copy 55 GB of ’empty space’ off of your 64 GB device and your image WILL be 64 GB in size. Where ‘tar’ and others can do various kinds of compression and since they read file by file restore things in full files of contiguous space. There are a few other tools too, and Berryboot brings their own with them. They have a ‘backup’ button and then you can “install” that image again in the future if desired. Which one to use? Depends a lot on what you are trying to do, which particular options matter to you, will you be moving between systems, are things very large but sparse, or just what all. Traditionally a “tarball” is used to move things around, often a compressed tar ball, so ending in .tar or .tgz or similar. Least space, lets you take only what you want, restore is automatically defragmented, and everybody has it. The use of cpio was mostly on System V type systems, but has spread. I find it less variable between systems than some early tar varieties. But often more complicated to set up. The “find” command has a built in ‘cpio’ option so you can easily use a find command to pick out any particular files you like based on just about any attribute and only THEY go to the output. You can spend weeks learning all the choices of the ‘find / cpio’ combinations… I rarely use it, but when needed it is nice to have. I often use ‘dd’ as it always just works. Wastes space. Doesn’t give fine control. Fast, grabs it all, and doesn’t complain much. Restores EXACTLY as was copied… Good for whole disk right back into THE SAME DISK TYPE, not so good for portability across divergence… These days I find myself using cp -a and rsync more. Which brings up rsync… This was designed to copy over the internet and handle stops, intermittent connections, timeouts, and restarts much better. But you can use it to duplicate a directory locally. rsync -avP /From/Dir /To/Dir It, too, has a few dozen options and will take about a week to learn them all (or at least most of them ;-) So I’ll use tar to make a tarball of some important directory or the /etc and /home/dir parts of a system where the rest is pretty generic. And I’ll use ‘dd’ to snag a chip image with full directory structure and partition structure preserved (including the FAT16, FAT32, ext4, swap etc etc layout) and restore it exactly. I’ll use rsync when I want a readable copy at the other end and want it checked as each file is copied. I’m slowly learning to remember to do ‘cp -a’ instead of my old ‘cpdir’ to just clone a subdirectory. And I rarely run ‘dump’ these days but will likely set it up just for nostalgia sake ;-) It tends to be focused on disk partitions and you are supposed to assure they are idle when dumping them. Kind of a pita really unless you go to ‘single user mode’ and stop all the daemons. Sorry you asked how to ‘image’ a system? 8-) BTW, I think that likely is not an exhaustive list. Systems Admins have been working for 40 years+ on better ways to copy exactly this or that thing (files, directories, partitions, disks, devices, whole systems) with all sorts of filtering for only some files not others and all sorts of partition spanning, or not and all sorts of conversions, or not, and all sorts of metadata preservation, or not, and portability, or not, and… So what all has been invented beyond my preferred set is hard to say for me. For example, I made cpdir before cp -a came along. I also have a ‘crush’ command that does a tar | compress > file.tarx that I made long before folks taught tar how to do inline compression. Since thousands of sysadmins were doing “tar | compress” someone just added compress as an option to tar. Now you can do it either way. Multiply that behaviour by a few dozen… As a final hint: Now, I mostly use dd to image the SD cards, tar | compress to grab selected file systems and sub-directories, and rsync to copy between systems or between device types. I rarely use dump, cpio, or cp -a as the first two are a pain to get right and the last one is ‘new’ for me. And remember “The man pages are your friend”… Thanks, EM. Sorry about turning this into a Linux discussion forum, but you’re so darn helpful. I edgamacated myself (and came across the dd command you illustrate — the different variations presented scared me a bit tho), but Mint had the tool I wanted — the Gnome Disk Manager. So I booted to the installation DVD to be safe, and used that program to image the 52 Gig mint partition to another, “share” partition made for miscellaneous uses (took ~30 minutes). The image file includes a separate bootsqm.dat file along w/it. So hopefully I can restore that to the mint partition if necessary. ‘Course, HD failure would nix that, but WD drives are very dependable. Prb’ly need to buy a few more thumbdrives tho (the drive manager can image to any big-enough attached drive or partition). Stressing Firefox alot — no problem yet. Great summary of copy image options! At work under Centos most of our backups are now written out to tape using gtar (Gnu Tar) mostly the same as traditional tar, and we just recently started using rsync to grab an image on a critical server and sync a backup server to the active server for our most important data. This gives us a manual fail over if the primary system takes a crap while avoiding the head aches of having a high availability cluster and hot fail over server. We just switch port numbers and the fail over server becomes the active data base and takes over the load with the same info the primary had at the time of the last rsync. This is a data base which does not change much being static data between updates. We still have some old backup tapes which were written out in UFS Dump but most everything has moved to gtar now. The big challenge with backups is technology, like changing tape formats and new tape loaders and such. Sometimes the new equipment or tape format forces you to over haul all your backup scripts. On small personal systems the same sort of transition has been going on for a while as spinning disks change from serial to parallel interfaces and now we have ssd disks (solid state disks) and of course the several versions of USB devices and SD cards. I like your idea of taking multiple images at various stages of development. Much easier to just say screw it and format and drop back a generation if you do something that totally mangles things. It looks like you can use dd for windows to do the same thing on a windows system. Guess I need to test that one of these days. @Beng135: Hey, it’s a Linux thread, so no worries! Many linux / unix commands can be scary, especially run as root. Lord help you if you swap i for o in that “if” and “of” set… The standard rule is to type the command, then sit on your hands while you read it, twice, and only then, pull a hand out to hit return… @Larry: Yeah, “time moves on” and the old backups don’t… I have some nice 9 Track Tape with some backups on it from about 20 years ago. Probably no longer readable even if I could find a 9 Track tape drive to use with them… IIRC, 10 years was the max to be expected before the oxide flaked and the magnetic flux faded… Not all that important a tape really ( one of them is the first 1/2 million primes that took weeks to calculate then… and now is a day, maybe… and the program to calculate them, that is better re-written since I think the language used may not still exist…) Most of my stuff has been in ‘rolling archives’ since those tapes as I learned from them… but a lot of it really ought to be tossed in the trash too. Does anyone really want my net-news archive from 1982?… or the config for it on an AIX machine? or…
https://chiefio.wordpress.com/2015/10/30/fedora-on-pi-a-short-note/
CC-MAIN-2021-04
refinedweb
9,357
76.96
About 7 months ago I completed work on re-implementing a data-flow process using Apache Spark and Kafka. After the soft-release I faced two main challenges with Apache Spark and I would like to share my experience and how I solved those problems. The implementation – Brief explanation Let me do my best to explain what the application does and how it does it without revealing sensitive company information. Below is a simplified illustration of what the process looks like. Fig. 1. The Spark application ingests data from two Kafka topics and then applies some computation on the messages from both topics based on some given business and application logic. The result is then output to another kafka topic. The application reads in batches from both input topics every 30 seconds, but writes to the output topic every 90 seconds. It is able to do this using a Spark feature called Window Operation. Basically a Window Operation allows you to apply computations on data streams that have been received over a set number of time windows. In the case of this application a unit of time is 30 seconds, the window length is 3 units of time, and the sliding interval is also 3 units of time. The application was deployed to production in client mode using docker. Challenges After the soft-release I ran into two major challenges; - Out of memory exceptions - Insufficient disk space errors Now I experienced these one after the other. The first one being the out of memory exceptions Out of Memory Exceptions: During the test release I started running into out of memory exceptions. After some research I figured out that I had to set the spark.executor.memory config param to something appropriate for the application. The spark executor memory determines the java heap size. By default the spark executor memory is 1G. I know what you are thinking, why isn’t 1G of memory enough. Well the truth is that even though the spark executor memory is set to 1G the application only has access to a fraction of that. This is as a result of how Spark manages it’s memory. Fig 2. Apache Spark Memory Management Model. For more detail on how Spark manages memory read this article. If spark.executor.memory = 1G then Spark memory = (1G - 300MB) * 0.75 = 525MB. So the Storage memory becomes 525MB/2 = 256MB. The Storage memory is the memory available to the application for caching data. Because the application made use of the window operation which puts a lot of data in cache it was always exceeding the 256MB especially during peak periods. To remedy this I set the spark.executor.memory to 4G, which now made the Storage memory = ((1G - 300MB) * 0.75)/2 = 1423MB Insufficient disk space errors: So after the fix for the memory issue and running the application for a few days everything seemed fine. But after some weeks our Systems team started noticing that the application was using a lot of disk space and it was growing consistently. As a temporary solution they would kill the docker container in which the application was running and spin up a new one. This cycle continued for weeks. root@docker:/app/code# ls -la /tmp/ drwxrwxrwt 110 root root 20K Jun 12 09:31 . drwxr-xr-x 75 root root 4.0K Jun 12 09:31 .. drwxr-xr-x 66 root root 4.0K Jun 9 11:55 blockmgr-0e460744-08e2-47a5-b706-d0fb026e0b59 drwxr-xr-x 66 root root 4.0K Jun 9 12:33 blockmgr-12b905bd-9d79-4ce9-b305-8ccf0b5b4b2c drwxr-xr-x 66 root root 4.0K Jun 9 12:00 blockmgr-16f0bfdf-f779-42da-b56f-ca392b97d29c drwxr-xr-x 66 root root 4.0K Jun 12 09:17 blockmgr-1808b3db-eb97-46d0-afcd-d205302fd863 drwxr-xr-x 2 root root 4.0K Jun 12 09:31 hsperfdata_root -rwxr--r-- 1 root root 258K Jun 9 13:14 snappy-1.1.2-0093e660-f792-4d6b-8d0d-9932aa3b4825-libsnappyjava.so -rwxr--r-- 1 root root 258K Jun 9 12:57 snappy-1.1.2-01f4243b-1cb5-4400-9878-a7c2a89788bc-libsnappyjava.so -rwxr--r-- 1 root root 258K Jun 9 10:40 snappy-1.1.2-022e3d11-d86e-4d22-bb39-850dcae123a2-libsnappyjava.so -rwxr--r-- 1 root root 258K Jun 12 09:31 snappy-1.1.2-03c1b15f-dcb1-4bdb-b9df-40cce262120f-libsnappyjava.so drwx------ 4 root root 4.0K Jun 9 13:03 spark-054a1704-dd37-4a72-8552-87031b45d362 drwx------ 4 root root 4.0K Jun 12 09:25 spark-0d6662aa-7036-41e4-b9aa-90ef9bfe0c91 drwx------ 4 root root 4.0K Jun 9 12:08 spark-0e51d1d9-749a-4f5c-8dba-c9283389a94f drwx------ 4 root root 4.0K Jun 9 14:21 spark-22831086-e35e-43e6-8df5-9232e5908bb6 With the help of the Systems team we found that the major culprit of the disk usage was the temp folder. We took a peek and found a bunch of temp files. The file size of each was very small but it adds up when you have a whole lot of them. After some research we found that when a Spark application starts up it creates three temp files. For some reason the container running our application was always restarting every couple of days or hours and each time it does that the application creates 3 new temp files. We also discovered that if a Spark application is deployed in cluster mode that the master node in the cluster will handle the clean up of the temp files. But since we deployed our application in client mode it was our responsibility to clean them up. Now as you can imagine our Systems team wasn’t very happy with always being paged due to disk space issues. So I had to figure out a way to clean up these temp files programmatically. So after further research I discovered SparkListner. SparkListener is a mechanism in Spark to intercept events that are emitted over the course of execution of a Spark application. One of such events is the OnApplicationStartEvent which is the perfect time to clean up the temp files. So I wrote a little logic to implement the SparkListner interface. public class CustomListener implements SparkListener { @Override public void onApplicationStart(final SparkListenerApplicationStart arg0) { final SparkTempCleanupService sparkTempCleanupService = new SparkTempCleanupService(); sparkTempCleanupService.cleanupTempFiles(); } } public class SparkTempCleanupService { public void cleanupTempFiles() { final File[] tempFiles = this.tempDir.listFiles(); //on a fresh start the tmp directory will have only four temp files, //if that is the case then don't bother. if (tempFiles.length > 4) { this.fetchTempFiles(tempFiles); this.sortTempFilesByLastModified(); this.selectTempFilesToBeDeleted(); this.deleteOldTempFiles(tempFiles); this.logger.info("Temp files cleanup COMPLETE!"); } else { this.logger.info("No temp files to delete. Nothing to do here, carry on..."); } } } The above is just a semi-pseudocode of the SparkListner implementation. We deployed and it worked like a charm. We haven’t had disk space issue since then. Lessons Learned - Understand your data and the kind of operation that needs to be performed on it and how that operation will be performed. This will give you some insight as to how much memory the operation may likely use and then using the Spark Memory formulae calculate how much memory to allocate. - Be aware of the temp files. Temp files are created each time a Spark application starts. Deploying a Spark application in client mode means you have to handle the cleaning up of the temp files. The temp files to be deleted are the ones whose name begins with either snappy-, spark-, or blockmgr-. Only delete the older ones, do not delete the ones created during the current application start up.
http://www.sibenye.com/2017/12/11/working-with-apache-spark-challenges-and-lessons-learned/
CC-MAIN-2019-35
refinedweb
1,276
56.96
See also: IRC log <scribe> Scribe: Cameron TB: motivated by discussion on the inkscape mailing list in the past month ... people interested in connectors again ... implemented a couple of years ago, a GSoC project ... someone suggested maybe we should see what the WG has to say about it ... or make a proposal to the SVG WG DS: do you have a proposal? TB: I asked them to make a proposal but they didn't, but I did ... I will compare the Inkscape implementation to the WG proposal ... both have this idea of a connector ... you have an object you're coming from, and one you're going to ... a start point on the object and an endpoint ... the original implementation had 9 points you could choose from, of which only the center point was implemented ... you go from the center of the bounding box to the intersection of the shape edge in the 8 directions ... so I don't think that's a good idea ... if you have a star, for example ... you probably want to go to the corners ... in the SVG proposal, you have this idea of a point ... which I think is a good idea. an editor like Inkscape has lots of snapping, so you can place it easily. ... once it's there one thing to be careful of is the user space ... if you scale/rotate the object around, the point should follow DS: it should shouldn't it? JG: you would just transform it with it TB: so that's one difference between the two, and I would favour the SVG proposal for that ... one thing Inkscape has, it allows you to specify that a connector consists of horizontal and vertical line, and it routes ... and then you can apply a curvature at the corners ... I'm not sure you really want to have the SVG group deal with the software of connector avoidance etc. DD: almost always when you draw graphs you want lines to avoid nodes TB: it's possible, it might make the spec overly complicated ... the one thing you have in the SVG proposal is the ability to specify a path ... so if you want something to avoid something, you can do it by hand DS: while still retaining the semantics of the connection TB: I think that's preferable DS: no one algorithm that we use is going to satisfy everybody ... so it's just an unbounded problem TB: I think it might be good to have, if you don't specify the path, to do a straight line or a simple horizontal/vertical thing DS: a compromise position might be possible, where you might want to say that slightly more complex -- you could say that you want a direct line, or that it uses only things along the horizontal/vertical axes ... and whether or not you want rounding on the corners ... it would not stop the lines from intersecting, but it would give a very simple routing that would solve many use cases TB: for keeping lines from intersecting, the problem here (Inkscape) is that they're all connected at the center point ... but if you move them apart a bit, which you can do with point elements, then it will look better DD: I can see the ports on a node being autogenerated DS: I can see that, it's not something I specified, but I did think about that TB: not sure how you would do it. you could do that Inkscape originally proposed behaviour DS: it's the nearest intersection with the stroke ... I think we can move forward on a Connectors module unless anyone thinks it's a bad idea ... rapid prototyping in Inkscape is a good idea TB: some things the SVG proposal has that Inkscape doesn't is the direction of the connection ... that could be implied by having the end and start DS: no it's not ... you always have an end/start ... it's whether it's two way or not TB: the ability to specify your own path ... the path length ... not sure how the path length is used ... it might've been so you could back off the length for the markers? DS: the pathLength attribute came from copy/paste CM: if it's a path like element, I think it makes sense to carry that attribute across TB: was focusable meant to be there too? DS: might've been a stub ... my idea, not sure how well I articulated this in the spec... [doug draws example on whiteboard] [explains accessibility/focusing benefit of implicit relationship set up by connectors, whether they are rendered or not] ED: if you have path data and you have a d attribute, do you get any sort of events when things move around? ... or detect it yourself using script? DS: I think that's an interested idea ... maybe an event when a port has changed ... don't know if you want to get an event any time anything changes DD: when new connections are created DS: or broken ... we should think about an API that maximises the ease with which somebody can make a library that plugs in to allow for different layouts ... what that API looks like I haven't examined ... I didn't have custom events in my script implementation ... connectioncreated, nodecreated -- when a port on a shape has been created ... if you have a connection where there would normally be drawn a line between things, and the two closest ports have changed -- [draws example] JG: is it even necessary to have that much complexity? ... it's not hard to compute the distance between two points ... and it's not always what you want CM: I'd like to see if something more general than for ports/connectors and script layout would be good for this use case JG: what might be useful is computing the closest points between two curves CM: that would be nice to have DD: there are lots of times you would want two edges to share a port as well DS: I did make consideration for whether a port could only hold one connection ... just throwing stuff out for API ideas ... wrote my script library two years ago, but it didn't have sophisticated layout stuff ... so rather than get in to specifics, we should look into an API so that script could plug in and perform layout TB: I looked briefly at what Dia does ... Inkscape algorithms do move the arrows from the center, by the way ... one difference in Dia is that you can specify a Bezier, quadratic or cubic, to connect the shapes DS: automatically? TB: you pick DS: but you don't say what the path is, you just say "I want a cubic"? TB: you can control it DS: if we're going to have an API for layout, one piece of metadata you might want to have is the weight ... ascribing a weight to a line ... could be useful for the script implemented layout algorithms DD: maybe even a vector of numbers, rather than scalars DS: if the attribute isn't processed, then it can contain any value, including a vector ... when I suggested adding a connector element, cyril suggested adding this functionality to path, so that it could be used as a fallback CC: can't remember saying that, but it would help with backwards compatibility JG: and having attributes to identify the start/end node CC: if the browser does not understand the behaviour it should understand the rendering DD: some of this edges have a default geometry which is shortest line between centroids, which means there is not always some path geometry RL: if you add more attributes to path, you're just adding a drag on when path is used and not used ... DOM node size in memory would increase CM: what about child elements to specify this? DS: feels unnatural TB: you can use a switch element for backwards compatibility DS: and if you're using script, you can just detect whether connectors are supported DD: one API people might want is to have automatic graph rendering ... suppose a user builds a graph, and they don't want to lay out the coordinates of anything, not even the nodes ... or they've only laid out the geometry of the nodes ... we'd assume that lines would automatically do the routing DS: I think we don't want to do automatic routing, or layout of nodes ... but what if there was a layout=auto and the UA could do whatever it wanted with the layout RL: the inconsistency in rendering would be too much of a problem <scribe> ACTION: Doug to add a weight attribute to the connectors spec [recorded in] <trackbot> Created ACTION-3144 - Add a weight attribute to the connectors spec [on Doug Schepers - due 2011-10-27]. <scribe> ACTION: Add attribute for auto straight/curved lines between nodes to the connectors spec [recorded in] <trackbot> Sorry, couldn't find user - Add <scribe> ACTION: Doug to Add attribute for auto straight/curved lines between nodes to the connectors spec [recorded in] <trackbot> Created ACTION-3145 - Add attribute for auto straight/curved lines between nodes to the connectors spec [on Doug Schepers - due 2011-10-27]. ISSUE: Investigate a script API for listening to object changes to facilitate JS layout more easily <trackbot> Created ISSUE-2426 - Investigate a script API for listening to object changes to facilitate JS layout more easily ; please complete additional details at . RL: I think this is more useful for authoring tools ... in terms of browser implementation, I think there are more things important to implement ... but to get authoring tools to interoperate I think that would be higher on their priority list DS: I think giving people some behaviour in browsers for free will promote the use of this more ... I'm trying to make very minimal additions to what the browsers would have to support ISSUE: Polylines and maybe other elements might support rounded linejoins, like rx/ry for rects <trackbot> Created ISSUE-2427 - Polylines and maybe other elements might support rounded linejoins, like rx/ry for rects ; please complete additional details at . CM: tensor control points on the meshes, how useful would they be? TB: it would be useful for pdf import at least ... cairo supports it [tav draws an example of a patch with tensor points] [issue with having to specify otherwise missing stops just to give the tensor point] scribe: another issue do you allow different colours instead of using previous colours defined at intersection points of patches ... PDF allows mesh patches to share edges in whatever order and position CC: so you would need to use one mesh per PDF patch, would result in a lot of output when converting CM: wonder if PDF allows points to have different colours on different sides CC: you could just have a zero size patch in between CM: it's probably not as useful for realistic looking images JG: so if PDF already allows strange patch ordering, it will be expensive to convert to SVG ... if you do exactly what PDF does ... TB: it's not good for editing JG: if you extend that not just to share one edge, but more than one edge CC: so start with something PDF-like, and add the ability to specify which edges are shared JG: if we do allow just a grid, and allow that grid edges not be shared, then effectively you can draw whatever you want CC: I'm fine with going with a grid, but I'd like to see some tests ... some examples of grids built with an authoring tool, and some made by other means maybe vectorisation tools TB: I saw one once where you specify triangles with no order at all, and another with arbitrary points ... I'd like to know why PDF does it like that <scribe> ACTION: Gaurav to ask about PDFs using non-grid gradient meshes [recorded in] <trackbot> Created ACTION-3146 - Ask about PDFs using non-grid gradient meshes [on Gaurav Jain - due 2011-10-27]. TB: another question is path syntax ... don't know whether you need to include H/h/V/v ... what might be useful is the shortcut curve commands, C/c/S/s CM: they don't make sense at every patch edge ... you could disallow them in those positions CC: it does make sense TB: ah it's not so useful after all, because you're not specifying the mesh grid lines as a whole ... what about Q/q/T/t ... trivial conversion but it's probably not worth it ... the last issue is arc commands ... the algorithm for filling this expects a bezier ... so you'd need to convert arcs to beziers ... I'm not sure about it ... the authoring tools can handle CC: so we're introducing a new type, right? ... a new datatype ... the path attribute would have a different datatype? TB: the form of arc that's used for regular paths is not that friendly CC: what if you have a path with arc commands and you want to fill it with a gradient mesh ... now what about the new path commands, catmull-rom and turtle graphics? CM: if you are disallowing arcs, you should disallow catmull-roms ... at maximum, include ones that convert into exactly one bezier JG: I know in Inkscape it would be easy to reuse the existing path reading code RL: it wouldn't be hard to have a flag on the path data reader [discussion about which commands to allow] CM: z feels a bit funny to me, since it goes to the end point instead of the start point of the patch path CC: if you leave off a Z, it's like you put a Z anyway yes? CM: that would make me happier someone: do we need letters at all? RESOLUTION: We allow just C/c/L/l in mesh path data ... We will leave out tensor control points from gradient meshes ... We will not allow multiple colours at mesh intersections, just use zero size patches instead <scribe> ACTION: Tav to update the mesh gradients page with these resolutions [recorded in] <trackbot> Created ACTION-3147 - Update the mesh gradients page with these resolutions [on Tavmjong Bah - due 2011-10-27]. CC: There's a document called Advanced Gradients Requirements, Anthony was editing it ... someone asked me to do some fixes to it ... I'll make those edits <tbah> TB: so what do we do about this? jwatt was looking into it CM: let's make these proper SVG tests for the Integration spec ED: the intrinsic sizing fixes in 1.2T got ported over to 1.1SE RL: current mozilla thoughts from jwatt on how to resolve the issues <scribe> ACTION: Doug to tell Cameron what is wrong with the table generating scripts for Integration [recorded in] <trackbot> Created ACTION-3148 - Tell Cameron what is wrong with the table generating scripts for Integration [on Doug Schepers - due 2011-10-27]. <scribe> ACTION: Cameron to contact jwatt about SVG sizing to summarise his thoughts so we can talk to CSS at TPAC [recorded in] <trackbot> Created ACTION-3149 - Contact jwatt about SVG sizing to summarise his thoughts so we can talk to CSS at TPAC [on Cameron McCormack - due 2011-10-27]. RL: upper limit for numOctaves ... I think Opera has a limit CM: and I think IE mentioned he limits it to 10? RL: in some of the attributes, you have integer optional integer ... but there's no type, it's number optional number ... wondering whether it makes sense to have an integer optional integer type ... I'd like it to cause the attribuet to be invalid if numbers are specified in the DOM attribute JG: I'd be against putting an explicit limit for numOctaves ... it shouldn't make a visible difference where you stop after a while RL: next, clip ... the meaning of the numbers differs between CSS 2.0 and 2.1 ... would be good to align with CSS 2.1 ... next, feTurbulence has seed="" which is really an integer, so why not make it one instead of a number and defining rounding ... next, would like to remove the duplicate SVGLoad, SVGAbort, etc. ... we should also drop the requirement to dispatch load to every element ... next, overflow:auto on markers ... doesn't make sense in combination with overflow-x/overflow-y ... makes sense in the current firefox implementation, which is opposite to what the spec says ... so I'd like auto to be equivalent to hidden for markers ... next, there's a test with styles on non-containers ... presentation attributes on elements to which they have no effect ... it's a performance problem ... next, are we taking SMIL3's allowReorder into SVG? ... some other SMIL3 things have been requested for SVG ... would be good to go through SMIL3 to find features we want to import <ed> [LUNCH] <ed> meeting adjourned, we'll discuss the remaining topics at TPAC <ed> trackbot, close telcon <trackbot> Sorry, ed, I don't understand 'trackbot, close telcon'. Please refer to for help <ed> trackbot, end meeting <ed> trackbot, end meeting This is scribe.perl Revision: 1.136 of Date: 2011/05/12 12:01:43 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/node/port/ No ScribeNick specified. Guessing ScribeNick: heycam Found Scribe: Cameron WARNING: No "Present: ... " found! Possibly Present: CC CM DD DS ISSUE JG RL TB ed https karl karlushi someone tbah trackbot You can indicate people for the Present list like this: <dbooth> Present: dbooth jonathan mary <dbooth> Present+ amy Got date from IRC log name: 20 Oct 2011 Guessing minutes URL: People with action items: add attribute auto between cameron curved doug for gaurav lines nodes straight tav[End of scribe.perl diagnostic output]
http://www.w3.org/2011/10/20-svg-minutes.html
CC-MAIN-2017-30
refinedweb
2,989
68.2
QtDesktop and workspace switch under GNOME Hi, I am using QtDesktop components with Qt 4.8. I have 2 qml files written as follows Toto.qml @import QtQuick 1.1 import QtDesktop 0.1 ApplicationWindow { id: toto width: 200 height: 200 visible : true Text { id: text anchors.fill: parent text: "toto" } Tutu { id:tutu } }@ and Tutu.qml @import QtQuick 1.1 import QtDesktop 0.1 ApplicationWindow { id: tutu width: 200 height: 200 visible : true Text { id: text anchors.fill: parent text: "tutu" } } @ The goal is to have 2 independent windows managed by the same process, running qmldesktopviewer Toto.qml works fine. But when I switch workspace and then back to the original workspace, I have only 1 window displayed. Using xwininfo, I can see that the other window is in 'UnmappedState'. Debugging qapplication_x11.cpp, I can see that - when switching wspace 1 to 2, there are 2 UnmapNotify events , one for each window - when switching from wspace 2 to 1, there only 1 MapNotify event, for firstly created window Toto I do not understand why only one MapNotify event is generated when switching back. Does anyone have an idea why this is happening? Any hint very wellcome. Thks
https://forum.qt.io/topic/23830/qtdesktop-and-workspace-switch-under-gnome
CC-MAIN-2017-43
refinedweb
198
59.7
Here we will see how to find the closest value for every element in an array. If an element x has next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1. To solve this, we will use the set in C++ STL. The set is implemented using the binary tree approach. In binary tree always the inorder successor is the next larger element. So we can get the element in O(log n) time. #include<iostream> #include<set> using namespace std; void nearestGreatest(int arr[], int n) { set<int> tempSet; for (int i = 0; i < n; i++) tempSet.insert(arr[i]); for (int i = 0; i < n; i++) { auto next_greater = tempSet.upper_bound(arr[i]); if (next_greater == tempSet.end()) cout << -1 << " "; else cout << *next_greater << " "; } } int main() { int arr[] = {10, 5, 11, 6, 20, 12}; int n = sizeof(arr) / sizeof(arr[0]); nearestGreatest(arr, n); } 11 6 12 10 -1 20
https://www.tutorialspoint.com/find-closest-value-for-every-element-in-array-in-cplusplus
CC-MAIN-2021-49
refinedweb
205
73.68
What comes after 'iptables'? Its: Performance: - Support for lookup tables – no linear rule evaluation required - No longer enforces overhead of implicit rule counters and address/interface matching Usability: - Transactional rule updates – all rules are applied atomically - Applications can subscribe to nfnetlink notifications to receive rule updates when new rules get added or removed - nft command-line tool can display a live-log of rules that are being matched for easier ruleset debugging What is nftables? Nftables was initially presented at the Netfilter Workshop 2008 in Paris, France and then released in March 2009 by long-time netfilter core team member and project lead, Patrick McHardy. It was merged into the Linux kernel in late 2013 and has been available since 2014 with kernel 3.13. It re-uses many parts of the netfilter framework, such as the connection tracking and NAT facilities. It also retains several parts of the nomenclature and basic iptables design, such as tables, chains and rules. Just like with iptables, tables serve as containers for chains, and the chains contain individual rules that can perform actions such as dropping a packet, moving to the next rule, or perform a jump to a new chain. What is being replaced? From a user point of view, nftables adds a new tool, called nft, which replaces all other tools from iptables, arptables and ebtables. From an architectural point of view it also replaces those parts of the kernel that deal with run-time evaluation of the packet filtering rule set. Why replace iptables? Despite its success, iptables has several architectural limitations that cannot be resolved without many fundamental design changes. The main problem stems from the fact that the ruleset representation is shared by the frontend tools like iptables and the kernel. This has multiple drawbacks. When a rule is added to an iptables ruleset, for example # allow inbound ssh connections iptables -t filter -A INPUT -p tcp --dport 22 -j ACCEPT Then the iptables tool first needs to dump the current ruleset — essentially an array of various data structures — then modifies this blob to contain the new rule, then send the entire set of rules back to the kernel. This also means that every add and remove operation is slow, as the entire table has to be processed and then replaced with a new one. The kernel has no idea what rule got modified, added or removed, from the ruleset in the table being replaced. All the kernel sees is that a new table ruleset is being loaded, it cannot detect which part of the rule set was removed or added, and which part of the ruleset has changed as a side effect (such as changed offsets when a rule jumps to a different chain). Userspace has no idea what the ruleset is doing. All the iptables tool provides is parsing of the command line arguments and the translation to the binary representation that the kernel expects. Userspace has no notion of ”IP” or ”TCP”. This also prevents rule set optimization steps in userspace without replicating the evaluation logic implemented in the kernel. Addition and removal of rules is not an atomic operation. If two rules are added at the exact same time, only one of those will take effect, as each process independently manipulates the current table, then asks kernel to swap the old with a new one — so the process that comes last will remove any changes made in-between its dump and commit operation. This was not a problem when iptables and its predecessor, ipchains, was originally developed at the end of the 1990s, as only the system administrator was expected to change packet filter rules. Nowadays this has changed. For example applications like docker or libvirt want to add NAT rules to provide connectivity for containers and virtual machines. The iptables rule set format is set in stone forever. Aside from a ”revision number” scheme that can be used to extend functionality provided by matches and targets the format of the rule blob cannot be altered without breaking compatibility. The current format imposes several restrictions: The kernel always performs matching of ip source and destination address, even if no address was given (the kernel will compare packet source and destination with 0.0.0.0/0 which will always succeeed). The input and output interface is also always tested for each packet, because like IP addresses these are stored in the header location of each rule. A counter is incremented whenever a rule matches. This is nice from a user’s perspective, as it allows for an easy and simple way to check if rules are being evaluated as expected, but this does become a performance problem when millions of packets are processed per second. An ever increasing number of special-features matches and targets. iptables comes with several ‘matches’ that implement various functionality to decide if a given packet is supposed to ‘match’ a given criterion. There a some basic matches that e.g. allow matching on UDP or TCP port numbers from the packet payload, and several matches that perform more elaborate checks, for instance the conntrack match that queries the connection tracking state and can be used to e.g. test if a packet is a reply to earlier packets seen in the other direction, policy matching to evaluate if a given packet is subject to IPsec processing, or even if a packet is being processed on a particular CPU (useful for load-balancing). When support for a new protocol has to be added both the kernel and iptables userspace need to be extended accordingly. iptables also has a number of more exotic targets — for example the HMARK target to set a packet mark based on a hash function (added to support load balancing via policy routing). Another problem is that iptables doesn’t allow for multiple actions (targets) to be executed in a rule. For instance it’s possible to create a rule that logs a packet, but we cannot — in the same rule — instruct the kernel to then also drop that packet. This makes it necessary to duplicate some rules when more than one action is desired, such as mark and accept. basic matching features are limited An iptables rule can only be used to match at most one source address (or network), and one destination address/network. It can also match against one source or destination interface only. To match against a list or range of addresses, external facilties such as the ”ipset” tool need to be used. nftables is designed to overcome all these limitations: - Support sets and maps to allow compact representation of rules rather than forcing a linear top-down evaluation approach as with iptables. - Addition and removal of rules is always atomic, no races happen when two programs add/remove rules simultaneously, i.e. userspace deletes and adds individual rules instead of the entire table. - The kernel provides a unique identification number for each individual rule which makes deletion of rules a lot simpler than with iptables - Applications can ask the kernel to get a notification when rules are added or removed. - No distinction between matches and targets anymore. nftables uses what it calls ‘expressions’ to implement functionality. It is possible to e.g. set a mark on a packet and accept it in the same rule. - Move most rule handling to userspace. While processing remains in the kernel, protocols are now handled in userspace.For instance, the kernel no longer knows how to load the TCP destination port, an IP source address, or the SPI from ESP headers. Instead, the nft tool would ask the kernel to load a number of bytes starting at a particular offset.Adding support for new transport headers therefore no longer needs kernelchanges, the nft tool only needs to be extended to know about the header fields,their names, sizes and location. - Allow monitoring of rule updates. The nft tool can be used to monitor changes in the rule set, e.g.”nft monitor” displays every rule added and removed from the kernel.It also offers a ‘trace mode’ where a system administrator can for instance do ‘nft add rule mangle prerouting ip saddr 10.2.3.4 meta nftrace set 1’. ”nft monitor trace” will then display every rule that gets matched by packets originating from the IP address 10.2.3.4. Nftables at a high level nftables implements a set of instructions, called expressions, which can exchange data by storing or loading it in a number of registers. In other words, the nftables core can be seen as a virtual machine. Applications like the nftables front end-tool nft can use the expressions offered by the kernel to mimic the old iptables matches while gaining more flexibility. For example, when nft is asked to check if a packet matches a given TCP destination port, it instructs the kernel to load 2 bytes at offset 2 from the start of the TCP header into a given register and then to compare that register with an immediate value (i.e. the port number): # nft add rule ip filter input tcp dport 22 To better understand what is happening behind the scenes, one can pass the --debug=netlink option to nft. Doing this with the above statement would yield the following debug output which shows the generated individual expressions that make up the rule: [ payload load 1b @ network header + 9 => reg 1 ] [ cmp eq reg 1 0x00000006 ] [ payload load 2b @ transport header + 2 => reg 1 ] [ cmp eq reg 1 0x00001600 ] So when the rule is evaluated in the kernel, it will first load the IP protocol field into register 1, then compare it with the number 6 (to check if the transport header is TCP), then load the TCP destination port, then check if it matches the number 22 (0x1600 shown here is the hexadecimal display of 22 in network byte order). The kernel is agnostic to the protocol details — it only loads data into registers and performs some comparisons. This register approach means that most high-level functionality is achieved by chaining these basic building blocks in some way. Most expressions either take data from registers or know how to store something in a register, others only have side-effects. Examples of expressions that don’t use registers: - log: causes the kernel to emit a log entry, either using the kernel ring buffer (like old iptables -j LOG or nflog, like iptables -j NFLOG). - limit: often combined with the log expression to avoid log flooding, can also be used to implement rate policing. Examples of expressions that store data in registers: - payload: loads data from the packet payload and places them in registers. - immediate: store a given number in a given register. This is for example used to implement the accept and drop statements in the kernel — when user would ask to drop a packet, nft will use the immediate expression to store the verdict code (accept, drop, …) in the verdict register. - meta: Ancillary data, such as the name of the input or output interface names the packet arrived on, the skb mark, the length/size of the packet, … - ct: Provides access to conntrack related data, such as the packet’s direction (original, reply), the conntrack counters (bytes/packets seen so far), the state (new, established, …) Some of these expressions also allow setting a few attributes, for instance the payload expression can also do the reverse — take a register content and place it into the packet at a certain location, the meta expression can set the packet mark, and so on. Other expressions can be used to manipulate register content. For example, if user would ask not to match the exact IP address 10.0.0.0 but the network 10.0.0.0/8, then nft tool would ask to load the IP address into a register, use the ‘bitwise’ expression to only retain the upper part of the address (10), and compare the register with the immediate value 10. The same is true when e.g. asking to match interface names starting with a particular prefix, e.g. ‘ppp’. Other expressions perform tests on a register: - cmp: checks if the content of a register is less, equal or greater than a given immediate value. This also means that kernel doesn’t need to support e.g. matching IP address ranges — userspace simply specifies two compare operations: reg1 >= 0xc0a80010 and reg1 <= 0xc0a80280 to determine if the IP address placed into the register is within an address range. - lookup: checks if register content is present in a given set. nftables supports sets of data, i.e. a given number of addresses, port numbers, interface names and so on. For example, in nftables one can create a rule that matches when the TCP destination port is contained in a set of values: # nft add rule ip filter input tcp dport { 80, 443, 8080 } Internally nft creates a new set, containing the three given numbers as keys, then asks the nftables machine to check if it can find a result: [ payload load 1b @ network header + 9 => reg 1 ] [ cmp eq reg 1 0x00000006 ] [ payload load 2b @ transport header + 2 => reg 1 ] [ lookup reg 1 set __set%d ] These are almost the same generated expressions as before, we check if the packet is a TCP packet, but instead of comparing the register with an immediate value, we ask the check if the register is contained in a set. A set can not only store keys — it can also store key and value pairs. The lookup expression can also retrieve the values from such key/value sets, i.e. userspace can create a table mapping keys to values and then ask to fill a register with content retrieved from that set. This can be used for instance to implement branching (verdict maps) in the ruleset. Verdict maps (aka jump tables) While an iptables rule can tell the kernel to jump to a custom chain rather than moving to the next rule, it is not possible to use branching. For instance, let us consider the following: iptables -N MGMT_PACKETS iptables -N VM1_PACKETS iptables -N VM2_PACKETS iptables -A FORWARD -i eth0 -s 192.168.0.1 -j MGMT_PACKETS iptables -A FORWARD -i tap0 -s 10.0.0.1 -j VM1_PACKETS iptables -A FORWARD -i tap1 -s 10.0.0.2 -j VM1_PACKETS This adds three new chains, then tells the kernel to evaluate packets being forwarded and coming from specific combinations of source addresses and input interfaces to a chain for more specific processing. Since rule set evaluation is linear, the kernel has to check all these rules until it finds one that matches — this will not scale when hundreds of interface and address combinations need to be considered. What should be used here is a lookup table. With nftables, it is possible to express the above in a single rule: chain forward { type ip filter hook forward priority 0; policy accept; iif . ip saddr vmap { eth0 . 192.168.0.1 : jump mgmt_packets, tap0 . 10.0.0.1 : jump vm1_packets, tap1 . 10.0.0.2 : jump vm2_packets } } chain vm1_packets {} chain vm2_packets {} chain local_packets {} The nftables ‘.’ syntax is used to concatenate two distinct sources together to obtain a single key: Here we tell nftables that we want to retrieve a jump target using a key that consists of the input interface and the IP source address. Now imagine the example with dozens or even hundreds of such ‘jump to this chain if packet came from this given interface/address pair’ — with iptables this will simply not scale anymore. With nft, however, adding more jump targets to the lookup table has no extra processing cost except the extra memory useage needed to store the additonal information. Flow statement Iptables offers a match named ‘hashlimit’. It is like the ‘limit’ match, except that the limit can be keyed to certain properties, for example one can use the hash limit to provide a limit per source IP address, or even per source and destination pairs. To do this, the hashlimit match dynamically creates these rate-limit counters and stores them in a hash table — hence the name. Instead of just implementing a 1:1 replacement, nftables applies the same concept in a much more generic manner: rather than just allow to dynamically instantiate limits per IP addresses or networks, it allows the user to instantiate an expression and key it to an arbitrary set of criteria. Example to allow a similar effect than the hashlimit match in iptables: nft add rule ip filter input flow table mylimit { ip saddr . tcp dport limit rate 10/second } The flow statement also offers a timeout option to automatically remove flows once it has not been seen anymore for a given period. The same statement can also be used for per-host or service accounting: nft add rule ip filter forward flow table ipacct { ip daddr counter } nft add rule ip filter forward flow table portcount { tcp dport counter } Flow tables can be listed with the command nft list flow tables And its contents can be inspected with nft list flow table filter ipacct table ip filter { flow table ipacct { type ipv4_addr elements = { 192.168.7.1 : counter packets 4 bytes 336, 192.168.0.7 : counter packets 10 bytes 688, 127.0.0.1 : counter packets 18 bytes 1512} } } Here the flow table lists the seen IP addresses and their counters, which provides a simple way to perform per host traffic accounting. Inet family To make it easier to create rule sets for host that use both IPv4 and IPv6 nftables comes with a new ‘inet’ family that can be used to create a single rule set used for both IPv4 and IPv6. This is done by using the inet keyword instead of the default ip one: table inet filter { chain input { type filter hook input priority 0; policy accept; tcp dport ssh ip saddr 1.2.3.4 } }’. One can inet filter input 5 [ meta load l4proto => reg 1 ] [ cmp eq reg 1 0x00000006 ] [ payload load 2b @ transport header + 2 => reg 1 ] [ cmp eq reg 1 0x00001600 ] inet filter input 6 [ meta load nfproto => reg 1 ] [ cmp eq reg 1 0x00000002 ] [ payload load 4b @ network header + 12 => reg 1 ] [ cmp eq reg 1 0x04030201 ]’: It will first test that the packet is IPv4 (nfprotocol 2), and only then will it load the payload from the packet. This is required to prevent false-positive matches when packets from a different family are processed. This allows adding ipv4 and ipv6 specific rules to the inet table, or addition of a rule that test e.g. an ipv6 header to the bridge family. Payload dependencies are common. The first rule shown above also has one — to prevent a false positive when processing e.g. a UDP packet to port 22 nftables injected a test on the layer 4 protocol — 6, better known as tcp. Getting started Users familiar with iptables, ip6tables, ebtables, arptables, iptables-save, iptables-restore and so on will notice that the syntax is completely different. But don’t be discouraged — there are a lot of conceptual similarities. It is possible to use both nftables and iptables at the same time. The only limitation is network address translation — if iptable_nat and/or ip6table_nat modules are loaded, nftables “nat” chains will have no effect. Use a recent distribution and install the ‘nftables’ package to get the ‘nft’ tool. nft is the only command that is needed to add/remove rules. nft can be used from the command line, in an interactive (shell-like) mode, or can restore a saved ruleset from a file. Once nft is available, one can start looking around — this is best done in a vm or on a test machine rather than a production system: # nft list tables On a new system this would not provide any output — there are no tables by default. One could now create a new table: # nft add table ip foo # nft list tables table ip foo # nft list table foo table ip foo {} As we can see, a new empty table named foo has been created, and it will only see ipv4 packets. Other families available in nftables are arp, ip6, bridge, inet and netdev. - The arp family will only see ARP packets, the ip6 family will only process IPv6 packets. - The bridge family only processes ethernet packets while tables in the - inet family receive bothIPv4 and IPv6 packets. The - netdev family can be used to attach a table directly to anetwork interface. Tables in the netdev family offer the new “ingress” hook point which can be used to filter any traffic received on that interface. Other than the family, which defines what packet types will be processed, tables have no special meaning at all, they only serve as a container for chains. A table also defines a distinct namespace, so it is possible to create chains with the same name as long as these reside in different tables. Adding chains Users familiar with iptables will remember that each table has built-in chains. In iptables these are called PREROUTING (for packets coming in), INPUT (for packets destined for the local machine), FORWARD (for packets that are being forwarded/routed), OUTPUT (for locally generated packets) and POSTROUTING for all packets being sent out. Nftables has none of these built-in chains. However, it defines these very same hook-points. Hook points are certain locations in the kernel networking stack that provide the ability to inspect packets and provide decisions based on inspection results, such as drop or accept. These hooks are internally also used by iptables, ip6tables, ebtables and arptables to register their builtin chains. So, let’s add a chain that hooks packets at the input hook point: # nft add chain ip foo bar '{ type filter hook input priority 0; }' # nft list table foo table ip foo { chain bar { type filter hook input priority 0; policy accept; } } What did we do here? We told the kernel that we want to have packets destined for the local machine (input hook) to be sent through the rules contained in the chain named ‘bar’. To mimic the iptables filter table, one would rename bar to INPUT and also create chain FORWARD { type filter hook forward; policy accept; } … and the same again for the output hook. Chains that include a hook name are called base chains. There can be several base chains, even with the same hook point. In this case, the chain with the lowest priority number (which can be negative a wel!l) is processed first. If base chains have the same priority, the order is undefined. Let’s add a rule: # nft add rule ip foo bar counter # nft list table foo table ip foo { chain bar { type filter hook input priority 0; policy accept; counter packets 2 bytes 168 } } As can be seen, we now have one table with one chain hooked into the input path with one rule that just increments a counter with every packet seen. Now you might be wondering why we have to do all this work just to add one single rule, or what the ‘type filter’ means. While it’s true that nftables does not have any builtin tables, it does ship with pre-created rule files that provide the nft-counterparts to the ip(6)tables built-in tables. Lets first undo our changes, then look at the mangle table as it would be created in nftables: # nft delete table foo # cat /etc/nftables/ipv4-mangle #!/sbin/nft -f table mangle { chain output { type route hook output priority -150; } } (Your distribution might have decided to place this elsewhere, e.g. in /usr/etc/nftables). This table can be loaded via # nft -f /etc/nftables/ipv4-mangle The special ‘route’ type tells the netfilter core that it should perform a new route lookup after the packet has traversed the chain. This is mostly used with the packet mark and the ‘ip rule’ command to implement policy routing. In the old iptables world, this property is hard-coded into the mangle table; in nftables, it is a base chain propert. Any chain that will alter packet properties for the purpose of route changes need this keyword for the re-lookup to be triggered. Similar skeleton rulesets exist for the other tables that were built-in to the old generation of tools, e.g: # ls /etc/nftables bridge-filter ipv4-filter ipv4-nat ipv6-filter ipv6-nat inet-filter ipv4-mangle ipv4-raw ipv6-mangle So, let’s try again with something more useful and add a simple IPv4 and IPv6 filter set: # nft -f /etc/nftables/inet-filter # nft add rule inet filter input iif lo accept … accept reply traffic to our own connections: # nft add rule inet filter input ct state established,related accept … make sure we accept ipv6 neighbor discovery: # nft add rule inet filter input ip6 nexthdr icmpv6 icmpv6 type { nd-neighbor-solicit, echo-request, nd-router-advert, nd-neighbor-advert } accept … and add a counter without a drop so we don’t accidentally lock ourselves out: # nft add rule inet filter input counter Let’s have a look at the new ruleset: # nft list table inet filter table inet filter { chain input { type filter hook input priority 0; policy accept; iif lo accept ct state established,related accept ip6 nexthdr ipv6-icmp icmpv6 type { nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert, echo-request} accept counter packets 0 bytes 0 } } Now, let’s see how to delete rules. in nftables, rules can be deleted using their internal ”handle”, which is just a number assigned to the rule by the kernel. To see the number, re-run the above command and specify the handle option: # nft --handle list table inet filter [..] counter packets 0 bytes 0 # handle 10 } } # nft delete rule inet filter input handle 10 After running the listing again, the counter rule is gone. In case you want to start anew without deleting and re-creating the table, one can use # nft flush table inet filter Which removes the rules while keeping all chains around. NAT The ipv4 nat table looks like this when defined in nftables: # cat /etc/netfilter/ipv4-nat table nat { chain prerouting { type nat hook prerouting priority -150; } chain postrouting { type nat hook postrouting priority -150; } } The only difference is the use of “type nat” which tells the kernel that the initial packet of a new connection should be passed to the given chain. Remember that the chain and table names are irrelevant, it would also be possible to e.g. # nft add chain filter myredirects “{ type nat hook prerouting; }” Which allows to set up network address translation in a chain “myredirects” in a table named filter. nft add rule filter myredirects ip saddr 192.168.0.024 tcp dport 80 redirect to :8080 nftables also supports snat, and masquerade. Just like with iptables MASQUERADE, the latter is a special case of snat where the snat mapping uses the primary address of the network interface. This is suitable for interfaces with dynamically assigned addresses such as dial-up connections. nft add rule nat postrouting ip saddr 192.168.0.0/24 oif eth0 snat 10.2.3.4 nft add rule nat postrouting ip saddr 192.168.0.0/24 oif eth0 masquerade Known Limitations There a few iptables matches and targets that still lack a native nft replacement. Most notably those are: - the policy match to examine the policy used by IPsec for handling a packet. - rpfilter filter match to perform a reverse path IP filter (reverse route lookup) test on a packet - TCPMSS target to alter the TCP Maximum Segment Size List of iptables matches with native nft replacements: - Ah, esp, dscp, sctp, ecn, hbh, hl, mac, mh, rt (payload expession) - Cgroup, cpu, mark, devgroup, length, owner, pkttype, realm, statistic (meta expression) - Connbytes, connlabel, connmark conntrack, helper (ct expression) - Comment - Hashlimit (flow statements) - Limit - Iprange, multiport (sets) List of iptables targets with native nft replacements: - CLASSIFY (meta) - DNAT, SNAT, MASQUERADE, REDIRECT - DSCP, ECN, HL, TTL (payload statement) - LOG, NFLOG (log statements) - MARK, TRACE (meta statement) - NFQUEUE - REJECT - TEE Arptables and ebtables are considered feature complete, i.e. all ebtables matches have native nft replacements, the only excepection is the ebtables “arpreply” target. Native replacements for the rpfilter and policy matches are being implemented. The ability to perform tcpmss mangling will be added later.
https://developers.redhat.com/blog/2016/10/28/what-comes-after-iptables-its-successor-of-course-nftables/
CC-MAIN-2018-09
refinedweb
4,750
55.98
Thanks for all the support! I managed to come up with a very solid beta of the program I’ve been working on a couple of days ago and testing is so far very positive. (We still don’t have the Windows build side yet, the last time we did that it worked identically once we got past the usual compile/link issues, crossed fingers!) I hope I don’t give the impression of someone beset by problems - this project has actually gone extremely well but there’s an awful lot of stuff in it and so not everything worked right the first time. However, it came out extremely well, and I attribute a lot of that to the virtues of Juce. Reliability and support The code has so far been extremely reliable. Perhaps you saw the various funkinesses I described in previous posts here - as I’d anticipated, each and every one of them was due to some gross error on my part. At least on the Mac side, I’d describe the threading model as “very consistent” - that’s a big deal when you’re writing multi-threaded code. I have about a dozen threads going, I haven’t even adjusted the priorities, and the program is fine. It uses quite a lot of CPU when it’s ripping things from a CD but when it gets into a quiescent, cached state the CPU is quite low. I generally assume that Windows versions of things work well because there are more Windows users, so this is good (Windows beta here we come!) And, of course, Jules’ level support is extremely high. Fast and small. I work quite hard to make my code fast and small but I am often disappointed when in the end the thing that I wrote starts up, runs or shuts down or slowly due to some other part I have no control over. This application bounces into life and shuts down just as fast (I have had recurrent issues in shutdown due to various contentions and race-conditions but I seem to have gotten past them). It runs very fast. It’s so fast that I see no difference between the debug and optimized builds (and yet I know from my benchmarks that parts of it are many times faster) - because I don’t ever seem to be waiting on the CPU. Now, I haven’t tested this on a little machine yet but it really seems light. And the optimized build is less than 3MB, compressed. And my code base is not small - I have about 20k lines of handwritten C++ code, 30k lines of generated code (Google protocol buffers, see below), and easily 100k lines of code in third-party libraries (although I’ll bet less than half of that actually gets linked in). Features Again, really hard to beat, at least in the areas of digital audio, UI and to a lesser extent graphics, where I’m working. Protocol buffers and other libraries I used quite a lot of other libraries in the course of this project, which worked fairly harmoniously. Probably the most central decision was the use of Google’s protocol buffer format for transfer data structures. Certainly the fact that I was very familiar with protos was a key point in my decision, but I wasn’t going to do it initially, but use XML and Juce things only. I did not do this, I used Google protobuffers, and I continue to be extremely glad of that decision every day. It’s not that there’s anything wrong with XML (well - there are a lot of things wrong with XML I suppose but that’s another story), but that the advantages of having a data description language are huge, and protos translate directly into C++ data structures with fast copy and access. In a nutshell, protos have all the advantages of Plain Old Data, because you can pass them around by value and store them in containers, but have a huge amount more functionality, particularly the ability to quickly serialize and de-serialize into either a human-readable form, or a tightly compressed-wire format. And they’re also extensible - not meaning that you can inherit from them (in fact, that’s almost always a bad idea, you should treat them as plain old data) but that there is a simple, systematic for your data structures to grow and change over time while still always being able to read your old files, or even have old versions of your application read your new data. Here’s a random proto file from my code:[code]package rec.util.file; message VolumeFile { enum Type { NONE = 0; CD = 1; MUSIC = 2; USER = 3; VOLUME = 4; }; enum Status { ONLINE = 1; OFFLINE = 2; DISK_OPEN = 3; WRITEABLE_DISK = 4; NO_DISK = 5; UNKNOWN = 6; }; optional Type type = 1 [default = NONE]; optional string name = 2; repeated string path = 3; optional Status status = 4 [default = ONLINE]; // I could have used other protos within this one as well… };[/code] and this automatically generates a C++ class called VolumeFile in namespace rec::util::file that has methods like Type type(), bool has_type(), set_type(Type), or (for repeated fields) methods like std::string path(int), int path_size(), and the like - but also reflection if you need it, at no cost if you don’t. Always On™ The program has a unique architecture that you might find entertaining. There is no Save button, and no database. Everything comes as a single .exe or .app with no external assets. Every operation is indefinitely undoable (well… I haven’t really hooked that up but we have the undo queue sitting there waiting), there will be a separate navigation and operation undo queue and you’ll be able to undo just commands on one item, and the current state immediately saved to disk. Almost every operation that’s time-consuming and doesn’t take too much space (like audio thumbnails or CDDB requests) is cached to disk. From the programmer’s standpoint, getting and setting data is very easy, and it’s very easy to create even a quite complex control that’s simply attached to a piece of persistent data, and works no matter when in your code you drop it (i.e., you don’t have to hook it up, or only have to hook it up once if you want to change it…) Again, it’s all protos. I have persistent protos that live in memory and correspond to actual disk files that are named after the data type. Your controls or processes can listen to these protos, and get updates when they change, or get a snapshot at any time. You can also send atomic editing operations to the protos. You don’t edit the data by holding some lock on it and then actually performing an edit, instead you prepare a data structure that contains that edit and then sending it to an edit queue… …except of course I have sprinkled a ton of semantic sugar on it so that your code ends up looking like: [code]// All this code is completely thread-safe, with the asterisk that it’s a bad idea // to start new data sources during the shutdown procedure. // Gets a consistent snapshot of the current top-level/“global” instance of VolumeFile. VolumeFile file = persist::get(); // A snapshot of TimeStretch for a specific file. TimeStretch stretch = persist::get(file); // persist::Data lets you do everything that’s not snapshots. persist::Data* data = persist::data(file_); TimeStretch s2 = data->get(); // Same as persist::get(). // Edit the persistent data. TimeStretch stretch = makeMyStretch(); data->set(stretch); // This operation is undoable, and goes off in a separate thread. if (data->get() != stretch) {} // No guarantee that it’s updated yet! // For a larger data structure, you can just change one part of it, // all undoably, all done in a separate thread. data->set(“time_stretch”, 1.2); data->clear(); // Clear the whole thing. data->clear(“time_stretch”); // Clear just one part to its default value. // Listeners and Broadcasters in my code are generic and so there’s one per proto class. data->addListener(this); // Unlike in Juce, you’re automatically unlistened in your destructor. // Listeners will eventually receive an update with the current value of the data in another thread. // Right now, everyone hears these updates, but it hasn’t been an issue. data->requestUpdate();[/code]
https://forum.juce.com/t/juce-makes-my-new-year-happy-a-case-study/6129
CC-MAIN-2020-29
refinedweb
1,402
64.44
I have to do a bubble sort with pointers for my class. I am having trouble with the output I want every array sort to be on a single line, not individual lines for each element. Here is an array example that I would want to print. I flipped the 1 and 9 to ensure that I was printing the proper value, not the location, when it was returning just one number. [9, 2, 3, 4, 5, 6, 7, 8, 1] Here is what it prints [9] [2] [3] [4] [5] [6] [7] [8] [1] How do I get this sample array onto just one line? #include <stdio.h> #define MAX 9 int val[] = {9, 2, 3, 4, 5, 6, 7, 8, 1}; int i; int main(){ for (i = 0; i < MAX; i++ { printf ("[%d]\n", val[i]); } return (0); } //end main I really don't see why you don't just remove the \n, which causes the newline. Then separate out the different parts of your output. #include <stdio.h> #define MAX 9 int val[] = {9, 2, 3, 4, 5, 6, 7, 8, 1}; int i; int main(void){ putchar('['); for (i = 0; i < MAX; i++) { if (i == MAX - 1) printf ("%d", val[i]); else printf ("%d, ", val[i]); } puts("]"); return (0); } //end main You cannot print the [ in the loop, or else it will print every time. Then, in the loop you want to print a comma unless you are at your last element where no elements should be printed next ( if (i == MAX - 1). Finally you print the newline and the closing bracket at the end once the loop finishes. Make note that puts() automatically prints a newline.
https://codedump.io/share/NSQKD4kwHoOv/1/c-array-on-a-single-line
CC-MAIN-2018-05
refinedweb
281
71.78
Introduction I. In this article, we will take a very hands-on approach to understanding multi-label classification in NLP. I had a lot fun building the movie genre prediction model using NLP and I’m sure you will as well. Let’s dig in! Table of Contents - Brief Introduction to Multi-Label Classification - Setting up our Multi-Label Classification Problem Statement - About the Dataset - Our Strategy to Build a Movie Genre Prediction Model - Implementation: Using Multi-Label Classification to Build a Movie Genre Prediction Model (in Python) Brief Introduction to Multi-Label Classification I’m as excited as you are to jump into the code and start building our genre classification model. Before we do that, however, let me introduce you to the concept of multi-label classification in NLP. It’s important to first understand the technique before diving into the implementation. The underlying concept is apparent in the name – multi-label classification. Here, an instance/record can have multiple labels and the number of labels per instance is not fixed. Let me explain this using a simple example. Take a look at the below tables, where ‘X’ represents the input variables and ‘y’ represents the target variables (which we are predicting): - ‘y’ is a binary target variable in Table 1. Hence, there are only two labels – t1 and t2 - ‘y’ contains more than two labels in Table 2. But, notice how there is only one label for every input in both these tables - You must have guessed why Table 3 stands out. We have multiple tags here, not just across the table, but for individual inputs as well We cannot apply traditional classification algorithms directly on this kind of dataset. Why? Because these algorithms expect a single label for every input, when instead we have multiple labels. It’s an intriguing challenge and one that we will solve in this article. You can get a more in-depth understanding of multi-label classification problems in the below article: Setting up our Multi-Label Classification Problem Statement There are several ways of building a recommendation engine. When it comes to movie genres, you can slice and dice the data based on multiple variables. But here’s a simple approach – build a model that can automatically predict genre tags! I can already imagine the possibilities of adding such an option to a recommender. A win-win for everyone. Our task is to build a model that can predict the genre of a movie using just the plot details (available in text form). Take a look at the below snapshot from IMDb and pick out the different things on display: There’s a LOT of information in such a tiny space: - Movie title - Movie rating in the top-right corner - Total movie duration - Release date - And of course, the movie genres which I have highlighted in the magenta coloured bounding box Genres tell us what to expect from the movie. And since these genres are clickable (at least on IMDb), they allow us to discover other similar movies of the same ilk. What seemed like a simple product feature suddenly has so many promising options. 🙂 About the Dataset We will use the CMU Movie Summary Corpus open dataset for our project. You can download the dataset directly from this link. This dataset contains multiple files, but we’ll focus on only two of them for now: - movie.metadata.tsv: Metadata for 81,741 movies, extracted from the November 4, 2012 dump of Freebase. The movie genre tags are available in this file - plot_summaries.txt: Plot summaries of 42,306 movies extracted from the November 2, 2012 dump of English-language Wikipedia. Each line contains the Wikipedia movie ID (which indexes into movie.metadata.tsv) followed by the plot summary Our Strategy to Build a Movie Genre Prediction Model We know that we can’t use supervised classification algorithms directly on a multi-label dataset. Therefore, we’ll first have to transform our target variable. Let’s see how to do this using a dummy dataset: Here, X and y are the features and labels, respectively – it is a multi-label dataset. Now, we will use the Binary Relevance approach to transform our target variable, y. We will first take out the unique labels in our dataset: Unique labels = [ t1, t2, t3, t4, t5 ] There are 5 unique tags in the data. Next, we need to replace the current target variable with multiple target variables, each belonging to the unique labels of the dataset. Since there are 5 unique labels, there will be 5 new target variables with values 0 and 1 as shown below: We have now covered the necessary ground to finally start solving this problem. In the next section, we will finally make an Automatic Movie Genre Prediction System using Python! Implementation: Using Multi-Label Classification to Build a Movie Genre Prediction Model (in Python) We have understood the problem statement and built a logical strategy to design our model. Let’s bring it all together and start coding! Import the required libraries We will start by importing the libraries necessary to our project: Load Data Let’s load the movie metadata file first. Use ‘\t’ as the separator as it is a tab separated file (.tsv): meta = pd.read_csv("movie.metadata.tsv", sep = '\t', header = None) meta.head() Oh wait – there are no headers in this dataset. The first column is the unique movie id, the third column is the name of the movie, and the last column contains the movie genre(s). We will not use the rest of the columns in this analysis. Let’s add column names to the aforementioned three variables: # rename columns meta.columns = ["movie_id",1,"movie_name",3,4,5,6,7,"genre"] Now, we will load the movie plot dataset into memory. This data comes in a text file with each row consisting of a movie id and a plot of the movie. We will read it line-by-line: Next, split the movie ids and the plots into two separate lists. We will use these lists to form a dataframe: Let’s see what we have in the ‘movies’ dataframe: movies.head() Perfect! We have both the movie id and the corresponding movie plot. Data Exploration and Pre-processing Let’s add the movie names and their genres from the movie metadata file by merging the latter into the former based on the movie_id column: Great! We have added both movie names and genres. However, the genres are in a dictionary notation. It will be easier to work with them if we can convert them into a Python list. We’ll do this using the first row: movies['genre'][0] Output: '{"/m/07s9rl0": "Drama", "/m/03q4nz": "World cinema"}' We can’t access the genres in this row by using just .values( ). Can you guess why? This is because this text is a string, not a dictionary. We will have to convert this string into a dictionary. We will take the help of the json library here: type(json.loads(movies['genre'][0])) Output: dict We can now easily access this row’s genres: json.loads(movies['genre'][0]).values() Output: dict_values(['Drama', 'World cinema']) This code helps us to extract all the genres from the movies data. Once done, add the extracted genres as lists back to the movies dataframe: Some of the samples might not contain any genre tags. We should remove those samples as they won’t play a part in our model building process: # remove samples with 0 genre tags movies_new = movies[~(movies['genre_new'].str.len() == 0)] movies_new.shape, movies.shape Output: ((41793, 5), (42204, 5)) Only 411 samples had no genre tags. Let’s take a look at the dataframe once again: movies.head() Notice that the genres are now in a list format. Are you curious to find how many movie genres have been covered in this dataset? The below code answers this question: # get all genre tags in a list all_genres = sum(genres,[]) len(set(all_genres)) Output: 363 There are over 363 unique genre tags in our dataset. That is quite a big number. I can hardy recall 5-6 genres! Let’s find out what are these tags. We will use FreqDist( ) from the nltk library to create a dictionary of genres and their occurrence count across the dataset: I personally feel visualizing the data is a much better method than simply putting out numbers. So, let’s plot the distribution of the movie genres: Next, we will clean our data a bit. I will use some very basic text cleaning steps (as that is not the focus area of this article): Let’s apply the function on the movie plots by using the apply-lambda duo: movies_new['clean_plot'] = movies_new['plot'].apply(lambda x: clean_text(x)) Feel free to check the new versus old movie plots. I have provided a few random samples below: In the clean_plot column, all the text is in lowercase and there are also no punctuation marks. Our text cleaning has worked like a charm. The function below will visualize the words and their frequency in a set of documents. Let’s use it to find out the most frequent words in the movie plots column: Most of the terms in the above plot are stopwords. These stopwords carry far less meaning than other keywords in the text (they just add noise to the data). I’m going to go ahead and remove them from the plots’ text. You can download the list of stopwords from the nltk library: nltk.download('stopwords') Let’s remove the stopwords: Check the most frequent terms sans the stopwords: freq_words(movies_new['clean_plot'], 100) Looks much better, doesn’t it? Far more interesting and meaningful words have now emerged, such as “police”, “family”, “money”, “city”, etc. Converting Text to Features I mentioned earlier that we will treat this multi-label classification problem as a Binary Relevance problem. Hence, we will now one hot encode the target variable, i.e., genre_new by using sklearn’s MultiLabelBinarizer( ). Since there are 363 unique genre tags, there are going to be 363 new target variables. Now, it’s time to turn our focus to extracting features from the cleaned version of the movie plots data. For this article, I will be using TF-IDF features. Feel free to use any other feature extraction method you are comfortable with, such as Bag-of-Words, word2vec, GloVe, or ELMo. I recommend checking out the below articles to learn more about the different ways of creating features from text: - An Intuitive Understanding of Word Embeddings: From Count Vectors to Word2Vec - A Step-by-Step NLP Guide to Learn ELMo for Extracting Features from Text tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=10000) I have used the 10,000 most frequent words in the data as my features. You can try any other number as well for the max_features parameter. Now, before creating TF-IDF features, we will split our data into train and validation sets for training and evaluating our model’s performance. I’m going with a 80-20 split – 80% of the data samples in the train set and the rest in the validation set: Now we can create features for the train and the validation set: # create TF-IDF features xtrain_tfidf = tfidf_vectorizer.fit_transform(xtrain) xval_tfidf = tfidf_vectorizer.transform(xval) Build Your Movie Genre Prediction Model We are all set for the model building part! This is what we’ve been waiting for. Remember, we will have to build a model for every one-hot encoded target variable. Since we have 363 target variables, we will have to fit 363 different models with the same set of predictors (TF-IDF features). As you can imagine, training 363 models can take a considerable amount of time on a modest system. Hence, I will build a Logistic Regression model as it is quick to train on limited computational power: from sklearn.linear_model import LogisticRegression # Binary Relevance from sklearn.multiclass import OneVsRestClassifier # Performance metric from sklearn.metrics import f1_score We will use sk-learn’s OneVsRestClassifier class to solve this problem as a Binary Relevance or one-vs-all problem: lr = LogisticRegression() clf = OneVsRestClassifier(lr) Finally, fit the model on the train set: # fit model on train data clf.fit(xtrain_tfidf, ytrain) Predict movie genres on the validation set: # make predictions for validation set y_pred = clf.predict(xval_tfidf) Let’s check out a sample from these predictions: y_pred[3] It is a binary one-dimensional array of length 363. Basically, it is the one-hot encoded form of the unique genre tags. We will have to find a way to convert it into movie genre tags. Luckily, sk-learn comes to our rescue once again. We will use the inverse_transform( ) function along with the MultiLabelBinarizer( ) object to convert the predicted arrays into movie genre tags: multilabel_binarizer.inverse_transform(y_pred)[3] Output: ('Action', 'Drama') Wow! That was smooth. However, to evaluate our model’s overall performance, we need to take into consideration all the predictions and the entire target variable of the validation set: # evaluate performance f1_score(yval, y_pred, average="micro") Output: 0.31539641943734015 We get a decent F1 score of 0.315. These predictions were made based on a threshold value of 0.5, which means that the probabilities greater than or equal to 0.5 were converted to 1’s and the rest to 0’s. Let’s try to change this threshold value and see if that improves our model’s score: # predict probabilities y_pred_prob = clf.predict_proba(xval_tfidf) Now set a threshold value: t = 0.3 # threshold value y_pred_new = (y_pred_prob >= t).astype(int) I have tried 0.3 as the threshold value. You should try other values as well. Let’s check the F1 score again on these new predictions. # evaluate performance f1_score(yval, y_pred_new, average="micro") Output: 0.4378456703198025 That is quite a big boost in our model’s performance. A better approach to find the right threshold value would be to use a k-fold cross validation setup and try different values. Create Inference Function Wait – we are not done with the problem yet. We also have to take care of the new data or new movie plots that will come in the future, right? Our movie genre prediction system should be able to take a movie plot in raw form as input and generate its genre tag(s). To achieve this, let’s build an inference function. It will take a movie plot text and follow the below steps: - Clean the text - Remove stopwords from the cleaned text - Extract features from the text - Make predictions - Return the predicted movie genre tags Let’s test this inference function on a few samples from our validation set: Yay! We’ve built a very serviceable model. The model is not yet able to predict rare genre tags but that’s a challenge for another time (or you could take it up and let us know the approach you followed). Where to go from here? If you are looking for similar challenges, you’ll find the below links useful. I have solved a Stackoverflow Questions Tag Prediction problem using both machine learning and deep learning models to achieve better results. Try to use different feature extraction methods, build different models, fine-tune those models, etc. There are so many things that you can try. Don’t stop yourself here – go on and experiment! Feel free to discuss and comment in the comment section below. The full code is available here.You can also read this article on Analytics Vidhya's Android APP 11 Comments What a great post Prateek! I’ve been looking for this kind of solution for multi-label problems. One thing in mind, though. Can I output the predicted tags as separate tags instead of an array. Like I want to see “Horror”, “Comedy” (without the punctuation marks), instead of [(“Horror”, “Comedy”)]. Help, I am just a newbie here. Thank you. Hey Rey, Glad you liked it. The predictions are in the form of a list. If you want to see tags separately then use the following inference function: def infer_tags(q): q = clean_text(q) q = q.lower() q = strip_stopwords(q) q_vec = tfidf_vectorizer.transform([q]) q_pred = clf.predict(q_vec) q_pred = multilabel_binarizer.inverse_transform(q_pred)[0] print(str(q_pred)[1:-1]) Have you tried a version based on LSTM model? Not yet. Will try it for sure. Great refresher 🙂 Thanks Pankaj!! Thanks for writing such a nice post. It is very helpful for learners like us. Hello Prateek, I’ve trained a similar model using the instructions in your article but when I want to predict the labels it gives me the answer in the form of raw alphabets like [‘(‘ , ‘)’ , ‘a’ , ‘b,’ ,’k’] instead of the genres like [‘action’, ‘comedy’] How can I solve this ? Hi Ahzam, it seems there is some issue with your code. You can send your code over email. I will have a look at it. Hello Prateek Wow, what a wonderful post.Thanks for sharing. good post!!
https://www.analyticsvidhya.com/blog/2019/04/predicting-movie-genres-nlp-multi-label-classification/?utm_source=blog&utm_medium=7-innovative-machine-learning-github-projects-in-python
CC-MAIN-2019-39
refinedweb
2,849
64.3
Prerequisites This article uses the following technologies: C#, XML, COM. This article discusses: COM activation context on Windows XP and Windows Server 2003. Working with manifest files and XML. Exposing .NET COM class libraries using interop. Simple COM registration using a side-by-side method When .NET first appeared it wasn’t unusual to hear the question “Is COM dead?” In fact, COM seems to be alive and well, and in this article I’ll look at the way that Windows XP and Windows Server 2003 allow you to use COM in a side-by-side way without installing the usual registration entries – you won’t need to use the Windows registry to use side-by-side COM components. COM servers traditionally require registration of a CLSID in the registry so that COM, acting on behalf of client programs, can locate the corresponding server on the system and instantiate the requested class. These registry entries identify the path to the server, the COM apartment model, and the type of the server. Whether it’s a DLL or an executable, .NET class libraries can also act as COM servers, and in these cases the path to the COM server points to mscoree.dll, which uses other information in the same registry key to locate the assembly containing the required class. Installation of COM servers is usually done by copying the file to a common location and adding registry entries that point to it. Because the COM server’s CLSIDs are unique, they occur once in the registry where the path to the server also occurs. This leads to the requirement that the installation location must be the same for all versions of this server because installation of the same COM server at a different location by a different product installation would effectively “steal” the first product’s registration entries. This situation also leads to the requirement that new versions of a COM server must support the existing interfaces used by older clients. In other words the whole idea that a new version of a COM server must support clients using its older interfaces is a consequence of the requirement that new versions of the server replace older versions at install time, because the registration is in one place in the system’s Registry. Windows XP SP1 and Server 2003 allow you to use side-by-side COM without these entries in the registry. You install your client program and its COM servers in the same folder, together with a manifest file that contains the registration data that would otherwise be in the registry. The manifest file is associated with the client program, and its name is that of the client executable with the .manifest suffix. Here’s an example manifest file to call a legacy COM DLL: < ?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?> <assembly xmlns=”urn:schemas-microsoft-com:asm.v1″ manifestVersion=”1.0″> 1: Manifest file for a legacy COM DLL As you might expect, the registration data is represented as XML, and the file node contains the COM registration data that would normally be in the registry. If this manifest is incorrectly formed, you’ll see an error message when the client process starts – it will fail if the associated manifest is incorrect. In other words, this manifest is checked as part of the Win32 API CreateProcess, and the content saved for later use. So COM doesn’t go to the manifest file when the code asks for a ProgId or to locate a class object; it uses the content built as part of CreateProcess. The error message you see if the manifest is incorrect is “The application has failed to start because the application configuration is incorrect,” together with text saying that reinstalling the application may fix this problem. There’s a more helpful error description in the System Event Log, with an Event Source of SideBySide and text describing exactly where the validation failed, such as: Syntax error in manifest or policy file “C:\Work Sample Stuff\Samples 1\COMNoReg\CallClient\Debug\CallClient.exe.Manifest” on line 3. The neat thing about this registration scheme is that the code in the COM client program does not need to change at all. A client program is coded in the usual way, such as in this code fragment: HRESULT hr = 0; CLSID cls; hr = CLSIDFromProgID (L”COMNoReg.GetString”, &cls); IDispatch* getit=NULL; hr = CoCreateInstance (cls, NULL, CLSCTX_INPROC_SERVER, __uuidof(IDispatch), (void**)&getit); Note that you don’t need to change anything about the COM server either – it’s only the installation and registration methods that have changed. An example directory structure would be an application folder containing the client program (named CallClient.exe in our example), the COM server COMNoReg.DLL, and the manifest file called CallClient.exe.manifest. You can still use a manifest if the COM classes are already registered in the registry because the manifest file takes precedence over the registry. As if that wasn’t cool enough, you can also expose COM classes from .NET class libraries in a similar way. The declarations in the manifest file are slightly different because an assembly is being named. Keep in mind that .NET COM DLLs don’t contain the traditional COM entry points such as DllGetClassObject – the classes are instantiated indirectly through mscoree.dll, which locates the assembly and constructs the COM-Callable Wrapper (CCW) that enables the client program to call the .NET class methods. If the DLL named in the example manifest file in Listing 1 referred to a .NET class library, an attempt to call it from the client program would get the error HRESULT 0x800401f9, meaning “Error in the DLL,” because the DLL does not export the traditional COM entry points. Consequently the manifest definition of a .NET class library that exposes COM interfaces is slightly different, as shown in Listing 2, where I’ve added a .NET DLL to the manifest. < ?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?> <assembly xmlns=”urn:schemas-microsoft-com:asm.v1″ manifestVersion=”1.0″> <assemblyidentity id=”NetClassLib”” publicKeyToken=”d355e8c58bc50a91″ version=”1.0.0.0″ /> <clrclass clsid=”{AFFA0179-0C8F-3F2D-9D38-1021ECC6F69A}” progid=”PDW.NetClass” threadingModel=”Both” id=”NetClassLib”.ExportedClass” runtimeVersion=”v1.1.4322″> </clrclass> 2: Interop assembly in the manifest file. If you’ve ever used Regasm.exe to register a .NET class library for COM Interop, you can see that the entries in the manifest file correspond to those generated in the Registry by running Regasm.exe on the .NET class library. The generated entries are the usual COM entries that would be created under the InprocServer32 key, but assembly information is also added so that Mscoree.dll can locate the class in the specified assembly, where strong name and version are part of the assembly’s identity. In the manifest information, the clrClass node contains the attributes that identify the exported class. It contains the name of the class in the full name format, . (NetClassLib.ExportedClass in this example) as well as the class Guid and ProgId. The .NET class library itself is identified by the assemblyIdentity specification, which names the assembly and its identifying attributes: name, version and public key token. Although you don’t need to recompile or change your existing COM client code to take advantage of using side-by-side with manifest files, you can choose to embed the manifest file in the resource section of the code file. You do this by adding these lines to your .rc file naming the manifest file: #define MANIFEST_RESOURCE_ID 1 MANIFEST_RESOURCE_ID RT_MANIFEST “winclient.exe.manifest” What if you have a manifest in the code file’s resource section and as a separate file? The separate file takes precedence over the manifest in the resource section. This can be useful when maintaining your application. Using the manifest in Listing 2 as an example, you first install the two COM servers and a client program with the manifest in its resources. If you need to ship a corrected version of the .NET class library (with a different strong name or version) you can simultaneously ship a manifest file to override the manifest embedded in the client program’s resources. If you want to update an existing COM client/server server configuration, there are three methods you can use to have the client call different methods or different versions of the COM server: You can update an existing installed registered (in the registry) COM server by adding the new version of the COM server to the existing application’s installation folder and also adding a manifest file that will be used by the client programs. This manifest file will take precedence over the registry entries identifying the existing COM server. You can have the manifest in the resources section of a client code file together with the COM servers used privately in the application folder. You can then add some combination of a new COM server and manifest file to the installed application to cause client programs to use a different COM server. You can update the existing installed manifest file to make it refer to a new COM server or to a different method in a COM server. A self-updating application To illustrate the versatility of this kind of COM installation, here’s an example using an application where the COM server can be dynamically reconfigured or updated. Let’s start with an update of the COM server itself. Although such an update would typically consist of replacing the COM server with a new version, I’ll make this a little different by adding a new COM server to the application and updating the client’s manifest file to use this new server. Using the manifest file and the .NET class example above, the existing application is using NetClassLib.Dll, and this has a specific name, version and public key token. So the scenario is that we will add NetClassLib2.Dll to this installed application, and have the application update the manifest file from NetClassLib.Dll to NetClassLib2.Dll. One of the reasons we can do this so easily in the .NET world is that .NET Reflection can give us the attributes required to identify the assembly, as well as the .NET framework support for processing XML. The following code fragments illustrate how to update the manifest, using a class with a constructor that opens the manifest file, first the basis for a class named ChangeXml that will update the manifest file: class ChangeXml { XmlDocument xd=new XmlDocument(); string _xmlfile=null; public ChangeXml(string xmlfile) { xd.Load (xmlfile); _xmlfile=xmlfile; } } Listing 3: Basis of a class to update the manifest. The XmlDocument class is used here because it’s convenient for navigating the XML in the manifest file and updating it. The constructor expects the name of the manifest file, which is then used to instantiate the XmlDocument object xd. We’ll start by creating an instance of this class: ChangeXml cx = new ChangeXml(“callclient.exe.manifest”); Then use the UpdateAssembly method to update the manifest file. This method will be called passing the name of the existing assembly in the manifest and the name of the new class library like this: cx.UpdateAssembly (“NetClassLib”, “NetClassLib2.dll”); Error handling is omitted from the method in Listing 4 for the sake of clarity. public bool UpdateAssembly (string assemblyname, string assemblypath) { // Get new assembly properties AssemblyName NewAssembly = AssemblyName.GetAssemblyName(assemblypath); byte [] pkt = NewAssembly.GetPublicKeyToken(); StringBuilder tmp = new StringBuilder(); foreach (byte b in pkt) { tmp.Append (b.ToString(“x2”)); } string pkts=tmp.ToString(); Version ver = NewAssembly.Version; string newname = NewAssembly.Name; // Find assembly in manifest and update it. XmlNode node; node = xd.DocumentElement; foreach(XmlNode n in node.ChildNodes) { string vx = n.Name; if (vx==”assemblyIdentity”) { XmlAttribute xtn = n.Attributes [“name”]; if (xtn.Value==assemblyname) { XmlAttribute xpk = n.Attributes [“publicKeyToken”]; xpk.Value = pkts; XmlAttribute xver = n.Attributes[“version”]; xver.Value = ver.ToString(); XmlAttribute xname = n.Attributes [“name”]; xname.Value = newname; break; } } } xd.Save (_xmlfile); return true; } Listing 4: Updating the manifest with assembly attributes As you’d expect, there are two main tasks in this method. First, the assembly attributes are obtained from the new assembly using .NET reflection, and secondly the manifest is updated with those attributes. The result is a manifest file that refers to the new assembly, NetClassLib2.Dll, and that contains the correct assembly attributes. Updating the manifest’s class At first glance, it seems unnecessary to think about updating the class reference in a manifest because, as we just saw, a new assembly can be substituted for the client to call. But look at the example class library code fragment in Listing 5. [ComVisible(true), GuidAttribute(“AFFA0179-0C8F-3F2D-9D38-1021ECC6F69A”)] [ProgId(“PDW.NetClass”)] [ClassInterface(ClassInterfaceType.AutoDual)] public class ExportedClass: IGetMyString { public void GetMyString() { Module mod = Assembly.GetExecutingAssembly().GetModules () [0]; string fullPath = mod.FullyQualifiedName; MessageBox.Show ( “ExportedClass method says ” + fullPath); } } [ComVisible(true), GuidAttribute(“5FBAC391-A637-47EC-B62E-3AB5E35F4F0D”)] [ProgId(“PDW.NetClass”)] public class AnotherExportedClass: IGetMyString { public void GetMyString () { Module mod = Assembly.GetExecutingAssembly().GetModules () [0]; string fullPath = mod.FullyQualifiedName; MessageBox.Show ( “AnotherExportedClass method says ” + fullPath); } } Listing 5: Two class methods with the same ProgId Listing 5 shows two classes that expose the same COM interface using a single ProgId, but they have a different class name and class Guid. The client program doesn’t know this, of course, because it simply requests the class Guid associated with a ProgId and instantiates the resulting class, all of which is specified in the manifest file. This means that the manifest file can be manipulated so that the client program will use whichever class is currently specified in the manifest file assocatiated with the ProgId. In other words, the clrClass specification can be updated depending on which method should be called. The method in Listing 6, added to the ChangeXml class previously described, will do this update, changing the clrClass specification to refer to another class. public bool UpdateClass(string assemblyname, StringDictionary classatts) { XmlNode node; node = xd.DocumentElement; foreach(XmlNode n in node.ChildNodes) { string vx = n.Name; if (vx==”assemblyIdentity”) { XmlAttribute tn = n.Attributes [“name”]; if (tn.Value==assemblyname) { XmlNode xcls = n.NextSibling; if (xcls.Name==”clrClass”) { // Update class attributes from dictionary foreach (DictionaryEntry de in classatts) { string xx = de.Key.ToString(); XmlAttribute pk = xcls.Attributes [de.Key.ToString()]; if (pk!=null) { pk.Value = de.Value.ToString(); } } } break; } } } xd.Save(_xmlfile); return true; } Listing 6: Changing the class associated with the ProgId. In this method the class attributes are passed in using a StringDictionary object. This uses Name/Value pairs that reflect the Name/Value structure of the XML attributes that will be changed, making it a versatile way to represent the changes we wish to make. The method is used in the following way: StringDictionary ClassChanges = new StringDictionary(); ClassChanges.Add (“clsid”, “{5FBAC391-A637-47EC-B62E-3AB5E35F4F0D}”); ClassChanges.Add (“name”, “NetClassLib.AnotherExportedClass”); cx.UpdateClass(“NetClassLib”, ClassChanges); These changes result in the client program now calling a different method. What we have here is a mechanism that can be used to change the class method being called by a legacy COM client program. It should be clear that you can’t achieve this kind of versatility in the traditional “one COM server for all” environment that’s usually associated with COM. This technique can be particularly useful when the COM methods are shims or stubs to some external implementation. Perhaps you can have alternative versions of the COM method that provide tracing and timing instrumentation, allowing you to use either an instrumented version or not. Or perhaps different versions of the method access different databases or different remote computers. The build process and manifests I didn’t use reflection to derive the COM class information from the assembly because it wasn’t appropriate for that particular use of two COM methods. .NET reflection is rich enough, however, that you could add generation of the manifest files to your build processes. .NET provides the RegistrationServices class to help find the COM information in an assembly. You just saw how to discover assembly attributes using reflection, and the code fragment shown in Listing 4 can be used to discover the COM information in an assembly. This code in Listing 7 assumes you have initialized an XmlTextWriter xt to create the XML file, and that you have an Assembly asm for which you are creating a manifest. RegistrationServices rs = new RegistrationServices(); Type [] register = rs.GetRegistrableTypesInAssembly(asm); foreach (Type t in register) { string sprogid = rs.GetProgIdForType(t); string sg = “{“+t.GUID.ToString()+”}”; string sname = t.FullName; string srtv = asm.ImageRuntimeVersion; xt.WriteStartElement (“clrClass”); xt.WriteAttributeString (“clsid”, sg); xt.WriteAttributeString (“progid”, sprogid); xt.WriteAttributeString (“name”, sname); xt.WriteAttributeString (“threadingModel”, “both”); xt.WriteAttributeString (“runtimeVersion”, srtv); xt.WriteEndElement (); } Listing 7: Creating XML COM entries in the manifest The framework’s RegistrationServices class is the basis of the Regasm.exe utility that registers COM class information in the system registry. Here it’s being used to find the types that can be registered, after which the code gets the COM registration information and writes it to the manifest file associated with the clrClass element. If you like, this is almost a version of Regasm.exe that writes the COM registration to an XML file instead of a registration file. This example does not include any Type Library information, and for that you’d use the TypeLibConverter class and its ConvertAssemblyToTypeLib to generate a type library for the COM client. The examples here are using the automation interface IDispatch, which means there is no requirement for a type library because the types being used are automation-compatible. The context APIs When a COM client instantiates a COM class, CoCreateInstance(Ex) will automatically find the context information that was configured in the manifest. If you want to discover for yourself what is configured for your application (perhaps because you want to find the details of the .NET classes that are configured) you can use the SxsLookupClrGuid Win32 API. This API in Sxs.dll must be linked to dynamically using the GetProcAddress Win32 API. The following code fragment assumes a function pointer declaration for pfn_SxsLookupClrGuid that was derived from calling GetProcAddress: BOOL FoundClass = (pfn_SxsLookupClrGuid)( SXS_LOOKUP_CLR_GUID_USE_ACTCTX | SXS_LOOKUP_CLR_GUID_FIND_CLR_CLASS, &theGuid, NULL, (PVOID) outputBuffer, (SIZE_T) OUTPUT_BUFFER_SIZE, &neededBufferSize ); See the Platform SDK documentation for the details (and the example code with this article). The first parameter is a set of flags that in this case specifies that the search should use the activation context (the contents of the manifest for the process) and also that the search is for a .NET runtime class. The second parameter is the address of the Win32 Guid that you’re searching for. When this call is successful the outputBuffer parameter is filled with the contents of a SXS_GUID_INFORMATION_CLR structure: typedef struct _SXS_GUID_INFORMATION_CLR { DWORD cbSize; DWORD dwFlags; PCWSTR pcwszRuntimeVersion; PCWSTR pcwszTypeName; PCWSTR pcwszAssemblyIdentity; } SXS_GUID_INFORMATION_CLR, *PSXS_GUID_INFORMATION_CLR; In this structure, pcwszTypeName points to the full name of the assembly, including the namespace, such as “NetClassLib.ExportedClass” in these examples, and pcwszAssemblyIdentity points to the complete assembly identity, “NetClassLib,publicKeyToken=”d355e8c58bc50a91â³,version=”1.0.0.0â³”. For more options, take a look at the CreateActCtx Win32 API that lets you name a manifest file. This function returns an activation context handle that you can use in place of the NULL as the third parameter to SxsLookupClrGuid. These context APIs are intended for developers building Interop applications where you need to do the type of thing that CoCreateInstance does – you can search the application’s context for the details of the configured .NET classes and associate a COM CLSID with a .NET assembly. Conclusion Installing COM servers in this side-by-side way is a big win compared to the traditional installation of registry entries that all refer to the same shared COM server, part of the problem area known as DLL Hell. At installation time, all you need do is copy the files to the application folder and you’re done. Your application works even if the COM servers are already registered because your manifest file takes precedence over the registry. You also have more choices for updating your application because you don’t need to consider other clients using the COM servers and you can configure the manifest and your .NET Interop libraries in a number of ways, as you’ve seen in this article. If you’re supporting operating systems prior to XP SP1 and Server 2003 you may not wish to design your applications to take advantage of this side-by-side technique. But note that Windows Server 2003 supports 64-bit systems, so you can choose to design your 64-bit applications to use this technique right from the start when the 64-bit .NET framework is available. Load comments
https://www.red-gate.com/simple-talk/dotnet/net-framework/simple-com-server-registration/
CC-MAIN-2020-29
refinedweb
3,457
55.64
Jim Fulton wrote: > On Jul 31, 2006, at 2:02 PM, Philipp von Weitershausen wrote: > ... >> Let's have a bug day this Friday. > > So how did that go? Riiiiight. Well, one of my server got hacked badly. I know, it's a poor excuse, but I ended up spending my whole long weekend (the only vacation time I had set aside for this summer) wiping the damn hard drive of that thing and reinstalling everything from backup, instead of fixing some bugs on Friday and spending some quality time with my li'l sisters... I see what I can do this weekend. I'll look into 673 and see whether I can make sense of 683. Actually, talking about 683: I once noticed that Zope 3 is declaring 'zope' as a namespace package the setuputils way where as Zope 2 does it the pkg_util way. I wonder which one is the one we should stick with? > I see more blocking issues than we had before. > > I think Christian is going to close 574 in the 574 in the next few days. > (I'll review it this weekend.) > > I think 670 is going to be deferred for lack of input. > > I think the remaining 3 issues don't require particularly deep expertise. > > You people better start fixing bugs, or else! > > How's that? Can I be a release manager? ;) Yes please! Philipp _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub:
https://www.mail-archive.com/zope3-dev@zope.org/msg05857.html
CC-MAIN-2018-47
refinedweb
241
83.15
I noticed a strange behavior when using multiprocessing. My main process sends data to a queue. Two spawned processes read from the queue and create cuda tensors. If I print the tensors I see the process running on gpu-1 copied to gpu-0 in nvidia-smi. Hence it looks as if I had 3 processes, 2 on gpu-0 and 1 on gpu-1. Two of this 3 processes have the same p-id, namely the p-id of the process running on gpu-1. Now if I print the tensor size or anything else, or if I don’t print anything at all I end up having only 2 processes each running on one gpu. The behavior is reproducible using multiprocessing as well as torch.multiporcessing. See code below for reproduction. Does anyone have an idea why this is? nvidia-smi output when printing tensor: nvidia-smi output otherwise: Code: import torch import torch.multiprocessing as mp def run(q, dev): t = torch.tensor([1], device=dev) for data in iter(q.get, None): new_t = torch.tensor([data], device=dev) t = torch.cat((t, new_t), dim=0) # Causes the Copy print(t) # Any of the following doesn't causes the copy print(t.size()) print('t') continue q.put(None) if __name__ == '__main__': ctx = mp.get_context('spawn') q = ctx.Queue() devices = [ torch.device('cuda:{}'.format(i)) for i in range(torch.cuda.device_count()) ] processes = [ ctx.Process(target=run, args=(q, dev)) for dev in devices ] for pr in processes: pr.start() for d in range(1, 1000000): q.put(d) q.put(None) for pr in processes: pr.join()
https://discuss.pytorch.org/t/multiprocessing-process-started-on-gpu-1-copied-to-gpu-0-when-printing-tensor/27476
CC-MAIN-2022-33
refinedweb
271
71.1
Dilip Daya <dilip.daya@hp.com>:> - .netns_ok flag indicates that someone has audited the code and madecertain it all works with network namespaces.Skimming the code I don't see anything that jumps out as me aswrong.@gmail.com> Date: Mon Jan 25 10:38:34 2010 +0000 netns xfrm: ipcomp support Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>However it is clear that no one has actually tested ipcomp withnetwork namespaces.If you have a clue what is going on with ip compression myrecommendation would be to add .netns_ok = 1. Verify that theeverything works and send the patch. You probably want toverify and test ipv6 as well. It really looks like the codeis fine and it just needs to be enabled.Eric
https://lkml.org/lkml/2011/11/9/401
CC-MAIN-2017-09
refinedweb
133
68.47
Hello friends! I hope you all will be absolutely fine and having fun. Today, I am going to share my knowledge about how can you make a simple program for DC Motor Speed Control using Arduino UNO. In my previous tutorial, DC Motor Direction Control using Arduino, I have just controlled the DC motor in both directions at constant speed using Arduino. I have also performed the DC Motor Direction Control in Matlab by sending different commands through serial port from Matlab and LabVIEW to the Arduino and then controlled the direction of rotation of DC motor. But in this tutorial I will rotate the same DC motor at variable speed in both clockwise and anti clockwise directions. In my previous tutorial, we have seen that input pins In1 & In2 of motor control driver L298 (H-Bridge) are useful to control the direction of rotation of the DC motor. In this tutorial, I have controlled its speed as well by providing different voltage levels at the enable pin of the DC motor control driver L298. It will be helpful to vary the speed of the DC motor in either clockwise or in anti clockwise direction. So, let’s get started with DC Motor Speed Control using Arduino UNO: DC Motor Speed Control using Arduino UNO In this tutorial we will learn that how to make an algorithm for DC Motor Speed Control using Arduino UNO. Speed control of any motor is always done y Pulse Width Modulation, abbreviated as PWM. PWM pulse can be generated using Arduino and L298 Enable Pin is used to get that PWM pulse and then it controls the motor speed accordingly. Before going into the further details I would like to tell you about the concept of PWM for controlling DC motor. Moreover, you can download the complete Arduino code for DC Motor Speed Control using Arduino by clicking the below button: Pulse Width Modulation (PWM) PWM stands for Pulse Width Modulation. It basically describes the type of the digital signal. PWM technique is an excellent technique to control the analog circuits with microcontroller’s digital PWM output. In this technique we can get analog results with the digital means. Digital control is used to create square wave. This pattern can vary voltages between full on i.e. 5V and full off i.e. 0V. The duration of on time i.e. when the the signal is present is known as pulse width. PWM waves for the different duty cycles are shown in the figure below. Duty cycle is basically the proportion of the time during which a system is operated. It can be expressed as a percentage. For example motor rotates for 1 second out of 100 seconds, it duty cycle can be represented as 1/100 or as 1%. For Arduino software coding the command analogWrite(255) shows the maximum i.e. 100% duty cycle. To achieve 50% duty cycle we have to update this command to analogWrite(127). Arduino UNO’s pin no 3, 5, 6,10 and 11 are used as PWM pins. In this project we can control the speed of the DC motor by providing high and low voltages to the enable pin of the motor control driver L298. For example, if a motor rotates with the maximum speed and 100% duty cycle at 12V and we provide it with the 6V then it will rotate with the half of the initial speed having 50% duty cycle. Motor Controller L298 The pins EnA and EnB of the motor controller L298 are used as the PWM pins. We can rotate the DC motor at different speed providing different high and low voltage levels to these pins of the motor control driver. If we start to reduce the maximum voltage at which the motor rotates at maximum speed, the speed of the motor also starts to reduce. In this way these enable pins are helpful to control the speed of the DC motor. Algorithm design and descrition In this section of the tutorial DC Motor Speed Control using Arduino UNO, I am going to explain you about designing as well as a detailed description of the designed algorithm. I will tell you about the entire algorithm in step by step procedure. Open your Arduino software, copy and paste the source code given below in your software. #include <LiquidCrystal.h> //Keyboard Controls: // // C - Clockwise // S - Stop // A - Anti-clockwise // Declare L298N Controller pins // Motor 1 int count=255; int dir1PinA = 2; int dir2PinA = 5; int speedPinA = 6; // PWM control LiquidCrystal lcd(8, 9, 10, 11, 12, 13); void setup() { Serial.begin(9600); // baud rate lcd.begin(20, 4); lcd.setCursor(5,0); lcd.print("DC Motor"); lcd.setCursor(5,1); lcd.print("Direction"); lcd.setCursor(5,2); lcd.print("Control"); lcd.setCursor(2,3); lcd.print("via Arduino UNO"); delay(3000); lcd.clear (); lcd.setCursor(0,2); lcd.print(""); lcd.setCursor(4,3); lcd.print("Projects.com"); //Define L298N Dual H-Bridge Motor Controller Pins pinMode(dir1PinA,OUTPUT); pinMode(dir2PinA,OUTPUT); pinMode(speedPinA,OUTPUT); analogWrite(speedPinA, 255);//Sets speed variable via PWM } void loop() { // Initialize the Serial interface: if (Serial.available() > 0) { int inByte = Serial.read(); int speed; // Local variable switch (inByte) { case 'C': // Clockwise rotation //analogWrite(speedPinA, 255);//Sets speed variable via PWM digitalWrite(dir1PinA, LOW); digitalWrite(dir2PinA, HIGH); Serial.println("Clockwise rotation"); // Prints out “Motor 1 Forward” on the serial monitor Serial.println(" "); // Creates a blank line printed on the serial monitor //lcd.clear(); lcd.setCursor(0,0); lcd.print("Clockwise rotation"); break; case 'S': // No rotation //analogWrite(speedPinA, 0); // 0 PWM (Speed) digitalWrite(dir1PinA, LOW); digitalWrite(dir2PinA, LOW); Serial.println("No rotation"); Serial.println(" "); //lcd.clear(); lcd.setCursor(0,0); lcd.print("No rotation"); break; case 'H': //Accelrating motor count=count+20; if (count>255) { count =255; } analogWrite(speedPinA,count); delay(50); //digitalWrite(dir1PinA, LOW); //digitalWrite(dir2PinA, HIGH); Serial.println("Motor is accelrating slowly"); Serial.println(" "); Serial.println(count); lcd.setCursor(0,0); lcd.print("Motor is accelrating"); break; case 'L': //Deaccelrating motor count=count-20; if (count<20) { count=20; } analogWrite(speedPinA,count); delay(50); //digitalWrite(dir1PinA, LOW); //digitalWrite(dir2PinA, HIGH); Serial.println("Motor is deaccelrating slowly"); Serial.println(" "); Serial.println(count); lcd.setCursor(0,0); lcd.print("Motor Deaccelrates"); break; case 'A': // Anti-clockwise rotation //analogWrite(speedPinA, 255); // Maximum PWM (speed) digitalWrite(dir1PinA, HIGH); digitalWrite(dir2PinA, LOW); Serial.println("Anti-clockwise rotation"); Serial.println(" "); //lcd.clear(); lcd.setCursor(0,0); lcd.print("Anti-clockwise"); break; default: // Turn off the motor if any other key is being pressed for (int thisPin = 2; thisPin < 11; thisPin++) { digitalWrite(thisPin, LOW); } Serial.println("Wrong key is pressed"); //lcd.clear(); lcd.setCursor(0,0); lcd.print("Wrong key is pressed"); } } } - In the previous tutorials, DC Motor Direction Control using Arduino and DC Motor Direction Control using Matlab we have learnt that how to control the direction of the DC motor. - We used the commands C, A and S for the clockwise rotation, anti clockwise rotation and stopping the motor respectively. - In this tutorial, we have added two further commands H and L for accelerating and de-accelerating the DC motor. - If we send the command H different times consecutively the speed of the motor will increase continuously. - If we send the command L different times consecutively, the speed of the motor will start to decrease. - Now, upload the source code to your Arduino UNO’s board. - Open the serial monitor at the top right of the Arduino Software. - And enter the commands in serial monitor periodically as explained above. Actual Hardware Setup - When we enter the command C in the serial monitor of the Arduino software. Motor will start rotating in the clockwise direction and a statement Clockwise rotation will be printed on serial port. - The same statement will be printed on the LCD as well as shown in the figure below. - When we enter the command A in the serial monitor of the Arduino software. Motor will start rotating in the anti clockwise direction and a statement Anti clockwise rotation will be printed on serial port. - The same statement will be printed on the LCD as well as shown in the figure below. - When we enter the command H in the serial monitor of the Arduino software. Motor will start accelerating and a statement Motor is accelerating will be printed on serial port. - The same statement will be printed on the LCD as well as shown in the figure below. - When we enter the command L in the serial monitor of the Arduino software. Motor will start to deaccelerate and a statement Motor Deaccelerates will be printed on serial port. - The same statement will be printed on the LCD as well as shown in the figure below. Thats all from the tutorial DC Motor Speed Control using Arduino UNO. I hope you have enjoyed this tutorial. If you face any sort of problem, you can ask me anytime without feeling any kind of hesitation. I will further explore my knowledge about Arduino projects in my later tutorials. Till then, Take care 🙂 3 Comments I want to find/write a program allowing me to use my dual H bridge to run a set up like what makebot mSpider (one of the set-ups for the mdraw bot kit) can do.Much like an X/Y plotter but hanging in mid air. Any suggestions for accomplishing this? I have tried to download many controller that would allow me to “draw” what I want to come out on the other end (at the “spider”) but I am having difficulties with zip files and such. I am currently experimenting with inkscape (recommended) but its not as easy to learn as they would like you to believe. I am trying to refamilurize myself with master cam but the “code” its generating is not being recgonized (has too many characters or such) by the controller. GRBL looks great but due to my inability to open zip files, its a bit of a loss. Any advice or insights you could lend would be greatly appreciated. please share circuit diagram Please give the circuit diagram of this project
https://www.theengineeringprojects.com/2017/04/dc-motor-speed-control-using-arduino.html
CC-MAIN-2019-13
refinedweb
1,689
54.32
offe1100Members Content count5 Joined Last visited Community Reputation105 Neutral About stoffe1100 - RankNewbie - [quote name='CableGuy' timestamp='1338661236' post='4945622'] I didn't quite get exactly what type of game you are creating and what exactly you are trying to achieve... If you can answer those question I might be able to help you rethink your problem [/quote] Hmm, I am actually just doing this to train myself on sdl. But if i say mario? something like that. - [quote name='CableGuy' timestamp='1338644114' post='4945571']? [/quote] Actually my map is stored in a 2 dimensional vector called map. For the moment it works pretty well when colliding Up, Down and left. But i only get slowed when i collide from the right side. And if i push towards a wall i get pushed to the top of the wall without pressing up key. And sometimes i just fall under the whole map when colliding. What i am really looking for is like a whole new structure for how my collsion should look like. I dont understand why it is over complicated? please tell me and i will try to explain. Also when im colliding my ball is bouncing very quickly. Which it shouldnt because everything should be calculated and set back within one frame! Ive been playing around with some stuffs and i updated the player::move() function. When it is like this the collision in the Y axis is working great. but the X axis collisions are super weird. Please help me, i have no clue on how to continue. I cant stop thinking of those problems. its really anoying stoffe1100 posted a topic in For BeginnersHello, i am trying to make some basic game that are using tiles. Until now it has gone pretty well and forward. But now im just totally stucked. I am trying to write a move funtion to move the player, and after that it checks if there is a collsion and if there is it moves the player back. It works at some parts. But generally it is acting very strange. Could you please take a look at it? Thanks in advice. I will send all the code i think is necessary and just reply if you need more. If there is anything else that looks strange just tell me, i want to learn as much as possible. Here is game.h [CODE] #include "base.h" #include "player.h" #ifndef GAME_H #define GAME_H class game : public base { public: game(void); ~game(void); private: bool InitSDL(); void GameLoop(); void HandleEvents(); void UpdateGame(); void Render(); void LoadMap(string filename); void BlitMap(); bool running; bool fullscreen; SDL_Event event; bool keys[400]; player * Player; SDL_Surface * screen,*Background,*Blocks; SDL_Rect BackgroundBox; vector< vector<int> > map; }; #endif [/CODE] Here is game.cpp [CODE] #include "game.h" SDL_Rect base::coord; game::game(void) { if(!this->InitSDL()){exit(1);} BackgroundBox.x = BackgroundBox.y = coord.x = coord.y = 0; coord.w = BackgroundBox.w = 800; coord.h = BackgroundBox.h = 600; fullscreen = false; Background = Load_Image("Background.png"); Blocks = Load_Image("Blocks.png"); this->LoadMap("test.TILEMAP"); Player = new player; Player->CurrentMap(map); this->GameLoop(); } void game::GameLoop() { Uint32 start, end; running = true; while(running) { start = SDL_GetTicks(); this->HandleEvents(); this->UpdateGame(); this->Render(); end = SDL_GetTicks(); if(1000/FPS > end - start) { SDL_Delay(1000/FPS - (end - start)); } } } void game::HandleEvents() { while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: running = false; break; case SDL_KEYDOWN: keys[event.key.keysym.sym] = true; break; case SDL_KEYUP: keys[event.key.keysym.sym] = false; break; } } } void game::UpdateGame() { Player->SetXvel(0); Player->SetYvel(0); if(keys[SDLK_a]){ coord.x-=vel; BackgroundBox.x-=vel; Player->SetXvel(-3); if(BackgroundBox.x <= 0) { BackgroundBox.x = Background->w - SCREEN_WIDTH; } } else if(keys[SDLK_d]){ coord.x+=vel; BackgroundBox.x+=vel; Player->SetXvel(3); if(BackgroundBox.x >= Background->w - SCREEN_WIDTH) { BackgroundBox.x = 0; } } if(keys[SDLK_w]){ Player->SetYvel(-3); }else if(keys[SDLK_s]){ Player->SetYvel(3); } else if(keys[SDLK_ESCAPE]){ running = false; }else if(keys[SDLK_F5]){ fullscreen = (!fullscreen); if(fullscreen) { screen = SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_BPP,SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_FULLSCREEN); }else{ screen = SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_BPP,SDL_HWSURFACE|SDL_DOUBLEBUF); } } Player->MovePlayer(); } void game::Render() { SDL_BlitSurface(Background,&BackgroundBox,screen,NULL); this->BlitMap(); Player->Blit(screen); SDL_Flip(screen); } void game::LoadMap(string filename) { ifstream in(filename.c_str()); int Width,Height,current; in >> Width >> Height; if(!in.is_open()) { cout << "Error: could not load "<< filename << endl; return; } for(int j = 0;j != Height;j++) { vector<int> TempVec; for(int k = 0; k != Width;k++) { if(in.eof()) { cout << "Error: File end reached to early" << endl; return; } in >> current; TempVec.push_back(current); } map.push_back(TempVec); } in.close(); } void game::BlitMap() {++) { SDL_Rect BlockRect = {(map[j][k]-1)*TILE_SIZE,0,TILE_SIZE,TILE_SIZE}; SDL_Rect DestRect = {k * TILE_SIZE - coord.x,j*TILE_SIZE,TILE_SIZE,TILE_SIZE}; SDL_BlitSurface(Blocks,&BlockRect,screen,&DestRect); } } } game::~game(void) { delete Player; SDL_FreeSurface(Blocks); SDL_FreeSurface(Background); SDL_Quit(); } bool game::InitSDL() { if(SDL_Init(SDL_INIT_EVERYTHING) == -1) { cout << "Error: could not initialize SDL" << endl; return false; }else{ cout << "SDL initialized!" << endl; } screen = SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_BPP,SDL_HWSURFACE|SDL_DOUBLEBUF); if(screen == NULL) { cout << "Error: could not initialize the screen" << endl; return false; }else{ cout << "screen initialized!" << endl; } if(TTF_Init() == -1) { cout << "Error: could not initialize TTF" << endl; return false; }else{ cout << "TTF initialized" << endl; } for(int i = 0; i != 400; i++) { keys[i] = false; } return true; } [/CODE] Here is player.h [CODE] #include "base.h" #ifndef PLAYER_H #define PLAYER_H class player : public base { public: player(void); void SetXvel(int vel); void SetYvel(int vel); void CurrentMap(vector<vector<int> > Map); void MovePlayer(); void Blit(SDL_Surface * screen); ~player(void); private: vector< vector<int> > map; SDL_Surface * image; SDL_Rect box; int Xvel,Yvel; bool Ground; }; #endif [/CODE] here is player.cpp [CODE] #include "player.h" player::player(void): Yvel(3), Xvel(5) { image = Load_Image("Player.png"); SDL_SetColorKey(image,SDL_SRCCOLORKEY,SDL_MapRGB(image->format,200,0,200)); box.w = image->w; box.h = image->h; box.x = SCREEN_WIDTH/2 - box.w/2; box.y = SCREEN_HEIGHT/2; Ground = false; } void player::SetXvel(int vel) { Xvel = vel; } void player::SetYvel(int vel) { Yvel = vel; } void player::MovePlayer() { box.x += Xvel; box.y += Yvel;++) { if(map[j][k] == 0) { continue; } SDL_Rect DestRect = {k * TILE_SIZE - coord.x,j*TILE_SIZE,TILE_SIZE,TILE_SIZE}; if(CheckCollision(box,DestRect)) { if(box.x+box.w >= DestRect.x) { box.x-=Xvel; } else if(box.x <= DestRect.x + DestRect.w) { box.x-=Xvel; } if(box.y+box.h >= DestRect.y) { box.y-=Yvel; } else if(box.y <= DestRect.y + DestRect.h) { box.y-=Yvel; } } } } } void player::CurrentMap(vector<vector<int> > Map) { map = Map; } void player::Blit(SDL_Surface * screen) { SDL_BlitSurface(image,NULL,screen,&box); } player::~player(void) { SDL_FreeSurface(image); } [/CODE] Here is a class which contains the most basic stuffs that all classes need. its called base Here is base.h [CODE] #ifndef BASE_H #define BASE_H #include <iostream> #include <fstream> #include <string> #include <vector> #include <SDL.h> #include <SDL_image.h> #include <SDL_ttf.h> using namespace std; class base { public: static const int SCREEN_WIDTH = 800; static const int SCREEN_HEIGHT = 600; static const int SCREEN_BPP = 32; static const int FPS = 60; static const int Gravity = 2; static const int vel = 2; static const int TILE_SIZE = 50; static SDL_Rect coord; base(void); SDL_Surface * Load_Image(string filename); bool CheckCollision(SDL_Rect r1,SDL_Rect r2); ~base(void); }; #endif [/CODE] Here is base.cpp [CODE] #include "base.h" base::base(void) { } SDL_Surface * base::Load_Image(string filename) { SDL_Surface * IMG = IMG_Load(filename.c_str()); if(IMG != NULL) { SDL_Surface * Opt = SDL_DisplayFormat(IMG); SDL_FreeSurface(IMG); cout << "Loading image " << filename << " Succeeded!" << endl; return Opt; }else{ cout << "Error: image " << filename << " could not be loaded" << endl; return NULL; } } bool base::CheckCollision(SDL_Rect r1,SDL_Rect r2) { if(r1.x > r2.x+r2.w){ return false; } else if(r1.y > r2.y+r2.h){ return false; } else if(r1.x+r1.w < r2.x){ return false; } else if(r1.y+r1.h < r2.y){ return false; }else{ return true; } } base::~base(void) { } [/CODE] stoffe1100 posted a topic in General and Gameplay ProgrammingHello! I have tried to make my first pong game in c++ with sdl. I can play it now, but i got a few problems that i have no idea on how to solve. I have googled around on it but i find nothing useful for me. So here is the problems this far, 1. When i enter fullscreen the screen flickers so much you cant see what is going on. [s]2. For some reason the ball dont colorkey.[/s] 3. I can´t hold down keys which is strange since i have actually made a bool array for the keys I wanna say it before you complain, Im really bad at english so please do not do uneccesary comments on that. Im new to sdl so if you got constructive critic please leave a comment and help me get better [img][/img] I know the code got a few memory leaks and bad code but i will fix it when i get the game to work properly first. Thank you in advance! So here comes the code. [img][/img] global_functions is just a class with some handy functions which felt uneccesary to post here because the post will get even larger. Here is main.cpp [CODE] #include <iostream> #include <SDL.h> #include <SDL_ttf.h> #include <SDL_Image.h> #include "paddle.h" #include "ball.h" #define FPS 30 using namespace std; SDL_Surface * screen; SDL_Event event; Uint32 start; bool keys[274] = {false}; bool fullscreen = false; bool running = true; bool init(); int main(int argc,char** argv) { if((!init())){SDL_Quit(); return 0;} paddle paddle1(1); paddle paddle2(2); ball Ball; while(running) { start = SDL_GetTicks(); while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: running = false; break; case SDL_KEYUP: keys[event.key.keysym.sym] = false; break; case SDL_KEYDOWN: if(event.key.keysym.sym == SDLK_f){fullscreen = (!fullscreen);} if(event.key.keysym.sym == SDLK_ESCAPE){running = false; break;} keys[event.key.keysym.sym] = true; break; } } if(keys[SDLK_w]){cout << "W IS DOWN" << endl; paddle1.Up();} if(keys[SDLK_s]){cout << "S IS DOWN" << endl; paddle1.Down();} if(keys[SDLK_UP]){cout << "ARROWUP IS DOWN" << endl;paddle2.Up();} if(keys[SDLK_DOWN]){cout << "ARROWDOWN IS DOWN" << endl; paddle2.Down();} if(fullscreen){screen = SDL_SetVideoMode(800,600,32,SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_FULLSCREEN);}else{screen = SDL_SetVideoMode(800,600,32,SDL_HWSURFACE|SDL_DOUBLEBUF);} SDL_FillRect(screen,NULL,NULL); paddle1.Blit(); paddle2.Blit(); Ball.update(paddle1.ReturnRect(),paddle2.ReturnRect()); SDL_Flip(screen); if(1000/FPS > SDL_GetTicks() - start){SDL_Delay(1000/FPS - (SDL_GetTicks() - start));} } SDL_Quit(); return 0; } bool init(){ if(SDL_Init(SDL_INIT_EVERYTHING) == -1){ std::cout << "Could not initialize sdl" << std::endl; return false; } std::cout << "SDL initilized" << std::endl; screen = SDL_SetVideoMode(800,600,32,SDL_HWSURFACE|SDL_DOUBLEBUF); if(screen == NULL){ std::cout << "Could not setup screen" << std::endl; return false; } std::cout << "Screen is setup" << std::endl; if(TTF_Init() == -1){ std::cout << "Could not initialize ttf" << std::endl; return false; } std::cout << "TTF initilized" << std::endl; SDL_WM_SetCaption("Pong",NULL); return true; } [/CODE] Here is paddle.h [CODE] #pragma once #include <iostream> #include <SDL.h> #include <SDL_ttf.h> #include <SDL_Image.h> #include "global_functions.h" class paddle { public: paddle(short nr); ~paddle(void); void Up(); void Down(); void Blit(); SDL_Rect ReturnRect(); private: int YVel; SDL_Surface * image; SDL_Rect box; }; [/CODE] Here is paddle.cpp [CODE] #include "paddle.h" paddle::paddle(short nr) { global_functions f; image = f.Load_Image("paddle.jpg"); image->refcount++; YVel = 50; box.w = image->w; box.h = image->h; box.y = SDL_GetVideoSurface()->h/2 - box.h/2; switch(nr) { case 1: box.x = 0; break; case 2: box.x = SDL_GetVideoSurface()->w - box.w; break; } } void paddle::Up() { box.y-=YVel; } void paddle::Down() { box.y+=YVel; if(box.y + box.h >= SDL_GetVideoSurface()->h) { box.y = SDL_GetVideoSurface()->h - box.h; } } void paddle::Blit() { SDL_BlitSurface(image,NULL,SDL_GetVideoSurface(),&box); } paddle::~paddle(void) { SDL_FreeSurface(image); } SDL_Rect paddle::ReturnRect() { return box; } [/CODE] Here is ball.h [CODE] #pragma once #include <SDL.h> #include "global_functions.h" class ball { public: ball(void); void update(SDL_Rect PaddleRect,SDL_Rect PaddleRect2); ~ball(void); private: SDL_Rect box; int XVel,YVel; SDL_Surface * image; }; [/CODE] Here is ball.cpp [CODE] #include "ball.h" ball::ball(void) { global_functions f; image = f.Load_Image("ball.bmp"); image->refcount++; SDL_SetColorKey(image,SDL_SRCCOLORKEY,SDL_MapRGB(image->format,200,0,200)); YVel = 5; XVel = 5; box.w = image->w; box.h = image->h; box.x = SDL_GetVideoSurface()->w/2 - box.w/2; box.y = SDL_GetVideoSurface()->h/2 - box.h/2; } void ball::update(SDL_Rect PaddleRect1,SDL_Rect PaddleRect2) { global_functions f; box.x+=XVel; box.y+=YVel; if(f.CheckCollision(box,PaddleRect1)||f.CheckCollision(box,PaddleRect2)) {XVel = -XVel;} if((box.y+box.h) >= SDL_GetVideoSurface()->h || box.y <= 0){YVel = -YVel;} SDL_BlitSurface(image,NULL,SDL_GetVideoSurface(),&box); } ball::~ball(void) { SDL_FreeSurface(image); } [/CODE] stoffe1100 posted a topic in General and Gameplay ProgrammingHello! Im new at SDL. I´m doing small experiments like what i was trying to do now when i got a stuck on a problem. I have made a button class called NewButton that got a bool function called CheckEvents that is supposed to return true if left mouse button was pressed while the mouse arrow is inside the "ButtonRect". It compiles fine and i can see my button on the screen. But nothing happends when i press it. I know the code is not completely object oriented but that is not what i am focusing on now And by the way, if you find any other things that i should have i mind please tell me, i wanna learn as much as possible [img][/img] And another question while i'm anyway starting a thread. Do i really have to pass in the screen surface to the button. Are there no way to make the screen variable global somehow. Seems dumb to do it this way. I have been sitting up half night now only looking at this.... Thanks in advance! Here is the main.cpp [code]#include <sdl.h> #include <string> #include "NewButton.h" SDL_Event event; bool running = true; SDL_Surface * screen = SDL_SetVideoMode(800,600,32,SDL_HWSURFACE|SDL_DOUBLEBUF); int main(int argc, char * args[]){ SDL_Surface * Image = SDL_LoadBMP("TestKnapp.BMP"); Image = SDL_DisplayFormat(Image); NewButton ExitButton(400,300,100,50,Image,screen); while; } } ExitButton.DrawToScreen(); SDL_Flip(screen); } return 0; } [/code] Here is NewButton.h [code]#pragma once #ifndef newbutton #define newbutton #include <SDL.h> #include <string> using namespace std; class NewButton { public: NewButton(int x,int y, int w, int h,SDL_Surface * Image,SDL_Surface * screen); void DrawToScreen(); bool CheckEvents(); private: SDL_Surface * LocalScreen; SDL_Surface * ButtonImage; SDL_Rect ButtonRect; SDL_Event event; int MouseX,MouseY; }; #endif[/code] Here is NewButton.cpp [code]#include "NewButton.h" #include <SDL.h> #include <string> using namespace std; NewButton::NewButton(int x,int y, int w, int h,SDL_Surface * Image,SDL_Surface * screen): LocalScreen(screen), MouseX(0), MouseY(0) { ButtonImage = Image; ButtonRect.x = x; ButtonRect.y = y; ButtonRect.w = w; ButtonRect.h = h; } void NewButton::DrawToScreen(){ SDL_BlitSurface(ButtonImage,NULL,LocalScreen,&ButtonRect); } bool NewButton::CheckEvents(){ if(SDL_PollEvent(&event)){ if(event.type == SDL_MOUSEBUTTONDOWN){ if(event.button.button == SDL_BUTTON_LEFT){ MouseX = event.button.x; MouseY = event.button.y; if((MouseX > ButtonRect.x) && (MouseY > ButtonRect.y) && (MouseX < (ButtonRect.x + ButtonRect.w)) && (MouseY < (ButtonRect.y + ButtonRect.h))){ return true; } } } } return false; }[/code]
https://www.gamedev.net/profile/197239-stoffe1100/?tab=topics
CC-MAIN-2017-30
refinedweb
2,471
52.76
The Microsoft.Office.Tools.Excel namespace contains a set of classes that extend and support the Microsoft Office Excel object model in projects created by using Visual Studio Tools for Office. The types in this namespace can be used only in Visual Studio Tools for Office projects. For more information about these projects, see Visual Studio Tools for Office Project Templates Overview. The Microsoft.Office.Tools.Excel namespace includes the following classes: The Workbook, Worksheet, and ChartSheet host item classes. For information about host items, see Host Items and Host Controls Overview and Excel Host Items. Host control classes, including Chart, ListObject, NamedRange, and XmlMappedRange. For information about host controls, see Host Items and Host Controls Overview. Classes that implement smart tag functionality in Excel, including Action and SmartTag. Various helper classes, such as event argument and event handler classes for events in the Excel host items and host controls.
http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.aspx
crawl-002
refinedweb
150
55.24
CDBLOCKEDREAD(3) BSD Programmer's Manual CDBLOCKEDREAD(3) cdblockedread - seek and read with 2048-byte alignment #include <mbfun.h> ssize_t cdblockedread(int fd, void *dst, size_t len, off_t ofs); The cdblockedread() function equals the following calls: lseek(fd, ofs, SEEK_SET); read(fd, dst, len); It however differs from that sequence in that it does proper error check- ing and I/O aligned to 2048 bytes, that is ofs is truncated down to a multiple of 2048, the difference is added to len which then is rounded up to a multiple of 2048, a temporary buffer is allocated to which the bytes are read, the correct bytes are then copied to dst and another lseek(2) to the original ofs + len is done to set the file seek pointer to the same value the above sequence of calls would have. This function is of limited use cases; one would be to read a random 512-byte sector from a CD-ROM using the raw mode (character) device; disklabel(8) does that. If no error occured and the call to read(2) returned exactly len bytes in one operation, cdblockedread() returns len. Otherwise, if the last call to lseek(2) failed but everything else succeeded, 0 is returned, -1 oth- erwise. This is because the seek pointer after reading is irrelevant to most applications using it. lseek(2), read(2), cd(4) The cdblockedread function is an MirOS BSD extension and first appeared in MirOS #11. Thorsten Glaser <tg@mirbsd.org> MirOS BSD #10-current August 14,.
http://mirbsd.mirsolutions.de/htman/sparc/man3/cdblockedread.htm
crawl-003
refinedweb
255
62.01
Remember Your Wii Friend Code the 1-800 Way Zonk posted more than 7 years ago | from the every-little-bit-helps dept. (1) stratjakt (596332) | more than 7 years ago | (#18522683) Re:Ya (2, Funny) Saige (53303) | more than 7 years ago | (#18522987) It's just that easy. Re:Ya (1) stratjakt (596332) | more than 7 years ago | (#18523201) Re:Ya (2, Insightful) Saige (53303) | more than 7 years ago | (#18523329):Ya (1) MS-06FZ (832329) | more than 7 years ago | (#18523347) Though when someone's beating me in Mario Kart, and stops at the finish line, waits 'til I get there, and then turns around and crosses it driving backwards, that sends a pretty clear message. Solid Snake Racing (1) tepples (727027) | more than 7 years ago | (#18523461) Re:Solid Snake Racing (2, Interesting) MS-06FZ (832329) | more than 7 years ago | (#18529339) Fag. (-1, Flamebait) Anonymous Coward | more than 7 years ago | (#18523991) Re:Ya (0) Anonymous Coward | more than 7 years ago | (#18524263) Re:Ya (1) Blakey Rat (99501) | more than 7 years ago | (#18529183) No friends, please. (2, Funny) Seumas (6865) | more than 7 years ago | (#18522685) Re:No friends, please. (4, Insightful) Simon80 (874052) | more than 7 years ago | (#18522883) Re:No friends, please. (0, Insightful) Anonymous Coward | more than 7 years ago | (#18522905) Re:No friends, please. (5, Funny) JFMulder (59706) | more than 7 years ago | (#18523083) Re:No friends, please. (-1, Redundant) Conception (212279) | more than 7 years ago | (#18523187) Do you get it? Wii! Like a penis! It's like I'm saying you have a small penis! Ah... it never gets old. Re:No friends, please. (0, Troll) Trogre (513942) | more than 7 years ago | (#18523363) Wii? 360? Too many jokes. Re:No friends, please. (1) Furp (935063) | more than 7 years ago | (#18523995) So, to beat a dead horse: Don't you mean annoying, Wii-tarded jokes? Re:No friends, please. (0, Flamebait) Forrest Kyle (955623) | more than 7 years ago | (#18525085) I like the Wii. It's a good piece of technology. However, that is a pretty bad marketing choice. I wonder if you'd be all "mature" and "grown up" if Sony was marketing a new console called the Twaught. Re:No friends, please. (1) Cornflake917 (515940) | more than 7 years ago | (#18529871) Re:No friends, please. (1) KDR_11k (778916) | more than 7 years ago | (#18532913) Easy Solution... (0) Anonymous Coward | more than 7 years ago | (#18522713) Re:Easy Solution... (4, Interesting) Seumas (6865) | more than 7 years ago | (#18522951):Easy Solution... (2, Interesting) Walpurgiss (723989) | more than 7 years ago | (#18523133) Re:Easy Solution... (2, Funny) Professor_UNIX (867045) | more than 7 years ago | (#18523145) Re:Easy Solution... (1) honkycat (249849) | more than 7 years ago | (#18523417) Re:Easy Solution... (1) Andy Dodd (701) | more than 7 years ago | (#18526443) Re:Easy Solution... (-1, Flamebait) Anonymous Coward | more than 7 years ago | (#18523227) Re:Easy Solution... (1) Seumas (6865) | more than 7 years ago | (#18523599) Re:Easy Solution... (1) naoursla (99850) | more than 7 years ago | (#18524959) Re:Easy Solution... (2, Interesting) asninn (1071320) | more than 7 years ago | (#18526193) Re:Easy Solution... (1) Blakey Rat (99501) | more than 7 years ago | (#18529149) The more neutral Netscape term "bookmarks" is much better for that purpose. WiTendoFi.com still works (5, Informative) GweeDo (127172) | more than 7 years ago | (#18522715) mywifitag.com/gweedo767 [mywifitag.com] That is a lot easier to remember than coming up with that crap. disclaimer: this guy works for them (1) headonfire (160408) | more than 7 years ago | (#18524861) Re:disclaimer: this guy works for them (1) aliquis (678370) | more than 7 years ago | (#18531161) Also I know there are plenty of friendcode sites for the DS, and I guess more than his support the wii aswell. screen names? (0) Anonymous Coward | more than 7 years ago | (#18522907) Re:screen names? (2, Insightful) pelrun (25021) | more than 7 years ago | (#18525475) My concern... (2, Interesting) earthbound kid (859282) | more than 7 years ago | (#18523313) Re:My concern... (1) SethraLavode (910814) | more than 7 years ago | (#18523335) Re:My concern... (1) trogdor8667 (817114) | more than 7 years ago | (#18524439) Re:My concern... (1) nbehary (140745) | more than 7 years ago | (#18524551) Re:My concern... (1) ChaosDiscord (4913) | more than 7 years ago | (#18524631) DRM complications to their hardware. Re:My concern... (1) zentu (584197) | more than 7 years ago | (#18525385) Re:My concern... (1) powerlord (28156) | more than 7 years ago | (#18529553) time for downloadable games. The requirement is that you have to have your user ID on the machine, so you can go over to a friends house, create an account, download a game, play, and then de-authorize their system/delete the account when you leave. Not sure, but you might just be able to de-authorize the system when you leave, and then reauthorize it the next time you are over, but remember not to leave your password on the system. I would be surprised with all the push for downloadable content that MS or Nintendo wouldn't have a similar system in place to help users keep their purchased content as they moved between machines. This is going to become even more critical later into the console cycle as machines wear out and need to be replaced/serviced, and as we start to transition to the "next-gen" consoles, whatever they are (even though its WAY to early for us to start thinking about that). Maybe via the "purge" feature? (1) LordRobin (983231) | more than 7 years ago | (#18530091) ------RM Tag... (0) Anonymous Coward | more than 7 years ago | (#18523867) Just write down the number. (1) Hamster Lover (558288) | more than 7 years ago | (#18523903) Re:Just write down the number. (1) freeweed (309734) | more than 7 years ago | (#18524755) (4, Insightful) The-Bus (138060) | more than 7 years ago | (#18524065) Brian Hastings made an excellent point [n4g.com] earlier this week: Even if you do play it, you can't do much with each other's friend codes. At least not yet. Re:Here's mine (0) Anonymous Coward | more than 7 years ago | (#18524533) Re:Here's mine (1) earthbound kid (859282) | more than 7 years ago | (#18525239) Re:Here's mine (1) grumbel (592662) | more than 7 years ago | (#18527539) they rely heavily on the next cool gimmicky. All that said, motion sensing doesn't have to stay a gimmick, just like with more powerful graphics hardware the important thing is what you do with it. You can use the new graphics power just to add some more shiny into the same old games and everybody will get bored soon after, you can however also put it to use and do games that where impossible on any other console before (for example huge crowds in Dead Rising). If motion sensing actually allows you to do things that you couldn't do with a normal controller then its great (speed and direction of the swing are seamlessly detected in Wii Sports), if its on the other side is just the same as a button-press (i.e. shake the Wiimote in Zelda for sword swing) then its pretty lame. At the moment most games have a tendency to go into the "lame" direction, they present you the same old game with the same old controls, just remapped to Wiimote motions. ### Right now my favorite Wii game is "Everybody Votes," Which kind of nicely shows that the Wii is in trouble right now. Re:Here's mine (1) earthbound kid (859282) | more than 7 years ago | (#18535633) button, then I'm sure the Wii has a future. Also, I don't agree that Zelda is the "bad" kind of motion control. If anything what Zelda tells us is that you can make games for the Wii that are the same as traditional button based games with no compromises. So, there doesn't have to be a binary choice between a system with motion controls and traditional games. Zelda tells us that one system can do both. Now, it's true that the sword swinging mechanism of Zelda isn't really treated differently by the system than a simple button press, but that doesn't mean it doesn't feel different to the user. Fighting with motion controls (particular the shield attack and spin attack on the nunchuck) is more visceral. It is a little worse for some timing things (I'm thinking particularly of the first form of the final boss, where you have to reflect fireballs with well timed sword swings), but in ordinary fights, the motion control is just more fun and preferable to button based controls. Plus, aiming with the Wii Remote is superior to aiming with a thumb stick (though admittedly still inferior to a mouse in terms of speed and accuracy). My prediction is that the Xbox 720 and the PlayStation 4 are going to also include a Wii-like system for direct pointing and motion detection. (Though hopefully, they'll come up with a way to do this without a sensor bar.) It lets you play a wider range of games without harming the ability to play traditional games. It's the future. Re:Here's mine (1) grumbel (592662) | more than 7 years ago | (#18541837) wiggling the Wiimote I haven't really won anything, its still an abstract action, just as a button press, that has no direct connection to the game. Nintendo also removed Gamecube and Classic Controller support, so that people don't have a way to try the other control scheme, I guess they had their reason. My main issue with the Wii is that Nintendo themself doesn't really seem to know what to do with it. Wii Sport was good and made good use of the controller, but with the rest of the games it just seems pointless. I have some doubt that this will change with Mario or Metroid, which after all worked perfectly fine with a normal controller. I simple miss that one killer title that shows that motion sensing is also good for 'real' games, not just mini-game collections, Zelda simply failed that one and everything announced so far doesn't look very impressive either. I do see some good use for motion based controls, however not for such simple devices as the Wiimote. To make motion control really useful you would need exact position and rotation sensing, which however the Wiimote can't do, all it does is measure acceleration, which just isn't enough for many situation where you might want to map the controllers action 1:1 into the game. Re:Here's mine (1) LKM (227954) | more than 7 years ago | (#18526561) Re:Here's mine (1) DigitalCrackPipe (626884) | more than 7 years ago | (#18529035) Back on topic, I exchanged a few friend codes but haven't used them after the first week. They're not the console's strongest point. Re:Here's mine (1) BarneyL (578636) | more than 7 years ago | (#18530415) It must all be true because he would have no reason to like, make all that stuff up. Hrm... Doesn't Nintendo transfer friend codes...? (1) tlhIngan (30335) | more than 7 years ago | (#18524431) Just would seem odd that Nintendo would transfer everything over except the friend code... Coming up: (2, Funny) nugneant (553683) | more than 7 years ago | (#18524875) (1) hcdejong (561314) | more than 7 years ago | (#18525729) number attached to prevent namespace collisions) is much more memorable than any code Nintendo can come up with. Re:Useless (0) Anonymous Coward | more than 7 years ago | (#18528511) The main problem with the interfaces that I think most users have is that they have this snazzy built in messaging system and USB ports on the Wii, but no USB keyboard support, you have to use the point and click interface, which is slow and clumsy if you're even a moderately experiences typist. There is a better way (1) Martian of Death (1081485) | more than 7 years ago | (#18527445) It has a learning curve up front, but once you get it down, you can mop up the floor with 16 digit numbers. High level summary: Map numbers to consonants. Insert vowels and the letters h, q, w, x, and y freely to make the consonants into words. For long numbers, make multiple words, preferably that have some relevance to the person or thing the number is associated with.. Example (banged on number pad to get this number): 4276930814557292 4 27 6 9 3 0 8 1 4 55 7 2 9 2 rank job maze, father will con ben If your string of words is hard to remember, the link mentions ways to memorize that as well. So here's really the underlying question (1) fistfullast33l (819270) | more than 7 years ago | (#18527781)?
http://beta.slashdot.org/story/82387
CC-MAIN-2014-42
refinedweb
2,147
76.35
Is it possible to directly compute the product (or for example sum) of two columns without using ?? grouped.apply(lambda x: (x.a*x.b).sum() df['helper'] = df.a*df.b grouped= df.groupby(something) grouped['helper'].sum() df.drop('helper', axis=1) grouped.apply(lambda x: (x.a*x.b).sum()/(df.b).sum()) I want to eventually build an embedded array expression evaluator (Numexpr on steroids) to do things like this. Right now we're working with the limitations of Python-- if you implemented a Cython aggregator to do (x * y).sum() then it could be connected with groupby, but ideally you could write the Python expression as a function: def weight_sum(x, y): return (x * y).sum() and that would get "JIT-compiled" and be about as fast as groupby(...).sum(). What I'm describing is a pretty significant (many month) project. If there were a BSD-compatible APL implementation I might be able to do something like the above quite a bit sooner (just thinking out loud).
https://codedump.io/share/Z6ahrE2XQAbj/1/groupby-functions-in-python-pandas-like-sumcol1col2-weighted-average-etc
CC-MAIN-2018-17
refinedweb
172
59.8
Overview While the title of this posts says "Urllib2", we are going to show some examples where you use urllib, since they are often used together. This is going to be an introduction post of urllib2, where we are going to focus on Getting URLs, Requests, Posts, User Agents and Error handling. Please see the official documentation for more information. Also, this article is written for Python version 2.x HTTP is based on requests and responses - the client makes requests and servers send responses. A program on the Internet can work as a client (access resources) or as a server (makes services available). An URL identifies a resource on the Internet. What is Urllib2? urllib2 is a Python module that can be used for fetching URLs. It defines functions and classes to help with URL actions (basic and digest authentication, redirections, cookies, etc) The magic starts with importing the urllib2 module. What is the difference between urllib and urllib2? While both modules do URL request related stuff,. Please see the documentation for more information. Urllib Urllib2 What is urlopen? urllib2 offers a very simple interface, in the form of the urlopen function. This function is capable of fetching URLs using a variety of different protocols (HTTP, FTP, ...) Just pass the URL to urlopen() to get a "file-like" handle to the remote data. Additionaly, urllib2 offers an interface for handling common situations - like basic authentication, cookies, proxies and so on. These are provided by objects called handlers and openers. Getting URLs This is the most basic way to use the library. Below you can see how to make a simple request with urllib2. Begin by importing the urllib2 module. Place the response in a variable (response) The response is now a file-like object. Read the data from the response into a string (html) Do something with that string. Note if there is a space in the URL, you will need to parse it using urlencode. Let's see an example of how this works. import urllib2 response = urllib2.urlopen('') print response.info() html = response.read() # do something response.close() # best practice to close the file Note: you can also use an URL starting with "ftp:", "file:", etc.). The remote server accepts the incoming values and formats a plain text response to send back. The return value from urlopen() gives access to the headers from the HTTP server through the info() method, and the data for the remote resource via methods like read() and readlines(). Additionally, the file object that is returned by urlopen() is iterable. Simple urllib2 script Let's show another example of a simple urllib2 script import urllib2 response = urllib2.urlopen('') print "Response:", response # Get the URL. This gets the real URL. print "The URL is: ", response.geturl() # Getting the code print "This gets the code: ", response.code # Get the Headers. # This returns a dictionary-like object that describes the page fetched, # particularly the headers sent by the server print "The Headers are: ", response.info() # Get the date part of the header print "The Date is: ", response.info()['date'] # Get the server part of the header print "The Server is: ", response.info()['server'] # Get all data html = response.read() print "Get all data: ", html # Get only the length print "Get the length :", len(html) # Showing that the file object is iterable for line in response: print line.rstrip() # Note that the rstrip strips the trailing newlines and carriage returns before # printing the output. Download files with Urllib2 This small script will download a file from pythonforbeginners.com website import urllib2 # file to be written to file = "downloaded_file.html" url = "" response = urllib2.urlopen(url) #open the file for writing fh = open(file, "w") # read from request while writing to file fh.write(response.read()) fh.close() # You can also use the with statement: with open(file, 'w') as f: f.write(response.read()) The difference in this script is that we use 'wb' , which means that we open the file binary. import urllib2 mp3file = urllib2.urlopen("") output = open('test.mp3','wb') output.write(mp3file.read()) output.close() Urllib2 Requests The Request object represents the HTTP request you are making. In its simplest form you create a request object that specifies the URL you want to fetch. Calling urlopen with this Request object returns a response object for the URL requested. The request function under the urllib2 class accepts both url and parameter. When you don't include the data (and only pass the url), the request being made is actually a GET request When you do include the data, the request being made is a POST request, where the url will be your post url, and the parameter will be http post content. Let's take a look at the example below import urllib2 import urllib # Specify the url url = '' # This packages the request (it doesn't make it) request = urllib2.Request(url) # Sends the request and catches the response response = urllib2.urlopen(request) # Extracts the response html = response.read() # Print it out print html You can set the outgoing data on the Request to post it to the server. Additionally, you can pass data extra information("metadata") about the data or the about request itself, to the server - this information is sent as HTTP "headers". If you want to POST data, you have to first create the data to a dictionary. Make sure that you understand what the code does. # Prepare the data query_args = { 'q':'query string', 'foo':'bar' } # This urlencodes your data (that's why we need to import urllib at the top) data = urllib.urlencode(query_args) # Send HTTP POST request request = urllib2.Request(url, data) response = urllib2.urlopen(request) html = response.read() # Print the result print html User Agents The way a browser identifies itself is through the User-Agent header. By default urllib2 identifies itself as Python-urllib/x.y where x and y are the major and minor version numbers of the Python release. This could confuse the site, or just plain not work. With urllib2 you can add your own headers with urllib2. The reason why you would want to do that is that some websites dislike being browsed by programs. If you are creating an application that will access other people’s web resources, it is courteous to include real user agent information in your requests, so they can identify the source of the hits more easily. When you create the Request object you can add your headers to a dictionary, and use the add_header() to set the user agent value before opening the request. That would look something like this: # Importing the module import urllib2 # Define the url url = '' # Add your headers headers = {'User-Agent' : 'Mozilla 5.10'} # Create the Request. request = urllib2.Request(url, None, headers) # Getting the response response = urllib2.urlopen(request) # Print the headers print response.headers You can also add headers with "add_header()" syntax: Request.add_header(key, val) urllib2.Request.add_header The example below, use the Mozilla 5.10 as a User Agent, and that is also what will show up in the web server log file. import urllib2 req = urllib2.Request('') req.add_header('User-agent', 'Mozilla 5.10') res = urllib2.urlopen(req) html = res.read() print html This is what will show up in the log file. “GET / HTTP/1.1? 200 151 “-” “Mozilla 5.10? urllib.urlparse The urlparse module provides functions to analyze URL strings. It defines a standard interface to break Uniform Resource Locator (URL) strings up in several optional parts, called components, known as (scheme, location, path, query and fragment) Let's say you have an url: The scheme would be http The location would be The path is index.html We don't have any query and fragment The most common functions are urljoin and urlsplit import urlparse url = "" domain = urlparse.urlsplit(url)[1].split(':')[0] print "The domain name of the url is: ", domain For more information about urlparse, please see the official documentation. urllib.urlencode When you pass information through a URL, you need to make sure it only uses specific allowed characters. Allowed characters are any alphabetic characters, numerals, and a few special characters that have meaning in the URL string. The most commonly encoded character is the space character. You see this character whenever you see a plus-sign (+) in a URL. This represents the space character. The plus sign acts as a special character representing a space in a URL Arguments can be passed to the server by encoding them with and appending them to the URL. Let's take a look at the following example. import urllib import urllib2 query_args = { 'q':'query string', 'foo':'bar' } # you have to pass in a dictionary encoded_args = urllib.urlencode(query_args) print 'Encoded:', encoded_args url = '?' + encoded_args print urllib2.urlopen(url).read() If I would print this now, I would get an encoded string like this: q=query+string&foo=bar Python's urlencode takes variable/value pairs and creates a properly escaped querystring: from urllib import urlencode artist = "Kruder & Dorfmeister" artist = urlencode({'ArtistSearch':artist}) This sets the variable artist equal to: Output : ArtistSearch=Kruder+%26+Dorfmeister Error Handling This section of error handling is based on the information from Voidspace.org.uk great article: "Urllib2 - The Missing Manual" urlopen raises URLError when it cannot handle a response. HTTPError is the subclass of URLError raised in the specific case of HTTP URLs. URLError Often, URLError is raised because there is no network connection, or the specified server doesn't exist. In this case, the exception raised will have a 'reason' attribute, which is a tuple containing an error code and a text error message. Example of URLError req = urllib2.Request('') try: urllib2.urlopen(req) except URLError, e: print e.reason (4, 'getaddrinfo failed') HTTPError Every HTTP response from the server contains a numeric "status code". Sometimes the status code indicates that the server is unable to fulfill '404' (page not found), '403' (request forbidden), and '401' (authentication URLError, e: print e.code print e.read() could not fulfill the request.' print 'Error code: ', e.code else: # everything is fine Please take a look at the links below to get more understanding of the Urllib2 library. Sources and:
https://www.pythonforbeginners.com/urllib2/how-to-use-urllib2-in-python
CC-MAIN-2020-16
refinedweb
1,698
58.18
Surfing With a Linker Alien (Comments) 2013-01-10T19:45:33+00:00 Apache Roller Re: My Relocations Don't Fit - Position Independence guest 2013-01-10T10:58:53+00:00 2013-01-10T10:58:53+00:00 <p. </p> <p>I did what is suggested above, -Kpic -xmodel=medium, but still see the problem. Any other suggestions? </p> Re: My Relocations Don't Fit - Position Independence rod 2011-06-14T13:04:46+00:00 2011-06-14T13:04:46+00:00 <p>Yes, only the pages that are written should become unsharable. However, there might be other overheads, like reserving swap space for the segment with the assumption that more pages are likely to be written.</p> Re: My Relocations Don't Fit - Position Independence Yon 2011-06-14T08:07:18+00:00 2011-06-14T08:07:18+00:00 <p>Quote: "If a shared object is built from position-dependent code, [...] the text segment is no longer sharable between multiple processes."</p> <p>If the text segment is bigger than one memory page, does the system really make a private copy of the whole segment ? I mean, don't you think that the system only makes a private copy of pages that contain code lines concerned by relocation (Copy-On-Write feature) ?</p> Re: My Relocations Don't Fit - Position Independence rod 2011-02-22T10:18:21+00:00 2011-02-22T10:18:21+00:00 <p>I notice from my gnu testing, that an a.out is created with the following reference:</p> <p>0804a004 00000207 R_386_JUMP_SLOT 00000000 __libc_start_main</p> <p>whereas yours has a __libc_start_main@@GLIBC_ reference.</p> <p>Perhaps there's something odd about how the versioned symbol __libc_start_main@@GLIB_2.0 is resolved from libc.so.6. A GNU compiler expert might have to unravel things from here.</p> Re: My Relocations Don't Fit - Position Independence Stefano B 2011-02-22T09:52:08+00:00 2011-02-22T09:52:08+00:00 <p>I see! Ok thank you very much anyway!<br/>..<br/> :)<br/> Best regards,<br/> Stefano B. </p> Re: My Relocations Don't Fit - Position Independence Rod 2011-02-22T09:30:59+00:00 2011-02-22T09:30:59+00:00 <p>Sorry, but I don't think there's anything I can offer.</p> <p>Your site doesn't let me see any content, perhaps it's expecting me to login. But I'm not familiar with PPC, Qemu, and I only play a little in the gnu/gld environment.</p> <p>On Solaris you can run pic, and non-pic code as an executable or shared object (although non-pic shared objects can have some address restrictions).</p> <p>If you can't build a simple a.out with pic, and have it execute, you're going to have to call in some other experts.</p> <p>Perhaps <a href="?" rel="nofollow">?</a></p> Re: My Relocations Don't Fit - Position Independence Stefano B 2011-02-21T14:34:33+00:00 2011-02-21T14:34:33+00:00 <p>Hi!<br/> I am also afraid it can be something not foreseen by who developed gnu gcc/ld .. a PIC executable is even not run by the shell.<br/> I run them using qemu-user that can load them fine and go to the correct entry-point (well actually only the current developed version, not the last official release 0.13)..<br/> I even do not have a Power-PC machine, I am running a Debian6 powerPC as a virtual machine in qemu-sytem.<br/> I am just a student who sees this things (linkers, compilers, relocations..) for the very first time, really not easy..<br/> I searched for LD_OPTIONS, all links are about Solaris, Sun .. <br/> In my ld I found a -Map option.. I created one and I've uploaded the result into:<br/> <a href="" rel="nofollow"></a><br/> together with dunps from objdump and readelf ..<br/> I dunno, if you have time, for sure they will tell much more to you than to me :)<br/> Thank you very much again!<br/> Stefano B.</p> Re: My Relocations Don't Fit - Position Independence Rod 2011-02-21T13:40:13+00:00 2011-02-21T13:40:13+00:00 <p>Sorry, I can't explain what you're seeing, must be some subtlety with gcc/gld. The only comparable experiment I can do reveals __libc_start_main as a .plt reference.</p> <p> ubuntu: cat > main.c<br/> void main(){}<br/> ubuntu: gcc main.c<br/> ubuntu: readelf -r a.out<br/> ...<br/> Relocation section '.rel.plt' at offset 0x264 contains 2 entries:<br/> Offset Info Type Sym.Value Sym. Name<br/> 0804a00 00000207 R_386_JUMP_SLOT 00000000 __libc_start_main</p> <p>Under Solaris you can set LD_OPTIONS-D<tokens> and discover how symbols are resolved and relocations built. I thought you could do this under gnu ld too, but I don't know the incantations.</p> Re: My Relocations Don't Fit - Position Independence Stefano B 2011-02-21T13:15:37+00:00 2011-02-21T13:15:37+00:00 <p>Hi!<br/> Thank you very much for your reply!<br/> Sure that reference is coming from a crt object file added by gcc, I checked that file and it is PIC.</p> <p>using readelf on my system:<br/> Symbol table '.dynsym' contains 10 entries:<br/> Num: Value Size Type Bind Vis Ndx Name</p> <p> 4: 00000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@GLIBC_2.0 (2)</p> <p>Symbol table '.symtab' contains 71 entries:<br/> Num: Value Size Type Bind Vis Ndx Name<br/> 60: 00000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@@GLIBC_</p> <p>So it is recognized as a function.<br/> readelf -s /lib/libc.so.6|grep __libc_start_main produces:<br/> 2320: 0001f720 224 FUNC GLOBAL DEFAULT 11 __libc_start_main@GLIBC_2.0</p> <p"</p> <p>Thank you again!<br/> Stefano B.</p> Re: My Relocations Don't Fit - Position Independence Rod 2011-02-21T12:34:19+00:00 2011-02-21T12:34:19+00:00 <p>Not being familiar with any PowerPC environments, I can only guess at<br/> what might be occurring.</p> <p>I suspect the reference to __libc_start_main is coming from one of the<br/> crt files provided by the compiler driver. In other words, this reference<br/> isn't from any of the files you are compiling -fPIC, but is from one of<br/> the other files, added to the link, by the compiler.</p> <p>Normally, non-pic references to external functions are translated into<br/> procedure linkage table references (.plt) by the link-editor. But, for<br/> this to occur, the link-editor must find a definition for the function,<br/> and validate that the definition is defined as a function (the symbol<br/> table entry should be defined as FUNC).</p> <p>On a system close to me I see:</p> <p>ubuntu: readelf -s /lib/libc.so.6 | fgrep __libc_start_main<br/> 2198: 00016c00 438 FUNC GLOBAL DEFAULT 12 __libc_start_main@@GLIBC_2.0</p> <p>If you reference a libc like this during your final link-edit, the reference to __libc_start_main should be resolved to the definition in libc, and a .plt relocation would be created for runtime.</p> <p>Hope this helps.</p> Re: My Relocations Don't Fit - Position Independence Stefano B 2011-02-21T05:39:09+00:00 2011-02-21T05:39:09+00:00 <p>Hi! I desperately need help! This post was the closest to my problem, I really hope you can help!!<br/> I need to create a powerpc PIE executable, that is not a shared library, but a real executable linked as pie. This executable will be run by QEMU-USER.<br/> I compile all with gcc -fPIC and then link with -Wl,-pie.<br/> Checking all the linked object files with "readelf -d myobjectfile | fgrep TEXT" all seem to be PIC as nothing is produced by the previous comand.<br/> Oddly giving the command "readelf -d mypie_executable | fgrep TEXT" to my final 'PIC' output executable i get: "0x00000016 (TEXTREL) 0x0"<br/> Then if I try to load the file with QEMU-USER i get: "error while loading shared libraries: R_PPC_REL24 relocation at 0xb31f95a0 for symbol `__libc_start_main' out of range" !!!<br/> Note that this happens with a simple hello world executable that does nothing: "int main(){ };"<br/> During the linking phase something wrong happens.. I think that the linker does not expect I want an executable to be PIC ..<br/> In fact this does not happen if I create a shared library, but I need an executable..<br/> I am compiling and linking in Debian6 gcc 4.4.5 PowerPC.<br/> "objdump -R myexecutable" gives:<br/> Offset = 5a0 Type = R_PPC_REL24 Value=__libc_start_main<br/> "readelf -r myexecutable" gives:<br/> rela.dym at offset 0x39c<br/> Offset=5a0 Info=40a Type=R_PPC_REL24 Sym.Value= 0000 Sym. Name+added = __libc_start_main<br/> I tried using "LD_OPTIONS=-Dreloc,detail" but I do not get the same showed before.. I get "/\* Script for ld -pie: link position independent executable \*/ and then the script.. not very easy for me to understand (i can post it if it can help) <br/> I really can't understand how it happens that from all PIC object files (if I checked all of them fine) linking with "pie" I get not a PIC executable!<br/> Thank you very very much in advance!<br/> Stefano B. </p> Re: My Relocations Don't Fit - Position Independence David Kirkby 2011-02-10T03:51:09+00:00 2011-02-10T03:51:09+00:00 <p>At least part of this problem was resolved for me. The developer of the ECL interpreter said he had used "computed gotos" which are a GCC extension. It was them which were causing the problem, so they have been disabled on Solaris. </p> Re: My Relocations Don't Fit - Position Independence David Kirkby 2010-10-29T00:15:43+00:00 2010-10-29T00:15:43+00:00 <p>Thank you. Sections 10 and 18 are:</p> <p>Section Header[10]: sh_name: .rel.text<br/> sh_addr: 0x21638 sh_flags: [ SHF_ALLOC SHF_INFO_LINK ]<br/> sh_size: 0x90 sh_type: [ SHT_REL ]<br/> sh_offset: 0x21638 sh_entsize: 0x8 (18 entries)<br/> sh_link: 5 sh_info: 18<br/> sh_addralign: 0x4 </p> <p>Section Header[18]: </p> <p>So it's section 18 I'm to be concerned about. </p> <p>After capturing the output of the compilation (a 138 MB file with 1556648 lines), I see 13 sections marked "debug: creating output relocations" Fortunately, those make up a small part of the output, though there are still 10,000 lines. </p> <p>These are here<br/> <a href="" rel="nofollow"></a></p> <p>but most are irrelevant. </p> <p>One or more sections are like this. </p> <p>debug: creating output relocations<br/> debug: type offset section symbol<br/> debug: R_386_JMP_SLOT 0x5368c .rel.plt __deregister_frame_info_bases</p> <p><snip></p> <p>debug: R_386_RELATIVE 0x7fa7 .rel.text __get_exit_frame_monitor_ptr<br/> debug: R_386_RELATIVE 0x7fb3 .rel.text __do_exit_code_ptr<br/> debug: R_386_RELATIVE 0x8026 .rel.text __fsr_init_value_ptr<br/> debug: R_386_RELATIVE 0x803f .rel.text trap_table</p> <p>Is it those .rel.text sections I should be looking at in more detail? Looking at just the sections marked "debug: creating output relocations", I see the string .rel.text on just 180 lines </p> <p>A couple of lines are </p> <p>debug: R_386_RELATIVE 0x30c57 .rel.text __get_exit_frame_monitor_ptr <br/> debug: R_386_RELATIVE 0x30c63 .rel.text __do_exit_code_ptr </p> <p>but there are 180 in total</p> <p><a href="" rel="nofollow"></a></p> <p>If I understand correctly, I should be looking at those addresses and seeing where they map back to an input section, to locate the suspect file. But how do I use that address information? </p> <p>"Section Header[18]: sh_name: .text" has 5 sets of numeric data, but I'm unsure how to use them, or the addresses in the file</p> <p><a href="" rel="nofollow"></a></p> <p>to actually get back to the relevant input section and so find the suspect code. </p> <p>Dave </p> Re: My Relocations Don't Fit - Position Independence Rod 2010-10-28T12:39:05+00:00 2010-10-28T12:39:05+00:00 <p>The ".rel." sections contain relocation records. These are the records that apply to the associated section, and indicate how offsets within that section must be updated. For example, the ".rel.got" contains the information that must be applied" to the ".got" section.</p> <p.</p> <p>Sections 1-25 are all you need to be concerned about, as these are SHF_ALLOC but not SHF_WRITE.<br/> Sections 39-52 can be ignored, as these don't have SHF_ALLOC, and won't become part of the memory image.</p> <p>But the most glaring section would seem to be:</p> <p>Section Header[18]: sh_name: .text</p> <p>as there's also a:</p> <p>Section Header[10]: sh_name: .rel.text</p> <p>The latter instructs how to update the former, and this is probably the culprit. Find out from the debugging information which input file is contributing this .text section. This will be your non-pic code.</p> Re: My Relocations Don't Fit - Position Independence David Kirkby 2010-10-28T09:39:21+00:00 2010-10-28T09:39:21+00:00 <p>Thank you. </p> <p>Yes, one of my versions of 'ld' is old, but I'm using my OpenSolaris machine for debugging this, as it's a lot quicker than any of my SPARCs. Hence the 'ld' issue is not a problem. </p> <p>I set:<br/> LD_OPTIONS=-Dreloc,detail -z nocombreloc</p> <p>built the library, then run </p> <p>$ elfdump -c libecl.so</p> <p>and get 52 sections.</p> <p>Section 11 is interesting:</p> <p>Section Header[11]: sh_name: .rel.got<br/> sh_addr: 0x216c4 sh_flags: [ SHF_ALLOC SHF_INFO_LINK ]<br/> sh_size: 0x2c0 sh_type: [ SHT_REL ]<br/> sh_offset: 0x216c4 sh_entsize: 0x8 (88 entries)<br/> sh_link: 5 sh_info: 26<br/> sh_addralign: 0x4</p> <p>as that appears to be a "got" section, but without any SHF_WRITE. Is that to be expected - I thought you were implying that the got sections should be writable. </p> <p>If I understand correctly, the first section where relocations would be permitted is this one, which is another "got" section. </p> <p>Section Header[26]: sh_name: .got<br/> sh_addr: 0x170dbc sh_flags: [ SHF_WRITE SHF_ALLOC ]<br/> sh_size: 0x1228 sh_type: [ SHT_PROGBITS ]<br/> sh_offset: 0x160dbc sh_entsize: 0x4 (1162 entries)<br/> sh_link: 0 sh_info: 0<br/> sh_addralign: 0x4</p> <p>as that has the SHF_WRITE flag. </p> <p>So it looks like I need to concern myself only with sections 1-25 and sections 39-52, as none of them have SHF_WRITE, whereas sections 26 to 38 are writable.</p> <p>Section Header[1]: sh_name: .SUNW_cap<br/> Section Header[2]: sh_name: .eh_frame_hdr<br/> Section Header[3]: sh_name: .hash<br/> Section Header[4]: sh_name: .SUNW_ldynsym<br/> Section Header[5]: sh_name: .dynsym<br/> Section Header[6]: sh_name: .dynstr<br/> Section Header[7]: sh_name: .SUNW_version<br/> Section Header[8]: sh_name: .SUNW_versym<br/> Section Header[9]: sh_name: .SUNW_dynsymsort<br/> Section Header[10]: sh_name: .rel.text<br/> Section Header[11]: sh_name: .rel.got<br/> Section Header[12]: sh_name: .rel.data<br/> Section Header[13]: sh_name: .rel.data.rel.ro.local<br/> Section Header[14]: sh_name: .rel.data.rel<br/> Section Header[15]: sh_name: .rel.data.rel.ro<br/> Section Header[16]: sh_name: .rel.plt<br/> Section Header[17]: sh_name: .plt<br/> Section Header[18]: sh_name: .text<br/> Section Header[19]: sh_name: .init<br/> Section Header[20]: sh_name: .fini<br/> Section Header[21]: sh_name: .rodata<br/> Section Header[22]: sh_name: .rodata.str1.1<br/> Section Header[23]: sh_name: .rodata.str1.4<br/> Section Header[24]: sh_name: .rodata.cst8<br/> Section Header[25]: sh_name: .rodata.cst4</p> <p>and </p> <p>Section Header[39]: sh_name: .symtab<br/> Section Header[40]: sh_name: .strtab<br/> Section Header[41]: sh_name: .comment<br/> Section Header[42]: sh_name: .debug_abbrev<br/> Section Header[43]: sh_name: .debug_info<br/> Section Header[44]: sh_name: .debug_line<br/> Section Header[45]: sh_name: .debug_frame<br/> Section Header[46]: sh_name: .debug_loc<br/> Section Header[47]: sh_name: .debug_pubnames<br/> Section Header[48]: sh_name: .debug_pubtypes<br/> Section Header[49]: sh_name: .debug_aranges<br/> Section Header[50]: sh_name: .debug_ranges<br/> Section Header[51]: sh_name: .debug_str<br/> Section Header[52]: sh_name: .shstrtab</p> <p>Before I go any further, am I right in thinking those sections above are the ones I should be concerned about? I'm puzzled by section 11, which is a "got" section, but not writable. </p> <p>Dave </p> Re: My Relocations Don't Fit - Position Independence Rod 2010-10-24T10:10:09+00:00 2010-10-24T10:10:09+00:00 <p.</p> <p>In the relocation diagnostics, it's the "out" relocations that are of interest:</p> <p>debug: out R_386_GLOB_DAT 0x1f .got cl_env_p</p> <p>However, the above relocation against the ".got" section shouldn't be a problem. As the .got section should be writable.</p> <p>If you look at the sections within your output file (elfdump -c) the sections that are read-only (ie. don't have the SHF_WRITE sh_flags set) are the sections that should \*not\* have relocations against them.</p> <p>The most common culprits of text relocations are against .text, .rodata or .rodata1. But maybe you have some other sections that are causing the error.</p> <p>Look for the "out" diagnostics that are against any read-only section.</p> Re: My Relocations Don't Fit - Position Independence David Kirkby 2010-10-24T09:41:59+00:00 2010-10-24T09:41:59+00:00 <p. </p> <p>I actually created a script 'inputloc' which showed only the section I \*think\* I need:</p> <p>#!/bin/sh<br/> if [ $# != 1 ] ; then <br/> echo "Usage $0 objectfile" 2>&1<br/> echo " Prints the section 'debug: collecting input relocations: section=.text'" 2>&1<br/> exit 1<br/> fi<br/> LD_OPTIONS=-Dreloc,detail ld -z nocombreloc -G $1 2>&1 | sed -n '/debug: collecting input relocations: section=.text/,/debug: collecting/p' </p> <p>but found that was outputing things on lots of files. </p> <p>drkirkby@hawk:~/sage-4.6.rc0/spkg/build/ecl-10.2.1.p3/src/build/ext$ inputloc bytecmp.o | more<br/> debug: collecting input relocations: section=.text, file=bytecmp.o<br/> debug: type offset section symbol<br/> debug: in R_386_GOTPC 0xd [2].rel.text _GLOBAL_OFFSET_TABLE_ <br/> debug: act R_386_GOTPC 0xd .text _GLOBAL_OFFSET_TABLE_ <br/> debug: in R_386_GOT32 0x1f [2].rel.text cl_env_p <br/> debug: out R_386_GLOB_DAT 0x1f .got cl_env_p <br/> debug: act R_386_GOT32 0x1f .text cl_env_p </p> <p>I don't know if that's a bad sign or not. I got the feeling from what you posted above that I should not have these. </p> Re: My Relocations Don't Fit - Position Independence Rod 2010-10-24T08:46:48+00:00 2010-10-24T08:46:48+00:00 <p>If you used the "-z nocombreloc" flag you wouldn't get a single .SUNW_reloc section, but would get individual .rel sections associated to the output sections that must be relocated.</p> <p. </p> Re: My Relocations Don't Fit - Position Independence David Kirkby 2010-10-24T06:15:03+00:00 2010-10-24T06:15:03+00:00 <p>Em, I'm still stuck on sorting out the problem with the ECL Lisp interpreter. </p> <p>I certainly have a text relocation problem: </p> <p>drkirkby@hawk:~/sage-4.6.rc0/local/lib$ elfdump -d libecl.so | grep TEXTREL<br/> [24] TEXTREL 0 <br/> [33] FLAGS 0x4 [ TEXTREL ]</p> <p>drkirkby@hawk:~/sage-4.6.rc0/local/lib$ elfdump -cN.text libecl.so</p> <p>Section Header[13]: <br/> drkirkby@hawk:~/sage-4.6.rc0/local/lib$ </p> <p>But I can't seem to find anything in the output of elfdump -r</p> <p>drkirkby@hawk:~/sage-4.6.rc0/local/lib$ elfdump -r libecl.so | grep Section<br/> Relocation Section: .SUNW_reloc<br/> Relocation Section: .rel.plt<br/> drkirkby@hawk:~/sage-4.6.rc0/local/lib$ elfdump -r libecl.so | grep text<br/> drkirkby@hawk:~/sage-4.6.rc0/local/lib$ </p> <p>So I'm puzzled. </p> <p>I built this with degbug information using LD_OPTIONS and ended up with a 150 MB file. It's hard to navigate that. </p> <p>Dave </p> Re: My Relocations Don't Fit - Position Independence Rodrick Evans 2010-09-18T08:55:38+00:00 2010-09-18T08:55:38+00:00 <p>The R_386_JMP_SLOT relocations are fine. This is how pic code resolves a function all. You want to looks at relocations against the .text section.</p> <p>Try to follow through a simple example. Compile some code without a PIC flag:</p> <p>% cat foo.c<br/> extern int bar();<br/> int foo() { return (bar()); }<br/> % cc -c foo.c<br/> % elfdump -r foo.o</p> <p>Relocation Section: .rela.text<br/> type offset addend section symbol<br/> R_SPARC_WDISP30 0x14 0 .rela.text bar</p> <p>Now follow this relocation through a link-edit that builds a shared object:</p> <p>% LD_OPTIONS=-Dreloc,detail ld -z nocombreloc -G foo.o<br/> ...<br/> debug: collecting input relocations: section=.text, file=foo.o<br/> debug: type offset addend section symbol<br/> debug: in R_SPARC_WDISP30 0x14 0 [13].rela.text bar <br/> debug: out R_SPARC_WDISP30 0x14 0 .text bar </p> <p>This indicates that ld() is going to generate a relocation against the .text section:</p> <p>debug: creating output relocations<br/> debug: type offset addend section symbol<br/> debug: R_SPARC_WDISP30 0x404 0 .rela.text bar </p> <p>Which you can see in the output file:</p> <p>% elfdump -r a.out</p> <p>Relocation Section: .rela.text<br/> type offset addend section symbol<br/> R_SPARC_WDISP30 0x404 0 .rela.text bar</p> <p>It's this relocation against the text section (.rela against the .text) that is resulting in the flag:</p> <p>% elfdump -d a.out | fgrep TEXT<br/> [11] TEXTREL 0 <br/> [16] FLAGS 0x4 [ TEXTREL ]</p> Re: My Relocations Don't Fit - Position Independence David Kirkby 2010-09-18T07:31:29+00:00 2010-09-18T07:31:29+00:00 <p>I'm still puzzled. I'm trying to compile the Lisp interpreter 'ECL'. </p> <p><a href="" rel="nofollow"></a><br/> (latest source is git clone git://ecls.git.sourceforge.net/gitroot/ecls/ecl<br/> )</p> <p>I'm doing this 32-bit on a Xeon processor as that's the fastest machine I've got, and requires no messing around with CFLAGS, but I get the same issues on SPARC or on 64-bit builds. </p> <p>I compiled with the debug options you suggest: I see in the output locations section:</p> <p>debug: creating output relocations<br/> debug: type offset section symbol<br/> debug: R_386_JMP_SLOT 0x806cfc8 .rel.plt atexit<br/> debug: R_386_JMP_SLOT 0x806cfcc .rel.plt __fpstart<br/> debug: R_386_JMP_SLOT 0x806cfd0 .rel.plt exit<br/> debug: R_386_JMP_SLOT 0x806cfd4 .rel.plt _exit<br/> debug: R_386_JMP_SLOT 0x806cfdc .rel.plt __deregister_frame_info_bases<br/> debug: R_386_JMP_SLOT 0x806cfe4 .rel.plt __register_frame_info_bases<br/> debug: R_386_JMP_SLOT 0x806cff8 .rel.plt fprintf<br/> debug: R_386_JMP_SLOT 0x806cffc .rel.plt printf<br/> debug: R_386_JMP_SLOT 0x806d008 .rel.plt __filbuf<br/> debug: R_386_JMP_SLOT 0x806d014 .rel.plt ungetc<br/> and thousands of similar lines. </p> <p>Then using the options -cN.text to elfdump I see:</p> <p>drkirkby@hawk:~/ecl$ elfdump -cN.text ./build/libecl.so</p> <p>Section Header[13]: sh_name: .text<br/> sh_addr: 0x37540 sh_flags: [ SHF_ALLOC SHF_EXECINSTR ]<br/> sh_size: 0x11bc0c sh_type: [ SHT_PROGBITS ]<br/> sh_offset: 0x37540 sh_entsize: 0<br/> sh_link: 0 sh_info: 0<br/> sh_addralign: 0x10 <br/> drkirkby@hawk:~/ecl$ </p> <p>I don't understand how I'm supposed to connect the offsets from the first set of data with what's in the second, to allow the suspect function to be identified. </p> Re: My Relocations Don't Fit - Position Independence Rod 2010-08-30T08:35:38+00:00 2010-08-30T08:35:38+00:00 <p>Well built 32-bit and 64-bit objects should \*not\* have relocations against read-only sections (ie. the TEXTREL test should reveal nothing).</p> <p>Looking at a SPARC machine I see these same objects have text relations too.</p> <p>First, I'd try and identify what the text relocations reference. For example, if I look at the first relocation:</p> <p>% elfdump -r /usr/lib/sparcv9/libglib-2.0.so<br/> ....<br/> type offset addend section symbol<br/> R_SPARC_RELATIVE 0xc89b8 0xc02d0 .SUNW_reloc</p> <p>it requires to update the offset at "0xc02d0".<br/> Now if I look at what section this is I see:</p> <p>% elfdump -c /usr/lib/sparcv9/libglib-2.0.so<br/> ....<br/> Section Header[13]: sh_name: .rodata1<br/> sh_addr: 0xbb290 sh_flags: [ SHF_ALLOC ]<br/> sh_size: 0xce16 sh_type: [ SHT_PROGBITS ]</p> <p>So, it looks like a read-only data item (const) needs relocating. This can happen if you have a table of addresses, and the table is defined const.</p> <p>The studio compilers recognize this condition and normally place the table in a .picdata section which is given write access, and gets places in the data segment. I see this object has a .picdata section too.</p> <p>What I'd do next is run your link-edit with LD_OPTIONS=-Dreloc,detail and trace back where the "0xc02d0" offset originates from (ie, which input file requires this relocation).</p> Re: My Relocations Don't Fit - Position Independence David Kirkby 2010-08-30T03:12:30+00:00 2010-08-30T03:12:30+00:00 <p>On my system at least, the following two files in the /usr file system shows an output with:</p> <p>$ elfdump -d library | fgrep TEXTREL</p> <p>\* /usr/lib/amd64/libcanberra.so<br/> \* /usr/lib/amd64/libglib-2.0.so</p> <p>Is this process applicable to SPARC? </p> <p>Should 32-bit shared libraries not show anything with the following command?</p> <p>$ elfdump -d library | fgrep TEXTREL </p> <p>What can I do when <br/> \* I know there's no assembler<br/> \* Compiling code, while setting </p> <p></a></p> Re: Direct Binding - now the default for OSNet components Oliver Kiddle 2008-07-21T06:42:20+00:00 2008-07-21T06:42:20+00:00 <p?</p> <p>Are there other differences between -zdirect and -Bdirect that I've missed?</p> <p>Thanks</p> Re: My Relocations Don't Fit - Position Independence Neil Martin 2008-04-12T05:58:27+00:00 2008-04-12T05:58:27+00:00 <p.</p>
https://blogs.oracle.com/rie/feed/comments/atom
CC-MAIN-2014-15
refinedweb
4,396
59.4
Hi All, I am creating multipage streamlit ui… In one page I have the option to upload File only In another page there are 10 slider buttons. The user should be able to move around the pages… When the user moves from one page to another, the contents of page1 which has 10 sliders are getting copied in the backgroud… is there any way I could get fresh Page when the user toggles between the pages… The code is as follows: main_app.py import app1 import app2 import streamlit as st PAGES = { "Page 1": app1, "Page 2": app2 } st.sidebar.title('Navigation') selection = st.sidebar.radio("Go to", list(PAGES.keys())) page = PAGES[selection] page.app() app1.py import streamlit as st def app(): st.empty() st.title('APP1') st.write('Welcome to app1') for i in range(10): st.slider("Helpful ?", 1, 5, key = str(i)) return app2.py import streamlit as st def app(): st.empty() st.title('Welcome to App2') uploaded_file = st.file_uploader("Upload New File") When we run 1st time Page looks like below When clicked on Page 2 If we see above, we can see welcome to Page/App 1 in background When I click on Page 1 again Now when I click on Page 2: It goes on forever!!! how can I get rid of this? Thank You, Chait
https://discuss.streamlit.io/t/ui-content-retains-on-using-multiple-sliders-buttons/15441
CC-MAIN-2021-39
refinedweb
225
74.08
The MEDiffraction class provides a simple colour singlet exchange matrix element to be used in the soft component of the multiple scattering model of the underlying event. More... #include <MEDiffraction.h> The MEDiffraction class provides a simple colour singlet exchange matrix element to be used in the soft component of the multiple scattering model of the underlying event. Definition at line 22 of file MEDiffraction. Called in the run phase just before a run begins.. The static object used to initialize the description of this class. Indicates that this is a concrete class with persistent data. Definition at line 291 of file MEDiffraction.h.
https://herwig.hepforge.org/doxygen/classHerwig_1_1MEDiffraction.html
CC-MAIN-2019-30
refinedweb
104
56.66
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Hi, the API of the SplineObject seems to suggest, one could have a spline with the open and closed segments (as one can set the closed flag on a per segment basis in SplineObject.SetSegment()). But I simply can't get it to work. Basically I'm doing something like the following, always ending up with all open segments: import c4d def main(): spline = c4d.SplineObject(6, c4d.SPLINETYPE_LINEAR) spline.ResizeObject(7, 2) spline.SetPoint(0, c4d.Vector(0.0, 0.0, 100.0)) spline.SetPoint(1, c4d.Vector(100.0, 0.0, 100.0)) spline.SetPoint(2, c4d.Vector(100.0, 100.0, 100.0)) spline.SetSegment(0, 3, True) spline.SetPoint(3, c4d.Vector(0.0, 0.0, 200.0)) spline.SetPoint(4, c4d.Vector(100.0, 0.0, 200.0)) spline.SetPoint(5, c4d.Vector(100.0, 100.0, 200.0)) spline.SetSegment(1, 3, False) spline.Message(c4d.MSG_UPDATE) doc.InsertObject(spline) c4d.EventAdd() if __name__=='__main__': main() Playing around with the Spline Pen, I'm somewhat afraid, this feature of the API is not working at all, as the Pen starts working with two spline objects as soon as a segment of the other "openess" gets involved. Not urgent at all, I can work with the obvious workaround of multiple splines. While writing this, I took a look at the C++ API and now, I'm pretty sure, I can answer the question myself already. In C++ such option does not seem to exist. Strangely so, this additional "closed" parameter in Python is not even optional. So, it's maybe more a request for a documentation fix than a real question. Cheers, Andreas hello Andreas ^^ As Sebastian pointed to me there's this structure on c++ so we are not sure if it's a documentation issue, something that have never been used or simply a bug. I have to dive into the code to have a look and probably send an email. I'll be back with information as soon as i have them. (with the release it can take a bit more time than usual) Hope you everything is running fine on your side man Cheers, Manuel Thanks, Manuel! Indeed I overlooked the C++ Segment struct. Take your time. Here everything's fine hi, sorry for the delay of this answer ... Well, as you understood, you can't have a spline with open and closed segments. It's global for the entire spline, either all closed or all opened. The parameter is there, in the structure. It's sometimes used internally instead of the spline parameter. Thanks, Manuel, for looking into it. Maybe worth a note in the docs? It is a bit confusing, isn't it? Cheers to the entire team, Andreas
https://plugincafe.maxon.net/topic/11754/spline-with-closed-and-open-segments
CC-MAIN-2021-31
refinedweb
503
73.88
How to move image inside a video This code is working fine. output of below codeIt creates a noise video and moves a circle inside the video from left to right. But I want to do a different thing. I want to add moving images not a circle. Further says I have to create a video. Inside the video, I have to move images from left to right like the circle of the above code. I am a beginner to opencv and python. Could someone please help for giving some advises or references to reach my final outcome. import numpy as np import cv2 from cv2 import VideoWriter, VideoWriter_fourcc def main2(): width = 1280 height = 720 FPS = 24 seconds = 10 radius = 150 paint_h = int(height / 2) img = cv2.imread('./before/mother.jpg') fourcc = VideoWriter_fourcc(*'MP42') video = VideoWriter('./circle_noise.avi', fourcc, float(FPS), (width, height)) for paint_x in range(-radius, width + radius, 6): frame = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8) cv2.circle(frame, (paint_x, paint_h), radius, (255, 255, 255), -1) video.write(frame) video.release() you mean you want to have a video stream where pictures moves all over the video while it playing right?
https://answers.opencv.org/question/205812/how-to-move-image-inside-a-video/?sort=latest
CC-MAIN-2019-39
refinedweb
198
75.5
Multithreading in Python programming is a well-known technique in which multiple threads in a system share their records space with the principle thread which makes statistics sharing and communique inside threads easy and efficient. Threads are lighter than procedures. Multi threads may execute in my opinion even as sharing their technique assets. The motive of multithreading is to run multiple tasks and function cells at identical times. Multithreading permits you to break down an application into multiple sub-responsibilities and run those tasks concurrently. In case you use multithreading well, your software speed, performance, and rendering can all be better. Python supports constructs for both multiprocessing as well as multithreading. in this tutorial, you may basically be that specialize in enforcing multithreaded programs with python. There are predominant modules that user may use to deal with threads in Python: - The thread module - The threading module Python Multithreading Example 1 import time def countdown(n): while n > 0: print('Thread-minus', n) n -= 1 time.sleep(5) # Create and launch a thread from threading import Thread t = Thread(target = countdown, args =(10, )) t.start() Output Thread-minus 10 When a thread instance is created, it doesn’t start executing until its start() method is invoked. Threads live in their own system-level thread and fully taken care of by the host operating system. Once started, threads run independently until the target function returns Multiprocessing in Python is a technique where user can execute parallelism in its truest shape. A couple of techniques are run across more than one CPU core which does now not share the assets amongst them. Each process may have many threads going for walks in its very own memory area. In Python, every method has its own instance of a Python interpreter doing the activity of executing the instructions. Multiprocessing permits you to create packages that could run concurrently (bypassing the GIL) and use everything of your CPU core. Although it is basically special from the threading library, the syntax is pretty comparable. The multiprocessing library offers every technique its own Python interpreter and each their personal GIL. Python Multithreading Example 2 import threading def print_cube(num): print("Cube: {}".format(num * num * num)) def print_square(num): print("Square: {}".format(num * num)) if __name__ == "__main__": t1 = threading.Thread(target=print_square, args=(10,)) t2 = threading.Thread(target=print_cube, args=(10,)) t1.start() t2.start() t1.join() t2.join() print("Successful") Output Square: 100 Cube: 1000 Successful Multithreading vs Multiprocessing Multithreading in python allows applications to be responsive. Think you have got a database connection and also you need to reply to consumer enter. Without threading, if the database connection is busy the utility will not be capable of replying to the consumer. By splitting off the database connection into a separate thread you could make the software greater responsive. also due to the fact both threads are in an equal manner, they are able to get entry to the same records structures – true performance, plus a flexible software design. Be aware that because of the GIL the app isn’t always definitely doing things immediately, but what we have executed is put the useful resource lock at the database into a separate thread in order that CPU time may be switched between it and the user interaction. CPU time receives rationed out among the threads. The user executes Multiprocessing for instances when they actually do want a couple of things at any given time. Assume your utility desires to connect to 6 databases and perform a complex matrix transformation on every dataset. Putting each task in a separate thread may help a bit due to the fact while one connection is idle some other one should get a few CPU time. However, the processing might no longer happen in parallel because the GIL means that you’re only ever using the resources of one CPU. By way of placing every process in a Multiprocessing procedure, each can run on its very own CPU and run at full efficiency. The multithreading module provides a very simple and intuitive API for spawning more than one thread in software.
https://www.developerhelps.com/python-multithreading/
CC-MAIN-2022-05
refinedweb
688
53.51
The Streaming Distributed Bootstrap The bootstrap (Efron 1979) is an incredibly practical method to estimate uncertainty from finite sampling on almost any quantity of interest. If, say, you’re training a model using just 30 training examples, you’ll likely want to know how uncertain your goodness-of-fit metric is. Is your AUC statistically consistent with 0.5? That’d be key to know, and you could estimate it with the bootstrap. The standard bootstrap, however, does not scale well to big data, and for unbounded data streams it’s in fact not well defined. The standard bootstrap assumes you have all your data locally available, it’s static, it fits into primary memory, and it’s easy to compute your metric of interest (AUC in the above example). There has been lots of exciting new research around scaling the bootstrap to unbounded and distributed data. The Bag of Little Bootstraps paper distributes the bootstrap, but issues a standard “static” bootstrap on each thread, so it doesn’t solve the unbounded data problem. The Vowpal Wabbit paper solves the unbounded data problem, but on a single thread. A Google paper puts together a bootstrap that is both streaming and distributed. The streaming distributed bootstrap is a really fun solution, and I’ve mocked up a Python package to test it out. In this article, I’m going to assume you’re already a fairly technical person who understands why you’d want to estimate uncertainty on a big data application. At the end of this post I’ll set loose a streaming bootstrap on the Twitter firehose, computing the mean tweet rate on top trending terms at the time I ran it, with streaming one-sigma error bands. I’ll be using the following R libraries and global settings for the R snippets. Refresher: the standard bootstrap Let’s start with a fake data set of $N=30$ points, and let’s say the data is drawn from a random uniform distribution. Here’s what it looks like. index count value 1: 1 1 0.23666352 2: 2 1 0.17972139 3: 3 1 0.04451190 4: 4 1 0.94861152 5: 5 1 0.97012678 6: 6 1 0.11215551 7: 7 1 0.81616358 8: 8 1 0.71385778 9: 9 1 0.54395965 10: 10 1 0.03084962 11: 11 1 0.58808657 12: 12 1 0.03196848 13: 13 1 0.78770594 14: 14 1 0.57319726 15: 15 1 0.23914206 16: 16 1 0.45210949 17: 17 1 0.74648136 18: 18 1 0.76919459 19: 19 1 0.50524423 20: 20 1 0.68976405 21: 21 1 0.88024924 22: 22 1 0.52815155 23: 23 1 0.03672133 24: 24 1 0.16118379 25: 25 1 0.23268336 26: 26 1 0.51450148 27: 27 1 0.18569415 28: 28 1 0.54663857 29: 29 1 0.89967953 30: 30 1 0.34810339 index count value The index identifies the data point, the count is simply the number of times that data point appears, and the value is “the data.” The mean of the data is 0.48 and the standard error on the mean is 0.05. I’m going to start by histogramming the counts of each index. This is a trivial histogram: there’s just one of everything. Now the bootstrap procedure is - resample the $N$ data points $N$ times with replacement, - compute your quantity of interest on the resampled data exactly as if it was the original data, and - repeat hundreds or thousands of times. The resulting distribution of the quantity of interest is an empirical estimate of the sampling distribution of that quantity. This means the mean of the distro is an estimate of the quantity of interest itself, and the standard deviation is an estimate of the standard error of that quantity. That last point is tricky and worth memorizing to impress your statistics friends at parties. (Just kidding, statisticians don’t go to parties!) Here’s an implementation of the bootstrap for this data set. The quantity of interest in this example is the mean of the data. My session gives me compare bootstrap mean 0.477468987332949 to sample quantity of interest 0.477104055796129 compare bootstrap standard deviation 0.0547528263387387 to the sample standard error of the quantity of interest 0.0555938381440978 So both the bootstrap mean and the data mean are consistent with the population mean of 0.5 within one standard error of the mean, and the analytical estimator of the standard error is consistent with the bootstrap standard deviation. All is good. Thinking more deeply about the resampling Now it gets interesting. It turns out that step #1 in the bootstrap procedure can be thought of as rolling an unbiased $N$ sided dice $N$ times, and counting the number of times each face (index) comes up. This is a result from elementary statistics: the counts of each face is distributed as \begin{equation} \mathrm{Multinomial}(N,\pmb{p}=(1/N,1/N,\dots,1/N)), \end{equation} where $\pmb{p}$ is a vector of $N$ probabilities. I’m going to simulate one single bootstrap iteration like this: Here’s a histogram of the number of times each data point comes up in this iteration: A bunch of points are resampled zero times, the 12th and 26th data points are resampled 3 times, and everything else is in between. I already know the resample counts are Multinomially distributed, but here’s a slightly different question: over the course of a full bootstrap simulation, what’s the distribution of the sample rate of just the first data point? This time the answer comes from thinking about coin tosses. In one single draw in one bootstrap iteration, the chances the first data point will be drawn is $1/N$. This is like flipping a coin that is biased as $p=1/N$. $N$ draws with replacement in one bootstrap iteration are like flipping that coin $N$ times, so the number of times the first data point comes up in one bootstrap iteration is distributed as $\mathrm{Binomial}(N,1/N)$. You can simulate this effect for 10000 bootstrap iterations in R by picking out the first row of 10000 Multinomial random number draws. I’m going to do this, then count the number of time each draw frequency per bootstrap iteration occurs, then compare the the Binomial random draw. Let’s take a look: frequency count binomial 1: 0 3630 3678.610464 2: 1 3698 3678.978362 3: 2 1907 1839.489181 4: 3 607 613.101738 5: 4 135 153.244776 6: 5 17 30.639760 7: 6 6 5.104584 Math works. The leap to big data: the Poisson trick So far I’ve been dealing with small data, at $N = 30$. With big data $N$ is either very large or, more often, unknown. Let’s think about what happens when $N$ gets huge. As $N$ grows the probability $p = 1/N$ of drawing the first data point is getting tiny, but the number of draws in a single bootstrap iteration is getting huge with $N$. It turns out this process converges, and the number of times you’d expect to see the first data point is Poisson distributed with mean 1. That is to say, \begin{equation} \mathrm{Binomial}(N,1/N) \xrightarrow{N\to\infty} \mathrm{Poisson}(1). \end{equation} The resampling procedure is independent of $N$! This was purely luck, and it means I don’t need to know the size of the full data set to bootstrap uncertainty estimates, and in fact if $N$ is large enough the bootstrapping procedure is nearly exact. Let’s take a look. The agreement between the Binomial and Poisson distributions is already extremely good at just $N=30$, and it only gets better with large $N$. Because the Poisson distribution is independent of the parameter $N$, I can turn the entire bootstrap process sideways: I’ll run 10000 bootstraps on each data point as it arrives in the stream, without regard to what will stream in later, as long as I can define an online update rule for the metric of interest. A streaming bootstrap of the mean The mean as the quantity of interest is a useful example because it has a simple update rule. Pseudocode of the online weighted mean update rule is as follows. Algorithm: WeightedMeanUpdate Input: Current mean, theta0 Aggregate weight of current mean, w0 New data, X Weight of new data, W Output: Updated mean, theta1 Aggregate weight of updated mean, w1 theta1 = (w0*theta0 + W*X)/(w0 + W) w1 = w0 + W return (theta1,w1) When W = 1, this reduces to an online unweighted mean update rule. For the very first data point, the mean and aggregate weight are set to 0. Using the Poisson trick, the streaming serial bootstrap algorithm is: Algorithm: StreamingSerialBootstrap Input: Unbounded set of data-weight tuples {(X[1],w[1]),(X[2],w[2]),...} Number of bootstrap realizations, r Output: Estimator value in each bootstrap realization, theta[k], k in {1,2,..,r} // initialize for each k in 1 to r do wInner[k] = 0 end // data arrives from a stream for each i in stream // do r bootstrap iteration // approximate resampling with replacement with the Poisson trick for k in 1 to r do weight = wInner[i]*PoissonRandom(1) (thetaInner[k],wInner[k]) = InnerOnlineUpdate(thetaInner[k],wInner[k],X[i],weight) end end The InnerOnlineUpdate must be set to WeightedMeanUpdate for the mean as the quantity of interest. thetaInner is an array representing a running estimate of the sample distribution of the mean at the $i$-th data point. I’ve mocked this up in a Python package called sdbootstrap. First export the R data to file. Then in the terminal, The output is - master update ID, which is the timestamp of the update, - bootstrap iteration ID, - quantity of interest, - number of total resamples Here are my top 10 lines: 1497630831.95 0 0.498431696583 35.0 1497630831.95 1 0.497802280908 32.0 1497630831.95 2 0.52108250027 34.0 1497630831.95 3 0.52590605129 34.0 1497630831.95 4 0.396820495147 26.0 1497630831.95 5 0.552172223237 32.0 1497630831.95 6 0.494006591897 29.0 1497630831.95 7 0.491453935547 27.0 1497630831.95 8 0.524614127751 31.0 1497630831.95 9 0.49028054256 25.0 The bootstrap mean (mean of column 3) is 0.4784 and the bootstrap standard error (standard deviation of column 3) is 0.0551, both close to the regular bootstrap values 0.4775 and 0.0548. So this seems to work fine even on just 30 data points. Distributing it Here’s a picture of what I’m about to construct. I’ll do it by way of example. Let’s generate $N = 10000$ data points uniformly distributed between 0 and 1 with awk’s random number generator. My top 10 entries are 0.237788 1 0.291066 1 0.845814 1 0.152208 1 0.585537 1 0.193475 1 0.810623 1 0.173531 1 0.484983 1 0.151863 1 A traditional bootstrap at 10000 iterations in R gives me compare bootstrap mean 0.498704013190406 to sample quantity of interest 0.49865821011823 compare bootstrap standard deviation 0.00287165409456161 to the sample standard error of the quantity of interest 0.00288191093375261 The Bag of Little Bootstrap authors pointed out that you can multithread the bootstrap by doing a bunch of independent bootstraps and collecting the results. Their approach is to over-resample the data and summarize immediately in each thread, then collect, but I want to maintain the full bootstrap distribution so I’ll do it a little differently. And importantly, I’ll do it for unbounded data: each thread will do the job of the streaming bootstrap in the previous section, and it won’t know how big the full data set is. This algo reuses the above StreamingSerialBootstrap in what I’m calling the inner bootstrap, and also implements an outer bootstrap procedure that collects each bootstrap iteration’s current state and does a aggregation to produce the a master bootstrap distribution. Algorithm: StreamingDistributedBootstrap Input: Unbounded set of data-weight tuples {(X[1],w[1]),(X[2],w[2]),...} Number of bootstrap realizations, r Number of nodes, s Output: Estimator value in each bootstrap realization, theta[k], k in {1,2,..,r} // initialize for each k in 1 to r do wOuter[k] = 0 for each j in 1 to s do wInner[j,k] = 0 end end // data arrives from a stream for each i in stream Assign tuple (X[i],w[i]) to node j in {1,2,...,s} // inner bootstrap // do r bootstrap iterations // approximate resampling with replacement with the Poisson trick for k in 1 to r do weight = wInner[i]*PoissonRandom(1) (thetaInner[j,k],wInner[j,k]) = InnerOnlineUpdate(thetaInner[j,k],wInner[j,k],X[i],weight) end if UpdateMaster() do (thetaMaster[k],wMaster[k]) = OuterOnlineUpdate(thetaMaster[k],wMaster[k],thetaInner[j,k],wInner[j,k]) // flush the inner bootstrap distros thetaInner[j,k] = 0 wInner[j,k] = 0 end end For the mean, set both InnerOnlineUpdate and OuterOnlineUpdate to WeightedMeanUpdate. thetaMaster is a running estimate of the sample mean at the $i$-th data point. Here it is with the Python package. I’m going distribute the data over 6 threads using the lovely Gnu parallel package ( brew install parallel). My top 10 output lines are 1497631385.97 5988 0.500353215188 9843.0 1497631385.97 5989 0.495968983126 10111.0 1497631385.97 5982 0.504122756197 9995.0 1497631385.97 5983 0.497282486683 10121.0 1497631385.97 5980 0.500647175678 10013.0 1497631385.97 5981 0.493803255786 9907.0 1497631385.97 5986 0.497372163828 10076.0 1497631385.97 5987 0.500258192842 9963.0 1497631385.97 5984 0.495168146999 10054.0 1497631385.97 5985 0.499804540368 10074.0 I’m getting a streaming distributed bootstrap mean of 0.49871 and a streaming distributed bootstrap standard deviation of 0.0028622 (compare to standard bootstrap values 0.49866 and 0.0028821, and to the direct data estimates 0.49866 and 0.0028819). This example and a lot of thinking convinces me that the algorithm is right and my implementation is right. It is certainly not a complete or rigorous proof, I leave that to others. Testing it on the Twitter firehose Just for fun, let’s set this loose on some Twitter search terms. This simplest average quantity I could think of was the mean time between tweets for different terms. Let’s call this inter-tweet time. I’m accessing the firehose via the t command line utility. The top trending term at the time of writing is “Whole Foods”. Here’s what some of the tweet data look like. ID,Posted at,Screen name,Text 875734500466081796,2017-06-16 15:19:09 +0000,RogueInformant,@ALT_uscis @amazon @WholeFoods How long until @WholeFoods offers its own credit card? 15% off you first 5 bundles o… 875734502785548288,2017-06-16 15:19:10 +0000,Fronk83,RT @CNET: Grocery a-go-go: #Amazon to buy #WholeFoods for $13.7 billion $AMZN 875734510230491136,2017-06-16 15:19:12 +0000,ultramet,So does this mean that @WholeFoods employees will now be treated in the same crappy way Amazon employees are? Feel bad for them. 875734517562183680,2017-06-16 15:19:14 +0000,framhammer,"RT @JacobAWare: Amazon, based on your recent purchase of #WholeFoods, you might also like: • South Park season 19 on blu-ray • asparagus water" 875734520993120256,2017-06-16 15:19:14 +0000,osobsamantar,"@GuledKnowmad @JeffBezos @amazon @WholeFoods Not any kind of milk, organic almond milk" 875734524080119808,2017-06-16 15:19:15 +0000,ChrisArvay,"#Roc @Wegmans Your move! @amazon buys @WholeFoods" I’ll convert the date to a timestamp in seconds and subtract the timestamp of the previous line, skipping the first one line of course. I’ll make use of a Gnu utility called stdbuf ( brew install gstdbuf from Homebrew on my Mac) that lets me disable the buffering that the awk stage is apparently inspiring. With no buffering I can turn on the firehose and get real-time updates of the bootstrap distribution at every 10 tweets. I’m disabling the inner bootstrap flush so that I can look at the cumulative effect of all data as a function of time. Normally I need to flush the inner bootstrap estimates upon updating the master outer bootstrap distribution. And I’m not parallelizing the inner bootstraps per trending term because I have just one data stream each – so this is not a full blown demo but it’s still cool and suggestive. I let it run for rew minutes. Plotting it up: The top term is significantly more popular than the next two, which themselves are indistinguishible from one another over the period I accumulated data. While I did not distribute each trending term’s bootstrap, I did already demo parallelizing the weighted mean bootstrap above so hopefully that’s enough to convince you that it’s possible over distributed Twitter streams. Summary I’ve sketched the train of logic that takes you from the standard bootstrap, to the streaming flavor, to the streaming-and-distributed flavor, and I did a cute Twitter firehose example. The purpose of this approach was not to prove anything rigorously but to make the concepts real and build deep intuition by actually doing it. This is not the streaming version of the Bag of Little Bootstrap. The BLB (1) maintains over-resampled bootstrap distributions over each shard and (2) immediately summarizes the sharded bootstraps locally on their own threads, then (3) collects and aggregates the summaries themselves to create a more precise summary. What I’ve done here is maintain exact streaming bootstraps over each shard and collected the full bootstrap distribution in a downstream master thread, then summarized. For the weighted mean and many data points, the streaming distributed bootstrap is equivalent to a single standard bootstrap. This is true for any online update rule that can handle aggregated versions of the statistic of interest. In cases where the update rule cannot handle aggregate versions of the statistic, maybe you’d just do a weighted mean update to compute the master bootstrap distribution. You can play many variations on this theme, as I’ve done a bit in this post, choosing any combination among - online or batch - distributed or single threaded - master bootstrap distribution thread or immediate mean & standard-deviation summarization I’ve toyed with more statistics, like quantiles and the exponentially weighted moving average (EWMA), both of which can be computed online. You can take a look at these updaters at.
https://www.highonscience.com/blog/2017/06/15/streaming-distributed-bootstrap/
CC-MAIN-2021-39
refinedweb
3,124
65.83
An Advanced 4.4BSD Interprocess Communication Tutorial Samuel J. Leffler Robert S. Fabry William N. Joy Phil Lapsley Computer Systems Research Group Department of Electrical Engineering and Computer Science University of California, Berkeley Berkeley, California 94720 Steve Miller Chris Torek Heterogeneous Systems Laboratory Department of Computer Science University of Maryland, College Park College Park, Maryland 20742. February 20, 2012 PSD:21-2 Advanced 4.4BSD IPC Tutorial 1. INTRODUCTION One of the most important additions to UNIX in 4.2BSD was interprocess communication. These facilities were the result of more than two years of discussion and research. The facilities provided in 4.2BSD incorporated many of the ideas from current research, while trying to maintain the UNIX philosophy of simplicity and conciseness. The 4.3BSD release of Berkeley UNIX improved upon some of the IPC facilities while providing an upward-compatible interface. 4.4BSD adds support for ISO protocols and IP multicasting. The BSD interprocess communication facilities have become a defacto standard for UNIX. UNIX has previously been very weak in the area of interprocess communication. Prior to the 4BSD facilities, the only standard mechanism which allowed two processes to communicate were pipes (the mpx files which were part of Version 7 were experimental). Unfortunately, pipes are very restrictive in that the two communicating processes must be related through a common ancestor. Further, the semantics of pipes makes them almost impossible to maintain in a. The BSD IPC allows processes to rendezvous in many ways. Processes may rendezvous through a UNIX file system- like name space (a space where all names are path names) as well as through a network name space. In fact, new name spaces may be added at a future time with only minor changes visible to users. Further, the communication facilities have been extended to include more than the simple byte stream provided by a pipe. These extensions have resulted in a completely new part of the system which users will need time to familiarize themselves with. It is likely that as more use is made of these facilities they will be refined; only time will tell. This document provides a high-level description of the IPC facilities in 4.4BSD and their use. It is designed to complement the manual pages for the IPC primitives by exam- ples of their use. The remainder of this document is organ- ized in four sections. Section 2 introduces the IPC-related system calls and the basic model of communication. Section 3 describes some of the supporting library routines users may find useful in constructing distributed applications. Section 4 is concerned with the client/server model used in developing applications and includes examples of the two February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-3 major types of servers. Section 5 delves into advanced topics which sophisticated users are likely to encounter when using the IPC facilities. February 20, 2012 through sockets. One such property is the scheme used to name sockets. For example, in the UNIX communication domain sockets are named with UNIX path names; e.g. a socket may be named ``/dev/foo''. Sockets normally exchange data only with sockets in the same domain (it may be possible to cross domain boundaries, but only if some translation protocols*; and the ISO OSI protocols, which are not documented in this tutorial. The underlying communication facilities provided by these domains have a significant influence on the internal system implementation as well as the interface to socket facilities available to a user. An example of the latter is that a socket ``operating'' in the UNIX domain sees a subset of the error conditions which are possible when operating in the Internet (or NS) domain. February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-5 A datagram socket supports bidirectional flow of data which is not promised to be sequenced, reliable, or undupli- cated. the Ethernet. A raw socket provides users access to the underlying communication protocols which support socket abstractions. These sockets are normally datagram oriented, though their exact characteristics are dependent on the interface pro- vided by the protocol. Raw sockets are not intended for the general user; they have been provided mainly for those interested in developing new communication protocols, or for gaining access to some of the more esoteric facilities of an existing protocol. The use of raw sockets is considered in section 5. A sequenced packet socket is similar to a stream socket, with the exception that record boundaries are preserved. This interface is provided only as part of the NS socket abstraction, and is very important in most serious NS applications. Sequenced-packet sockets allow the user to manipulate the SPP or IDP headers on a packet or a group of packets either by writing a prototype header along with whatever data is to be sent, or by specifying a default header to be used with all outgoing data, and allows the user to receive the headers on incoming packets. The use of these options is considered in section 5. Another potential socket type which has interesting properties is the reliably delivered message socket. The reliably delivered message socket has similar properties to a datagram socket, but with reliable delivery. There is currently no support for this type of socket, but a reliably delivered message protocol similar to Xerox's Packet Exchange Protocol (PEX) may be simulated at the user level. More information on this topic can be found in section 5.. February 20, 2012: s = socket(AF_UNIX, SOCK_DGRAM, 0); The default protocol (used when the protocol argument to the socket call is 0) should be correct for most every situation. However, it is possible to specify a protocol other than the default; this will be covered in section 5. There are several reasons a socket call may fail. Aside from the rare occurrence of lack of memory (ENOBUFS), a socket request may fail due to a request for an unknown protocol (EPROTONOSUPPORT), or a request for a type of socket for which there is no supporting protocol (EPROTO- TYPE). 2.3. Binding local names A socket is created without a name. Until a name is bound to a socket, processes have no way to reference it and, consequently, no messages may be received on it. Com- municating processes are bound by an association. In the Internet and NS domains, an association is composed of local and foreign addresses, and local and foreign ports, while in the UNIX domain, an association is composed of local and foreign path names (the phrase ``foreign pathname'' means a pathname created by a foreign process, not a pathname on a foreign system). In most domains, associations must be unique. In the Internet domain there may never be duplicate _________________________ * The manifest constants are named AF_whatever as they indicate the ``address format'' to use in interpreting names. February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-7 <protocol, local address, local port, foreign address, foreign port> tuples. UNIX domain sockets need not always be bound to a name, but when bound there may never be dupli- cate <protocol, local pathname, foreign pathname> tuples. The pathnames may not refer to files already existing on the system in 4.3; the situation may change in future releases. The bind system call allows a process to specify half of an association, <local address, local port> (or <local pathname>), while the connect and accept primitives are used to complete a socket's association. In the Internet domain, binding names to sockets can be fairly complex. Fortunately, it is usually not necessary to specifically bind an address and port number to a socket, because the connect and send calls will automatically bind an appropriate address if they are used with an unbound socket. The process of binding names to NS sockets. February 20, 2012 Connection establishment is usually asymmetric, with one process a ``client'' and the other a ``server''. The server, when willing to offer its advertised services, binds a socket to a well-known address associated with the service and then passively ``listens'' on its socket. It is then possible for an unrelated process to rendezvous with the server. The client requests services from the server by, February 20, 2012. February 20, 2012. Accept normally blocks. That is, accept will not return until a connection is available or the system call is interrupted by a signal to the process. Further, there is no way for a process to indicate it will accept connections from only a specific individual, or individuals. It is up to the user process to consider who the connection is from and close down the connection if it does not wish to speak February 20, 2012 With a connection established, data may begin to flow. To send and receive data there are a number of possible calls. With the peer entity at each end of a connection anchored, a user can send or receive a message without specifying the peer. As one might expect, in this case, then the normal read and write system calls are usable, write(s, buf, sizeof (buf)); read(s, buf, sizeof (buf));, February 20, 2012 of the datagram facilities found in contemporary packet switched networks. A datagram socket provides a symmetric interface to data exchange. While processes are still likely to be client and server, there is no requirement for connection establishment., the sendto primitive is used, sendto(s, buf, buflen, flags, (struct sockaddr *)&to, tolen); February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-13, as this simply results in the system recording the peer's address (as com- pared to a stream socket, where a connect request initiates establishment of an end to end connection). Accept and listen are will return true when an error indication has been received. The next operation will return the error, and the error status is cleared. Other of the less important details of datagram sockets are described in section 5. 2.8. Input/Output multiplexing One last facility often used in developing applications is the ability to multiplex i/o requests among multiple sockets and/or files. This is done using the select call: #include <sys/time.h> #include <sys/types.h> ... fd_set readmask, writemask, exceptmask; struct timeval timeout; ... select(nfds, &readmask, &writemask, &exceptmask, &timeout);. February 20, 2012 PSD:21-14 Advanced 4.4BSD IPC Tutorial The macros FD_SET(fd, &mask) and FD_CLR(fd, &mask) have been provided for adding and removing file descriptor fd in the set mask. The set should be zeroed before use, and the macro FD_ZERO(&mask) has been provided to clear the set mask. The parameter nfds in the select call specifies the range of file descriptors (i.e. one plus the value of the largest descriptor) to be examined in a set. A timeout value may be specified if the selection is not to last more than a predetermined period of time. If the fields in timeout are set to 0, the selection takes the form of a poll, returning immediately. If the last to, or have exceptional conditions pending. The status of a file descriptor in a select mask may be tested with the FD_ISSET(fd, &mask) macro, which returns a non-zero value if fd is a member of the set mask, and 0 if it is not. To determine if there are connections waiting on a socket to be used with an accept call, select can be used, followed by a FD_ISSET(fd, &mask) macro to check for read readiness on the appropriate socket. If FD_ISSET returns a non-zero value, indicating permission to read, then a. February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-15 #include <sys/time.h> #include <sys/types.h> ... fd_set read_template; struct timeval wait; ... for (;;) { wait.tv_sec = 1; /* one second */ wait.tv_usec = 0; FD_ZERO(&read_template); FD_SET(s1, &read_template); FD_SET(s2, &read_template); nb = select(MAX(s1, s2) + 1, &read_template, NULL, NULL, &wait); if (nb <= 0) { An error occurred during the select, or the select timed out. } if (FD_ISSET(s1, &read_template)) { Socket #1 is ready to be read from. } if (FD_ISSET(s2, &read_template)) { Socket #2 is ready to be read from. } } In 4.2, the arguments to select were pointers to integers instead of pointers to fd_sets. This type of call will still work as long as the number of file descriptors being examined is less than the number of bits in an integer; however, the methods illustrated above should be used in all current programs. Select provides a synchronous multiplexing scheme. Asynchronous notification of output completion, input avai- lability, and exceptional conditions is possible through use of the SIGIO and SIGURG signals described in section 5. February 20, 2012 PSD:21-16 Advanced 4.4BSD IPC Tutorial 3. NETWORK LIBRARY ROUTINES The discussion in section 2 indicated the possible need to locate and construct network addresses when using the interprocess communication facilities in a distributed environment. To aid in this task a number of routines have been added to the standard C run-time library. In this; e.g. ``the login server on host monet''. This name, and the name of the peer host, must then be translated into network addresses which are not necessarily suitable for human consumption. Finally, the address must then used in locating a physical location and route to the service. The specifics of these three mappings are likely to vary between network architectures. For instance, it is desir- able for a network to not require hosts to be named in such a way that their physical location is known by the client host. Instead, underlying services in the network may dis- cover the actual location of the host at the time a client host wishes to communicate. This ability to have hosts named in a location independent manner may induce overhead in connection establishment, as a discovery process must take place, but allows a host to be physically mobile without requiring it to notify its clientele of its current location. Standard routines are provided for: mapping host names to network addresses, network names to network numbers,: February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-17 struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type (e.g., AF_INET) */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses, null terminated */ }; #define h_addr h_addr_list[0] /* first address, network byte order */ The routine gethostbyname(3N) takes an Internet host name and returns a hostent structure, while the routine gethostbyaddr(3N) maps Internet host addresses into a hos- tent structure. The official name of the host and its public aliases are returned by these routines, along with the address type (family) and a null terminated list of variable length address. This list of addresses is required because it is possible for a host to have many addresses, all having the same name. The h_addr definition is provided for backward compatibility, and is defined to be the first address in the list of addresses in the hostent structure. The database for these calls is provided either by the file /etc/hosts (hosts(5)), or by use of a nameserver, named(8). Because of the differences in these databases and their access protocols, the information returned may differ. When using the host table version of gethostbyname, only one address will be returned, but all listed aliases will be included. The nameserver version may return alternate addresses, but will not provide any aliases other than one given as argument. Unlike Internet names, NS names are always mapped into host addresses by the use of a standard NS Clearinghouse service, a distributed name and authentication server. The algorithms for mapping NS names to addresses via a Clearing- house are rather complicated, and the routines are not part of the standard libraries. The user-contributed Courier (Xerox remote procedure call protocol) compiler contains routines to accomplish this mapping; see the documentation and examples provided therein for more information. It is expected that almost all software that has to communicate using NS will need to use the facilities of the Courier com- piler. An NS host address is represented by the following: February 20, 2012: #include <sys/types.h> #include <sys/socket.h> #include <netns/ns.h> ... u_long netnum; struct sockaddr_ns dst; ... bzero((char *)&dst, sizeof(dst)); /* * There is no convenient way to assign a long * integer to a ``union ns_net'' at present; in * the future, something will hopefully be provided, * but this is the portable way to go for now. * The network number below is the one for the NS net * that the desired host (gyre) is on. */ netnum = htonl(2266); dst.sns_addr.x_net = *(union ns_net *) &netnum; dst.sns_family = AF_NS; /* * host 2.7.1.0.2a.18 == "gyre:Computer Science:UofMaryland" */ dst.sns_addr.x_host.c_host[0] = 0x02; dst.sns_addr.x_host.c_host[1] = 0x07; dst.sns_addr.x_host.c_host[2] = 0x01; dst.sns_addr.x_host.c_host[3] = 0x00; dst.sns_addr.x_host.c_host[4] = 0x2a; dst.sns_addr.x_host.c_host[5] = 0x18; dst.sns_addr.x_port = htons(75); February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-19 3.2. Network names As for host names, routines for mapping network names to numbers, and back, are provided. These routines return a netent structure: /* * Assumption here is that a network number * fits in 32 bits -- probably a poor one. */ struct netent { char *n_name; /* official name of net */ char **n_aliases; /* alias list */ int n_addrtype; /* net address type */ int n_net; /* network number, host byte order */ }; into your code), or by querying the Clearinghouse for addresses. The internetwork router is the only process that needs to manipulate network numbers on a regular basis; if a process wishes to communicate with a machine, it should ask the Clearinghouse for that machine's address (which will include the net number). 3.3. Protocol names For protocols, which are defined in /etc/protocols, the protoent structure defines the protocol-name mapping used with the routines getprotobyname(3N), getprotobynumber(3N), and getprotoent(3N): struct protoent { char *p_name; /* official protocol name */ char **p_aliases; /* alias list */ int p_proto; /* protocol number */ }; In the NS domain, protocols are indicated by the "client type" field of a IDP header. No protocol database exists; see section 5 for more information. 3.4. Service names Information regarding services is a bit more compli- cated. A service is expected to reside at a specific ``port'' and employ a particular communication protocol. February 20, 2012 PSD:21-20 Advanced 4.4BSD IPC Tutorial This view is consistent with the Internet domain, but incon- sistent with other network architectures. Further, a service may reside on multiple ports. If this occurs, the higher level library routines will have to be bypassed or extended. Services available are contained in the file /etc/services. A service mapping is described by the servent structure, struct servent { char *s_name; /* official service name */ char **s_aliases; /* alias list */ int s_port; /* port number, network byte order */ char *s_proto; /* protocol to use */ };. February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-21 If we wanted to make the remote login program indepen- dent of the Internet protocols and addressing scheme we would be forced to add a layer of routines which masked the network dependent aspects from the mainstream login code. For the current facilities available in the system this does not appear to be worthwhile. Aside from the address-related data base routines, there are several other routines available in the run-time library which are of interest to users. These are intended mostly to simplify manipulation of names and addresses. Table 1 summarizes the routines for manipulating variable length byte strings and handling byte swapping of network addresses and values. ____________________________________________________________________________ |Call | Synopsis | |________________|_________________________________________________________| |bcmp(s1, s2, n) | compare byte-strings; 0 if same, not 0 otherwise | |bcopy(s1, s2, n)| copy n bytes from s1 to s2 | |bzero(base, n) | zero-fill n bytes starting at base | |htonl(val) | convert 32-bit quantity from host to network byte order| |htons(val) | convert 16-bit quantity from host to network byte order| |ntohl(val) | convert 32-bit quantity from network to host byte order| |ntohs(val) | convert 16-bit quantity from network to host byte order| |________________|_________________________________________________________|. February 20, 2012 PSD:21-22 Advanced 4.4BSD IPC Tutorial ); } bzero((char *)&server, sizeof (server)); bcopy(hp->h_addr, (char *)&server.sin); } ... } Figure 1. Remote login client code. February 20, 2012'' and a ``server process''. We will first consider the properties of server processes, then client processes. A server process. Alternative schemes which use a service server may be used to eliminate a flock of server processes clogging the system while remaining dormant most of the time. For Inter- net servers in 4.4BSD, this scheme has been implemented via inetd, the so called ``internet super-server.'' Inetd listens at a variety of ports, determined at start-up by reading a configuration file. When a connection is requested to a port on which inetd is listening, inetd executes the appropriate server program to handle the client. With this method, clients are unaware that an intermediary such as inetd has played any part in the connection. Inetd will be described in more detail in section 5. A similar alternative scheme is used by most Xerox ser- vices. In general, the Courier dispatch process (if used) February 20, 2012 PSD:21-24 Advanced 4.4BSD IPC Tutorial accepts connections from processes requesting services of some sort or another. The client processes request a par- ticular <program number, version number, procedure number> triple. If the dispatcher knows of such a program, it is started to handle the request; if not, an error is reported to the client. In this way, only one port is required to service a large variety of different requests. Again, the Courier facilities are not available without the use and installation of the Courier compiler. The information presented in this section applies only to NS clients and services that do not use Courier.). February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-25 */ ... #endif sin.sin_port = sp->s_port; /* Restricted port -- see section 5 */ ... f = socket(AF_INET, SOCK_STREAM, 0); ... if (bind(f, (struct sockaddr *) &sin, sizeof (sin)) < 0) { ... } ... listen(f, 5); for (;;) { int g, len = sizeof (from); g = accept(f, (struct sockaddr *) &from, &len); if (g < 0) { if (errno != EINTR) syslog(LOG_ERR, "rlogind: accept: %m"); continue; } if (fork() == 0) { close(f); doit(g, &from); } close(g); } } Figure 2. Remote login server. February 20, 2012. Once a server has established a pristine environment, it creates a socket and begins accepting service requests. The bind call is required to insure the server listens at its expected location. It should be noted that the remote login server listens at a restricted port number, and must therefore be run with a user-id of root. This concept of a ``restricted port number'' is 4BSD specific, and is covered in section 5. The main body of the loop is fairly simple: for (;;) { int g, len = sizeof (from); g = accept(f, (struct sockaddr *)&from, &len); if (g < 0) { if (errno != EINTR) syslog(LOG_ERR, "rlogind: accept: %m"); continue; } if (fork() == 0) { /* Child */ close(f); doit(g, &from); } close(g); /* Parent */ } An accept call blocks the server until a client requests service. This call could return a failure status if the call is interrupted by a signal such as SIGCHLD (to be dis- cussed in section 5). Therefore, the return value from February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-27 accept is checked to insure a connection has actually been established, and an error report is logged via syslog if an error has occurred. With a connection in hand, the server then the doit routine because it requires it in authenticating clients. a connection when invoked. Let us consider more closely; February 20, 2012 PSD:21-28 Advanced 4.4BSD IPC Tutorial will not be con- sidered here. 4.3. Connectionless servers While connection-based services are the norm, some ser- vices are based on the use of datagram sockets. One, in particular, is the ``rwho'' service which provides users with status information for hosts connected to a local area network. This service, while predicated on the ability to broadcast information to all hosts connected to a particular network, is of interest as an example usage of datagram sockets. A user on any machine running the rwho server may find out the current status of a machine with the ruptime(1) pro- gram. The output generated is illustrated in Figure 3. Figure 3. ruptime output. February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-29 Status information for each host is periodically broad- cast by rwho server processes on each machine. The same server process also receives the status information and uses it to update a database. This database is then interpreted to generate the status information for each host. Servers operate autonomously, coupled only by the local network and its broadcast capabilities. Note that the use of broadcast for such a task is fairly inefficient, as all hosts must process each message, whether or not using an rwho server. Unless such a service is sufficiently universal and is frequently used, the expense of periodic broadcasts outweighs the simplicity. Multicasting is an alternative to broadcasting. Setting up multicast sockets is described in Section 5.10. The rwho server, in a simplified form, is pictured in Figure 4. There are two separate tasks performed by the server. The first task is to act as a receiver of status information broadcast by other hosts on the network. This job is carried out in the main loop of the program. Packets received at the rwho port are interrogated to insure they've been sent by another rwho server process, then are time stamped with their arrival time and used to update a file indicating the status of the host. When a host has not been heard from for an extended period of time, the database interpretation routines assume the host is down and indicate such on the status reports. This algorithm is prone to error as a server may be down while a host is actually up, but serves our current needs. The second task performed by the server is to supply information regarding the status of its host. This involves periodically acquiring system status information, packaging it up in a message and broadcasting it on the local network for other rwho servers to hear. The supply function is triggered by a timer and runs off a signal. Locating the system status information is somewhat involved, but unin- teresting. Deciding where to transmit the resultant packet is somewhat problematical, however. Status information must be broadcast on the local net- work. For networks which do not support the notion of broad- cast another scheme must be used to simulate or replace broadcasting. One possibility is to enumerate the known neighbors (based on the status messages received from other rwho servers). This, unfortunately, requires some bootstrapping information, for a server will have no idea what machines are its neighbors until it receives status messages from them. Therefore, if all machines on a net are freshly booted, no machine will have any known neighbors and thus never receive, or send, any status information. This is the identical problem faced by the routing table management February 20, 2012 PSD:21-30 Advanced 4.4BSD IPC Tutorial) { syslog(LOG_ERR, "setsockopt SO_BROADCAST: %m");) syslog(LOG_ERR, "rwhod: recv: %m"); continue; } if (from.sin_port != sp->s_port) { syslog(LOG_ERR, "rwhod: %d: bad from port", ntohs(from.sin_port)); continue; } ... if (!verify(wd.wd_hostname)) { syslog(LOG_ERR, "rwhod: malformed host name from %x",); } } Figure 4. rwho server. February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-31 process in propagating routing status information. The standard solution, unsatisfactory as it may be, is to inform one or more servers of known neighbors and request that they always communicate with these neighbors. If each server has at least one neighbor supplied to it, status information may then propagate through a neighbor to hosts which are not (possibly) directly neighbors. If the server is able to support networks which provide a broadcast capability, as well as those which do not, then networks with an arbitrary topology may share status information*. It is important that software operating in a distri- buted environment not have any site-dependent information compiled into it. This would require a separate copy of the server at each host and make maintenance a severe headache. 4.4BSD attempts to isolate host-specific information from applications by providing system calls which return the necessary information*. A mechanism exists, in the form of an ioctl call, for finding the collection of networks to which a host is directly connected. Further, a local network broadcasting mechanism has been implemented at the socket level. Combining these two features allows a process to broadcast on any directly connected local network which sup- ports the notion of broadcasting in a site independent manner. This allows 4.4BSD to solve the problem of deciding how to propagate status information in the case of rwho, or more generally in broadcasting: Such status information is broadcast to connected networks at the socket level, where the connected networks have been obtained via the. February 20, 2012'' (via MSG_PEEK) at out of band data. If the socket has a process group, a SIGURG signal is generated when the protocol is notified of its existence. A process can set the process group or process id to be informed by the SIGURG signal via the appropriate fcntl call, as described below for SIGIO. If multiple sockets may have out of band data awaiting delivery, a select call for excep- tional conditions may be used to determine those sockets with such data pending. Neither the signal nor the select indicate the actual arrival of the out-of-band data, but only flushs any pending output from the remote process(es), all data up to the mark in the data stream is discarded. To send an out of band message the MSG_OOB flag is sup- plied to a send or sendto calls, while to receive out of band data MSG_OOB should be indicated when performing a recvfrom or recv call. To find out if the read pointer is currently pointing at the mark in the data stream, the SIOCATMARK ioctl is provided: February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-33 io rou- tine used in the remote login process to flush output on receipt of an interrupt or quit signal is shown in Figure 5. It reads the normal data up to the mark (to discard it), then reads the out-of-band byte. #include <sys/ioctl.h> #include <sys/file.h> ... oob() { int out = FWRITE, mark; char waste[BUFSIZ]; /* flush local terminal output */ ioctl(1, TIOCFLUSH, (char *)&out); for (;;) { if (ioctl(rem, SIOCATMARK, &mark) < 0) { perror("ioctl"); break; } if (mark) break; (void) read(rem, waste, sizeof (waste)); } if (recv(rem, &mark, 1, MSG_OOB) < 0) { perror("recv"); ... } ... } Figure 5. Flushing terminal I/O on receipt of out of band data. A process may also read or peek at the out-of-band data without first reading up to the mark. This is more difficult when the underlying protocol delivers the urgent data in- band with the normal data, and only sends notification of its presence ahead of time (e.g., the TCP protocol used to implement streams in the Internet domain). With such proto- cols, the out-of-band byte may not yet have arrived when a recv is done with the MSG_OOB flag. In that case, the call will return an error of EWOULDBLOCK. Worse, there may be enough in-band data in the input buffer that normal flow control prevents the peer from sending the urgent data until the buffer is cleared. The process must then read enough of the queued data that the urgent data may be delivered. February 20, 2012 PSD:21-34 Advanced 4.4BSD IPC Tutorial Certain programs that use multiple bytes of urgent data and must handle multiple urgent signals (e.g., telnet(1C)) need to retain the position of urgent data within the stream. This treatment is available as a socket-level option, SO_OOBINLINE; see setsockopt(2) are lost. 5.2. Non-Blocking Sockets It is occasionally convenient to make use of sockets which do not block; that is, I/O requests which cannot com- plete immediately and would therefore cause the process to be suspended awaiting completion are not executed, and an error code is returned. Once a socket has been created via the socket call, it may be marked as non-blocking by fcntl as follows: #include <fcntl.h> ... int s; ... s = socket(AF_INET, SOCK_STREAM, 0); ... if (fcntl(s, F_SETFL, FNDELAY) < 0) perror("fcntl F_SETFL, FNDELAY"); exit processes should be prepared to deal with such return codes. If an operation such as a send cannot be done in its entirety, but partial writes are sensible (for example, when using a stream socket), the data that can be sent immediately will be processed, and the return value will indicate the amount actually sent. 5.3. Interrupt driven socket I/O The SIGIO signal allows a process to be notified via a signal when a socket (or more generally, a file descriptor) has data waiting to be read. Use of the SIGIO facility requires three steps: First, the process must set up a SIGIO signal handler by use of the signal or sigvec calls. February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-35 Second, it must set the process id or process group id which is to receive notification of pending input to its own pro- cess id, or the process group id of its process group (note that the default process group of a socket is group zero). This is accomplished by use of an fcntl call. Third, it must enable asynchronous notification of pending I/O requests with another fcntl call. Sample code to allow a given pro- cess to receive information on pending I/O requests as they occur for a socket s is given in Figure 6. With the addi- tion of a handler for SIGURG, this code can also be used to prepare for receipt of SIGURG signals. #include <fcntl.h> ... int io_handler(); ... signal(SIGIO, io_handler); /* Set the process receiving SIGIO/SIGURG signals to us */ if (fcntl(s, F_SETOWN, getpid()) < 0) { perror("fcntl F_SETOWN"); exit(1); } /* Allow receipt of asynchronous I/O signals */ if (fcntl(s, F_SETFL, FASYNC) < 0) { perror("fcntl F_SETFL, FASYNC"); exit(1); } Figure 6. Use of asynchronous notification of I/O requests. 5.4. Signals and process groups Due to the existence of the SIGURG and SIGIO signals each socket has an associated process number, just as is done for terminals. This value is initialized to zero, but may be redefined at a later time with the F_SETOWN fcntl, such as was done in the code above for SIGIO. To set the socket's process id for signals, positive arguments should be given to the fcntl call. To set the socket's process group for signals, negative arguments should be passed to fcntl. Note that the process number indicates either the associated process id or the associated process group; it is impossible to specify both at the same time. A similar fcntl, F_GETOWN, is available for determining the current process number of a socket. Another signal which is useful when constructing server processes is SIGCHLD. This signal is delivered to a process when any child processes have changed state. Normally February 20, 2012 PSD:21-36 Advanced 4.4BSD IPC Tutorial servers use the signal to ``reap'' child processes that have exited without explicitly awaiting their termination or periodic polling for exit status. For example, the remote login server loop shown in Figure 2 may be augmented as shown in Figure 7. int reaper(); ... signal(SIGCHLD, reaper); listen(f, 5); for (;;) { int g, len = sizeof (from); g = accept(f, (struct sockaddr *)&from, &len,); if (g < 0) { if (errno != EINTR) syslog(LOG_ERR, "rlogind: accept: %m"); continue; } ... } ... #include <wait.h> reaper() { union wait status; while (wait3(&status, WNOHANG, 0) > 0) ; } Figure 7. Use of the SIGCHLD signal. If the parent server process fails to reap its chil- dren, a large number of ``zombie'' processes may be created. 5.5. Pseudo terminals Many programs will not function properly without a ter- minal for standard input and output. Since sockets do not provide the semantics of terminals, it is often necessary to have a process communicating over the network do so through a pseudo-terminal. A pseudo- terminal is actually a pair of devices, master and slave, which allow a process to serve as an active agent in communication between processes and users. Data written on the slave side of a pseudo-terminal is supplied as input to a process reading from the master side, while data written on the master side are processed as terminal input for the slave. In this way, the process mani- pulating the master side of the pseudo-terminal has control over the information read and written on the slave side as if it were manipulating the keyboard and reading the screen February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-37 on a real terminal. The purpose of this abstraction is to preserve terminal semantics over a network connection- that is, the slave side appears as a normal terminal to any pro- cess reading from or writing to it. For example, the remote login server uses pseudo- terminals for remote login sessions. A user logging in to a machine across the network is provided a shell with a slave pseudo-terminal as standard input, output, and error. The server process then handles the communication between the programs invoked by the remote shell and the user's local client process. When. Under 4.4BSD, the name of the slave side of a pseudo- terminal is of the form /dev/ttyxy, where x is a single letter starting at `p' and continuing to `t'. y is a hexade- cimal digit (i.e., a single character in the range 0 through 9 or `a' through `f'). The master side of a pseudo-terminal is /dev/ptyxy, where x and y correspond to the slave side of the pseudo-terminal. In general, the method of obtaining a pair of master and slave pseudo-terminals is to find a pseudo-terminal which is not currently in use. The master half of a pseudo- terminal is a single-open device; thus, each master may be opened in turn until an open succeeds. The slave side of the pseudo-terminal is then opened, and is set to the proper terminal modes if necessary. The process then forks; the child closes the master side of the pseudo-terminal, and execs the appropriate program. Meanwhile, the parent closes the slave side of the pseudo-terminal and begins reading and writing from the master side. Sample code making use of pseudo-terminals is given in Figure 8; this code assumes that a connection on a socket s exists, connected to a peer who wants a service of some kind, and that the process has disassociated itself from any previous controlling terminal. February 20, 2012 PSD:21-38 Advanced 4.4BSD IPC Tutorial gotpty = 0; for (c = 'p'; !gotpty && c <= 's'; c++) { line = "/dev/pty) { syslog(LOG_ERR, "All network ports in use"); exit(1); } line[sizeof("/dev/")-1] = 't'; slave = open(line, O_RDWR); /* slave is now slave side */ if (slave < 0) { syslog(LOG_ERR, "Cannot open slave pty %s", line); exit(1); } ioctl(slave, TIOCGETP, &b); /* Set slave tty modes */ b.sg_flags = CRMOD|XTABS|ANYP; ioctl(slave, TIOCSETP, &b); i = fork(); if (i < 0) { syslog(LOG_ERR, "fork: %m"); exit(1); } else if (i) { /* Parent */ close(slave); ... } else { /* Child */ (void) close(s); (void) close(master); dup2(slave, 0); dup2(slave, 1); dup2(slave, 2); if (slave > 2) (void) close(slave); ... } Figure 8. Creation and use of a pseudo terminal February 20, 2012.'' In the NS domain, the available socket protocols are defined in <netns/ns.h>. To create a raw socket for Xerox Error Protocol messages, one might use: #include <sys/types.h> #include <sys/socket.h> #include <netns/ns.h> ... s = socket(AF_NS, SOCK_RAW, NSPROTO_ERROR); 5.7. Address binding As was mentioned in section 2, binding addresses to sockets in the Internet and NS domains can be fairly com- plex. As a brief reminder, these associations are composed of local and foreign addresses, and local and foreign ports. Port numbers are allocated out of separate spaces, one for each system and one for each domain on that system. Through the bind system call, a process may specify half of an February 20, 2012 PSD:21-40 Advanced 4.4BSD IPC Tutorial bind a specific port number to a socket, but leave the local address unspecified, the following code might be used: ed (specified as zero), in which case the system will select an appropriate port number for it. This shortcut will work both in the Internet and NS domains. For example, to bind a specific local address to a socket, but to leave the local port number unspecified: hp = gethostbyname(hostname); if (hp == NULL) { ... } bcopy(hp->h_addr, (char *) sin.sin_addr, hp->h_length); sin.sin_port = htons(0); bind(s, (struct sockaddr *) &sin, sizeof (sin));: February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-41. For example, the Internet file transfer protocol, FTP,, an option call must be performed prior to address binding: ... int on = 1; ... setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); bind(s, (struct sockaddr *) &sin, sizeof (sin)); February 20, 2012 PSD:21-42 Advanced 4.4BSD IPC Tutorial related socket option, SO_REUSEPORT, which allows completely duplicate bindings, is described in the IP multicasting sec- tion. 5.8. Socket Options It is possible to set and get a number of options on sockets via the setsockopt and getsockopt system calls. These options include such things as marking a socket for broadcasting, not to route, to linger on close, etc. In addition, there are protocol-specific options for IP and TCP, as described in ip(4), tcp(4), and in the section on multicasting below. The general forms of the calls are: setsockopt(s, level, optname, optval, optlen); and getsockopt(s, level, optname, optval, optlen); The parameters to the calls are as follows: s is the socket on which the option is to be applied. Level specifies the protocol layer on which the option is to be applied; in most cases this is the ``socket level'', indicated by the symbolic constant SOL_SOCKET, defined in <sys/socket.h>. The actual option is specified in optname, and is a symbolic constant also defined in <sys/socket.h>. Optval and Optlen point to the value of the option (in most cases, whether the option is to be turned on or off), and the length of the value of the option, respectively. For getsockopt, optlen is a value-result parameter, initially set to the size of the storage area pointed to by optval, and modified upon return to indicate the actual amount of storage used. An example should help clarify things. It is sometimes useful to determine the type (e.g., stream, datagram, etc.) of an existing socket; programs under inetd (described below) may need to perform this task. This can be accom- plished as follows via the SO_TYPE socket option and the getsockopt call: #include <sys/types.h> #include <sys/socket.h> int type, size; size = sizeof (int); if (getsockopt(s, SOL_SOCKET, SO_TYPE, (char *) &type, &size) < 0) { ... } February 20, 2012)); February 20, 2012: */ #define IFNAMSIZ 16 struct ifreq { char ifr_name[IFNAMSIZ]; /* if name, e.g. "en0" */ union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; short ifru_flags;_data ifr_ifru.ifru_data/* for use by interface */ The actual call which obtains the interface configuration is February 20, 2012 specified by an ifreq structure as follows: struct ifreq *ifr; ifr = ifc.ifc_req; for (n = ifc.ifc_len / sizeof (struct ifreq); --n >= 0; ifr++) { /* * We must be careful that we don't use an interface * devoted to an address family other than those intended; * if we were interested in NS interfaces, the * AF_INET would be AF_NS. */TOPOINT)) == 0) continue;. February 20, 2012 PSD:21-46 Advanced 4.4BSD IPC Tutorial struct sockaddr dst; if (ifr->ifr_flags & IFF_POINTTOPOINT) { if (ioctl(s, SIOCGIFDSTADDR, (char *) ifr) < 0) { ... } bcopy((char *) ifr->ifr_dstaddr, (char *) &dst, sizeof (ifr->ifr_dstaddr)); } else if (ifr->ifr_flags & IFF_BROADCAST) { if (ioctl(s, SIOCGIFBRDADDR, (char *) ifr) < 0) { ... } bcopy((char *) ifr->ifr_broadaddr, (char *) &dst, sizeof (ifr->ifr_broadaddr)); } After the appropriate ioctl's have obtained the February 20, 2012 Multicast Datagrams To send a multicast datagram, specify an IP multicast address in the range 224.0.0.0 to 239.255.255.255 as the destination address in a sendto(2) call. The definitions required for the multicast-related socket options are found in <netinet/in.h>. All IP addresses are passed in network byte-order. By default, IP multicast datagrams are sent with a time-to-live (TTL) of 1, which prevents them from being for- warded beyond a single subnetwork. A new socket option allows the TTL for subsequent multicast datagrams to be set to any value from 0 to 255, in order to control the scope of the multicasts: u_char ttl; setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); February 20, 2012 PSD:21-48 Advanced 4.4BSD IPC Tutorial with less than a certain TTL from traversing certain sub- nets. The thresholds enforce the following convention: ________________________________|_____________ Scope | Initial TTL _________________________________|_____________ restricted to the same host | 0 restricted to the same subnet | 1 restricted to the same site | 32 restricted to the same region | 64 restricted to the same continent| 128 unrestricted | 255 ________________________________|_____________ "Sites" and "regions" are not strictly defined, and sites may be further subdivided into smaller administrative units, as a local matter. An application may, perhaps using the TTL sequence 0, 1, 2, 4, 8, 16, 32. The multicast router mrouted(8), refuses to forward any multicast datagram with a destination address between 224.0.0.0 and 224.0.0.255, inclusive, regardless of its TTL. This range of addresses is reserved for the use of routing protocols and other low-level topology discovery or. There is no multicast address (or any other IP address) for all hosts on the total Internet. The addresses of other well-known, permanent groups are published in the "Assigned Numbers" RFC, which is available from the InterNIC. Each multicast transmission is sent from a single net- work interface, even if the host has more than one multicast-capable interface. (If the host is also serving as a multicast router, a multicast may be forwarded to interfaces other than originating interface, provided that the TTL is greater than 1.) The default interface to be used for multicasting is the primary network interface on the system. A socket option is available to override the default for subsequent transmissions from a given socket: February 20, 2012. set to 0 to disable loopback, and set to 1 to enable loopback. This option improves performance for appli- cations pro- gram) or for which the sender does not belong to the desti- nation. 5.10.2. Receiving IP Multicast Datagrams Before a host can receive IP multicast datagrams, it following structure: February 20, 2012 IP layer if any socket has claimed a membership in the destination group of the datagram; however, delivery of a multicast datagram to a particular socket is based on the destination port (or protocol type, for raw sockets), just as with unicast datagrams. To receive multicast datagrams sent to a particular port, it is necessary to bind to that local port, leaving the local address unspecified (i.e., INADDR_ANY). To receive multicast datagrams sent to February 20, 2012ast addresses accepted by a particular interface. The address to be added or deleted is passed as a sockaddr structure of family AF_UNSPEC, within the standard ifreq structure. These ioctls are for the use of protocols other than IP, and require superuser privileges. A link-level multicast address added via SIOCADDMULTI is not automatically deleted when the socket used to add it goes away; it must. February 20, 2012 PSD:21-52 Advanced 4.4BSD IPC Tutorial #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #include <stdio.h> #define EXAMPLE_PORT 60123 #define EXAMPLE_GROUP "224.0.0.250" main(argc) int argc; { struct sockaddr_in addr; int addrlen, fd, cnt; struct ip_mreq mreq; char message[50]; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); exit(1); } bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(EXAMPLE_PORT); addrlen = sizeof(addr); if (argc > 1) { /* Send */ addr.sin_addr.s_addr = inet_addr(EXAMPLE_GROUP); while (1) { time_t t = time(0); sprintf(message, "time is %-24.24s", ctime(&t)); cnt = sendto(fd, message, sizeof(message), 0, (struct sockaddr *)&addr, addrlen); if (cnt < 0) { perror("sendto"); exit(1); } sleep(5); } } else { /* Receive */ if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); exit(1); } mreq.imr_multiaddr.s_addr = inet_addr(EXAMPLE_GROUP); mreq.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-53 perror("setsockopt mreq"); exit(1); } while (1) { cnt = recvfrom(fd, message, sizeof(message), 0, (struct sockaddr *)&addr, &addrlen); if (cnt <= 0) { if (cnt == 0) { break; } perror("recvfrom"); exit(1); } printf("%s: message = \"%s\"\n", inet_ntoa(addr.sin_addr), message); } } } 5.11. NS Packet Sequences The semantics of NS connections demand that the user both be able to look inside the network header associated with any incoming packet and be able to specify what should go in certain fields of an outgoing packet. Using different calls to setsockopt, it is possible to indicate whether pro- totype headers will be associated by the user with each out- going packet (SO_HEADERS_ON_OUTPUT), to indicate whether the headers received by the system should be delivered to the user (SO_HEADERS_ON_INPUT), or to indicate default informa- tion that should be associated with all outgoing packets on a given socket (SO_DEFAULT_HEADERS). The contents of a SPP header (minus the IDP header) are: struct sphdr { u_char sp_cc; /* connection control */ #define SP_SP 0x80 /* system packet */ #define SP_SA 0x40 /* send acknowledgement */ #define SP_OB 0x20 /* attention (out of band data) */ #define SP_EM 0x10 /* end of message */ u_char sp_dt; /* datastream type */ u_short sp_sid; /* source connection identifier */ u_short sp_did; /* destination connection identifier */ u_short sp_seq; /* sequence number */ u_short sp_ack; /* acknowledge number */ u_short sp_alo; /* allocation number */ }; Here, the items of interest are the datastream type and the connection control fields. The semantics of the datastream February 20, 2012: #include <sys/types.h> #include <sys/socket.h> #include <netns/ns.h> #include <netns/sp.h> ... struct sockaddr_ns sns, to; int s, on = 1; struct databuf { struct sphdr proto_spp; /* prototype header */ char buf[534]; /* max. possible data by Xerox std. */ } buf; ... s = socket(AF_NS, SOCK_SEQPACKET, 0); ... bind(s, (struct sockaddr *) &sns, sizeof (sns)); setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_OUTPUT, &on, sizeof(on)); ... buf.proto_spp.sp_dt = 1; /* bulk data */ buf.proto_spp.sp_cc = SP_EM; /* end-of-message */ strcpy(buf.buf, "hello world\n"); sendto(s, (char *) &buf, sizeof(struct sphdr) + strlen("hello world\n"), (struct sockaddr *) &to, sizeof(to)); ...: February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-55 #include <sys/types.h> #include <sys/socket.h> #include <netns/ns.h> #include <netns/sp.h> ... struct sockaddr sns; int s, on = 1, off = 0; ... s = socket(AF_NS, SOCK_SEQPACKET, 0); ... bind(s, (struct sockaddr *) &sns, sizeof (sns)); setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_OUTPUT, &off, sizeof(off)); setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_INPUT, &on, sizeof(on)); ... Output is handled somewhat differently in the IDP world. The header of an IDP-level packet looks like: struct idp { u_short idp_sum; /* Checksum */ u_short idp_len; /* Length, in bytes, including header */ u_char idp_tc; /* Transport Control (i.e., hop count) */ u_char idp_pt; /* Packet Type (i.e., level 2 protocol) */ struct ns_addr idp_dna; /* Destination Network Address */ struct ns_addr idp_sna; /* Source Network Address */ };: February 20, 2012 PSD:21-56 Advanced 4.4BSD IPC Tutorial #include <sys/types.h> #include <sys/socket.h> #include <netns/ns.h> #include <netns/idp.h> ... struct sockaddr sns; struct idp proto_idp; /* prototype header */ int s, on = 1; ... s = socket(AF_NS, SOCK_DGRAM, 0); ... bind(s, (struct sockaddr *) &sns, sizeof (sns)); proto_idp.idp_pt = NSPROTO_PE; /* packet exchange */ setsockopt(s, NSPROTO_IDP, SO_DEFAULT_HEADERS, (char *) &proto_idp, sizeof(proto_idp)); ... Using SO_HEADERS_ON_OUTPUT is somewhat more difficult. When SO_HEADERS_ON_OUTPUT is turned on for an IDP socket, the socket becomes (for all intents and purposes) a raw socket. In this case, all the fields of the prototype header (except the length and checksum fields, which are computed by the kernel) must be filled in correctly in order for the socket to send and receive data in a sensible manner. To be more specific, the source address must be set to that of the host sending the data; the destination address must be set to that of the host for whom the data is intended; the packet type must be set to whatever value is desired; and the hopcount must be set to some reasonable value (almost always zero). It should also be noted that simply sending data using write will not work unless a con- nect or sendto call is used, in spite of the fact that it is the destination address in the prototype header that is used, not the one given in either of those calls. For almost all IDP applications , using SO_DEFAULT_HEADERS is easier and more desirable than writing headers. February 20, 2012 Advanced 4.4BSD IPC Tutorial PSD:21-57 type 255. Finally, the closing process replies with a zero-length packet with substream type 255; at this point, the connection is considered closed. The following code fragments are simplified examples of how one might handle this three-way handshake at the user level; in the future, support for this type of close will probably be provided as part of the C library or as part of the kernel. The first code fragment below illustrates how a process might handle three-way handshake if it sees that the process it is com- municating with wants to close the connection: #include <sys/types.h> #include <sys/socket.h> #include <netns/ns.h> #include <netns/sp.h> ... #ifndef SPPSST_END #define SPPSST_END 254 #define SPPSST_ENDREPLY 255 #endif struct sphdr proto_sp; int s; ... read(s, buf, BUFSIZE); if (((struct sphdr *)buf)->sp_dt == SPPSST_END) { /* * SPPSST_END indicates that the other side wants to * close. */ proto_sp.sp_dt = SPPSST_ENDREPLY; proto_sp.sp_cc = SP_EM; setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp, sizeof(proto_sp)); write(s, buf, 0); /* * Write a zero-length packet with datastream type = SPPSST_ENDREPLY * to indicate that the close is OK with us. The packet that we * don't see (because we don't look for it) is another packet * from the other side of the connection, with SPPSST_ENDREPLY * on it it, too. Once that packet is sent, the connection is * considered closed; note that we really ought to retransmit * the close for some time if we do not get a reply. */ close(s); } ... To indicate to another process that we would like to close the connection, the following code would suffice: February 20, 2012 PSD:21-58 Advanced 4.4BSD IPC Tutorial #include <sys/types.h> #include <sys/socket.h> #include <netns/ns.h> #include <netns/sp.h> ... #ifndef SPPSST_END #define SPPSST_END 254 #define SPPSST_ENDREPLY 255 #endif struct sphdr proto_sp; int s; ... proto_sp.sp_dt = SPPSST_END; proto_sp.sp_cc = SP_EM; setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp, sizeof(proto_sp)); write(s, buf, 0); /* send the end request */ proto_sp.sp_dt = SPPSST_ENDREPLY; setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp, sizeof(proto_sp)); /* * We assume (perhaps unwisely) * that the other side will send the * ENDREPLY, so we'll just send our final ENDREPLY * as if we'd seen theirs already. */ write(s, buf, 0); close(s); ... 5.13. Packet Exchange The Xerox standard protocols include a protocol that is both reliable and datagram-oriented. This protocol is known as Packet Exchange (PEX or PE) and, like SPP, is layered on top of IDP. PEX is important for a number of things: Courier remote procedure calls may be expedited through the use of PEX, and many Xerox servers are located by doing a PEX ``BroadcastForServers'' operation. Although there is no implementation of PEX in the kernel, it may be simulated at the user level with some clever coding and the use of one peculiar getsockopt. A PEX packet looks like: /* * The packet-exchange header shown here is not defined * as part of any of the system include files. */ struct pex { struct idp p_idp; /* idp header */ u_short ph_id[2]; /* unique transaction ID for pex */ u_short ph_client; /* client type field for pex */ }; February 20, 2012 One of the daemons provided with 4.4BSD is inetd, the so called ``internet super-server.'' Having one daemon listen for requests for many daemons instead of having each daemon listen for its own requests reduces the number of idle daemons and simplies their implementation. Inetd han- dles two types of services: standard and TCPMUX. A standard service has a well-known port assigned to it and is listed in /etc/services (see services(5)); it may be a service that implements an official Internet standard or is a BSD- specific service. TCPMUX services are nonstandard and do not have a well-known port assigned to them. They are invoked from inetd when a program connects to the "tcpmux" well- known port and specifies the service name. This is useful for adding locally-developed servers. Inetd is invoked at boot time, and determines from the file /etc/inetd.conf the servers for which it is to listen. Once this information has been read and a pristine environ- ment created, inetd proceeds to create one socket for each service it is to listen for, binding the appropriate port February 20, 2012 PSD:21-60 Advanced 4.4BSD IPC Tutorial number to each socket. Inetd then performs a select on all these sockets for read availability, waiting for somebody wishing a connection to the service corresponding to that socket. Inetd then performs an accept on the socket in question, forks, dups the new socket to file descriptors 0 and 1 (stdin and stdout), closes other open file descriptors, and execs the appropriate server. Servers making use of inetd are considerably servers under inetd is the getpeername call, which returns the address of the peer (process) connected on the other end of the socket. For example, to log the Internet address in ``dot notation'' (e.g., ``128.32.0.4'') of a client connected to a server under inetd, the following code might be used: struct sockaddr_in name; int namelen = sizeof (name); ... if (getpeername(0, (struct sockaddr *)&name, &namelen) < 0) { syslog(LOG_ERR, "getpeername: %m"); exit(1); } else syslog(LOG_INFO, "Connection from %s", inet_ntoa(name.sin_addr)); ... While the getpeername call is especially useful when writing programs to run with inetd, it can be used under other cir- cumstances. Be warned, however, that getpeername will fail on UNIX domain sockets. Standard TCP services are assigned unique well-known port numbers in the range of 0 to 1023 by the Internet Assigned Numbers Authority (IANA@ISI.EDU). The limited number of ports in this range are assigned to official Internet protocols. The TCPMUX service allows you to add locally-developed protocols without needing an official TCP port assignment. The TCPMUX protocol described in RFC-1078 is simple: ``A TCP client connects to a foreign host on TCP port 1. It sends the service name followed by a February 20, 2012 is closed.'' In 4.4BSD, the TCPMUX service is built into inetd, that is, inetd listens on TCP port 1 for requests for TCPMUX services listed in inetd.conf. inetd(8) describes the format of TCPMUX entries for inetd.conf. The following is an example TCPMUX server and its inetd.conf entry. More sophisticated servers may want to do additional processing before returning the positive or: February 20, 2012 PSD:21-62 Advanced 4.4BSD IPC Tutorial char line[BUFSIZ]; FILE *fp; ... /* Use stdio for reading data from the server */ fp = fdopen(sock, "r"); if (fp == NULL) { fprintf(stderr, "Can't create file pointer\n"); exit(1); } /* Send service request */ sprintf(line, "%s\r\n", "current_time"); if (write(sock, line, strlen(line)) < 0) { perror("write"); exit(1); } /* Get ACK/NAK response from the server */ if (fgets(line, sizeof(line), fp) == NULL) { if (feof(fp)) { die(); } else { fprintf(stderr, "Error reading response\n"); exit(1); } } /* Delete <CR> */ ')) != NULL) { if (*lp = 'n';x(line, ' } switch (line[0]) { case '+': printf("Got ACK: %s\n", &line[1]); break; case '-': printf("Got NAK: %s\n", &line[1]); exit(0); default: printf("Got unknown response: %s\n", line); exit(1); } /* Get rest of data from the server */ while ((fgets(line, sizeof(line), fp)) != NULL) { fputs(line, stdout); }.
http://mirbsd.mirsolutions.de/htman/sparc/manPSD/21.ipc.htm
crawl-003
refinedweb
10,116
54.12
Board index » oberon All times are UTC > The way I understand it, Oberon is an entire operating system in itself. > I don't know if you can run it on top of Linux. From what I know about > it I doubt it. I've been told that implementations of Oberon, as currently available on MS-DOS and some Unix (was it SPARC?), is built on top of the existing OS, so under MS-DOS it uses the DOS filesystem (of course with ugly cludges for the namespace limitations...) So an implementation on top of other Un*x variants should be possible. The greatest effort for porting would probably go into the compiler, but it is rather small. Olaf There already is a compiler back-end for the i386, but source isn't free. So we get to wait for the ETHZ people to do a linux port instead of doing it ourselves... -- Jay Carlson Flat text is just *never* what you want. ---stephen p spackman. Learning Oberon or Oberon/F
http://computer-programming-forum.com/28-oberon/84f01fc9101e1a31.htm
CC-MAIN-2017-34
refinedweb
170
74.69
At Thu, 27 Oct 2005 09:33:39 +0200, ness <address@hidden> wrote: > I don't agree with you this time. It is not out job to determine the > visions of the Hurd. Other guys have done this, and not only for a short > time, AFAIK. Can you elaborate on that? I have digged out Thomas' paper on the Hurd design, which is the only public information about the Hurd design goals that I know of. The only other information is maybe the announcement that the Hurd will be written as the core of the GNU system, which is not very enlightening. Now, I have done something evil, because I limited your options to public documents. If you look at internal discussions, you can find a lot of very specific goals. However, all this are about things in the "POSIXish" world of the Hurd, and about certain usage scenarios, like filesystem tricks (union namespace for package installation, etc). If I look for underlying operating system and kernel requirements, or other technical discussions about security etc, I find very little even in all the sources available to me. What is the vision of the operating system _below_ the POSIX layer? There seems to be somewhat of a gap right there, which we maybe can fill. And if we don't do it, who else will? When I came to the Hurd in 1997, it was essentially dead. It was not yet officially declared death, but it was pretty close. > What we first want is to iron out some of the Hurd's > problems. If we _have_ a running Hurd and can say "no more large > problems left", _then_ is the time to look further. > Actually, the Hurd in it's current state is really poweful. When I came > to the Hurd, I first tried to boot the actual one. There was, in fact, > one unsolvable problem, no driver for my hd existed. When I later tried > it in qemu, there were two things because of whom I'd not want to use > it: it was damn slow and buggy. > Of course now, as I'm more familiar with the internal problems, I see > other issues. > However, what I wanna say with this: it's not the time to look for > visions - we need hard code, that's it. Do you trust me if I say that Neal and I both have tried to fix the Hurd's problems with hard code, and we think it just doesn't work out this way? (I didn't check with Neal, but I think he will agree with this broad characterization). I am only saying this to interest you in looking a bit deeper and trying to understand the issues instead ignoring them "for now". They are not going to go away by ignoring them. The reason is that the problems are not engineering problems, or even labor problems. We have these types of problems as well, and they may cloude your view on the other issues. The real problems are architectural. Of course, if you believe this or not depends on your goals. But if you read my stance on Thomas' paper in my other mail, you will see why I think that we are totally in line with the original Hurd goals. Thanks, Marcus
http://lists.gnu.org/archive/html/l4-hurd/2005-10/msg00681.html
CC-MAIN-2016-26
refinedweb
552
79.8
Absolute Imports with Create React App By default ES6 modules in create-react-app use relative paths, which is fine for cases where the files you’re importing are relatively close within the file tree: import { createGoal } from ‘./actions’import { selectAuth } from ‘./selectors’;import App from ‘../App’; But using relative paths is a real pain when you start dealing with deeply nested tree structures because you end up with dot-dot syndrome: import { editUser } from ‘../../../AppContainer/actions’;import { selectAuth } from ‘../../../AppContainer/selectors; And what happens when you decide you want to move that file? Or maybe you want to import the same module in another file? It was tedious enough counting how many dots you needed to traverse the first time but now you must recount every single time because as you change the location of a file you also change its relative path with respect to other files. What if there was a way to import a file the same way every time, regardless of where the file sat in relation to another? This is where absolute imports come in handy: import { editUser } from ‘containers/AppContainer/actions’;import { selectAuth } from ‘containers/AppContainer/selectors; No matter where you import those files from the path will be the same. No more counting dots. Implementing Absolute Imports in Create-React-App After digging through a bunch of github issues I was finally able boil down the steps required to implement absolute imports in create-react-app applications down to two steps: - Create a ‘.env’ file at the root level (same level as package.json) - Set an environment variable, ‘NODE_PATH’ to ‘src/’ And that’s it. From what I understand, create-react-app is configured in such a way that its webpack configuration will automatically pick up ‘.env’ files and read the ‘NODE_PATH’ environment variable, which can then be used for absolute imports. Custom environment variables also work both during development and in production because the variables are embedded during build time instead of runtime, so your app will have access to its environment by ‘process.env’: The discussions: The pull requests: Here’s a quick example of converting from relative to absolute imports. First we create our files and folders. We have our AppContainer that loads AppRoutes. Notice how it uses relative imports. We want absolute imports. - Create a ‘.env’ file at the root level (same level as package.json) - Set an environment variable, ‘NODE_PATH’ to ‘src/’ And now we can use absolute imports. And it works just fine. Conclusion Absolute imports can save you a lot of time and headaches because you no longer have to account for how many dots you need anytime you’re importing or changing the location of a file. Thanks to create-react-app it’s quite simple to set up an environment that allows you to do just that. I’m a developer who documents new tools and concepts I come across and find interesting enough to share. Please click that heart button and/or leave a comment so I can write content more suited to your interests.
https://medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d
CC-MAIN-2019-30
refinedweb
513
54.63
Using low cost LeafLab Maple Mini boards with mbed. Dependencies: mbed-MapleMini mbed Table of Contents Using Maple Mini board with mbed¶ Sparkfun used to sell a board (now available on eBay and from other online sellers for less than $4) which provides an affordable and flexible way for users to try out new ideas and build prototypes. The board is equipped with an STM32F103CBT6 microcontroller compatible with the mbed NUCLEO-F103RB platform. Microcontroller features¶ - STM32F103CBT6 in LQFP48 package - ARM®32-bit Cortex®-M3 CPU - 72 MHz max CPU frequency - VDD from 2.0 V to 3.6 V - 128 KB Flash - 20 KB SRAM - GPIO (34) - Two push buttons: RESET, USER BUTTON - Mini-B USB connector Maple Mini board pinout¶ Courtesy of Wim Huiskamp Zoom in Information Only the labels printed in blue/white or green/white (i.e. PB_8, PC_13, D15, A0 ...) must be used in your code. The other labels are given as information (alternate-functions, power pins, ...). You can also use these additional pin names: LED1=PB_1 SERIAL_TX=PA_2 I2C_SCL=PB_6 SPI_MOSI=PA_7 PWM_OUT=PB_3 SERIAL_RX=PA_3 I2C_SDA=PB_7 SPI_MISO=PA_6 SPI_SCK =PA_5 SPI_CS =PB_6 Schematic¶ The schematic is available here. Using the mbed online compiler to build programs for Maple Mini¶ - Create a program as if it was for a NUCLEO-F103RB board (select NUCLEO-F103RB as target platform in the online compiler). Or click here to import this demo into your online compiler (then you can skip the following two steps). - Import the mbed-MapleMini library into your project. - Add #include "MapleMini.h"to main.cpp before #include "mbed.h"(the position matters!). Blinking on-board LED: "); } } Information Additional example program using the Maple Mini board: Programming the Maple mini board¶ You can use the NUCLEO virtual disk to program the Maple Mini (drag and drop programming). To do that, an additional NUCLEO board is needed (any type equipped with ST-LINK/V2-1 will do). - Remove the two jumpers from the CN2 connector as illustrated in Figure 8: - Connect the NUCLEO board CN4 debug connector to the Maple Mini Maple Mini board. - Connect the NUCLEO board to your PC using a USB cable. - Maple's flash memory is protected. In order to start downloading programs to the board the protection has to be removed. That could be acomplished with the STM32 ST-LINK Utility. Once installed and running, in Target->Settings switch to Hot Plug mode. - In Target->Option bytes disable the Read Out Protection and turn the Flash sectors protection off as well. - After that you'll be able to fully erase the chip (including the LeafLabs Maple boot loader). Warning Once the chip has been erased the board cannot be used with LeafLabs Maple IDE anymore! - Exit the STM32 ST-LINK Utility. From now on you'll be able to download programs to the board. - To program the Maple Mini board, click on the Compile button and save the binary to the NUCLEO virtual disk . For more details have a look at the User Manual, chapter 6.2.4 Using ST-LINK/V2-1 to program and debug an external STM32 application. Using serial port (not just for debugging)¶ - Connect an FTDI or similar USB-Serial Maple Mini downloaded to the NUCLEO board, remove the two jumpers again. Offline compilation and debugging with CooCox CoIDE¶ NOTE: The pictures below are just for illustration (some belong to the STM32F103C8T6 - Blue Pill project). - I do not recommend to use the Beta version but rather install CoIDE V1.7.8. - If not done yet then download and install the GNU Arm Embedded Toolchain onto your PC. - Keep the NUCLEO board ( ST-LINK) connected to the Maple Mini board as in the set-up for online programming. - Export your program from the mbed online compiler to CooCox CoIDE. - Save the file into a folder on you PC's hard drive and unzip. - Run CoIDE and open the project. - On the menu bar click on Project. Choose Select Toolchain Path and select the path to the GNU Arm Embedded Toolchain. Once completed the path will apply to all projects. (It is not necessary to repeat this for each project but rather do it only once after installing the toolchain.) - To setup the debugger, open the Debugger tab and use the following settings: - To ensure that the execution of instructions during debugging is performed in the foreseen sequence, go to the Compile tab and select None (-O0) optimization. - To be able to use the Serialclass in application programs built offline, in the Projectside bar navigate to headers/mbed/TARGET_NUCLEO_F103RB/TARGET_STM/TARGET_STM32F1and open the device.hheader file for editing by double-clicking on it. Then add a new line saying #include "mbed_config.h"as below: After such modification the program should compile with no errors. - Another option is to use the default serial port which is automatically created by the mbed library. In such case no Serialobject (like Serial pc(PA_2, PA_3);) has to be created. Instead the global printffunction is called as below. In this case also the binary code becomes smaller. The default settings are 9600 bits/s, one start bit, eight data bits, no parity bit, one stop bit. "); printf("Blink\r\n"); } } - Open main.cpp for editing and rebuild the project by clicking on the Rebuild button. - Reprogram the board by clicking on the Download Code To Flash button: NOTE: Any time you launch the debugger the program is getting recompiled and the board reprogrammed. So you can skip this step. I included it just to illustrate how easily you can (re)program the board offline. - Set up some debug points and launch the debugger by clicking on the Start Debug button: - You can execute the instructions step by step (or run to the next debug point) and observe the variables and outputs whether they are changing as expected... Happy coding and debugging :-)
https://os.mbed.com/users/hudakz/code/MapleMini_Hello/wiki/Homepage
CC-MAIN-2020-10
refinedweb
979
64.71
Quick Links RSS 2.0 Feeds Lottery News Event Calendar Latest Forum Topics Web Site Change Log RSS info, more feeds Topic closed. 313 replies. Last post 2 years ago by Honey502. hell of a call gary!!!...tearin em down as always!!! I gave that pick with the flips to some women upstairs at work.They better have caught it lol Thanks Cieli and Jonny Well , if they didn't play it , you got something on them now Jonny ....... which is hard to do I bet they played it though 885 eve 550* (560/590 ) 580/058* rest of the week..or 5x0 The P4 areas have dictated a winning split pair for the next week Gonna move these forward , as they still look like to me that they may have a chance Jonny hit the 055 off these But I like his 560 590 580 058 I have them presently as 058* 850 506 605 ( flip 509 ) His 55 still looks good to me also Have seen it as 055 again and 005 500 ( 155 115 154 may have a shot also ) I also like 015 510 951 961 914 all seen a lot this week And I have seen the 540 350 454 545 a lot this week also No Promises I like these pairs today..........they are Heavy in the workouts 00 99 ( 66 ) 80 91 ( 61 ) 60 ( 90 ) .....for the week, 2x6 or 2x9..the eve P4 has been holding a split pair pattern for the past couple weeks. 256/259* or 229/266 *229*299* Ole ' Hawkeye looking Good here also I like his 292** ( 299 ) and flips I have 249** 246 Here is one I really like 239*** ( flip 236 ) 238 248 looks good to me also from the recent workouts His 256 ( 259 ) is in the workouts also Better watch Ole ' Hawkeye's numbers in his post above in the future Of course that is good advice for anytime ......... for sure I got these in for today mid/eve. Im sensing that 5.... For some reason my instinct is telling me 537, 577, 553... Just cant narrow it down. Seeing Key 1 6 ( flip 9 ) today either draw Put with your 5 BFW is 15 65 ( 95 ) Like 547 574 too All those above seen a lot this week Mid 574 ( Straight * ) Man I Wished I Lived In Connecticut Nice Call on the Key 5 digit BFW I still be looking for the Key 1 6 ( flip 9 ) tonite Like 547 574 too All those above seen a lot this week. What a call Astek! I knew that 5 was leading and played em all up and down. Been there done that. They will get you every time. Straight hit! If only 537 or 577 hit. I had $5 on them both straight... Wow that was close to a nice hit BFW It seems like they most always know doesn't it ( I know Ky. does ) Maybe they bring your 537 577 back soon I dont know Beautiful Call once again on your #Key 5 ( Nice Job ) You suppose they would throw a two digit return tonite Not saying they are going too , but if they did , and if they hit my keys 1 6 ( or flip 9 ) Would be 541 546 549 571 576 579 471 476 479 I got a few of those already posted But don't bet the farm...........as there may be a two digit return and there may not I am just speculating , you know , kinda like the stock market which is controlled also 902 602 219 931 621 476 479 218 186 189 935 635 549 546 211 212 might have a chance for a few draws your 347 sure looks Good 837 also 376 379 11 pair looks decent 118 188 119 199 166 166 141 144 Any 11 ( or Mate ) Im going with the 9 to lead tonight. Going to give your top line a play with the flips. I like your 1 6 key. I also sense JBG's 99 double may be coming up. Quote: Originally posted by JonnyBgood07 on September 25, 2014 Weekend shot....by order of rank 72x or 74x 720, 725, 740, 745..if I have my way then 720 or 740 139/136* 135 519/516* 513* Miracle pick is 990/099 Well checking back , I misread my Keys BFW I should have listed them as 0 6 ( flip 9 ) I thought it was the 1 but rechecking I see it as the 0 Which of course could be the 1 also ( but I dont like to use 4 keys ) I never even use three keys really ( the Only time I do ...is when one of my main TWO keys are the 6 or the 9 ) That is the only time I will use three keys ( because of the flip 6 9 ) which in my book , and the way I play , is the same digit any day Otherwise I only use TWO keys for TWO draws , ONE of the two to hit within Two draws When they miss the mid day like they did today , they both can show up in the eve sometimes , but not all the time , and I also did not design them to do that ( as I only look for One key out of the Two ) and if they do that, then they have done their job , the way I designed them to do So.....recapping ... Keys 0 6 ( flip 9 ) which in above post would be the 540 570 470 Others stay the same , just in case there would be a two digit return ( which I am not sure there will be ) I just now realized BFW that Jonny had the 745 in this post here I cant believe I missed seeing that today , but I did Anyway Great Call by Jonny The two digit return did happen that I talked about , but missed all three of my key digits I listed it with None of my keys hit They usually have a better success rate than that , but not this time it looks like When Ole ' Hawkeye says to watch for a pair , it just keeps hitting 473 74* pair 574 74* pair Mid Day number ( I had forgot about this and realize he had it before anyone ) 744 74* pair Three times ( Jonny was sure keyed in on that one ) That is just mind boggling..time and time again..hit after hit.. WTG Gary! "No matter how bad things may get, I'd like to thank my middle finger for always sticking up for me.." 9/29/14 M/E +22 744 74 44 96 66 18 88 30 00 52 22 God Bless America CT PAIR ALERT SMD FILES FRONT PAIRS BACK PAIRS Below is the Overdue Pair-Sum Chart. Here is a brief explanation of how it works. The Front Pair has the 2 most overdue sum pairs for CT. The Sums 9 Pair is out for 91 skips. That means the front pairs in your Cash 3 combination should be 90-18-27-36-or 45...depending on what balls or digits that are due in your state. The second most overdue sum from pair is 40-13-59-68-77 or 22. You back pairs work exactly the same way. You back pairs are that due the most are 20-39-48-57-66-11. The BESt way to determine EXACTLY what sum pairs to play is to look at your states Overdue TTT's found on the SMD Reds hot Sheets. Here is a glimpse of your states Overdue TTT's as they are right now.... BTW, I have charts for every single state.-2016 Speednet Group. All rights reserved.
https://www.lotterypost.com/thread/279888/20
CC-MAIN-2016-50
refinedweb
1,294
80.96
There is a lot of data being generated in today’s digital world, so there is a high demand for real time data analytics. This data usually comes in bits and pieces from many different sources. It can come in various forms like words, images, numbers, and so on. Twitter is a good example of words being generated in real time. We also have websites where statistics like number of visitors, page views, and so on are being generated in real time. There are so much data that it is not very useful in its raw form. We need to process it and extract insights from it so that it becomes useful. This is where Spark Streaming comes into the picture! It is exceptionally good at processing real time data and it is highly scalable. It can process enormous amounts of data in real time without skipping a beat. So how exactly does Spark do it? How do we use it? How does it work?. We can process this data using different algorithms by using actions and transformations provided by Spark. This processed data can be used to display live dashboards or maintain a real-time database. You know how people display those animated graphs based on real time data? This is how they do it! Let’s see how Spark Streaming processes this data. It receives input data streams and then divides it into mini-batches. These mini-batches of data are then processed by the core Spark engine to generate the output in batches. Spark’s basic programming abstraction is Resilient Distributed Datasets (RDDs). To simplify it, everything is treated as an RDD (like how we define variables in other languages) and then Spark uses this data structure to distribute the computation across many machines. Spark Streaming provides something called DStream (short for “Discretized Stream”) that represents a continuous stream of data. A live stream of data is treated as a DStream, which in turn is a sequence of RDDs. These DStreams are processed by Spark to produce the outputs. An actual example Everything feels better if we just discuss an actual use case. Let’s consider a simple real life example and see how we can use Spark Streaming to code it up. Let’s say you are receiving a stream of 2D points and we want to keep a count of how many points fall in each quadrant. We will be getting these points from a data server listening on a TCP socket. Let’s see how to do it in Spark. The code below is well commented, so just read through it and you’ll get an idea. We will be discussing it in detail later in this blog post. import sys from pyspark import SparkContext from pyspark.streaming import StreamingContext # Function to map the point to the right quadrant def get_quadrant(line): # Convert the input string into a pair of numbers try: (x, y) = [float(x) for x in line.split()] except: print "Invalid input" return ('Invalid points', 1) # Map the pair of numbers to the right quadrant if x > 0 and y > 0: quadrant = 'First quadrant' elif x < 0 and y > 0: quadrant = 'Second quadrant' elif x < 0 and y < 0: quadrant = 'Third quadrant' elif x > 0 and y < 0: quadrant = 'Fourth quadrant' elif x == 0 and y != 0: quadrant = 'Lies on Y axis' elif x != 0 and y == 0: quadrant = 'Lies on X axis' else: quadrant = 'Origin' # The pair represents the quadrant and the counter increment return (quadrant, 1) if __name__ == "__main__": if len(sys.argv) != 3: raise IOError("Invalid usage; the correct format is:\nquadrant_count.py <hostname> <port>") # Initialize a SparkContext with a name spc = SparkContext(appName="QuadrantCount") # Create a StreamingContext with a batch interval of 2 seconds stc = StreamingContext(spc, 2) # Checkpointing feature stc.checkpoint("checkpoint") # Creating a DStream to connect to hostname:port (like localhost:9999) lines = stc.socketTextStream(sys.argv[1], int(sys.argv[2])) # Function that's used to update the state updateFunction = lambda new_values, running_count: sum(new_values) + (running_count or 0) # Update all the current counts of number of points in each quadrant running_counts = lines.map(get_quadrant).updateStateByKey(updateFunction) # Print the current state running_counts.pprint() # Start the computation stc.start() # Wait for the computation to terminate stc.awaitTermination() How to run the program? We will discuss the details of the above program shortly. For now, just save it in a file called “quadrant_count.py”. As we discussed earlier, we need to set up a simple server to get the data. Let’s set up the data server quickly using Netcat. It is a utility available in most Unix-like systems. Open the terminal and run the following command: $ nc -lk 9999 Then, in a different terminal, navigate to your spark-1.5.1 directory and run our program using: $ ./bin/spark-submit /path/to/quadrant_count.py localhost 9999 Make sure you provide the right path to “quadrant_count.py”. You can enter the datapoints in the Netcat terminal like this: The output in the Spark terminal will look like this: How does it work? We start the program by importing “SparkContext” and “StreamingContext”. StreamingContext is the main entry point for all our data streaming operations. We create a StreamingContext object with a batch interval of 2 seconds. It means that all our quadrant counts will be updated once every 2 seconds. Using this object, we create a “DStream” that reads streaming data from a source, usually specified in “hostname:port” format, like localhost:9999. In our example, “lines” is the DStream that represents the stream of data that we receive from the server. In this DStream, each item is a line of text that we want to process. We split the lines by space into individual strings, which are then converted to numbers. In this case, each line will be split into multiple numbers and the stream of numbers is represented as the lines DStream. Next, we want to count the number of points belonging to each quadrant. The lines DStream is further mapped to a DStream of (quadrant, 1) pairs, which is then reduced using updateStateByKey(updateFunction) to get the count of each quadrant. Once it’s done, we will print the output using running_counts.pprint() once every 2 seconds. Understanding “updateFunction” We use “updateStateByKey” to update all the counts using the lambda function “updateFunction”. This is actually the core concept here, so we need to understand it completely if we want to write meaningful code using Spark Streaming. Let’s look at the following line: updateFunction = lambda new_values, running_count: sum(new_values) + (running_count or 0) This function basically takes two inputs and computes the sum. Here, “new_values” is a list and “running_count” is an int. This function just sums up all the numbers in the list and then adds a new number to compute the overall sum. This list just has a single element in our case. The values we get will be something a list, say [1], for new_values indicating that the count is 1, and the running_count will be something like 4 indicating that there are already 4 points in this quadrant. So we just sum it up and return the updated count. Start and stop One thing to note here is that the real processing hasn’t started yet. Spark Streaming only sets up the computation it will perform when it is started only when it’s needed. This is called lazy evaluation and it is one of cornerstones of modern functional programming languages. There’s no need to evaluate anything until it’s actually needed, right? To start the processing after all the transformations have been setup, we finally call stc.start() and stc.awaitTermination(). We are done! You can now process data in real time using Spark Streaming. It is great at processing data in real time and data can come from many different sources like Kafka, Twitter, or any other streaming service. Enjoy fiddling around with it! ——————————————————————————————————— Very nice article and got lot of information…..
https://prateekvjoshi.com/2015/12/22/analyzing-real-time-data-with-spark-streaming-in-python/
CC-MAIN-2020-40
refinedweb
1,334
65.01
Component-preload.js,Minification and Uglification For Enhancing The Performance Of SAPUI5 application In this blog, we’ll look at the use of building, Component-preload.js, minification, and uglification for enhancing the performance of application. SAPUI5 applications are build with the MVC pattern and therefore consist of multiple files, like views or controllers, With fragments, it’s possible to split up parts of views even further into smaller logical units. Although having a lot of difference files based on their functionality is good during the development, it’s bad when running on a production server. Every necessary file fires a separate network request. You have to wait until all network requests are completed before the app is usable. you may not notice this delay in your corporate network[which is not in my case 😀 😀 :P], but you’d notice in on a mobile phone with a moderate connection speed. To solve this issue, you can package different files into a single file, a process called bundling. through bundling, your app only has to load a single file instead of all the separate files, which speeds up the loading time of your application because your app has to wait only for a single file to load. In SAPUI5, this single file is called Component-preload.js . this file contains all the code of your application in a minified version. Minification means removing all unnecessary white-space and comments, Which also decreases the file size. In addition, the javascript source code is also uglified. Ugification means that your source code will not be as readable as before. Minification via a Grunt Task Runner You can minify your SAPUI5 application source code via a Grunt task. The Grunt task is called openui5_preload is in Node Package Manager(NPM) called grunt-openui5. Grunt is a task runner based on node.js. A task runner can run certain tasks, like linting, minification, bundling, executing unit tests. The idea behind a task runner is to automate repetitive work. Node.js Setup Setting up Node.js is pretty straightforward: - Navigate to and download Node.js - Follow the installer instructions. You can test the installation by opening your “Node.js command prompt” {not the usual cmd one ;)} *NPM is installed automatically with Node.js* Grunt Setup Now you can install Grunt command-line tool NPM package globally( -g parameter stands for globally) from the command line by typing the following: npm install -g grunt-cli after running the install command, you should see a similar output as that shown below. That completes the Node.js and Grunt setup. Now that you know about the Grunt task runner and Node.js, let’s dive into an example to see the task in action. Create Gruntfile.js and package.json manually by right clicking on the project name . The structure of the application is shown below also note the Gruntfile.js and package.json files. Gruntfile.js contains the task for minifying the SAPUI5 application, and package.json contains all the required modules. when you run the this application and look at Google Chrome’s NETWORK tab, you’ll see that app-salarycard files requested separately. Gruntfile.js Now let’s look at Gruntfile.js Inside grunt.initConfig is one configuration object, dir, which refers to the name of the webapp(i.e. Projectname– Salarycard) and the name of the destination folder, dist . Then there are three tasks:Copy, clean, and openui5_preload. The copy task is responsible for copying all the files to the dist folder.The clean task removes all the files inside the dist folder. The actual minification of the SAPUI5 application happens inside openui5_preload . To configure the task, you need to provide the namespace of the application with the prefix setting and the component with the components setting. The cwd property defines the root directory of your application. In src we have listed all the default settings . When you want to include additional files or exclude certain files, you have to set the src property and list all your desired settings.If you use the src property, the default settings of the src property will be ignored. This means that if you forget to list ‘**/*.view.xml‘, then the view files won’t be minified anymore. grunt.loadNpmTasks loads various plugins, like grunt-contrib-clean for cleaning directories or grunt-openui5 to minify the application.Those tasks expect different configuration settings, like openui5_preload:{ . . . }, which we previously defined inside grunt,initConfig({. . . }). At the end, you’ll see grunt.registerTask. Here, we register two tasks:build and default . The default task runs when you type “grunt” inside the command line(Node.js command line). package.json Here is package.json file code looks like name: <any name> description: <free text> author: <free text> We have listed dependencies like grunt-openui5 or grunt-contrib-clean inside the devDependencies setting.This mean that those packages are only needed during development of the application and not when running in production mode. Now, open the command line and switch to the Salarycard directory, Inside the command line and type “npm install” . As you can see in below screen shot all the required dependencies are installed. Running NPM install Command: Now, all the listed dependencies inside package.json are installed in the node_module folder, as you can see below and check for the below files inside node_module folder, no need to go in depth Running Grunt Now, type “grunt” inside the command line to start the minification process. When you look inside your project, you’ll now see the dist folder which contains the Component.preload.js file as shown below. dist folder with Component-preload.js file Below image shows an excerpts of the Component-preload.js file, in which all the application files are listed as module and included in the minified source code. Now, move the Component-preload.js file out of dist folder to WebContent folder of the application. Below is the folder structure after moving the Component-preload.js file into WebContent folder. Now, we will open Component-preload.js file to change the file path to load properly. before change: after change the Component-preload.js file will look like below [WebContent removed]. As we never provide the WebContent folder path anytime in our development. If you run the application again and inspect the network trace again in Google Chrome, you’ll see that Component-preload.js is loaded instead of all the separate files shown in below screen shot. comparison Before and After : We can observe that number of request reduced to 25 after loading of Component-preload.js file. Now, we may delete all the un-necessary files/folders like Gruntfile.js, package.json, node_module, dist . {at this point these files are not required anymore because we have achieved our motive i.e. minifing the files}. Note: if you change any source code in the file you need to run the “grunt” command again to minify the source code again otherwise it won’t work properly. How To Debug The Application After Minification and Uglification As we had noticed that after loading of Component-preload.js file our Views, controllers files are not visible anymore in Network trace. So don’t worry there is always a way for the developers :). We need to add a parameter to the application url i.e. sap-ui-debug=true which will load all the minified files into the Network tab in readable format. Here we can see our files Method-2: You can switch off the Component-preload.js file loading by addling the URL parameter “sap-ui-xx-componentPreload=off” i.e.:- “” That’s all on Componet-preload.js, minification and uglification, Hope you enjoyed this blog. ***IMPORTANT Once we Share the application to ABAP server we need to provide a BSP application name starts with “Z” , And the Component-preload.js file will look like below, A file name with 44 characters will be created. As we have created a brand new BSP application , So the file path won’t work anymore in Component-preload.js file, If you run the BSP application you can still observe the Component.preload.js file loads correctly but along with that all other files like *.view.xml, *.controller.js, *.json etc loads which was’t our requirement, So to avoid this conflict it’s always better to create a BSP application starts with “Z” in ABAP server (ZDEMOSALCAD) and create a project in eclipse with the exact name as BSP application to avoid this conflict in future. (Thanks to my colleague Sanika for this information) For example Create a BSP Application name : ZDEMOSALCAD Then create Eclipse Project Name with the exact same name : ZDEMOSALCAD Thanks & regards, Suman Kumar Panigrahi Hi! Interesting post!! Please check my approach with js minification in Best regards Hi Enric, Thanks, and yes I had gone through your blog and found it interesting and very helpful while struggling to achieve this, Thanks a lot and keep blogging. Regards. Suman Kumar Hi Suman, I have followed all steps but the Component-preload.js request GET 404 (not found). Could you please help me on this error? Structure in my Eclipse project Content in UI5RepositoryPathMapping.xml file Structure of the my BSP application Network trace Component-preload.js not found !!! Kind regards, Norman Hi Suman, I’m happy to see your blog post is as recent as Sept 2017. I’m also looking at this topic, however I can’t get Component-preload.js to load when I place it next to Component. It no longer 404’s for me at runtime, as it always used to. I have confirmed this across multiple examples; old apps, running with legacy UI5 versions, normal WebIDE, full-stack WebIDE, Trial WebIDE… none of these load Component-preload.js anymore when inspecting + network tab. When I place my Component-preload.js in my webapp directory to do a test, it is simply ignored. This is running via WebIDE mind you, not serving locally, nor working with Eclipse. Appreciate any help. Jason Hi Jason, Can you please share you folder structure. Thanks & regards, Suman Kumar. Hi Suman, sure: You can see that it’s next to Component.js according to SAP’s own template. When running via the WebIDE (the next screenshot below), where the red arrow is, there USED to always be a request for Component-preload.js, but not anymore. Other items are still requested like the resource bundles and 404 when not there. The development component is always used. You should be able to replicate by choosing any app of yours with Component-preload and implement on a free SCP Trial account. And if you do replicate, then I think the enquiry needs to escalate to SAP. Jason Great news Suman & readers, A colleague identifed the change. The WebIDE applies a URL parameter, “sap-ui-xx-componentPreload=off”, by default now. By ‘now’, I don’t mean the change was necessarily recent, only within my attention span to this issue. Removing this URL parameter results in a successful request to Component-preload.js. This makes sense for WebIDE development, as without this, the presence of Component-preload.js in the main code of the app would be an annoying problem for dev workflow. It appears SAP intend for preloaded/optimized production builds to be arranged from the /dist folder. Lots of debatable decisions there for CI/CD. Noteworthy also, I tried adding a Run Configuration with a URL Parameter set as sap-ui-xx-componentPreload=on, but this had no effect (must not be a real setting). Yes Jason you are right, SAP has by default add/appending the URL parameter ““sap-ui-xx-componentPreload=off” in dev client for make the life easier for the developers. :), Another easiest way to un-grunt or un-compress the views and controllers is “ctrl+Shift+Alt+P” where you can check the debugging option and refresh the app to see the actual views and controller source codes. Hi Jason, How did u perform the Grunt task in SCP WebIDE? I guess it’s provided by default by SAP if I am not wrong. The above blog is written based on ecliplse IDE, So I have to replicate the same scenario in WebIDE as well. Thanks & Regards Thanks for covering important topic. I have a question, I generated a Component-preload.js, but as far as I understand, this file optimizes a loading process of internal SAPUI5files only. In my project there are quite a lot custom JS and I would like to optimize them as well. The question is how can I establish in SAPUI5environment DEVand PRDbranches, to separate minified and uglified files from those, who are dedicated for ongoing development. Thanks. One more question, do I understand it correctly that Grunt-script can be replaced with NPM-script? Is there any way to make URL parameter “sap-ui-xx-componentPreload=off” inactive/ineffective. Component-preload.js should always load even if URL parameter “sap-ui-xx-componentPreload=off” is entered.
https://blogs.sap.com/2017/09/16/component-preload.jsminification-and-uglification-for-enhancing-the-performance-of-sapui5-application/
CC-MAIN-2020-40
refinedweb
2,180
58.18
Given a set of n strings arr[], find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string. Examples: Input: arr[] = {"geeks", "quiz", "for"} Output: geeksquizfor Input: arr[] = {"catg", "ctaagt", "gcta", "ttca", "atgcatc"} Output: gctaagttcatgcatc Shortest Superstring Greedy Approximate Algorithm Shortest Superstring Problem is a NP Hard problem. A solution that always finds shortest superstring takes exponential time. Below is an Approximate Greedy algorithm. Let arr[] be given set of strings. 1) Create an auxiliary array of strings, temp[]. Copy contents of arr[] to temp[] 2) While temp[] contains more than one strings a) Find the most overlapping string pair in temp[]. Let this pair be 'a' and 'b'. b) Replace 'a' and 'b' with the string obtained after combining them. 3) The only string left in temp[] is the result, return it. Two strings are overlapping if prefix of one string is same suffix of other string or vice verse. The maximum overlap mean length of the matching prefix and suffix is maximum. Working of above Algorithm: arr[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"} Initialize: temp[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"} The most overlapping strings are "catgc" and "atgcatc" (Suffix of length 4 of "catgc" is same as prefix of "atgcatc") Replace two strings with "catgcatc", we get temp[] = {"catgcatc", "ctaagt", "gcta", "ttca"} The most overlapping strings are "ctaagt" and "gcta" (Prefix of length 3 of "ctaagt" is same as suffix of "gcta") Replace two strings with "gctaagt", we get temp[] = {"catgcatc", "gctaagt", "ttca"} The most overlapping strings are "catgcatc" and "ttca" (Prefix of length 2 of "catgcatc" as suffix of "ttca") Replace two strings with "ttcatgcatc", we get temp[] = {"ttcatgcatc", "gctaagt"} Now there are only two strings in temp[], after combing the two in optimal way, we get tem[] = {"gctaagttcatgcatc"} Since temp[] has only one string now, return it. Below is C++ implementation of above algorithm. // C++ program to find shortest superstring using Greedy // Approximate Algorithm #include <bits/stdc++.h> using namespace std; // Utility function to calculate minimum of two numbers int min(int a, int b) { return (a < b) ? a : b; } // Function to calculate maximum overlap in two given strings int findOverlappingPair(string str1, string str2, string &str) { // max will store maximum overlap i.e maximum // length of the matching prefix and suffix int max = INT_MIN; int len1 = str1.length(); int len2 = str2.length(); // check suffix of str1 matches with prefix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare last i characters in str1 with first i // characters in str2 if (str1.compare(len1-i, i, str2, 0, i) == 0) { if (max < i) { //update max and str max = i; str = str1 + str2.substr(i); } } } // check prefix of str1 matches with suffix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare first i characters in str1 with last i // characters in str2 if (str1.compare(0, i, str2, len2-i, i) == 0) { if (max < i) { //update max and str max = i; str = str2 + str1.substr(i); } } } return max; } // Function to calculate smallest string that contains // each string in the given set as substring. string findShortestSuperstring(string arr[], int len) { // run len-1 times to consider every pair while(len != 1) { int max = INT_MIN; // to store maximum overlap int l, r; // to store array index of strings // involved in maximum overlap string resStr; // to store resultant string after // maximum overlap for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { string str; // res will store maximum length of the matching // prefix and suffix str is passed by reference and // will store the resultant string after maximum // overlap of arr[i] and arr[j], if any. int res = findOverlappingPair(arr[i], arr[j], str); // check for maximum overlap if (max < res) { max = res; resStr.assign(str); l = i, r = j; } } } len--; //ignore last element in next cycle // if no overlap, append arr[len] to arr[0] if (max == INT_MIN) arr[0] += arr[len]; else { arr[l] = resStr; // copy resultant string to index l arr[r] = arr[len]; // copy string at last index to index r } } return arr[0]; } // Driver program int main() { string arr[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"}; int len = sizeof(arr)/sizeof(arr[0]); cout << "The Shortest Superstring is " << findShortestSuperstring(arr, len); return 0; } // This code is contributed by Aditya Goel Performance of above algorithm: The above Greedy Algorithm is proved to be 4 approximate (i.e., length of the superstring generated by this algorithm is never beyond 4 times the shortest possible superstring). This algorithm is conjectured to 2 approximate (nobody has found case where it generates more than twice the worst). Conjectured worst case example is {abk, bkc, bk+1}. For example {“abb”, “bbc”, “bbb”}, the above algorithm may generate “abbcbbb” (if “abb” and “bbc” are picked as first pair), but the actual shortest superstring is “abbbc”. Here ratio is 7/5, but for large k, ration approaches 2. There exist better approximate algorithms for this problem. Please refer below link. Shortest Superstring Problem | Set 2 (Using Set Cover) Applications: Useful in the genome project since it will allow researchers to determine entire coding regions from a collection of fragmented sections. Reference: This article is contributed by Piyush. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Recommended Posts: - Transform One String to Another using Minimum Number of Given Operation - Recursive function to do substring search - Fractional Knapsack Problem - Remove spaces from a given string -.
https://www.geeksforgeeks.org/shortest-superstring-problem/
CC-MAIN-2018-34
refinedweb
927
57
in the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that it is called on; no new class is created., eq=True, order=False, unsafe_hash=False, frozen=False) class C: ... The parameters to dataclass()are: init: If true (the default), a __init__()method will be generated. If the class already defines __init__(), this parameter is ignored. repr: If true (the default), a __repr__()method). explicitly whether.and default_factory. init: If true (the default), this field is included as a parameter to the generated __init__()method. repr: If true (the default), this field is included in the string returned by the generated __repr__()method. compare: If true (the default), this field is included in the generated equality and comparison methods ( __eq__(), __gt__(), et al.). hash: This can be a bool or None. If true, this field is included in the generated __hash__()method. If None(the default), use the value of compare: this would normally be the expected behavior. A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than Noneis discouraged. One possible reason to set hash=Falsebut compare=Truewould be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons. metadata: This can be a mapping or None. None is treated as an empty dict. This value is wrapped in MappingProxyType()to make it read-only, and exposed on the Fieldobject. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata. If the default value of a field is specified by a call to field(), then the class attribute for this field will be replaced by the specified defaultvalue. If no defaultis provided, then the class attribute will be deleted. The intent is that after the dataclass()decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after: @dataclass class C: x: int y: int = field(repr=False) z: int = field(repr=False, default=10) t: int = 20 The class attribute C.z __init__() method is generated, then __post_init__() will not automatically be called. Among other uses, this allows for initializing field values that depend on one or more other fields. For example: @dataclass class C: a: float b: float c: float = field(init=False) def __post_init__(self): self.c = self.a + self.b The __init__() method generated by dataclass() does not call base class __init__() methods. If the base class has an __init__() method that has to be called, it is common to call this method in a __post_init__() method: @dataclass class Rectangle: height: float width: float @dataclass class Square(Rectangle): side: float def __post_init__(self): super().__init__(self.side, self.side) Note, however, that in general the dataclass-generated __init__() methods don’t need to be called, since the derived dataclass will take care of initializing all fields of any base class that is a dataclass itself. See the section below on init-only variables for ways to pass parameters to __post_init__(). Also see the warning about how replace() handles init=False fields. Class variables¶ One of two places where dataclass() actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar. If a field is a ClassVar, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function. Init-only variables¶ The other place where dataclass() inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type dataclasses.InitVar. If a field is an InitVar, it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level fields() function. Init-only fields are added as parameters to the generated __init__() method, and are passed to the optional __post_init__() method. They are not otherwise used by dataclasses. For example, suppose a field will be initialized from a database, if a value is not provided when creating the class: @dataclass class C: i: int j: int = None database: InitVar[DatabaseType] = None def __post_init__(self, database): if self.j is None and database is not None: self.j = database.lookup('j') c = C(10, database=my_database) In this case, fields() will return Field objects for i and j, but not for database. Frozen instances that it finds, adds the fields from that base class to an ordered mapping of fields. After all of the base class fields are added, it adds its own fields to the ordered mapping. All of the generated methods will use this combined, calculated ordered mapping of fields. Because the fields are in insertion order, derived classes override base classes. An example: @dataclass class Base: x: Any = 15.0 y: int = 0 @dataclass class C(Base): z: int = 10 x: int = 15 The final list of fields is, in order, x, y, z. The final type of x is int, as specified in class C. The generated __init__() method for C will look like: def __init__(self, x: int = 15, y: int = 0, z: int = 10): Default factory functions¶ If a field()specifies a default_factory, it is called with zero arguments when a default value for the field is needed. For example, to create a new instance of a list, use:mylist: list = field(default_factory=list) If a field is excluded from __init__()(using init=False) and the field also specifies default_factory, then the default factory function will always be called from the generated __init__()function. This happens because there is no other way to give the field an initial value. Mutable default values¶, if this code was valid:@dataclass class D: x: List = [] def add(self, element): self.x += element it would generate code similar to:class D: x = [] def __init__(self, x=x): self.x = x def add(self, element): self.x += element assert D().x is D().x This has the same issue as the original example using class C. That is, two instances of class Dthat. It is a subclass of AttributeError.
https://docs.python.org/3/library/dataclasses.html?highlight=dataclasses
CC-MAIN-2021-31
refinedweb
1,120
63.49
We got a heads up on when we'd first see the first release of Silverlight 2, and now we have a timeframe to look forward to for the final version. Silverlight 2.0 RTM is expected to be ready by Summer 2008. With Silverlight 2 beta 1 released, beta 2 is expected in Q2CY08, probably in May. Beta 2 will contain the full set of namespaces, as well as the final set of controls, but neither of these has been revealed. While the changes between beta 1 and beta 2 will be quite significant, not much will change between beta 2 and the final, save bug fixes and tweaks here and there. Websites developed using version 1.0 will be compatible when 2.0 comes out. The download size may increase a little bit, but the final size is, of course, still unknown. Microsoft is trying to keep the download size of the Silverlight installer as low as possible. There aren't many plans for adding support for more formats in Silverlight. Although Silverlight currently supports playing VC-1, WMV, MP3 and WMA content, it is unlikely that it will support arbitrary codecs because of licensing costs and because the download size would grow substantially. Silverlight currently supports the MMS streaming server protocol and this is also unlikely to change. On the other hand, Flash may not have .gif support, but Silverlight hasn't ruled it out. The idea is still being discussed: the main issue is the amount of work needed to integrate animated .gif functionality into Silverlight's animation scheme. Further reading - Ashish Thapliyal's Blog: Silverlight Roadmap questions You must login or create an account to comment.
http://arstechnica.com/information-technology/2008/04/silverlight-2-rtm-targeted-for-late-summer-release/
CC-MAIN-2014-52
refinedweb
281
64.61
Sides of right angled triangle from given area and hypotenuse in Python In this article, we will learn how to find all the sides of a right-angled triangle from a given area and hypotenuse in Python. Examples Input: hypotenuse = 10, area = 24 Output: Base = 6, Height = 8 Input: hypotenuse = 5, area = 10 Output: No triangle possible Some of the property of a right-angled triangle are Let’s consider a right-angle triangle with height a, base b the hypotenuse c will be c² = a² + b² A right-angle triangle will have a maximum area when both the base and height to each other. All the sides of a right-angled triangle from a given area and hypotenuse in Python 1. Firstly create a function area() that takes base, the hypotenuse as arguments. - Calculate the height using the base and hypotenuse height = math.sqrt(hypotenuse*hypotenuse – base*base). - return the area of the triangle 0.5 * height * base. 2. Now create a function idesOfRightAngleTriangle() that calculates the sides of the triangle - Firstly, calculate the maximum possible side when the area is maximum. and calculate the area using the area() function. - Compare given the area a with the maximum area, if a>maxArea then print “No possible”. - Using binary search calculate the base and the height of the triagle. import math def area(base, hypotenuse): height = math.sqrt(hypotenuse*hypotenuse - base*base) return 0.5 * base * height def sidesOfRightAngleTriangle(h, a): hsqrt = h*h maxAreaSide = math.sqrt(hsqrt/2.0) maxArea = area(maxAreaSide, h) if (a>maxArea): print("No possible") return low = 0.0 high = maxAreaSide while (abs(high-low)>1e-6): base = (low+high)/2.0 if (area(base, h) >= a): high = base else: low = base height = math.ceil(math.sqrt(hsqrt - base*base)) base = math.floor(base) print("Base: ", base) print("Height: ", height) h = int(input("Enter the hypotenuse: ")) a = int(input("Enter the area: ")) sidesOfRightAngleTriangle(h, a) Output Enter the hypotenuse: 5 Enter the area: 6 Base: 3 Height: 4 Enter the hypotenuse: 5 Enter the area: 7 No possible Also, read
https://www.codespeedy.com/sides-of-right-angled-triangle-from-given-area-and-hypotenuse-in-python/
CC-MAIN-2021-17
refinedweb
345
55.74
The ExportInterface class provides a data export interface for Qtopia. More... #include <interfaces/importexport.h> List of all member functions. When Qtopia Desktop starts up it automatically scans for plugins and registers any plugins that support the ExportInterface. Qtopia Desktop is able to export data from the Qtopia device in the formats supported by the ExportInterfaces it finds. Writing an input interface plugin is achieved by subclassing this base class, reimplementing the pure virtual functions exportData(), externalApplicationName(), palmtopApplicationName(), dataSets() and exportSettings() and exporting the class with the Q_EXPORT_PLUGIN macro. See the Qtopia Plugins documentation for details. See also Qtopia Desktop Classes. Returns a list of the data formats that this export interface can handle. Qtopia Desktop can export data in the "addressbook", "datebook", "todolist" and "categories" formats. This function is called by Qtopia Desktop when the user requests the export of Qtopia data. It is passed an interface to Qtopia Desktop, center. The name of the export format is passed in dataSet, and the data to be exported is passed in the data value list. The function should export the data in the dataSet format. Returns TRUE if the data is successfully exported; otherwise returns FALSE. Returns a widget that the user can use to set any options that can affect the export process. The returned widget will appear in the import/export tab of the Qtopia Desktop settings dialog, which is also its parent widget. May return 0 if there are no user-settable options. Returns the name of the application that imports data in the exported format. This is usually the name of the external application that exports data in the format this ExportInterface writes. The name may be displayed to the user. Returns the name of the Qtopia application that the data should be exported from. This file is part of the Qtopia platform, copyright © 1995-2005 Trolltech, all rights reserved.
http://doc.trolltech.com/qtopia2.2/html/exportinterface.html
crawl-001
refinedweb
314
57.27
a hack to get AVFS to compile if you get the following errors when you try to do so: /usr/include/linux/time.h:9: error: redefinition of `struct timespec' /usr/include/linux/time.h:15: error: redefinition of `struct timeval' make[1]: *** [mount.o] Error 1 Hack is edit out the following lines from time.h in /usr/include/linux #ifndef _STRUCT_TIMESPEC #define _STRUCT_TIMESPEC struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; #endif /* _STRUCT_TIMESPEC */ struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; do something like //#ifndef _STRUCT_TIMESPEC //#define _STRUCT_TIMESPEC //struct timespec { // time_t tv_sec; /* seconds */ // long tv_nsec; /* nanoseconds */ //}; //#endif /* _STRUCT_TIMESPEC */ //struct timeval { // time_t tv_sec; /* seconds */ // suseconds_t tv_usec; /* microseconds */ //}; Build avfs according to its install instructions. Return time.h to its previous, unedited state. Once avfs installed ROX has got its icing plus some cherries. This will stop the header conflicts that are causing AVFS compile to drop out. The probelm is not confined to SUSE 9 or kernel 2.4.21 but is due to some libc distributions including the linux header files it was built with and the conflicts not being taken care of. Hope this saves some other poor sap seveal hours of digging. Regards Nick Quoting Tristan McLeay <zsau@...>: > I think you'd lose the concept of a buddylist that way. Also, email is > mostly about _what's been done_; IM is about _what's happening_. If you > want a Communication program like you describe, mine won't be it. You > might have to write it yourself :) Actually, that's kind of the point. Why should the IM client keep a seperate list of contacts? That all it is, right? Identification methods for communicating with people. I guess it has to do with different perceptions of the same thing. I see IM as instant email. BTW, how is email only about 'what's been done'? This email program hasn't been created, and its being discussed in email. ;) (note: I'm not trying to be an arse. Just pointing out different perceptions). I'll tell you what. I'll just wait for your email program, and add IM to it. lol... Jk. Got to love OSS... Good thoughts... Later, Chris-- Later, Chris
https://sourceforge.net/p/rox/mailman/rox-users/?viewmonth=200312&viewday=2
CC-MAIN-2018-05
refinedweb
365
68.16
Resque Resque (pronounced like "rescue") is a Redis-backed library for creating background jobs, placing those jobs on multiple queues, and processing them later. A note about branches This branch is the master branch, which contains work towards Resque 2.0. If you're currently using Resque, you'll want to check out the 1-x-stable branch, and particularly its README, which is more accurate for the code you're running in production. Also, this README is written first, so lots of things in here may not work the exact way that they say they might here. Yay 2.0! Back to your regularly scheduled README. You can't always do work right away. Sometimes, you need to do it later. Resque is a really simple way to manage a pile of work that your application needs to do: 1.5 million installs can't be wrong! To define some work, make a job. Jobs need a work method: class ImageConversionJob def work # convert some kind of image here end end Next, we need to procrastinate! Let's put your job on the queue: resque = Resque.new resque << ImageConversionJob.new Neat! This unit of work will be stored in Redis. We can spin up a worker to grab some work off of the queue and do the work: bin/resque work This process polls Redis, grabs any jobs that need to be done, and then does them. :metal: Installation To install Resque, add the gem to your Gemfile: gem "resque", "~> 2.0.0.pre.1", github: "resque/resque" Then run bundle. If you're not using Bundler, just gem install resque. Requirements Resque is used by a large number of people, across a diverse set of codebases. There is no official requirement other than Ruby 1.9.3 or newer. We of course recommend Ruby 2.0.0, but test against many Rubies, as you can see from our .travis.yml. We would love to support non-MRI Rubies, but they may have bugs. We would love some contributions to clear up failures on these Rubies, but they are set to allow failure in our CI. We officially support Rails 2.3.x and newer, though we recommend that you're on Rails 3.2 or 4. Backwards Compatibility Resque uses SemVer, and takes it seriously. If you find an interface regression, please file an issue so that we can address it. If you have previously used Resque 1.23, the transition to 2.0 shouldn't be too painful: we've tried to upgrade interfaces but leave semantics largely in place. Check out UPGRADING.md for detailed examples of what needs to be done. Jobs What deserves to be a background job? Anything that's not always super fast. There are tons of stuff that an application does that falls under the 'not always fast' category: - Warming caches - Counting disk usage - Building tarballs - Firing off web hooks - Creating events in the db and pre-caching them - Building graphs - Deleting users And it's not always web stuff, either. A command-line client application that does web scraping and crawling is a great use of jobs, too. In Redis Jobs are persisted in Redis via JSON serialization. Basically, the job looks like this: { "class": "Email", "vars": { "to": "foo@example.com", "from": "steve@example.com" } } When Resque fetches this job from Redis, it will do something like this: json = fetch_json_from_redis job = json["class"].constantize.new json["vars"].each {|k, v| job.instance_variable_set("@#{k}", v) } job.work Ta da! Simple. Failure When jobs fail, the failure is stored in Redis, too, so you can check them out and possibly re-queue them. Workers You can start up a worker with $ bin/resque work This will basically loop over and over, polling for jobs and doing the work. You can have workers work on a specific queue with the --queue option: $ bin/resque work --queues=high,low $ bin/resque work --queue=high This starts two workers working on the high queue, one of which also polls the low queue. You can control the length of the poll with interval: $ bin/resque work --interval=1 Now workers will check for a new job every second. The default is 5. Queue Priority Queues are picked off in order of their priority. A job from a lower priority queue will only be picked off if there are no jobs for a higher priority queue available. See Resque::WorkerQueueList#search_order for more details. Configuration You can configure Resque via a YAML .resque file in the root of your project: queues: 'high,med,low' require: 'some_context.rb' pid_file: 'tmp/pids/resque.pid' interval: 1 daemon: true timeout: 5 graceful_term: false Then pass the configuration to the resque CLI: bin/resque work -c='./.resque'. You can also configure Resque via Resque.configure: Resque.configure do |config| # Set the redis connection. Takes any of: # String - a redis url string (e.g., 'redis://host:port') # String - 'hostname:port[:db][/namespace]' # Redis - a redis connection that will be namespaced :resque # Redis::Namespace - a namespaced redis connection that will be used as-is # Redis::Distributed - a distributed redis connection that will be used as-is # Hash - a redis connection hash (e.g. {:host => 'localhost', :port => 6379, :db => 0}) config.redis = 'localhost:6379:alpha/high' end Hooks and Plugins Please see HOOKS.md and PLUGINS.md. Contributing Please see CONTRIBUTING.md. Other Implementations You can write your Resque workers in other languages, too: Anything we missed? If there's anything at all that you need or want to know, please email either the mailing list or Steve Klabnik and we'll get you sorted.
http://www.rubydoc.info/github/resque/resque/master/frames
CC-MAIN-2016-07
refinedweb
941
75.71
Build an IoT Condition Monitoring App 08/16/2018 You will learn - How to use SAP Web IDE to build an application that leverages UI controls and data from IoT Application Enablement - How to use templates to speed up developing prototypes for certain use cases. - How to use the sensor chart UI control to discover patterns in your initial sensor data. SAP Web IDE Full-Stack is a powerful, extensible, web-based integrated development tool that simplifies end-to-end application development for SAP Cloud Platform. Start SAP Web IDE Full-Stack using the URL provided by your team administrator. The URL would look something like this: only that the account ID would be different. You would find it at, where you should find your global account, your Neo sub-account, and SAP Web IDE Full-Stack under Services. To log in, use the same email address and password you are using within the thing modeler. The home screen looks like this: In SAP Web IDE go to Preferences > Features. Turn on the following features: - IoT Application Enablement - Layout Editor - Storyboard. In the Development perspective, right-click Workspace and create a new project from a template (there are other ways to do this, for example, from the home page). Choose IoT Application from the Internet of Things category, and click Next. Enter greenhousemonitor as a project name and your user ID as the namespace, then click Next. On the Data Source tab, select: IoTAS-ADVANCEDLIST-THING-ODATAor similar as a service - All property sets for your greenhouse thing type in your package (search for greenhouse) Click Next, keeping all of the default settings for each of the page types until the wizard is finished. This generates a multi-page IoT application for you. SAP Web IDE will generate the code and will open the new application in the Code Editor. Now open the application folder and select any of the subfolders to examine the generated source files. You can change the generated source code afterwards as you see fit. Right now we want to explore the data that we have collected with the application. So to see a preview of the application you can start it right from SAP Web IDE. To do so, click the green button (below the Deploy menu in the picture above). This should bring up the application in a new tab. Depending on how many devices you have on-boarded, you will see one or multiple greenhouses in the list on the left. Click one to zoom in and once you have zoomed in to see only one click on it in the map, and then click Analysis Page. (Feel free to explore the other options on how to navigate the application another time). This will show this chart: Now you can add measures other then humidity with the Measured Values button, change the time-frame with the slider at the bottom or with the buttons labeled 7 Days, and you can look for patterns in the data. The example below shows 2 patterns – the light sensor in this case seems to jump between two extremes, day vs night. Let’s look at the second one: the humidity provides 140% values at times – these values are probably due to an error in the sensor. You will discover that if you collect sensor data from the real world, there will always be surprises, both in that you cannot see what you thought you would find in the data, and also that you see patterns in the data that you did not expect to see. For more support on in-depth topics on building an IoT Application, refer to under IoT. Prerequisites - Configuration You or someone else, that is an administrator in your global account, has walked through the following end-to-end configuration and onboarding guide: SAP IoT Application Enablement: Onboarding - Setting up Your Account. - Tutorials: Create Thing Model
https://developers.sap.com/hungary/tutorials/iot-express-5-use-webide-template.html
CC-MAIN-2018-43
refinedweb
653
59.23
#include <lvt/Shape.h> Inheritance diagram for Curve: 30 4 Default constructor. Sets the the subdivision of the curve into 30 segments, and sets the order of the curve to 4 (for a cubic curve). [inline] Adds a new control point to the curve. Clears all control points from the curve. Returns the number of control points in the curve. Returns the number of segments the curve will be subdivided into when being rendered. Returns the order of the spline. [virtual] Draws the shape. Implements Shape. Sets the number of segments in which to subdivide the curve. The default is 30. Sets the order of the spline. The order of the curve is its degree + 1. The order is clamped to the range [0, GL_MAX_EVAL_ORDER].
http://liblvt.sourceforge.net/doc/ref/class_l_v_t_1_1_curve.html
CC-MAIN-2017-17
refinedweb
125
78.75
whee WHEE!!WHEE!! Whee is a very simple framework/router/thing for node that emphasizes magic. Things just work, even though they probably shouldn't. Some batteries included. WARNING: This is more of a whimsical little experiment than a production-ready web framework. Seriously, I made most of this on a plane on very little sleep. If you want something more battle-tested and realistic (and you should), check out express, restify or hapi. InstallationInstallation # npm i --save whee UsageUsage First of all, require it: var w = And now, here's a Hello World: ; Go ahead and try it! It's that simple! Whee! You can also do all your other favorite HTTP verbs, like put and delete. The w object is also your this object, so you can call it that way, which is sometimes handy. Especially for CoffeeScript people. //JavaScript //CoffeeScriptwget '/'-> @send 'Hello, World!'listen 3000 You have access to send, sendJson, sendHtml and sendError on the w object, which are all pass-throughs to send-data. You have access to textBody',jsonBody ,formBody andanyBody on thew object, which are all pass-throughs to [body](). Instead of being passed in to the callback, the parsed body is then attached atw.body`. Heresy? Yup, probably. Too bad. There's also some basic redirect and static file stuff built in, but I'm a lazy README author so you can find those in the tests. Magic RevealedMagic Revealed This magic comes from hiding the necessary bits (like your req and res objects that you're used to) away in continuation local storage. Go read up on it. You'll love it! Also, it explains this stuff way better than I do. Basically it lets you keep a context around for as long as your continuation chain lasts. For our purposes, that means the length of an HTTP request and response cycle. This is great news because we can hide stuff away in there! Don't worry, req and res aren't gone forever. There's accessible at w.req and w.res, so long as you're inside a handler. If you want to hide your own stuff in there, you've got a few options: The Direct WayThe Direct Way Grab the whee namespace from cls and interact with it directly: var ns =;// then, somewhere in a request handler ...ns;// ....var session = ns; You can also use your own namespace. The Magic WayThe Magic Way This sets up accessors on the w object: var w = ;w;// then, somewhere in a request handler ...w;// ....var session = wmysessionthing; This is how the builtins are added! The Easy WayThe Easy Way A context object is provided for you on w so you can just put stuff there: // somewhere in a request handler ...wcontextmysessionthing = some: 'thing';// ...var session = wcontextmysessionthing; With each of these, remember that this stuff carries over to your next continuation, and so on, until you're done dealing with that request. CompatibilityCompatibility What about your connect/express middleware? Well we wouldn't want to leave that giant mountain of code behind. Luckily there's a pretty cool function called wrap that we can use. It takes a function that would ordinarily take in a request and response object, and returns a function that has those arguments already prepended via whee's magic. var w = ;var morgan = w;// morgan is a pretty good logging middleware; Yes, for now, you'll have to call your middlewares directly. But being deliberate like this is half the fun right? Wheeeeeee!!! LICENSELICENSE See LICENSE file.
https://www.npmjs.com/package/whee
CC-MAIN-2018-43
refinedweb
590
74.59
« China, U.S. Debts and the Economy | David Mason's Blog | John Thain: Poster Boy For Greed and Incompetence » This is not the time to cut taxes My op-ed piece, "This is not the time to cut taxes," appears in the 1/13/09 issue of The Christian Science Monitor. The subtitle of the piece is, "To increase federal revenue, taxes must go up, not down." There I write that ." I conclude the article with these thoughts: ." Advertisement So, I guess someone didn't take Macroeconomics? I'm not going to get too vicious here, but to a first approximation, tax cuts and government spending are the same thing in the time of recession. Tax increases and spending cuts, also. You can argue about multipliers and incentives, but by and large private income and government spending both contribute to economic activity. So raising taxes (or foregoing tax cuts) in a recession is not an approved method. I'm not making an argument about tax rates, only about timing. Saying this isn't the time for tax cuts is just wrong. If there was ever a time, this is it. January 12, 2009 6:16 PM | Reply | Permalink I agree w/ El Presidente. A large tax cut will be a lot more stimulative (and more quickly) than a large infrastructure project. And on the individual side, a temporary suspension of social security taxes would also quickly revive the consumer. I agree we need to start sacrificing. But that doesn't mean we just go out and raise taxes so we can continue to spend like drunken sailors. We need to make sure that the things the government is spending on is more productive than the dollar the private sector would spend it on. And some point we still need to pay it back January 12, 2009 6:43 PM | Reply | Permalink I think Obama can get away with his "middle class tax cuts" but should increase taxes on larger net incomes. I would point out that Mason in this blog entry is looking 2 years ahead (the end of next year is Dec. 2010). We will have a lot more data long before then. If public borrowing can be done cheaply, it's sometimes better than collecting taxes. But going into a recession, incomes and profits are generally decreasing so that even keeping tax rates constant means depressed tax revenues. That means even more borrowing should be expected. This tends to drive up the cost of borrowing, making taxes a better choice at some point. If you're going to spend the money, be prepared to pay the price. One thing taxes do is to curtail wasteful consumer spending, as people have less cash on hand. Do you trust people to spend wisely, or do you trust the government to spend wisely? Clearly this depends in part on who's in charge in the government at the time, as well as how one defines "waste". I don't see how tax cuts do a good job of creating jobs going into a recession. And from what I've seen of "multipliers", even economists seem to think that they don't have as much stimulative effect as other methods. January 13, 2009 1:52 AM | Reply | Permalink OK - I missed the part about looking two years ahead. To say we should do it, but only in two years, is a cop out in my opinion. Let's talk about what we should do today. I think we should have a business tax cut today as well as the consumer tax cut (ie I agree with Obama). We don't need taxes to curtail "wasteful consumer spending" - we have enough people who are unemployed that are already curtailing non-essential spending. You don't see how tax cuts do a good job of creating jobs? Take a look at what we did post-9/11. We cut taxes on capital investments for businesses. Businesses responded to this and dramatically increased their investments. January 13, 2009 7:59 AM | Reply | Permalink A few points: 1. The reason Paul Krugman et al. frequently say tax cuts are "less stimulative" than government spending is that people save some of that money, rather than spending it. So suggesting that "wasteful consumer spending" is the problem misses the point. Wasteful consumer spending is stimulative, and consumer saving is good too; it reduced the debt load and provides investment capital. 2. The 2001-2002 tax cuts actually didn't stimulate a significant increase in business investment (well, except in residential real estate). That's not to say they didn't have a positive effect on growth, but since they were financed by deficit spending, rather than cuts in programs, government borrowing took up much of the potential for investment. Think of it this way. Instead of opening new factories, people bought T-bonds. That's the net effect. January 13, 2009 11:36 AM | Reply | Permalink EP, your point 1 contradicts itself. You say tax cuts aren't effective because some of that is saved, but then you say that saving is stimulative. It's not a good time to encourage what I call "churning" of the economy, aka "wasteful spending". I agree that buying Treasuries doesn't help much now (giving tax cuts so people can buy new guvmint debt). But with fractional reserve banking, people putting money into CDs etc. could help private borrowing by significantly increasing the availability of money. Trouble is, not that many people with good credit want to borrow for productive (non wasteful) purposes right now. So I tend to agree that "savings" via Treasuries or bank CDs etc. isn't a great use of government money (remember, tax cuts are replaced by guv. borrowing). But if the Feds can borrow at 0% and we individuals can get 4% on our secure deposits, great! (fictional notion alert) January 13, 2009 11:56 PM | Reply | Permalink 1. I absolutely agree that the government ought to borrow as much as it can at 0% before rates go up, there's just no reason not to unless you think the FRB is going to allow deflation (and I don't). 2. My point wasn't that borrowing or spending was good; quite the opposite. I was pointing out that in terms of creating a sustainable recovery, tax cuts being saved by consumers wasn't a bad thing. 3. I'm not sure what the difference between spending and "wasteful spending" is; unless you mean spending by the government on foriegn military and security adventures (wink). January 14, 2009 10:13 AM | Reply | Permalink 1. Even with deflation: If we don't spend it, we can invest it or buy out extant Treasuries thus reducing future debt service costs. We are paying 0% in nominal rate so it's like printing money without the monetary inflation side effects! 2. Good and bad depend on the effective rates of return (tax cuts vs. outright public spending). 3. Churning and sending wealth/money overseas as trade deficits (as distinct from investing wisely overseas!), both count as wasteful spending, domestically speaking. It isn't about military adventurism or financing Israel's mass murder in Gaza, it's just economics. And programs which lead to trickle up domestically are also suspect. January 14, 2009 10:29 PM | Reply | Permalink I would encourage people to read the whole op-ed piece at the CSM link. My post was simply an excerpt from that piece. In the original, I mention that there is almost no economic or historical evidence that shows that tax cuts lead to net increases in government revenue. And we are desperately in need of such revenue, at a time when the government is bankrupt and the spending needs overwhelming. As to macroeconomics, most textbooks suggest that tax cuts generate much less economic activity than government spending. And at least two Nobel prize winning economists, Paul Krugman and Joseph Stiglitz, have argued as I do against (most) tax cuts. January 13, 2009 6:09 PM | Reply | Permalink David, The point here is not about "increases in government revenue". You're on the wrong page of the playbook when you talk about that. It's about how tax cuts etc. affect the economy in current, and near future, circumstances. Government isn't exactly bankrupt, it's just deep in debt -- it arguably can go deeper before defaulting. The macro-scale (if not macro-economic) question is: Do tax cuts cost more or less than government borrowing at this time? This comes down to efficiency - is private use of money which would have gone to taxes more or less efficient than guvmint borrowing which is needed to replace the lost tax revenue, today? Also keep in mind that Obama by giving "middle class" tax cuts is keeping a big campaign promise. If he doesn't raise taxes on the high high end, those people generally won't complain (but I think he should raise those tax rates anyway). January 14, 2009 12:10 AM | Reply | Permalink
http://tpmcafe.talkingpointsmemo.com/talk/blogs/david_mason/2009/01/this-is-not-the-time-to-cut-ta.php
crawl-002
refinedweb
1,515
72.05
ChangeProposals/extensionslikesvg currently my preferred resolution on ISSUE-41, in preference to my other two proposals. I'm sure there are bugs/things that could be improved in this. This should be seen as a model of what a good solution might look like, rather than something set in stone. Contents - 1 Summary - 2 Rationale - 3 Details - 4 Impact - 5 References Summary An extension spec can integrate itself with HTML following the model taken previously by SVG and MathML. A spec defines a "root element" (e.g. svg or math) that content for the extension can be included under. This root element should have a default namespace xmlns declaration, giving the namespace for the extension. The root element MUST also have its @extension attribute set, to inform the user agent that this element should be treated as an extension root and that the default namespace it defines should be applied to the contained nodes. If the extension becomes part of a future version of HTML, then the expectation is that it will become legal to omit the xmlns declaration and @extension attribute.. They should ideally also register the names of all element types and attributes that they define. If a spec has registered its root element and a document omits the namespace declaration for a registered root element, then a user agent that supports that extension should behave as if the registered namespace had been set. Although such a document is still technically non-conforming, this allows a user agent to correctly handle documents that conform to a future version of HTML that has made this extension part of standard HTML. An extension spec may also define attributes that can be attached to nodes from other namespaces (including HTML). All such attributes must be prefixed, and the prefix should be registered in the central registry. If a document uses such a prefix then it must bind the prefix to the correct namespace using an xmlns declaration. A document that uses such extensions is not valid HTML, however it is valid "extended HTML". Rationale This proposal is designed to allow for the creation of several kinds of extension: - "platform extensions" such as SVG and MathML that define new types of content that can be rendered in a browser. These extensions are expected to be vendor-neutral and have a specification. They may become part of HTML in the future. Although such extensions have their own specification, it is useful to provide guidelines for spec authors directing how such a spec should be integrated with HTML, and guidelines for authors of user-agents, advising them about what kinds of markup they should expect to see when a document is using an extension. - "language extensions" such as RDFa that define new attributes on top of nodes from other namespaces. They need to have a way to avoid name clashes between attributes defined by other extensions. - "vendor-specific experimental extensions" such as the experimental features that Webkit and Mozilla have created. There should be guidelines about how vendors should create such extensions in a non-destructive way. In the design of this proposal, we are motivated by the following goals: - There should be minimal changes to the parsing of existing documents. For this reason, an xmlns default namespace declaration on a root node is only obeyed by the parser if the root node contains the @extension attribute. - It should be possible for a vendor-neutral extension to become part of HTML in the future without documents needing to support both the old and the new syntax. For this reason, we do not require that a name from an extension be prefixed, and make clear the expectation that it will become legal for a namespace declaration to be omitted from a root node once it becomes part of HTML. - If a user agent supports an extension, and that extension subsequently becomes part of standard HTML, then the user agent should understand use of the extension when it is used in the new version of HTML, even if the new standard comes out after the user agent was released. For this reason, a user agent should infer the correct namespace for the root node of an extension that it understands - since this would be conforming in a future version of HTML where this feature had been made standard. - It is useful for authors if a conformance checker warns them about things that are likely to have been unintentional mistakes, or things that might be undesirable for interoperability reasons. For this reason, a conformance checker should require that the default namespace be declared and the @extension attribute be present for any extension that is being used - even though a supporting user agent will infer this. The lack of a default namespace and @extension attribute may indicate that the user is not aware that they are using an extension that may not be present in all user agents. - Specs like RDFa may need to add attributes to elements from other namespaces. Such attributes need to take care not to clash with each other. For this reason, we require that all such attributes contain a prefix indicating what extension they are part of. - Experience has shown that users find prefixes confusing and don't understand the relationship between a prefix and a namespace. We thus require that a prefix always map to the same namespace, and that this mapping be registered. - Some current documents contain xmlns declarations for prefixes, but have JavaScript code that assumes that the prefix is treated as being textually part of the name. To avoid breaking such code, an xmlns declaration for a namespace is only followed by a parser if the element that contains the xmlns declaration also sets the @extension attribute. Details These modifications are based on the W3C working draft as of March 4th, 2010: I've probably missed some bits, but hopefully this is enough to get the gist of it. Section 2.2.2: Extensibility Add the following text: If a document uses such an extension then it is not valid HTML. A document may however be considered "valid extended HTML" if it only uses extensions that conform to the criteria below: An extension specification may define one or more "root elements" that can contain elements designed by the extension specification. Such root elements MUST be registered in the HTML WG registry, together with their namespace. Such a root element MUST have an xmlns declaration giving a default namespace, which must be the same as the namespace registered in the registry, and it MUST have the @extension attribute set, to indicate that the elements inside have semantics defined by the extension. If a user agent that does not support the extension encounters an unknown element with an @extension attribute and a default namespace, then the user agent MUST apply that namespace to all element names inside the root element, unless this namespace is overridden by an intermediate root element. An extension specification may define attributes that can be applied to elements from other namespaces. Such such attributes must be prefixed by a prefix that is unique to that extension. Such a prefix MUST be registered in the HTML WG registry, together with it's namespace. If a document uses such a prefix, it MUST contain an xmlns declaration binding the prefix to its registered namespace, and the element with the xmlns declaration MUST have the @extension attribute set. In the future, if an extension becomes part of HTML, it is expected that the future version of the HTML standard will remove the requirement for the root element to declare its default namespace, or for there to be a namespace declaration for any prefixes. If a user agent supports an extension, and encounters a root element for that extension that does not have an xmlns declaration of an @extension attribute, then the user agent should behave as if both were present. Similarly, if a user agent supports an extension and encounters a registered prefix that does not have an xmlns declaration in the document, then it should act as if the prefix had been declared. These rules allow the user agent to behave correctly if the extension becomes part of standard HTML. unknown element contains an "xmlns" attribute, then it must be the same namespace that that element is associate with in the HTML WG extension root element registry. Section 8.2.3.1: The insertion mode After the following bullet: If node is an element from the MathML namespace or the SVG namespace, then set the foreign flag to true. insert the following bullet: If node has the "extension" attribute set and has an "xmlns" attribute, then set the foreign flag to true. Section 8.2.5.1: Creating and inserting elements Replace the following: If the newly created element has an xmlns attribute in the XMLNS namespace whose value is not exactly the same as the element's namespace, that is a parse error. with the following: If the newly created element has an xmlns attribute in the XMLNS namespace whose value is not exactly the same as the element's namespace, that is a parse error, unless the element has an "extension" attribute set. If the element has an "extension" attribute set, then this is an "extension prefix binding". The parser should record the binding between the prefix and the namespace, and use this to parse attributes later in the document with that prefix. Section 8.2.5.10: The "in body" insertion mode After the bullet called "A start tag whose tag name is 'svg'", insert the following: mode to "in foreign content". Section 8.1.2: Elements Replace Foreign elements Elements from the MathML namespace and the SVG namespace. with Foreign elements Elements from the MathML namespace, the SVG namespace, or an extension namespace. Remove the block quote that starts with "The HTML syntax does not support namespace declarations". Section 8.1.2.3: Attributes Replace No other namespaced attribute can be expressed in the HTML syntax. with When a element has an attribute with a prefix specified by an "extension prefix binding", the namespace of the attribute is that specified by the extension prefix binding. Impact Positive Effects - Future extensions can be added to HTML in the same way that SVG and MathML were integrated in the past - Provides guidelines for spec authors to help them write specs that work well with HTML - Helps user agents know what to expect from documents that use unknown extensions, and how to handle such documents gracefully - Extensions can be merged into a future version of HTML without the need for document to continue to support a previous syntax - Existing XML markup can be pasted directly into HTML, without having to worry about prefixes - A document can use extensions and parse correctly in both HTML and XML - Since "xmlns" only has meaning when the extension attribute is set, parsing behaviour is unchanged for pre-existing documents - Copy/paste problems with prefixes go away, since prefixed attributes have a fixed meaning. Negative Effects - Documents that use @extension and @xmlns will parse differently in older versions of HTML that do not support this feature. In older browsers, a prefixed attribute will be in the HTML namespace and will not be split into prefix and localname. Javascript that manipulates such attributes is recommended to use only nodeName and not localName unless they are sure their browser supports this feature. - If a document omits the namespace declaration for an extension root node, then the namespace of descendant elements will be different when parsed by user agents that support the extension or do not support it. This includes user agents that support a future version of HTML that includes the extension. This is also the case for SVG and MathML in HTML5. Conformance Classes Changes A new conformance class of "extended HTML" is defined, that allows an HTML document to contain prefixed attributes defined by an extension specification. Risks Unsure. References - HTML5 Working Draft as of 4th March 2010:
http://www.w3.org/html/wg/wiki/index.php?title=ChangeProposals/extensionslikesvg&redirect=no
CC-MAIN-2014-52
refinedweb
2,005
53.65
django-fab-deploy 0.7.4 Django deployment tool django-fab-deploy is a collection of Fabric scripts for deploying and managing django projects on Debian/Ubuntu servers. License is MIT. Please read the docs for more info. CHANGES 0.7.4 (2012-03-01) - django-fab-deploy now is compatible with fabric 1.4 (and require fabric 1.4); - nginx and wsgi scripts are now compatible with upcoming django 1.4; example of django 1.4 project configuration is added to guide; - shortcut for passing env defaults in define_host decorator; - Ubuntu 10.04 apache restarting fix; - config_templates/hgrc is removed; - tests are updated for fabtest >= 0.1; - apache_is_running function. In order to upgrade install fabric >= 1.4 and make sure your custom scripts work. 0.7.3 (2011-10-13) - permanent redirect from to domain.com is added to the default nginx config. Previously they were both available and this leads to e.g. authorization issues (user logged in at was not logged in at domain.com with default django settings regarding cookie domain). 0.7.2 (2011-06-14) - Ubuntu 10.04 (lucid) initial support (this needs more testing); - backports for Ubuntu 10.04 and 10.10; - docs are now using default theme; - remote django management command errors are no longer silinced; - invoking create_linux_account with non-default username is fixed; - define_host decorator for easier host definition; - default DB_USER value (‘root’) is deprecated; - default nginx config uses INSTANCE_NAME for logs. In order to upgrade please set DB_USER to ‘root’ explicitly in env.conf if it was omitted. 0.7.1 (2011-04-21) - DB_ROOT_PASSWORD handling is fixed 0.7 (2011-04-21) - requirement for root ssh access is removed: django-fab-deploy is now using sudo internally (thanks Vladimir Mihailenco); - better support for non-root mysql users, mysql_create_user and mysql_grant_permissions commands were added (thanks Vladimir Mihailenco); - hgrc is no more required; - ‘synccompress’ management command is no longer called during fab up; - coverage command is disabled; - nginx_setup and nginx_install are now available in command line by default; - mysqldump no longer requires project dir to be created; - home dir for root user is corrected; - utils.detect_os is now failing loudly if detection fails; - numerous test running improvements. In order to upgrade from previous verions of django-fab-deploy, install sudo on server if it was not installed: fab install_sudo 0.6.1 (2011-03-16) - verify_exists argument of utils.upload_config_template function was renamed to skip_unexistent; - utils.upload_config_template now passes all extra kwargs directly to fabric’s upload_template (thanks Vladimir Mihailenco); - virtualenv.pip_setup_conf command for uploading pip.conf (thanks Vladimir Mihailenco); - deploy.push no longer calls ‘synccompress’ management command; - deploy.push accepts ‘before_restart’ keyword argument - that’s a callable that will be executed just before code reload; - fixed regression in deploy.push command: ‘notest’ argument was incorrectly renamed to ‘test’; - customization docs are added. 0.6 (2011-03-11) - custom project layouts support (thanks Vladimir Mihailenco): standard project layout is no longer required; if the project has pip requirements file(s) and a folder with web server config templates it should be possible to use django-fab-deploy for deployment; - git uploads support (thanks Vladimir Mihailenco); - lxml installation is fixed; - sqlite deployments are supported (for testing purposes).' 0.5.1 (2011-02-25) - Python 2.5 support for local machine (it was always supported on servers). Thanks Den Ivanov. 0.5 (2011-02-23) - OS is now auto-detected; - Ubuntu 10.10 maverick initial support (needs better testing?); - fabtest package is extracted from the test suite; - improved tests; - fab_deploy.system.ssh_add_key can now add ssh key even if it is the first key for user; - ‘print’ calls are replaced with ‘puts’ calls in fabfile commands; - django management commands are not executed if they are not available.. 0.4.2 (2011-02-16) - tests are included in source distribution 0.4.1 (2011-02-14) - don’t trigger mysql 5.1 installation on Lenny 0.4 (2011-02-13) - env.conf.VCS: mercurial is no longer required; - undeploy command now removes virtualenv. 0.3 (2011-02-12) - Debian Squeeze support; - the usage of env.user is discouraged; - fab_deploy.utils.print_env command; - fab_deploy.deploy.undeploy command; - better run_as implementation. In order to upgrade from 0.2 please remove any usages of env.user from the code, e.g. before upgrade: def my_site(): env.hosts = ['example.com'] env.user = 'foo' #... After upgrade: def my_site(): env.hosts = ['foo@example.com'] #... 0.2 (2011-02-09) - Apache ports are now managed automatically; - default threads count is on par with mod_wsgi’s default value; - env.conf is converted to _AttributeDict by fab_deploy.utils.update_env. This release is backwards-incompatible with 0.1.x because of apache port handling changes. In order to upgrade, - remove the first line (‘Listen …’) from project’s config_templates/apache.config; - remove APACHE_PORT settings from project’s fabfile.py; - run fab setup_web_server from the command line. 0.1.2 (2011-02-07) - manual config copying is no longer needed: there is django-fab-deploy script for that 0.1.1 (2011-02-06) - cleaner internals; - less constrains on project structure, easier installation; - default web server config improvements; - linux user creation; - non-interactive mysql installation (thanks Andrey Rahmatullin); - new documentation. 0.0.11 (2010-01-27) - fab_deploy.crontab module; - cleaner virtualenv management; - inside_project decorator. this is the last release in 0.0.x branch. 0.0.8 (2010-12-27) Bugs with multiple host support, backports URL and stray ‘pyc’ files are fixed. 0.0.6 (2010-08-29) A few bugfixes and docs improvements. 0.0.2 (2010-08-04) Initial release. - Author: Mikhail Korobov - Documentation: django-fab-deploy package documentation - Download URL: - License: MIT license - Requires Fabric (>=1.4.0), jinja2 - Package Index Owner: kmike - DOAP record: django-fab-deploy-0.7.4.xml
https://pypi.python.org/pypi/django-fab-deploy
CC-MAIN-2017-39
refinedweb
960
52.15
What: $neutralDark: $neutral: $neutralLight: $neutralLighter: $neutralLightest: Silvestar Bistrović: How might you pick names for colors? You might get a kick out of what to call a sunny yellow versus a sunflower yellow, or you might just want some help. Here’s one project for that, and here’s another: See the Pen Color Namer by Maneesh (@maneeshc) on CodePen. There is even a Sublime Text plugin for converting them (to whatever syntax you want): And since we’re on the topic of naming: I personally use Chir.ag’s Name that Color utility. I’ve been using it for years and I LOVE it. I first give a name to all the colors I use using that tool, for example “$color-cornflower-blue: #6195ED;” and then I create variables like $nav-bg-color: $color-cornflower-blue. That way if I ever need need to update a color, I update it in a single location, on a single variables file. Ha! I just named a color variable $cornfloweryesterday. :) I’ve generally stuck to themes (typically fruit) butI really like the idea appending the actual color on there — hadn’t considered that. I do this too, but with the help of an app. Sipapp.io uses a lot of those color names by default, so I’ve created some custom formatters so I can just cmd+click the colour dock and have it added to my code. Gave up on naming colors after reading David Walsh’s post: Pretty much this. Best flexibility you can get. Opps, just saw your comment after adding my own. I also use this website (have done so for the past 4-ish years). I also use this technique. It’s easier to navigate, for me, and when i need to change a color slightly, i change the values. When i need to radically change the color, i switch the variable in the attributes. I’m using variables in this way. I try never to use colournames or positions. So everything can change easily. To avoid ‘look-a-like colors’ I use with great joy for many years. Implementing these color-name-variables I use the same tactic as Emma does. I use both color names as variables, and UI color configuration variables. Here’s what I mean: I like this because I pull partials from project to project while changing the brand colors. This way I only need to configure colors in one place rather than following my compiler errors all over the place. I also prefix variables so I can use my autocomplete tooling in Visual Code to look them up quickly. I like to think of my variables file almost as a “class” with publicand privateproperties for colors and sizes. For colors, I’ll typically really only use brand/theme-related colors, a palette of grays, and status colors (like success, warning, danger, info). In this case my “private” colors that I only use within my variables file would be a one-to-one for a named color and a hex code, like or possibly further variants like:to $sprucethroughout many files.. lowering saturation when rising brightness, and vice-versa. It definitely depends on the project I’m working on. If there are set guidelines, I have to follow them, but if I’m playing around for myself, I’m using names that are descriptive for me and will remember 6 months from now. You can watch my latest video where I use them to give color on the website I’m creating Having worked on the AngularJS Material team, I’m partial to Primary, Accent, and Warn. But I also use the material colors like “green-500”. But I don’t use the same values. I use the rgb values to use custom opacity. And then I use CSS variables as a theming mechanic: I use this website to name all my SCSS colour variables — I never have much trouble coming up with variable names for colors in my css, I use the same principle in every project. For brand colors I use the folowing: $color-brand-1st, $color-brand-2nd, etc… When there are lighter and darker variants of color I just put -lightor -dark. Behind them. I try to have a maximum of 5 color variants per color. My color definitions would look something like this: I generaly strike to be as abstract as i can because lets say we ha a variable called $red: red. Now if the brand identity changed to blue we would have $red: blue. Which is confusing. I have tried many different approaches to naming conventions and found that the following works fine. Define meaningful color names – they should either come from an online color pallette eg. – or from brand guidelines eg. $toyota-red: #fc0000; Map meaningful names to actual implementations: It’s a simple approach, but proxying implementation colors to our defined colors means we can change the implementation without breaking or renaming the actual colors, just be sure to not use the meaningful colors directly. Neil I personnally prefer having 2 level of abstraction for colors: 1. I name all my colors ( $eerie_black: #0d1321, $mesty_rose: #ffeddf, $flame: #d85922, etc.) 2. I add the second layer: with semantic names: $color-primary-default: $flame, $color-text-default: $eerie_black, etc.) The first layer goal is to give a more human freindly name to colors and lets you use them as basis. The second is the one I’ll use over all my css. To help remembering the names I always use go from the more global to the more specific (level 1 : color/size/etc., level 2: primary/accent/warning/etc., level3: default/lighter/etc.) with this method I can have the autocomplete helping me to remember the names and suggest the good variable. This also helps me with theme swipping or color changes over the app/site I very often try to keep names semantic. For example, when I define “accent”, I don’t want to know whether it is yellow, green or blue. I just want to know that this is the color used for accents. Same goes for “leading text” etc. Sometimes I do break this rule and name those variables with color names. But this tends to bite me right after I do this, especially when the project is just starting. We are using the sketch plugIn prism to generate color names. The plugIn generates the names of the colors. Another benefit is the same color naming in sketch and css. I’ve been doing it like this for years (firstly with LESS, and now with SASS): Then consume base colors at component level – e.g. buttons: I like this one! I always go with simple $red, $blue, $dark-green, etc. and I keep all of my global variables (usually that also includes @media breakpoints and often general spacing units) in the same place, either at the top of the file if there’s just a single stylesheet or in a variables-specific file. I see the benefits of other naming conventions, but with my general organizational system this works well. If I have brand colors to work with, instead of just setting $primary-color or –primaryColor to a hex value, I’ll define the colors as before and then assign those SCSS variables to the CSS variable properties. That way I can set –primaryColor for an entire section or page or site but still have clearly named values associated with it, and it makes it easy to change the –primaryColor in an intuitive way. I started to use on this way, but sometimes just get too long =( :root{ } --c-primary:#66287f; --c-primary-dark:#270036; --c-secundary:#00c5cd; --c-text-primary:#ffffff; --c-text-secundary:#656565; --c-text-secundary-light:#cccccc; --c-aux:#d68b00; Call me old fashioned, but I like to call my colours after the names of my colours. Blue being blue, red being red, and grey being light-grey… or medium-grey. It’s my current project, WIP stuff. So, there were some mistakes $grey-l20 should be hsl(0, 2%, 20%), of cause and $color-secondary: $grey-l16. What I’m exploring right now is a mix of multiple naming schemes. Sometimes you want a specific color (e.g. the warm color for a warning), sometimes you just want whatever the accent color is. To be semantic, you should be able to reference either. So, I define variables like –color-green, –color-red etc, and then alias them, like –color-accent: var(–color-red); etc. Time will show how this will do, but so far it seems better than picking an individual naming scheme. My struggle with colors: I don’t actually reference any colour directly in my actual css. I create maps that parallel my ITCSS architecture, where successive maps reference only preceding ones as much as possible, in a theme file at the start, and then use a helper function to return whatever token (doesn’t have to be a colour; I have a sister config file with spacing, font-size, etc.), passing it the map and a list of strings that is the path through the map to the value. Huge benefit of this is to allow use of defaults and graceful failure for undefined values and a self-documenting cascade. Re: defaults: if a value isn’t defined, but the rest of the path is valid, it’ll look for a ‘default’ key, even halfway through the path. So I would reference a component colour through that component’s map, but it would reference the fill map, or the type map, etc., which would ultimately reference a generic colours map, where each value is named according to whatever colour it literally is. so token($btn, fill)would resolve to #00fgiven the following maps: And all it takes to set up a theme is to declare a duplicate structure (or however much of it is needed) in some preceding custom theme file, wherever that may be, and in the base theme file do this instead: I use name-that-colorby Chirag Mehta and it’s absolutely golden. I struggled with naming color variables for years – since I discovered named+abstract colors I never looked back. I typically use the song titles of the album I am listening to a lot, i find this keeps me more engaged I feel like I went through the same journey of color variable naming as you described in the beginning of your article. One thing that has helped me recently is Visual Studio Code’s Intellisense of A) telling me the value of a sass variable when I hover over it and B) suggesting variable names as I start to type them. Sorry not sure if it was out of the box functionality or if it was a Sass plugin I installed. Thanks for the great article! Hi! Thanks for sharing! Several years ago I designed enterprise color framework to be used for all our applications. The idea was quite simple, color names should not refer to a specific color or UI element. So I broke down colors into several meaningful types: – Fills – Strokes – Lines – Text – Alt colors Then I broke down each type into categories: – Basic: Most of the UI elements are using these colors – Contrast: Dark colors for all high contrast elements – Accent: Colors for CTA elements – Text: Colors to support typography – Generic: Generic colors And finally I’ve introduced gradients for each category – Strong – Medium – Base – Light – Subtle So I ended up with some sort of hierarchical namespace for the whole palette. We do support light and dark color themes and the color framework worked out quite well. Each palette is defined in XML file and converted into corresponding *.scss file during project build. This approach prove itself to be very flexible and time saving on large projects. By the way, Microsoft introduced something very similar for their UWP apps – Seeing how naming things is hard, I’ve created a npm library for this: And a VS Code extension: Maybe this is helpful to someone else :)
https://css-tricks.com/what-do-you-name-color-variables/
CC-MAIN-2022-21
refinedweb
2,020
61.36
's very useful to know which other OSes work and *how* they work.If another OS (particularly a popular one like Windows) works, and weknow it's using the ACPI namespace, that tells us we need a changelike yours. If another OS works but is using SPMI, that tells usnothing about whether we should make this change.If no other OS uses the namespace, then we might be adding a Linuxchange just to deal with a firmware defect on this machine, and thatsort of change could easily break other machines.I don't think that's the case here; I think we *should* make thechange you're proposing. But it's just a good practice to bediligent about documenting the reasons for the changes we make.Bjorn
https://lkml.org/lkml/2010/7/27/265
CC-MAIN-2017-34
refinedweb
127
68.4
table of contents NAME¶ bsearch - binary search of a sorted array SYNOPSIS¶ #include <stdlib.h> void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); DESCRIPTION¶. RETURN VALUE¶ The bsearch() function returns a pointer to a matching member of the array, or NULL if no match is found. If there are multiple elements that match the key, the element returned is unspecified. ATTRIBUTES¶ For an explanation of the terms used in this section, see attributes(7). CONFORMING TO¶ POSIX.1-2001, POSIX.1-2008, C89, C99, SVr4, 4.3BSD. EXAMPLES¶) { const struct mi *mi1 = m1; const struct mi *mi2 = m2; return strcmp(mi1->name, mi2-->name, res->nr); } exit(EXIT_SUCCESS); } SEE ALSO¶ hsearch(3), lsearch(3), qsort(3), tsearch(3) COLOPHON¶ This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at
https://dyn.manpages.debian.org/bullseye/manpages-dev/bsearch.3.en.html
CC-MAIN-2022-21
refinedweb
163
65.42
![endif]--> Processing is an open source language/ development tool for writing programs in other computers. Useful when you want those. Library for Processing v2.0: processing2-arduino.zip (Updated 6 Nov. 2013) (properties file here: processing2-arduino.txt) Library for Processing v1.5: processing-arduino.zip (Updated 11 Nov. 2011) (properties file here: processing-arduino.txt) Note: if you run Linux, you need to change Arduino.jar into arduino.jar, because Linux is case sensitive and it does not work if you don't change this letter (Arduino.jar is in the folder "library" of this Processing Library). [0]in this line arduino = new Arduino(this, Arduino.list()[0], 57600);To find the correct item in the array, run this code in Processing: import processing.serial.*; import cc.arduino.*; println(Arduino.list());The output window will enumerate your serial ports. Select the number corresponding to the serial port in your Arduino environment found under Tools > Serial Port. These functions are in the Processing Arduino Library and communicate (from Processing) with a Arduino, upon which the Firmata sketch has been installed. Arduino.list(): returns a list of the available serial devices. If your Arduino board is connected to the computer when you call this function, its device will be in the list. Arduino(parent, name, rate): create an Arduino object. Parent should be "this" (without the quotes); name is the name of the serial device (i.e. one of the names returned by Arduino.list()); rate is the speed of the connection (typically 57600). Note that in the v2 library, the rate parameter is optional. pinMode(pin, mode): set a digital pin to input, output, or servo mode (Arduino.INPUT, Arduino.OUTPUT, or Arduino.SERVO). digitalRead(pin): returns the value of a digital pin, either Arduino.LOW or Arduino.HIGH (the pin must be set as an input). digitalWrite(pin, value): writes Arduino.LOW or Arduino.HIGH to a digital pin. analogRead(pin): returns the value of an analog input (from 0 to 1023). analogWrite(pin, value): writes an analog value (PWM wave) to a digital pin that supports it (pins 3, 5, 6, 9, 10, and 11); value should be from 0 (always off) to 255 (always on). servoWrite(pin, value): writes a value to a servo motor; value should be from 0 to 180.); } If you're having trouble getting this to work, you can ask for help in the Arduino Forum. If you've found a bug in the Arduino (Firmata) library for Processing, please report it on the GitHub issues list.
http://playground.arduino.cc/Interfacing/Processing
CC-MAIN-2016-18
refinedweb
424
61.02
How to Play, Record and Merge Videos in iOS and Swift Learn the basics of working with videos on iOS with AV Foundation in this tutorial. You’ll play, record and even do some light video editing! Version - Swift 5, iOS 13, Xcode 11 Recording videos and playing around with them programmatically is one of the coolest things you can do with your phone. However, not nearly enough apps offer this ability, which you can easily add using the AV Foundation framework. AV Foundation has been a part of macOS since OS X Lion (10.7) and iOS since iOS 4 in 2010. It’s grown considerably since then, with well over 100 classes to date. This tutorial gets you started with AV Foundation by covering media playback and some light editing. In particular, you’ll learn how to: - Select and play a video from the media library. - Record and save a video to the media library. - Merge multiple clips into a single, combined video complete with a custom soundtrack. Avoid running the code in this tutorial on the simulator because. A free account will work just fine for this tutorial. Ready? Lights, cameras, action! Getting Started Download the project materials by clicking the Download Materials button at the top or bottom of the tutorial. Open the starter project and look around. This project contains a storyboard and several view controllers with the UI for a simple video playback and recording app. The main screen contains the three buttons below, which segue to other view controllers: - Select and Play Video - Record and Save Video - Merge Video Build and run and test the buttons. Only the three buttons in the initial scene do anything, but you’ll change that soon! Selecting and Playing Video The Select AVKit import MobileCoreServices Importing AVKit gives you access to AVPlayer, which plays the selected video. MobileCoreServices contains predefined constants such as kUTTypeMovie, which you’ll need later on. Next, add the following class extensions at the end of the file. Make sure PlayVideoViewController to adopt the UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols. You’ll use the system-provided UIImagePickerController to let the user browse videos in the photo library. That class communicates back to your app through these delegate protocols. Although the class is named “image picker”, rest assured it works with videos too! Next, head back to PlayVideoViewController‘s main class definition and add the following code to playVideo(_:): VideoHelper.startMediaBrowser(delegate: self, sourceType: .savedPhotosAlbum) This is a call to a helper method called startMediaBrowser(delegate:sourceType:) from VideoHelper. This call will open the image picker, setting the delegate to self. The source type of .savedPhotosAlbum opts to choose an image from the camera roll. Later, you’ll add helper tools of your own in VideoHelper. To see what’s under the hood of this method, open VideoHelper.swift. It does the following: - Checks if the source is available on the device. Sources include the camera roll, the camera itself and the full photo library. This check is essential whenever you use UIImagePickerControllerto pick media. If you don’t do it, you might try to pick media from a non-existent source, which will usually result in a crash. - If the source you want is available, it creates a UIImagePickerControllerand sets its source and media type. Since you only want to select videos, the code restricts the type to kUTTypeMovie. - Finally, it presents UIImagePickerControllermodally. Now, you’re ready to give your project another whirl! Build and run. Tap Select and Play Video on the first screen, then tap Play Video on the second screen. The camera roll will pop up like this: Once you see the list of videos, select one. You’ll proceed to another screen that shows the video in detail, along with buttons to Cancel, Play and Choose. Tap the Play button and, unsurprisingly, the video will play. If you tap the Choose button, however, the app just returns to the Play Video screen! This is because you haven’t implemented any delegate methods to handle choosing a video from the picker. Back in Xcode open PlayVideoViewController.swift again and find the UIImagePickerControllerDelegate extension. Then add the following delegate method implementation: func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { // 1 guard let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String, mediaType == (kUTTypeMovie as String), let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL else { return } // 2 dismiss(animated: true) { //3 let player = AVPlayer(url: url) let vcPlayer = AVPlayerViewController() vcPlayer.player = player self.present(vcPlayer, animated: true, completion: nil) } } Here’s what you’re doing in this method: - You get the media type of the selected media and URL and ensure it’s a video. - Next, you dismiss the image picker. - In the completion block, you create an AVPlayerViewControllerto play the media. Build and run. Tap Select and Play Video, then Play Video and choose a video from the list. The video will play in the media player. Recording Video Now that you have video playback working, it’s time to record a video using the device’s camera and save it to the media library. Open RecordVideoViewController.swift and add the following import: import MobileCoreServices Then, add the following to the end of the file: // MARK: - UIImagePickerControllerDelegate extension RecordVideoViewController: UIImagePickerControllerDelegate { } // MARK: - UINavigationControllerDelegate extension RecordVideoViewController: UINavigationControllerDelegate { } This adopts the same protocols as PlayVideoViewController. Next, add the following code to record(_:): VideoHelper.startMediaBrowser(delegate: self, sourceType: .camera) It uses the same helper method as in PlayVideoViewController, except that it accesses .camera to instruct the image picker to open in the built in camera mode. Build and run to see what you have so far. Go to the Record screen and tap Record Video. Instead of the Photo Gallery, the camera UI opens. When the alert dialog asks for camera permissions and microphone permissions, click OK. Finally, start recording a video by tapping the red record button at the bottom of the screen; tap it again when you’re done recording. Now, you have two options: use the recorded video or do a retake. Tap Use Video. You’ll notice that it just dismisses the view controller. That’s because — you guessed it — you haven’t implemented an appropriate delegate method to save the recorded video to the media library. Saving Video Back in RecordVideoViewController.swift, add the following method to the UIImagePickerControllerDelegate extension: func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { dismiss(animated: true, completion: nil) guard let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String, mediaType == (kUTTypeMovie as String), // 1 let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL, // 2 UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(url.path) else { return } // 3 UISaveVideoAtPathToSavedPhotosAlbum( url.path, self, #selector(video(_:didFinishSavingWithError:contextInfo:)), nil) } Don’t worry about the error — you’ll take care of that shortly. - As before, the delegate method gives you a URL pointing to the video. - Verify that the app can save the file to the device’s photo album. - If it can, save it. UISaveVideoAtPathToSavedPhotosAlbum is the function provided by the SDK to save videos to the device’s photo album. You pass it the path to the video you want to save as well as a target and action to call back, which will inform you of the status of the save operation. Next, add the implementation of the callback to the main class definition: @objc func video( _ videoPath: String, didFinishSavingWithError error: Error?, contextInfo info: AnyObject ) { let title = (error == nil) ? "Success" : "Error" let message = (error == nil) ? "Video was saved" : "Video failed to save" let alert = UIAlertController( title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction( title: "OK", style: UIAlertAction.Style.cancel, handler: nil)) present(alert, animated: true, completion: nil) } The callback method simply displays an alert to the user, announcing whether the video file was saved or not, based on the error status. Build and run. Record a video and select Use Video when you’re done recording. If you’re asked for permission to save to your video library, tap OK.. Your user will select two videos and a song from the music library, and the app will combine the two videos and mix in the music. The project already has a starter implementation in MergeVideoViewController.swift, with the code similar to the code you wrote to play a video. The big difference is when merging, the user must select two videos. That part is already set up, so the user can make two selections that will be stored in firstAsset and secondAsset. The next step is to add the functionality to select the audio file. Selecting the Audio File UIImagePickerController provides functionality to select only video and images from the media library. To select audio files from your music library, you must use(mediaPickerController, animated: true, completion: nil) The code above creates a new MPMediaPickerController instance and displays it as a modal view controller. Build and run. Now, tap Merge Video, then Load Audio. Select a song from the list and you’ll notice that nothing happens. That’s right! MPMediaPickerController needs delegate methods! To implement them, find the MPMediaPickerControllerDelegate extension at the bottom of the file and add the following two methods to it: func mediaPicker( _ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection ) { // 1 dismiss(animated: true) { // 2 let selectedSongs = mediaItemCollection.items guard let song = selectedSongs.first else { return } // 3 let title: String let message: String if let url = song.value(forProperty: MPMediaItemPropertyAssetURL) as? URL { self.audioAsset = AVAsset(url: url) title = "Asset Loaded" message = "Audio Loaded" } else { self.audioAsset = nil title = "Asset Not Available" message = "Audio Not Loaded" } // 4 let alert = UIAlertController( title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) { // 5 dismiss(animated: true, completion: nil) } The code above is similar to the delegate methods for UIImagePickerController. Here’s what it does: - Dismiss the picker just like you did before. - Find the selected songs and, from that, the first one in the case that multiple are selected. - Obtain the URL to the media asset that backs the song. Then make an AVAssetpointing to the song that was chosen. - Finally, for mediaPicker(_:didPickMediaItems:), show an alert to indicate if the asset was successfully loaded or not. - In the case the media picker was canceled, simply dismiss the view controller. Build and run, then go to the Merge Videos screen. Select an audio file and you’ll see the Audio Loaded message. You now have all your assets loading correctly so it’s time to merge the various media files into one file. But before you get into that code, you need to do a bit of setup. Merging Completion Handler You will shortly write the code to merge your assets. This will need a completion handler that saves the final video to the photo album. You’ll add this first. Add the following import statement at the top of the MergeVideoViewController.swift file: import Photos Then, add the method below to MergeVideoViewController: func exportDidFinish(_ session: AVAssetExportSession) { // 1 activityMonitor.stopAnimating() firstAsset = nil secondAsset = nil audioAsset = nil // 2 guard session.status == AVAssetExportSession.Status.completed, let outputURL = session.outputURL else { return } // 3 let saveVideoToPhotos = { // 4 let changes: () -> Void = { PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputURL) } PHPhotoLibrary.shared().performChanges(changes) { saved, error in DispatchQueue.main.async { let success = saved && (error == nil) let title = success ? "Success" : "Error" let message = success ? "Video saved" : "Failed to save video" let alert = UIAlertController( title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction( title: "OK", style: UIAlertAction.Style.cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } } // 5 if PHPhotoLibrary.authorizationStatus() != .authorized { PHPhotoLibrary.requestAuthorization { status in if status == .authorized { saveVideoToPhotos() } } } else { saveVideoToPhotos() } } Here’s what that code does: - There’s a spinner that will animate when the assets are being processed. This stops the spinner and then clears the assets ready to select new ones. - Ensure that the processing is complete and there is a URL of the resulting video. - Create a closure that… - Tells the photo library to make a “create request” from the resulting video before showing an alert to indicate if this succeeds or fails. - Check if there is permission to access the photo library. If there is not permission, then ask for it before running the closure that saves the video. Otherwise, simply run the closure immediately as permission is already granted. Now, you’ll add some code to merge(_:). Because there’s a lot of code, you’ll complete this in steps. Merging: Step 1 In this step, you’ll merge the videos into one long video. Add the following code to merge(_:): guard let firstAsset = firstAsset, let secondAsset = secondAsset else { return } activityMonitor.startAnimating() // 1 let mixComposition = AVMutableComposition() // 2 guard let firstTrack = mixComposition.addMutableTrack( withMediaType: .video, preferredTrackID: Int32(kCMPersistentTrackID_Invalid)) else { return } // 3 do { try firstTrack.insertTimeRange( CMTimeRangeMake(start: .zero, duration: firstAsset.duration), of: firstAsset.tracks(withMediaType: .video)[0], at: .zero) } catch { print("Failed to load first track") return } // 4 guard let secondTrack = mixComposition.addMutableTrack( withMediaType: .video, preferredTrackID: Int32(kCMPersistentTrackID_Invalid)) else { return } do { try secondTrack.insertTimeRange( CMTimeRangeMake(start: .zero, duration: secondAsset.duration), of: secondAsset.tracks(withMediaType: .video)[0], at: firstAsset.duration) } catch { print("Failed to load second track") return } // 5 // TODO: PASTE CODE A In the code above: - You create an AVMutableCompositionto hold your video and audio tracks. - Next, you create an AVMutableCompositionTrackfor the video and add it to your AVMutableComposition. - Then, you insert the video from the first video asset to this track. Notice that insertTimeRange(_:ofTrack:atStartTime:)allows you to insert a part of a video, rather than the whole thing, into your main composition. This way, you can trim the video to a time range of your choice. In this instance, you want to insert the whole video, so you create a time range from CMTime.zeroto your video asset duration. - Next, you do the same thing with the second video asset. Notice how the code inserts firstAssetat time .zero, and it inserts secondAssetat the end of the first video. That’s because this tutorial assumes you want your video assets one after the other, but you can also overlap the assets by playing with the time ranges. // TODO: PASTE CODE Ais a marker — you’ll replace this line with the code in the next section. In this step, you set up two separate AVMutableCompositionTrack instances. Now, you need to apply an AVMutableVideoCompositionLayerInstruction to each track to make some editing possible. Merging the Videos: Step 2 Next up is to add instructions to the composition to tell it how you want the assets to be merged. Add the next section of code after track code above in merge(_:). Replace // TODO: PASTE CODE A with the following code: // 6 let mainInstruction = AVMutableVideoCompositionInstruction() mainInstruction.timeRange = CMTimeRangeMake( start: .zero, duration: CMTimeAdd(firstAsset.duration, secondAsset.duration)) // 7 let firstInstruction = AVMutableVideoCompositionLayerInstruction( assetTrack: firstTrack) firstInstruction.setOpacity(0.0, at: firstAsset.duration) let secondInstruction = AVMutableVideoCompositionLayerInstruction( assetTrack: secondTrack) // 8 mainInstruction.layerInstructions = [firstInstruction, secondInstruction] let mainComposition = AVMutableVideoComposition() mainComposition.instructions = [mainInstruction] mainComposition.frameDuration = CMTimeMake(value: 1, timescale: 30) mainComposition.renderSize = CGSize( width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) // 9 // TODO: PASTE CODE B Here’s what’s happening in this code: - First, you set up mainInstructionto wrap the entire set of instructions. Notice that the total time here is the sum of the first asset’s duration and the second asset’s duration. - Next, you set up two instructions, one for each asset. The instruction for the first video needs one extra addition: You set its opacity to 0 at the end so it becomes invisible when the second video starts. - Now that you have your AVMutableVideoCompositionLayerInstructioninstances for the first and second tracks, you simply add them to mainInstruction. Next, you add mainInstructionto the instructions property of an instance of AVMutableVideoComposition. You also set the frame rate for the composition to 30 frames/second. // TODO: PASTE CODE Bis a marker — you’ll replace this line with the code in the next section. OK, so you’ve now merged your two video files. It’s time to spice them up with some sound! Merging the Audio: Step 3 To give your clip some musical flair, add the following code to merge(_:). Replace // TODO: PASTE CODE B with the following code: // 10 if let loadedAudioAsset = audioAsset { let audioTrack = mixComposition.addMutableTrack( withMediaType: .audio, preferredTrackID: 0) do { try audioTrack?.insertTimeRange( CMTimeRangeMake( start: .zero, duration: CMTimeAdd( firstAsset.duration, secondAsset.duration)), of: loadedAudioAsset.tracks(withMediaType: .audio)[0], at: .zero) } catch { print("Failed to load Audio track") } } // 11 guard let documentDirectory = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask).first else { return } let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .short let date = dateFormatter.string(from: Date()) let url = documentDirectory.appendingPathComponent("mergeVideo-\(date).mov") // 12 guard let exporter = AVAssetExportSession( asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) else { return } exporter.outputURL = url exporter.outputFileType = AVFileType.mov exporter.shouldOptimizeForNetworkUse = true exporter.videoComposition = mainComposition // 13 exporter.exportAsynchronously { DispatchQueue.main.async { self.exportDidFinish(exporter) } } Here’s what the code above does: - Similarly to video tracks, you create a new track for your audio and add it to the main composition. You set the audio time range to the sum of the duration of the first and second videos, because that will be the complete length of your video. - Before you can save the final video, you need a path for the saved file. Create a unique file name based upon the current date and time that points to a file in the documents folder. - Render and export the merged video. To do this, you create an AVAssetExportSessionthat transcodes the contents of the composition to create an output of the form described by a specified export preset. Because you’ve already configured AVMutableVideoComposition, all you need to do is assign it to your exporter. - After you’ve initialized an export session with the asset that contains the source media, the export presetNameand outputFileType, you run the export by invoking exportAsynchronously(). Because the code performs the export asynchronously, this method returns immediately. The code calls the completion handler you supply to exportAsynchronously()whether the export fails, completes or the user cancels it. Upon completion, the exporter’s status property indicates whether the export has completed successfully. If it fails, the value of the exporter’s error property supplies additional information about the reason for the failure. AVComposition combines media data from multiple file-based sources. At its top level, before and that will come up again. Finally, build and run. Select two videos and an audio file and merge the selected files. You’ll see a Video Saved message, which indicates that the merge was successful. At this point, your new video will be present in the photo album. Go to the photo album or browse using the Select and Play Video screen in the app and you might notice some orientation issues in the merged video. Maybe portrait video is in landscape mode, and sometimes videos are upside down. This is due to the default AVAsset orientation. All movie and image files recorded using the default iPhone camera app have the video frame set to landscape, so the iPhone saves the media in landscape mode. You’ll fix these problems next. Orienting Video AVAsset has a preferredTransform that contains the media orientation information. It applies this to a media file whenever you view it using the Photos app or QuickTime. In the code above, you haven’t applied a transform to your AVAssets, hence the orientation issue. Fortunately, this is an easy fix. Before you can do it, however, you need to add the following helper method to VideoHelper in VideoHelper.swift: static func orientationFromTransform( _ transform: CGAffineTransform ) -> (orientation: UIImage.Orientation, isPortrait: Bool) { var assetOrientation = UIImage.Orientation.up var isPortrait = false let tfA = transform.a let tfB = transform.b let tfC = transform.c let tfD = transform.d if tfA == 0 && tfB == 1.0 && tfC == -1.0 && tfD == 0 { assetOrientation = .right isPortrait = true } else if tfA == 0 && tfB == -1.0 && tfC == 1.0 && tfD == 0 { assetOrientation = .left isPortrait = true } else if tfA == 1.0 && tfB == 0 && tfC == 0 && tfD == 1.0 { assetOrientation = .up } else if tfA == -1.0 && tfB == 0 && tfC == 0 && tfD == -1.0 { assetOrientation = .down } return (assetOrientation, isPortrait) } This code analyzes an affine transform to determine the input video’s orientation. Next, add the following import: import AVFoundation and one more helper method to the class: static func videoCompositionInstruction( _ track: AVCompositionTrack, asset: AVAsset ) -> AVMutableVideoCompositionLayerInstruction { // 1 let instruction = AVMutableVideoCompositionLayerInstruction(assetTrack: track) // 2 let assetTrack = asset.tracks(withMediaType: AVMediaType.video)[0] // 3 let transform = assetTrack.preferredTransform let assetInfo = orientationFromTransform(transform) var scaleToFitRatio = UIScreen.main.bounds.width / assetTrack.naturalSize.width if assetInfo.isPortrait { // 4 scaleToFitRatio = UIScreen.main.bounds.width / assetTrack.naturalSize.height let scaleFactor = CGAffineTransform( scaleX: scaleToFitRatio, y: scaleToFitRatio) instruction.setTransform( assetTrack.preferredTransform.concatenating(scaleFactor), at: .zero) } else { // 5 let scaleFactor = CGAffineTransform( scaleX: scaleToFitRatio, y: scaleToFitRatio) var concat = assetTrack.preferredTransform.concatenating(scaleFactor) .concatenating(CGAffineTransform( translationX: 0, y: UIScreen.main.bounds.width / 2)) if assetInfo.orientation == .down { let fixUpsideDown = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) let windowBounds = UIScreen.main.bounds let yFix = assetTrack.naturalSize.height + windowBounds.height let centerFix = CGAffineTransform( translationX: assetTrack.naturalSize.width, y: yFix) concat = fixUpsideDown.concatenating(centerFix).concatenating(scaleFactor) } instruction.setTransform(concat, at: .zero) } return instruction } This method takes a track and an asset and returns a AVMutableVideoCompositionLayerInstruction which wraps the affine transform needed to get the video right-side up. Here’s what’s going on, step-by-step: - You create AVMutableVideoCompositionLayerInstructionand associate it with your track. - Next, you create AVAssetTrackfrom your AVAsset. An AVAssetTrackprovides the track-level inspection interface for all assets. You need this object to access the dimensions of the asset and preferredTransform. - Then, you save the preferred transform and the amount of scale required to fit the video to the current screen. You’ll use these values in the following steps. - If the video is in portrait, you need to recalculate the scale factor — the default calculation is for videos in landscape. All you need to do then is apply the orientation rotation and scale transforms. - If the video is in landscape, there’s a similar set of steps to apply the scale and transform. However, there’s one extra check, because the user could have produced the video in either landscape left or landscape right. Because there are two landscapes, the aspect ratio will match but the video might be rotated 180 degrees. The extra check for a video orientation of .downhandles this case. With the helper methods set up, find merge(_:) in MergeVideoViewController.swift. Locate where firstInstruction and secondInstruction are created and replace them with the following: let firstInstruction = VideoHelper.videoCompositionInstruction( firstTrack, asset: firstAsset) let secondInstruction = VideoHelper.videoCompositionInstruction( secondTrack, asset: secondAsset) The changes above will use the new helper functions and implement the rotation fixes you need. Whew — that’s it! Build and run. Create a new video by combining two videos — and, optionally an audio file — and you’ll see that the orientation issues disappear when you play it back. Where to Go From Here? Download the final project using the Download Materials link at the top or bottom of this tutorial. You should now have a good understanding of how to play video, record video and merge multiple videos and audio in your apps. AV Foundation gives you a lot of flexibility when playing with videos. You can also apply any kind of CGAffineTransform to merge, scale or position videos. If you haven’t already done so, take a look at the WWDC videos on AV Foundation, such as WWDC 2016 session 503, Advances in AVFoundation Playback. Also, be sure to check out the Apple AVFoundation Framework documentation. I hope this tutorial has been useful to get you started with video manipulation in iOS. If you have any questions, comments or suggestions for improvement, please join the forum discussion below!
https://www.raywenderlich.com/10857372-how-to-play-record-and-merge-videos-in-ios-and-swift
CC-MAIN-2022-33
refinedweb
3,956
50.94
Testing FBSnapshotTestCase. This class allows you create snapshot tests. A snapshot test compares the UI of a view with a snapshot of how the view should look like. Let’s see how this works. The UI I would like to test looks like this: There are two stack views with a label, a button and two text fields. Installing FBSnapshotTestCase using Carthage I’m a Carthage person. So I will show you how to use Carthage to install FBSnapshotTestCase in the test target and use it to add a snapshot test for a simple login screen. Create a Cartfile that looks like this: github "facebook/ios-snapshot-test-case" Then ask Carthage to create the dynamic framework with the command carthage update --platform iOS Carthage will fetch the source code from github and build the framework. When Carthage is finished, drag the framework from the Carthage/Bild/iOS folder to Link Binary with Libraries build phase of you test target: Next, add a new run script build phase to the test target. Put in the command /usr/local/bin/carthage copy-frameworks and add the Input File $(SRCROOT)/Carthage/Build/iOS/FBSnapshotTestCase.framework. In Xcode it should look like this: Configure FBSnapshotTestCase Next you need to configure the directories where the snapshots should be put. You can also tell FBSnapshotTestCase to create a diff image whenever a snapshot test fails. This means, when a test fails, an image is created that shows the difference between the expected UI and the UI that made the test fail. That way you can figure out what changed in the UI. Open the scheme you use of the test and add the following environment variables: FB_REFERENCE_IMAGE_DIR: $(SOURCE_ROOT)/$(PROJECT_NAME)Tests/FailureDiffs FB_REFERENCE_IMAGE_DIR: $(SOURCE_ROOT)/$(PROJECT_NAME)Tests/ReferenceImages In Xcode this looks like this: Create the snapshot To create a snapshot test, add a subclass of FBSnapshotTestCase to your test target and add the following import statements: import FBSnapshotTestCase @testable import SnapshotTestDemo Next, add the test method: func test_LoginViewSnapshot() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let sut = storyboard.instantiateInitialViewController() as! ViewController _ = sut.view recordMode = true FBSnapshotVerifyView(sut.view) } The first two lines create an instance of the view controller you want to test. The line _ = sut.view triggers the loading of the view. This is necessary because otherwise the view is nil in the test. The line recoredMode = true tells the FBSnapshotTestCase that it should create the reference snapshot. With FBSnapshotVerifyView(sut.view) the reference snapshot is compared with the current UI of the view. Run the test. The test will fail because FBSnapshotVerifyView() doesn’t find a reference snapshot to compare the view with. Open the directory of the test target in Finder. There is now a directory ReferenceImages_64. In this directory you can find all the snapshots recored in record mode. Now remove the line recordMode = true from the test and run the test again. The test succeeds. Nice! From now on, whenever the UI of the login screen changes you will be notified by a failing test. Diff images But how do we know that the snapshot test really works? Easy, let’s change the UI and see what happens. Change something in the UI. In the example UI the spacing of the inner stack view holding the text field and the button is 20 points. I change it to 21 and run the test again. The test fails and there is a new directory with the name FailureDiffs in the directory of the test target. In this new directory you can find all diff images of the failing tests. In my case, the diff image looks like this: Awesome! With this image it should be easy to find the change in the UI that made the test fail. If you wan’t to learn more about testing (especially Test-Driven iOS Development) I have written a book about it. The feedback for the first edition was quite good and many readers said that it helped them to get their head around test-driven iOS development. Have fun and test all your UIs!
http://swiftandpainless.com/testing-the-user-interface-with-fbsnapshottestcase/
CC-MAIN-2018-34
refinedweb
682
72.76
Hello all, This is some code that another poster put up a while ago. Just for the heck of it, I tried to compile his solution, but i can't get the poiner syntax on the bubblesort function to work. I modified the call in main() to take a ref instead of *array[], in order to get it to actually even ATTEMPT to enter the function. Otherwise I got a plethora of compiler complaints. I still, do but now they are confined to the function definition in this present form. I get a segmentation violation when strcmp() tries to read the arrays in. You might ask why I don't use ref syntax instead? Thats because the OP had it this way, and I would like to better understand how to structure code that uses pointers. Thanks in advance! #include<iostream> using namespace std; #include<cstring> using std::strncmp; void BubbleSort( const char *array[] , int size ); int main() { const int ArraySize = 10; const char * Array[] = { "Toronto", "Montreal", "Alberta", "Quebec", "NewYork", "Calgary", "Edmonton", "NewJersey", "Ontario", "California" }; cout << "The unsorted arangement of the town names is: \n"<<endl; for ( int i = 0; i < ArraySize; i++ ) { cout <<" " << Array[i]; cout << endl << "\n"; } BubbleSort( &Array[ArraySize] , ArraySize); cout << "The sorted arangement of the town names is: \n"<<endl; for ( int j = 0; j < ArraySize; j++ ) { cout <<" " << Array[j]; cout << endl << "\n"; } return 0; } void BubbleSort( const char *array[] , int size ) { int result; for ( int next = 0; next < size - 1 ; ++next ) { for ( int j = 0; j < size - 1 - next; ++j ) { result = (strcmp (( array[j]),( array[j+1]))); if (result > 0) swap ( array[j] , array[j+1] ); } } }
https://www.daniweb.com/programming/software-development/threads/64297/problem-with-function-arg-pointer-syntax
CC-MAIN-2018-39
refinedweb
271
62.51
DSON, Genesis content, and Poser Sorry if this has been covered before, but I'm not finding anything on the forum specific to my queries. I have managed to install the DSON into Poser, and Genesis loads up in my Poser scene without any hassles. I found a thread on the forum that was somewhat helpful, stating that any Genesis products that were bought previously, if they have been updated to work for the DSON, the downloads can be reset and you just get the new product downloads. I have done that for: Genesis Creature Creator Bundle Genesis Evolution: Morph Bundle Genesis Evolution: Muscularity But there are only trx files, and nothing associated with the DSON as was mentioned in previous threads I read, to tell the products apart. And these products are listed on the DSON compatible page. Any help to clear up this confusion would be greatly appreciated Those packs have been updated and those are the right type files. They were updated before they started putting DSON on in the file names. So, the products that are listed on the DSON category, even though no new files are displayed when I reset the downloads, the files with trx are safe to install? With all the problems people seem to be having with making this DSON work, I don't want to push my luck and install something that is going to break the whole thing. Morph packs like those, the Iconic shapes, and the Ethnicity morphs don't have presets -- the dials are there when you load Genesis. Therefore they don't need Poser Companion Files. They work in Poser as is, no update needed. Thankyou very much for clarifying that. And just one more thing; for other products, such as hair, for example, when I reset the downloads, can someone explain to me what the different files are. I read something in a previous thread, but I can't find it now: DSON Core Poser Companion Legacy The DSON Core is pretty clear- they are the ones I have to install in the DSON, but what about the Poser Companion? And Legacy, am I right in amusing they are the downloads required for DS4 installations? Yes, DSON Core for DS 4.5 or Poser Poser Companion Files for Poser Legacy for DS 4.0 Thanks very much for clarifying that for me! Thanks a lot for clarifying the different file types, man, I was also scared to mess all my Poser folders up somehow. Why don't DAZ people explain this a little in detail somewhere, how can a normal human being guess what is behind those file types??? Up to now I have started all the "Legacy" files as well, and only god knows where these installers have put all the files which obviously I don't need at all... Very annoying. Thanks a million for replacing DAZ3D in helping us... Just to clarify this one more time for me with little brain:)) Do I need to install both of these for Genesis products to work in PoserY DSON Core for DS 4.5 or Poser Poser Companion Files for Poser Or is the Poser Companion the only file that is needed? Until now I used both the DSON Core and the Poser Companion to install into my Poser Genesis folder. And now, that I know that I need the DSON Core files to work in DS 4.5 my DS might even find files lol. Yes in Poser you need both the DSON Core file and the Poser Companion file. Oh thank God, I thought I done something stupid again:)) I would not be hard on yourself-although I think you are kidding here. It IS confusing-and took me awhile to figure out as well. A nice diagram showing what goes where would be nice. I am sure I am doing something wrong also...I have anstalled all the files (and to be honest I think its just pure luck cos I really dont understand fully which files go where) and I got Genesis to load up from my Poser library but OK all the base parameters are there but none of the morph packs and various creatures or M5/V5 etc are showing, I am sure I missed (or messed up) a major step, can anyone point me to a good guide on how to set this thing up properly please? The morphs are ALL located under Body/Actor/ not on the body part- except expressions-which may be found under Head/Actor/ Yeah... I'm confused too. I thought I had installed everything correctly for Poser Pro 2012 on an iMac 3.4 GHz Intel Core i7 with 16 GB running OSX 10.8.2 but all I get when trying to load anything Genisis is: "Traceback (most recent call last): File "/Users/Shared/Poser Pro 2012 Content/Runtime/libraries/character/DAZ People/Genesis.py", line 1, in import dson.dzdsonimporter ImportError: No module named dson.dzdsonimporter" What I got was "DSON Importer for Poser - Mac64" and "Genesis Starter Essentials - Poser Companion - Mac" and "DSON Importer for Poser - Genesis Starter Essentials - DSON Core - Mac." I have installed these into both places possible (PP12 has split the Runtime into one for Python in the main Poser app folder and one for Content in a user shared folder). So, as far as I can tell, none of it works in Poser Pro 2012 on a Mac. Did you update Poser to SR3? It works on my mac. I think that error message says you didn't. It sounds to me like you don't have the DSON importer installed in the right place. A year later and I'm still confused on Poser's directories... but I've installed the DSON Importer into /Applications/Poser Pro 2012. I assume this is to enable the plug-ins correctly. All my Genesis content I've loaded into a separate Runtime. It appears the way this works is that the DSON Importer Plugin is called from the Poser Helper file. It then loads the Genesis content dynamically. This is why the morphs don't need a companion file, the plug-in finds them and loads them automatically.. I agree, Genesis is ok but in my opinion, when I am very honest, I prefer the V4.2 and the separate G4. I have such a lot of CDI Morphs to make the cutest characters or the scariest, Morphia is one great example for fab. use of V4.2 and and and... Yes, it is easier in a way to have Genesis and have all the dials there but it does not take long to Inject , for example , all Morphss of V4.2 , A4, G4,S4,Creature Morphs in to Morphia and save that to your Character Folder. As long as Genesis slows down my iMac 64 bit that much and all takes so long I do prefer to work with my lovely G4. And Kids 4 of course, with the cute CDI Moprhs applied. HEAVEN so when install poser companion i need both "DSON Core file and the Poser Companion file" and they'll go in to my runtime That is how I do it and yes, you need the DSON Core and the Poser Companion file. I have an extra * Genesis * Runtime. The DSON Importer I installed where my Poser Pro 2012 holds its python scripts, on my Mac it is in my Applications folder. id like to do that but how?i have a pc,and where do i find the files to go where thanks On a PC you run the DSON Importer to where you have your Poser installed * where the phyton scripts are and such * Then you can make a new Runtime, call it Genesis for example , and install the other files in there and all the DSON products you might purchase for Poser + Genesis in the Future. You need to download the PC files of Poser Companion PC and DSON Core PC . Hope that helps. I write Python Scripts for Poser and frankly I cannot get this to work consistently. I had it working at one point after some fighting but I had to reinstall Windows 7. I have Poser Pro 2012 installed on a different drive than C: All my content is outside of C:\ I installed the DSON importer to my main Poser directory. That seams logical and straight forward to me. I created a new content directory (Genesis) and pointed to that in Poser. I installed the other two exes to this directory (D:\Content\Genesis) It all should work, right? Well, no. The Sub D Dragon loads fine. Genesis loads but has no geometry (in other works is not visible but in the scene). So I'm baffled as to what kind of witchcraft I must perform to get this to work. I mean it all "seems" simple but obviously it isn't. And yes, I downloaded the correct bits and version of the DSON importer (and well, the dragon is loading). Any thoughts? Do I need to invest in chicken bones that I need to shake over the computer? :) It looks like you have installed everything correctly. There is one thing which you should check: In Scripts!DSON Support!Import Preferences there is a link to a "writable runtime folder" This needs to be a folder to which Poser can write - in other words not in program files. Check if this is correct and pointing to your genesis runtime or another "safe" one. The default should be the default Poser one (users/public/documents/Poser Pro 2012 Content) In that same tool there is also a log tool. See if that gives any hint of why genesis does not load I don't have anything in Program Files, pretty much ever (if I can help it). Nothing on my D: drive is write protected. The log seems to show that Genesis is loading. I've tried to different installs but it basically looks like the text below. But, you know, blank Genesis. I'm probably just going to give up because this is already eating up much of my (limited) free time but I DO appreciate the help. I just thought it would be nice to get the DSON content compatible with my scripts and such. Oh well. Yes, everything seems absolutely normal - except that it does not find anything of the support files (dynamic assets as DAZ calls it) because it seems to write an empty CR2 file - which is of course invisible. You could probably trace the route via the duf file (if it is not compressed), but if you installed it correctly these should all be there But there is something bothering me here: DS uses the "Content" folder as its own main folder - is it possible that the installer for the essentials got confused? But this will take time to figure out. It's very weird because it IS dynamically generating an .obj file (which it should be) geometry followed by numbers and dashes in parenthesis, looks like a registry string then .obj The .obj IS genesis when it's loaded into UVMapper Pro. Opened up the generated cr2 and it points to the .obj correctly to. I do have two genesis.cr2's though. Hrm. It may be from different attempts, but in your description you save you have the content in D:\Content\Genesis but the log file reads File Path: D:/Content/DAZ Studio/Runtime/libraries/Character/DAZ People/Genesis.duf Yeah, but I've tried different locations by uninstalling, reinstalling. What does the cr2 file say in the main poser runtime:DSON:autoadapted:content files - it is in one of its subfolders (randomly generated, so I can't give you the name) I missed that different content folder - the way it is now, it won't work
http://www.daz3d.com/forums/discussion/comment/163397/
CC-MAIN-2018-13
refinedweb
1,989
70.33
This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including @weknow/react-svgloader with all npm packages installed. Try it out: require()any package directly from npm awaitany promise instead of using callbacks (example) This service is provided by RunKit and is not affiliated with npm, Inc or the package authors. This is a ReactJS Component for SVG file loading by Ajax and DOM injection. This component allow us to insert any SVG file specifying a path and adding a class name for css customization. Please refer to the example file to see it working. To run the example: cd example npm install npm start As you will be able to see in example in order to use the component we need to importe it as: import SvgLoader from 'bv-react-svgloader'; Then, in the render method we can just call it like: <SvgLoader src='/svg/logo.svg' className="App-logo svg-logo"/> Install this component is easy, just use npm as: npm install bv-react-svgloader
https://npm.runkit.com/%40weknow%2Freact-svgloader
CC-MAIN-2020-05
refinedweb
184
52.6
Developing General Java Applications Last reviewed on 2019-02-24 - Project Setup - Creating and Editing Java Source Code - Compiling and Running the Application - Testing and Debugging the Application - Building, Running, and Distributing the Application - Other Common Tasks The following short tutorial takes you through some of the basic steps of developing a Java SE application in the NetBeans IDE. This tutorial assumes you already have some familiarity with developing Java applications. Along the way, you will see some of the IDE’s. Project Setup The application you create will contain two projects: A Java Class Library project, MyLib, in which you will create a utility class. A Java Application project, MyApp, with a main class that implements a method from the library project’s utility class. After you create the projects, you will add the library project, MyLib, to the classpath of the application project, MyApp. Then you will code the application. The library project will contain a utility class with a method named acrostic . The method acrostic takes an array of words as a parameter and then generates an acrostic based on those words. The MyApp project will contain a class Main that calls method acrostic and passes the words that are entered as arguments when the application is run. Creating a Java Class Library Project To open a new Java project, press: or, select File > New Project… from the menu bar. Then Choose Project by selecting Categories: Java with Ant and Projects: Java Class Library, then click Next >. For Name and Location, set Project Name: MyLib. Change Project Location: to any directory on your computer. From now on, this tutorial refers to this directory as NetBeansProjects. The specified path is then shown as Project Folder: / NetBeansProjects/MyLib Optionally, select Use Dedicated Folder for Storing Libraries checkbox and specify the location for the libraries Folder:. See Sharing a Library with Other Users in Developing Applications with NetBeans IDE for more information on this option. Finally, click Finish. The MyLib project will be created and opens in the Projects window. Creating a Java Application Project Open a new Java Project, as shown above. Then Choose Project by selecting Categories: Java with Ant and Projects: Java Application, then click Next >. for Name and Location, set Project Name: MyApp. Make sure the Project Location is set to NetBeansProjects. Optionally, select the Use Dedicated Folder for Storing Libraries checkbox. Ensure that the Create Main Class checkbox is selected and, enter acrostic.Main as the main class. Finally, click Finish. The MyApp project is displayed in the Projects window and Main.java opens in the source editor. Configuring the Compilation Classpath Since class MyApp is going to depend on class: In the Projects window, right-click the Libraries node for the MyApp project and choose Add Project… as shown in the image below. If necessary, in the Add Project window browse to NetBeansProjects and, select the MyLib project folder. When you do so, you will see Project Name: MyLib and, Project JAR Files: dist/MyLib.jar can be added to the project. Notice that a JAR file is shown for MyLib even though you have not actually built one yet. This JAR file will get built when you build and run the MyApp project. Select Add Project JAR Files then expand the Libraries node of MyApp in the Projects window and, you will see that MyLib project’s JAR file has been added to the MyApp project’s classpath. Creating and Editing Java Source Code Now you need to create a Java package and, add the method that will construct the acrostic. After that you need to implement the method acrostic in class Main. Creating a Java Package and Class File In the Projects window, right-click the MyLib project node and select New > Java Class… . Alternatively, regardless of where you are in the project, press: or, select File > New File… from the menu bar. Then in the New File window select: Project: MyLib, Categories: Java and File Types: Java Class then click Next. In the New Java Class window, type: Class Name: LibClass and Package: org.me.mylib. Click Finish and LibClass.java opens in the source editor. In LibClass.java, place the cursor on the line after the class declaration public class LibClass {. Type or paste in the following method code: public static String acrostic(String[] args) { StringBuffer b = new StringBuffer(); for (int i = 0; i < args.length; i++) { if (args[i].length() > i) { b.append(args[i].charAt(i)); } else { b.append('?'); } } return b.toString(); } If the code that you pasted in is not formatted correctly, press: or, Source > Format from the menu bar or, right-click Format to reformat the entire file. Then save your file: or, select File > Save from the menu bar. Editing a Java File Now you will add some code to class Main.java. In doing so, you will see the source editor’s code completion and, code template features. Select the Main.java tab in the source editor. If it isn’t already open, select the Projects window and expand MyApp > Source Packages > acrostic and either: double-click Main.java or, right-click and select Open. In the method main, delete the comment: // TODO code application logic here and, in its place type the following: String result = Li At this point stop typing but leave the cursor immediately after Li. Invoke code completion by pressing Ctrl+Space, a short list of options appears. However, the class that you want, LibClass might not be there. If you press Ctrl+Space again a longer code completion list appears containing LibClass, select LibClass and press Enter. The IDE fills in the rest of the class name and also automatically creates an import statement for the class. In the main method, type a period ( . ) after LibClass, the code completion box opens again. Select the acrostic(String[]args) method and press Enter. The IDE fills in the acrostic method and highlights the args parameter, press Enter again to accept args as the parameter, end the line with a semicolon ( ; ). The line should look, as follows: String result = LibClass.acrostic(args); Press Enter to start a new line. Then type sout and press Tab. The sout abbreviation expands to System.out.println(""); with the cursor positioned between the quotation marks. Type Result = inside the quotation marks and + result after the end quotation mark. The final line should look like the following line. System.out.println("Result = " + result); Save the file. Compiling and Running the Application Now you need to set the main class and execution arguments so that you can run the project. Setting the Main Class and Execution Arguments: From the Projects window, right-click the MyApp project node and select Properties. The Project Properties window opens, select the Categories: Run node in the dialog’s left-hand pane. In the right-hand pane set Arguments: However we all feel zealous and select OK. Running the Application Now that you have created the application and provided runtime arguments for the application, you can test run the application in the IDE. To run the application in the IDE: First, press F11 to clean and build your project or, in the Projects window right-click the MyApp project node and choose Clean and Build or, select Run > Clean and Build Project (MyApp) from the menu bar. Then, you can press F6 or, in the Projects window right-click the MyApp project node and choose Run or, select Run > Run Project (MyApp) from the menu bar . In the Output window, you should see the output from the program, Result = Hello, the acrostic of the phrase that was passed as an argument to the program. Testing and Debugging the Application. Creating JUnit Tests To create a JUnit test, from the Projects window select the LibClass.java node and press: or, select Tools > Create/Update Tests from the menu bar or, in the Projects window, right-click the LibClass.java node and and select Tools > Create/Update Tests. In the Create/Update Tests dialog box, click OK to run the command with the default options. In the Projects window you will see that the IDE has created the org.me.mylib package, the LibClassTest.java file in the MyLib > Test Packages folder and, created the MyLib > Test Libraries folder. Finally the file LibClassTest.java is opened in the editor. In the Projects window, right-click the Test Libraries node and select Properties. In the Project Properties - MyLib window, select Categories: Libraries. In the right-hand pane select the Compile Tests tab and click the ` + ` button. From the pop-up list select Add Library, from the Global Libraries folder select JUnit 4.x and click Add Libray repeat, this time selecting the Hamcrest 1.x library. In LibClassTest.java, delete the body of the public void testAcrostic() method and, in place of the deleted lines, type or paste in the following: System.err.println("Running testAcrostic..."); String result = LibClass.acrostic(new String[]{"fnord", "polly", "tropism"}); assertEquals("Correct value", "foo", result); Then Save the file. Running JUnit Tests In the Projects window, select the MyLib project node and press: or, select Run > Test Project (MyLib) from the menu bar or, right-click the MyLib project node and select Test. A notification pops up telling you "Tests completed successfully for project: MyLib", and then instructs you to open the Test Results window, were you will receive confirmation of success. You can also run a single test file rather than testing the entire project. Right-click the LibClass.java node in the Projects window and choose Run > Test File. Alternatively, if LibClassTest.java is open in the editor, select Run > Test File from the menu bar. The JUnit API documentation is available from the IDE. To look for Javadoc references, select Help > Javadoc References from the menu bar and select JUnit. If this is the first time you try to access Javadoc in the IDE, you need to first choose Help > Javadoc References > More Javadoc. You can learn more about JUnit by visiting Debugging the Application In this section, you will use the debugger to step through the application and watch the values of variables change as the acrostic is assembled. To run the application in the debugger: In the LibClass.java file, go to the acrostic method and place the insertion point anywhere inside b.append(args[i].charAt(i));, then set a breakpoint by pressing: or, select Debug > Toggle Line Breakpoint from the menu bar or, in the left hand margin right-click the specified line and select Breakpoint > Toggle Line Breakpoint. Select the MyApp project node in the Projects window and, press: or, select Debug > Debug Project (MyApp) from the menu bar or, right-click and select Debug. The IDE opens the Debugging window and runs the project in the debugger until the breakpoint is reached. Select the Variables window in the bottom of the IDE and expand the args node. The array of strings contains the phrase you entered as the command arguments. Press F7 or, select Debug > Step Into from the menu bar to step through the program and watch the b variable change as the acrostic is constructed. When the program reaches the end, the debugger windows close. For more information, see Writing JUnit Tests in NetBeans IDE. Building, Running, and Distributing the Application Once you are satisfied that your application works properly, you can prepare the application for deployment outside of the IDE. In this section you will build the application’s JAR file and then run the JAR file from the command line. Building the Application The main build command in the IDE is the Clean and Build command. The Clean and Build command deletes previously compiled classes and other build artifacts and then rebuilds the entire project from scratch. To build the application, press Shift+F11 or, if Main.java is open in the editor, select Run > Clean and Build Project (MyApp) from the menu bar or, in the projects window right-click on the MyApp node and select Clean and Build. Output from the Ant build script appears in the Output window, If the window does not appear automatically, open it manually by choosing Window > Output from the menu bar. When you clean and build your project, the following things occur: Output folders that have been generated by previous build actions are deleted, " cleaned ". In most cases, these are the buildand distfolders. buildand distfolders are added to your project folder, hereafter referred to as the PROJECT_HOME folder. You can view these folders in the Files window. All of the sources are compiled into .classfiles, which are placed into the PROJECT_HOME/buildfolder. A JAR file containing your project is created inside the PROJECT_HOME/distfolder. If you have specified any libraries for the project, in addition to the JDK, a libfolder is created in the distfolder. The libraries are copied into dist/lib. The manifest file in the JAR is updated to include entries that designate the main class and any libraries that are on the project’s classpath. To find more about manifest files, you can read this chapter from the Java Tutorial. Running the Application Outside of the IDE To run the application outside of the IDE: On your system, open up a command prompt or terminal window. In the command prompt, change directories to the MyApp/dist directory. At the command line, type the following statement: java -jar MyApp.jar However we all feel zealous The application then executes and returns the following output as shown in the image below: Result = Hello Distributing the Application to Other Users Now that you have verified that the application works outside of the IDE, you are ready to distribute the application. To distribute the application: On your system, create a zip file that contains the application JAR file ( MyApp.jar) and the accompanying lib folder that contains MyLib.jar. Send the file to the people who will use the application. Instruct them to unpack the zip file, making sure that the MyApp.jar file and the lib folder are in the same folder. Instruct the users to follow the steps in the Running the Application Outside of the IDE section above. Other Common Tasks You have now completed the main part of the tutorial, but there are still some basic tasks that have not been covered. This section includes a few of those tasks. Making the Javadoc Available in the IDE To view the Java SE API documentation in the NetBeans IDE, select either: Source > Show Documentation or, Window > IDE Tools > Javadoc Documentation from the menu bar. However, for some third-party libraries, API documentation is not available. In these cases, the Javadoc resources must be manually associated with the IDE. If you have not already installed the Javadoc for your JDK then go to: and, download the file. To install, select Tools > Java Platforms from the menu bar and, in the Java Platform Manager window select the Javadoc tab and click Add ZIP/Folder…. Navigate to the download file, select and then click the Add ZIP/Folder button, finally click Close. Generating Javadoc for a Project You can generate compiled Javadoc documentation for your project based on Javadoc comments that you have added to your classes. To generate Javadoc documentation for a project: From the Projects window select the MyLib project node then select Run > Generate Javadoc (MyLib) from the menu bar. The generated Javadoc is added to the dist folder of the project. In addition, the IDE opens a web browser that displays the Javadoc.
https://netbeans.apache.org/kb/docs/java/javase-intro.html
CC-MAIN-2021-17
refinedweb
2,596
64.2