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
Created on 2008-05-10 18:47 by neves, last changed 2010-08-03 23:53 by terry.reedy. This issue is now closed. Doctest doesn't obey the specified file encoding for unicode literals. I've put the minimum test case that demonstrate the error in the attached file. The program has the # -*- coding: utf-8 -*- as the first line and is saved in this encoding. My computer environment is configured as iso8859-1. Doctest ignores the file encoding specification and interprets the u'á' as u'á' (the utf-8 text decoded as iso8859-1 ) I've reproduced this error in python 2.5 in linux and windows. This is the output of the program below that runs the function normalize from inside doctest and directly from python. They show different results. ********************************************************************** File "doctesteerror.py", line 7, in __main__.normalize Failed example: normalize(u'á') Expected: u'b' Got: u'\xc3\xa1' ********************************************************************** 1 items had failures: 1 of 1 in __main__.normalize ***Test Failed*** 1 failures. without doctest ===>>> b I believe the problem is in your test file, not doctest. The enclosing doctest string is not specified as a unicode literal, so the file encoding specification ultimately has no effect on it. At least that is how I read the documentation regarding the effect of the ecoding declaration (.") If you change the test file so that the string enclosing the test is a unicode literal then the test passes: user@gutsy:~/tmp$ cat test_iso-8859-15.py # -*- coding: utf-8 -*- import doctest def normalize(s): u""" >>> normalize(u'á') u'b' """ return s.translate({ord(u'á'): u'b'}) doctest.testmod() print 'without doctest ===>>>', normalize(u'á') user@gutsy:~/tmp$ python test_iso-8859-15.py without doctest ===>>> b ----- There is a problem with this, though: doctest now will be unable to correctly report errors when there are output mismatches involving unicode strings with non-ASCII chars. For example if you add an 'x' to the front of your unicode literal to be normalized you'll get this when you try to run it: user@gutsy:~/tmp$ python test_iso-8859-15.py Traceback (most recent call last): File "test_iso-8859-15.py", line 12, in <module> doctest.testmod() File "/usr/lib/python2.5/doctest.py", line 1799, in testmod runner.run(test) File "/usr/lib/python2.5/doctest.py", line 1345, in run return self.__run(test, compileflags, out) File "/usr/lib/python2.5/doctest.py", line 1261, in __run self.report_failure(out, test, example, got) File "/usr/lib/python2.5/doctest.py", line 1125, in report_failure self._checker.output_difference(example, got, self.optionflags)) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 149: ordinal not in range(128) user@gutsy:~/tmp$ This issue is reported in #1293741, but there is no fix or guidance offered there on how to work around the problem. I'd appreciate feedback on whether what I've said here is correct. I'm currently trying to diagnose/fix problems with use of unicode literals in some tests and this is as far as I've got. That is, I think I need to be specifying the enclosing strings as unicode literals, but then I run into #1293741. If the conclusion I've reached is correct, then trying to figure out a fix for that problem should be where I focus my efforts. If, however, I shouldn't be specifying the enclosing string as a unicode literal, then attempting to fix the problem as described here would perhaps be more useful. Though I do not know how the doctest code can know the file's encoding specification? In 3.1.2, where the docstring is unicode, the doctest of normalize works fine, as Karen said. I think she is right: without the encoding being explicitly passed to doctest, it cannot affect how the sub-interpreter used by doctest compiles the strings as code. I am therefore closing this as invalid (or won't fix, or out-of-date). In any case, it strikes me as a feature request, and test modules, especially, should not be enhanced in bugfix releases. If one thinks of it as a bug, the bug was fixed in 3.0 but cannot be backported.
https://bugs.python.org/issue2811
CC-MAIN-2021-25
refinedweb
706
66.74
This example shows how to call external functions from a simulation or generated code by using the Legacy Code Tool. Time: 45 minutes Goals Understand... How to evaluate a C function as part of a Simulink® model simulation How to call a C function from code generated by Simulink® Coder™ Task: Open the model.Task: Open the model. Replacement Process Simulink® models are one part of Model-Based Design. For many applications, a design also includes a set of existing C functions that have been tested and validated. The ability to easily integrate these functions into a Simulink® model and generated code is critical to using Simulink® in the controls development process. This module shows how to create a custom Simulink® block that calls an existing C function. Once the block is part of the model, you can take advantage of the simulation environment to further test the system. As an example, the Lookup blocks (lookup tables) in the PI controllers are replaced with calls to an existing C function. The function is defined in the files SimpleTable.c and SimpleTable.h. Task: View SimpleTable.c.Task: View SimpleTable.c. Task: View SimpleTable.h.Task: View SimpleTable.h. Creating a Block That Calls a C Function To specify a call to an existing C function, you use an S-Function block. You can automate the process of creating the S-Function block by using the Simulink® Legacy Code Tool. Using this tool, you specify an interface for your existing C function. The tool then uses that interface to automate creation of an S-Function block. Complete steps 1 through 6 below to create an S-Function block for an existing C function SimpleTable.c. A link to more information on using the Legacy Code Tool is provided at the end of this module. 1. Task: Create the function interface definition structure.Task: Create the function interface definition structure. def=legacy_code('initialize') The data structure def defines the function interface to the existing C code. 2. Task: Populate the function interface definition structure.Task: Populate the function interface definition structure. 3. Task: Create the S-function.Task: Create the S-function. legacy_code('sfcn_cmex_generate',def) 4. Task: Compile the S-function.Task: Compile the S-function. legacy_code('compile',def) 5. Task: Create the S-Function block.Task: Create the S-Function block. legacy_code('slblock_generate',def) S-function creation is a one-time task. Once the block exists, you can reuse it in any model. 6. Task: Create the TLC file.Task: Create the TLC file. legacy_code('sfcn_tlc_generate',def) Steps 1 through 5 created an S-function block that calls the specified function at each time step during simulation. Step 6 creates a TLC file, which is the component of an S-Function that specifies how Simulink® Coder™ generates code for the block. Validating the External Code in the Simulink® Environment When you integrate existing C code with a Simulink® model, always validate the results. In this example, you replace Lookup blocks with an existing C function. To validate the replacement, you compare simulation results produced with the Lookup block with results produced with the new S-Function block. 1. Task: Open the validation model.Task: Open the validation model. The Sine Wave block produces output values from [-2 : 2]. The input range of the lookup table is from [-1 : 1]. The output from the lookup table is the absolute value of the input. The lookup table output clips the output at the input limits. 2. Task: Run the validation model.Task: Run the validation model. The following figure shows the validation results. Note that the existing C code and the Simulink® table block provide the same output values. Validating the C Code as Part of the Simulink® Model After you validate the functionality of the existing C function code as a standalone component, validate the S-function in the model. Use the test harness model to complete the validation. 1. Task: Open the test harness.Task: Open the test harness. 2. Task: Run the test harness.Task: Run the test harness. The simulation results match the expected golden values: Calling the C Function from the Generated Code Simulink® Coder™ uses the TLC file to process the S-Function block like any other block in the system. Calls to the C code of the S-Function block: Can use data objects Are subject to expression folding, an operation that combines multiple computations into a single output calculation 1. Task: Build the full model.Task: Build the full model. 2. Task: Examine the generated code ( PI_Control_Reusable.c).Task: Examine the generated code ( PI_Control_Reusable.c). The generated code now calls the SimpleTable C function. The following figures show the generated code before and after the C code integration. Before the integration, the generated code called rt_Lookup. After the integration, the generated code calls the C function SimpleTable. Further Study Topics Using the Legacy Code ToolUsing the Legacy Code Tool Writing S-functions for use in code generationWriting S-functions for use in code generation
http://au.mathworks.com/help/rtw/examples/calling-external-c-code-from-the-simulink-model-and-generated-code.html?nocookie=true
CC-MAIN-2015-14
refinedweb
839
59.9
Journal: Relationship Change: Updated (2) 1 So, you've found my journal. Chances are, you're probably here because you're bored, and you noticed that I have a journal entry. I'm afraid you won't find much of interest here, but that's not why you're reading. You're reading this because you're interested to know why I'd be posting about the Slashdot relationship change notice you probably received because I have either added you as a friend or because I have culled you from my friends list and you would like to know why. Fortunately, it's really simple. The Friends List is my User Bookmarks It really is that simple. If you're on my friends list, you've probably made it there because you happened to have made an interesting, insightful, or humorous post that I enjoyed so much, I've decided to make you stick out like a sore thumb. I browse with friends set to +5, regardless of their modifier, so I will always see your posts no matter how ornery the moderators happen to be feeling. (Bonus: If you got moderated into oblivion, I have mod points, and you've put the time and effort into writing a good post, I might be able to get you out of it if I'm feeling charitable and want to mod you up.) However: If you're on my friends list, it doesn't mean I agree with you. It just means I enjoyed a post you made. If you've made it here, you've been selected as my friend exclusively for the reasons I outlined above. Chances are, you wouldn't like me in person--I'm generally politically conservative (with some socially liberal leanings, and I mean this in terms of the United States' political system), I'm religious but somewhat secular in my views, and I could probably outline a further 100+ reasons why you wouldn't like me regardless of your political affiliations (yes, I piss off even some conservatives). But here's the deal: I added you precisely because you shared a great post with the rest of Slashdot, made me laugh, or I disagree--but you made a good enough point that I think may have received an unfair shake from the moderators, so I'm watching out to make sure you don't get zinged again by someone who has it out for you (karma stalking). That said, there are some exceptions to the rules I've outlined above. Specifically, I occasionally friend individuals I might otherwise call "flaming liberal nutjobs," because I happen to have some appreciation for the points or argument they're making. I probably disagree completely, but if that person happens to be arguing with someone who is quite clearly a total moron, I'll probably add them simply because they're the only party showing at least some signs of intelligence. I may also add people for various other reasons such as generally snarky behavior, a propensity for trolling idiots, playing devil's advocate, or because you won the lottery (not really--but you get the idea). In other words, there is probably a why behind, well, why you got added--and received the "relationship changed" notice--but it could be for any reason. Two examples that come to mind are the users spun and tepples. Both of these guys are probably liberals, probably borderline crazy, and I know very well that they can get under the skin of other Slashdot users--and that is exactly why I like them. Both of these two characters have the tendency to get on the nerves of people who either have no sense of humor or, generally speaking, are exhibiting traits endemic to idiots. I seldom agree with either of them (spun for political reasons, tepples because of his occasional pro-Apple leanings), but because they go out of their way to make lesser beings look stupid, I applaud their efforts. Sure, they sometimes get a little out of line--don't we all?--but I think that the vast majority of people who become targets of their ridicule deserve it. Sometimes it isn't deserved, certainly, but oftentimes it is well-placed. They even occasionally post things that I enjoy reading. Other individuals, like Opportunist, cayenne8, TheRaven64, and at least a dozen other people who may or may not have added me in return (see my fans list for a comprehensive rundown of most of these people--save for a handful--and sorry if I haven't expressly mentioned you) make posts that I greatly enjoy reading. Again, I may not always agree with them, but these individuals are typically very civil, respectful, and informative in the majority of their posts. Sometimes their posts are just outright entertaining. Minor update: I should have added mcgrew to this list a long while back, because he's another one of the individuals whose posts I enjoy reading. Although, if I recall correctly, I had added him precisely because of a journal entry he had posted (either on mcgrew or another account) that I found very educational. mcgrew also continues to update his journal fairly regularly, so you should put some effort into reading it if you don't already. Yes, I'm guilty of not reading it as much as I should, too! Of course, you could probably guess which of the two groups you fall into--or maybe you can't. Either way, you've done something I enjoyed if you're reading this. Big Deal You Long-winded Baffoon! Why Should I Care that You Added Me? Well, you shouldn't. There are some minor benefits, but in most circumstances, you shouldn't care. If you don't care, you probably wouldn't be reading this. For the rest of you that have more time on your hands than I do (you are reading this, after all), here's what benefits you may (or may not) receive by being friended by me: 1) People on my friends list are more likely to be modded up whenever they make a good post. - This means that if there's 2 posts I find really interesting and I have only 1 mod point left, yours gets priority. There is one exception to this (below). 2) Your posts will be visible to me, regardless of their rating. - I browse with friends set to +5. That means you'll have at least an audience of one. This really only implies #1, but you get the idea. 3) If I catch a post hinting that you've been the victim of a karma stalker, I might (if I'm feeling charitable) look through your comment history for posts I feel were unfairly modded down. If I have the points, I may try to make what corrections I can to offset the damage to your karma. As I mentioned, there is an exception to #1: If I have 1 mod point and you've made an interesting post, you will receive priority if you have friended me in return. Fans of mine receive priority over friends, so if you need a bit of a karma boost, and I feel you've made a good post, I'll probably throw you a bone karma-wise. I usually feel a bit more charitable toward people with whom I am both a friend and a fan. Of course, your posts really do need to be worthy of a boost; if you post some inane one-liner (e.g. "in Soviet Russia..."), I don't care who you are. I'll ignore the post, and it won't receive any moderation from me. The one exception to this is that your meme usage--or whatever it is--has to be exceedingly clever. If it is, I may mod you funny. Of course, +1, Funny doesn't receive a karma boost, but if the post is something I feel worthy of karma (and it's funny), I might mod you +1, Insightful/Informative and let the other moderators sort out and puzzle over why a funny post got modded "incorrectly." I can't guarantee you'll keep the karma given the meta moderation, of course, but that's just how things are. Okay, but You Removed Me from Your Friends List I'm sorry. It happens. I don't read Slashdot incessantly enough to be a subscriber, so I'm fairly satisfied with my friends list being limited to 200 people. Unfortunately, this is a limit that I hit about a year or two ago, so I do occasionally need to cull my friends list. If you're reading this because I removed you, I'm truly very sorry. However, there are some ground rules I've set for people I'll remove, and if you're here, I removed you because you matched one of these rules: 1) Friends on my list must have at least one (1) post or one (1) journal entry made sometime within the last year or so. This means, for example, that since it is February 2011 as of the time of this writing, you'll be culled from my list if your last comment (or journal entry) was on or before February 2010. Yes, you may still browse Slashdot while not actively participating, but I have no way to tell the difference between someone who doesn't visit the site anymore and someone who just doesn't want to comment anymore. 2) You've marked me as a foe. This doesn't happen often (if at all), but someone who marks me as a foe will probably be taken off of my friends list. I might even add you as a mutual foe. I might just leave you neutral. Or, hell, I might just change my mind at random every day for three weeks. I figure that anyone who marks me as a foe either doesn't like something I wrote and can't handle a respectful or vehement disagreement (translation: you're being petty) or you're just in a bad mood--and that's OK! That's what I'm here for. I'm here to remind you that you might just have one last friend in the world. Or not. It depends! 3) Your account has been banned/deleted/disappeared. Okay, this doesn't happen (as far as I know), but there's nothing much else to say about it either way. 4) You're trolling (and not in the good way) or generally contributing to behavior that I don't like. Maybe you used a derogatory term toward someone inappropriately. Maybe you're starting to spam Goatse links. Maybe you're trolling in an exceedingly childish form. If that's the case, I'll remove you. I friend people exclusively because I enjoy their posts. If I stop enjoying them, I'll remove them very quickly. 5) I removed you because I felt like it. This hasn't happened yet (unlike #4 and earlier), but I do reserve the right to remove you for whatever reason I like. In short, I need the room on my list, and your number came up. I'm sorry. I truly am. There is a silver lining, though: If you continue to make insightful posts, I may just re-friend you again. Just remember one thing. You're on my friends list because your posts entertain me or maybe because I learned something from you. As such, if you continue to be fairly reasonable with others and continue to participate on Slashdot, you'll probably stay on my friends list indefinitely. There is yet one more exception to the culling that I occasionally perform (like now) on my friends list. If you have added me as a friend, you're automatically immune to culling. I don't have a lot of fans, so I can't imagine that the number of fans will approach 200 users any time soon, and for the foreseeable future, if you've friended me in return, you'll never be removed from my list. Fans are slightly more likely to receive beneficial moderation than exclusively friends, but you do still have to make a worthwhile post. Okay, I get it. Do You ever Downvote Friends/Fans/Foes? Nope. I never downvote except in cases of obvious spam which is almost never. I will never, ever, ever, ever downvote anyone. Even if you've added me to your foe list and you hate everything I stand for, I will never downvote your posts. Modding posts down is, as far as I'm concerned, a filtration method for spam and clearly abusive posts. I realize some Slashdotters tend to resort to downvotes as a means of -1, Disagree, and I think that's wrong. That's why you'll never receive a downvote, even if I disagree with you 100%. Of course, as I pointed out, you will probably receive upvotes from me for various reasons--much more often if you're a friend or a fan--and it's not because I agree with you. Upvotes are useful for increasing the visibility of quality posts, posts that correct the obvious errors of others, or posts that otherwise deserve to be made more visible. Again, you're on my friends list because it's a useful bookmark to make your posts more visible to me. Nothing more, nothing less. There are some (rough) rules that I follow to maintain the quality of my "organic bookmark" system, and if you're here, hopefully you've learned a little about why you received that ominous note: Relationship Changed.
http://slashdot.org/~Zancarius/journal/
CC-MAIN-2014-41
refinedweb
2,294
68.5
NAME fpathconf, pathconf - get configuration values for files SYNOPSIS #include <unistd.h> long fpathconf(int fd, int name); long pathconf(char *path, int name); DESCRIPTION-zero if the chown(2) call may not be used on this file. If fd or path refer to a directory, then this applies to all files in that directory. The corresponding macro is _POSIX_CHOWN_RESTRICTED. _PC_NO_TRUNC returns non-zero if accessing filenames longer than _POSIX_NAME_MAX generates an error. The corresponding macro is _POSIX_NO_TRUNC. _PC_VDISABLE returns non-zero if special character processing can be disabled, where fd.21 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/karmic/en/man3/pathconf.3.html
CC-MAIN-2015-11
refinedweb
112
59.9
A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400. For example, - 1999 is not a leap year - 2000 is a leap year - 2004 is a leap year Program to Check Leap Year #include <stdio.h> int main() { int year; printf("Enter a year: "); scanf("%d", &year); // leap year if perfectly visible by 400 if (year % 400 == 0) { printf("%d is a leap year.", year); } // not a leap year if visible by 100 // but not divisible by 400 else if (year % 100 == 0) { printf("%d is not a leap year.", year); } // leap year if not divisible by 100 // but divisible by 4 else if (year % 4 == 0) { printf("%d is a leap year.", year); } // all other years are not leap year else { printf("%d is not a leap year.", year); } return 0; } Output 1 Enter a year: 1900 1900 is not a leap year. Output 2 Enter a year: 2012 2012 is a leap year.
https://cdn.programiz.com/c-programming/examples/leap-year
CC-MAIN-2020-40
refinedweb
176
77.77
We show how to apply Diffusion Spectrum Imaging [Wedeen08] to diffusion MRI datasets of Cartesian keyhole diffusion grad.dsi import DiffusionSpectrumModel. dsmodel = DiffusionSpectrumModel(gtab) Lets just use one slice only from the data. dataslice = data[:, :, data.shape[2] // 2] dsfit = dsmodel.fit(dataslice) Load an odf reconstruction sphere sphere = get_sphere('repulsion724') Calculate the ODFs with this specific sphere ODF = dsfit.odf(sphere) print('ODF.shape (%d, %d, %d)' % ODF.shape) ODF.shape (96, 96, 724) In a similar fashion it is possible to calculate the PDFs of all voxels in one call with the following way PDF = dsfit.pdf() print('PDF.shape (%d, %d, %d, %d, %d)' % PDF.shape) PDF.shape (96, 96, 17, 17, 17) We see that even for a single slice this PDF array is close to 345 MBytes so we really have to be careful with memory usage when use this function with a full dataset. The simple solution is to generate/analyze the ODFs/PDFs by iterating through each voxel and not store them in memory if that is not necessary. from dipy.core.ndindex import ndindex for index in ndindex(dataslice.shape[:2]): pdf = dsmodel.fit(dataslice[index]).pdf() If you really want to save the PDFs of a full dataset on the disc we recommend using memory maps ( numpy.memmap) but still have in mind that even if you do that for example for a dataset of volume size (96, 96, 60) you will need about 2.5 GBytes which can take less space when reasonable spheres (with < 1000 vertices) are used. Let’s now calculate a map of Generalized Fractional Anisotropy (GFA) [Tuch04] using the DSI ODFs. from dipy.reconst.odf import gfa GFA = gfa(ODF) import matplotlib.pyplot as plt fig_hist, ax = plt.subplots(1) ax.set_axis_off() plt.imshow(GFA.T) plt.savefig('dsi_gfa.png', bbox_inches='tight', origin='lower', cmap='gray') See also Calculate DSI-based scalar maps for calculating different types of DSI maps. Wedeen et al., Diffusion spectrum magnetic resonance imaging (DSI) tractography of crossing fibers, Neuroimage, vol 41, no 4, 1267-1277, 2008. Tuch, D.S, Q-ball imaging, MRM, vol 52, no 6, 1358-1372, 2004. Example source code You can download the full source code of this example. This same script is also included in the dipy source distribution under the doc/examples/ directory.
https://dipy.org/documentation/1.4.1./examples_built/reconst_dsi/
CC-MAIN-2021-25
refinedweb
388
57.87
. Discussion This is a library I created to manage SQL server databases. It now works with SQL2005's sqlcmd, in addition to the SQL2000 and SQL7's osql.exe. The previous revision included the option for integrated security, and the test section on the library itself; I also cleaned some old code and comments and removed the references to the string module. Later I will add support for Sybase (or maybe someone else will do it!). If you are a system engineer or database administrator and find yourself doing a lot of scripts and batch files doing calls to osql.exe you will find this library useful. CallProc. I can't execute procedures like EXEC sp_addlogin ... Is there a special way to do that ? Thanks You what's dbcp, Hi, when i run your script i get erros, dbcp is not defined. python can't find this module. where can i get it. please reply. thanks dbcp and Pretty Printer. Hi Khawaja dbcp is the module from another colaborator (Steve Holden). Do a search on the Cookbook for "Pretty Printer" and you will find it. Save it as a module named dbcp and your dblib will work ok. I will be updating dblib soon, thanks for trying it EXEC ok with sp_addllogin. Hi Bertrand Thanks for testing dblib! Sorry for the late reply I tested using the sp_addlogin with EXEC (and without it) and it worked fine. Just make sure you configure the sql statement with a combination of double quotes and single quotes: lst = cu.execute("EXEC sp_addlogin 'test3', 'test3'") And it should work ok. I will be working more on this from now on. Best regards Jorge Updated test program follows dblib_test.py test program to test dblib.py from dblib import * from dbcp import pp #Pretty Printer imported here c = Connection('SERVERNAME', 'sa', 'password','pubs') print c.constr #print the connection string print c.connected #prints 1 if connected OK cu = c.cursor #create the cursor lst = cu.execute('select * from authors') print 'rowcount=' + str(cu.rowcount) #test print of record count rows = cu.fetchall() print pp(cu, rows, rowlens=1) new test using sp_addlogin, no EXEC lst = cu.execute("sp_addlogin 'test2', 'test2'") print 'rowcount=' + str(cu.rowcount) #test print of record count rows = cu.fetchall() print pp(cu, rows, rowlens=1) c.close() new test using EXEC lst = cu.execute("EXEC sp_addlogin 'test3', 'test3'") print 'rowcount=' + str(cu.rowcount) #test print of record count rows = cu.fetchall() print pp(cu, rows, rowlens=1) checking the logins were created: lst = cu.execute("select name from master..syslogins") print 'rowcount=' + str(cu.rowcount) #test print of record count rows = cu.fetchall() print pp(cu, rows, rowlens=1) c.close() ----------------------------------------------------- Not getting all fields. Hi there: I'm not getting all of the fields from my query: sql="""select contact1.,contact2. from contact1 left outer join contact2 on contact1.accountno=contact2.accountno""" c = Connection(...) cu = c.cursor #create the cursor lst = cu.execute(sql) print cu.fieldnames I'm getting 31 field names but the two combined tables should have 194. thanks Greg Please try this. Hi Greg - thanks for using dblib! I made a copy of the authors table (named it authors2) from SQL server pubs database and run this version of your query sql="select authors.,authors2. from authors left outer join authors2 on authors.au_id=authors2.au_id" c = Connection('(local)',db='pubs') cu = c.cursor #create the cursor lst = cu.execute(sql) print cu.fieldnames And got the complete set of columns ['au_id', 'au_lname', 'au_fname', 'phone', 'address', 'city', 'state', 'zip', 'contract', 'au_id', 'au_lname', 'au_fname', 'phone', 'address', 'city', 'state', 'zip', 'contract'] Regards - Jorge Memory Usage. After downloading and kicking around your osql module, I'm quite happy with its performance. The only difficulty I'm having with it concerns memory usage. When running the following query with cursor.execute() SELECT TOP 2000000 * FROM DATA I end up using about 1.5 gigs of memory, which is rather what I expected. However, after I have closed and deleted all of the connection and cursor objects associated with the query, and all variables which took data from the query, the memory isn't released. Even after deleting all the variables created in the scrpit, the memory remains allocated, only to be released when I exit the python session. Is there something I can do to recover this memory without needing to exit python altogether? Thanks, Brian Known issue with Python interpreter. Hi Brian, thanks for using dblib I did some tests and could verify the fact: memory not being released. I did a little fix that improved a little: from 22MB went down to 16MB when closing the cursor, and before exiting Python; did not notice improvement when closing the connection Doing some Google I found that this will be fixed in version 2.5 The original link that took me to the previous one was this: For the time being, please test my partial fix (please fix indentation): changed the close function in the cursor: def close(self): self.records=None #NEW LINE ADDED self=None return self And here is the test section, I used the AdventureWorks2000 database with a cross join to get a good sized recordset if __name__ == '__main__': WTF ? Hi, Why on earth should one use this recipe and start an osql process from within Python to execute SQL requests, when there are sane and proven alternatives like ODBC and ADO ? What are the possible advantages ? There is no way this can be faster, more compatible, more maintainable than the already existing alternatives... Don't touch this recipe without a 10-foot pole ! Except as a toy example of the power of os.popen, do yourself a favor and forget about this. Sorry to be so harsh but this gives me the creeps. Really. FYI, there is a Daily WTF article about this here : Counterpoint. Depending on your circumstances, this module could be a better choice than ODBC or ADO. ODBC (or the more popular mxODBC) requires that you have the win32all package installed (usually not a problem but your situation may be different). Use of mxODBC in a commercial environment requires a license, available at a very reasonable cost. The ADO approach requires the ctypes package for the ADO related modules I've seen. Docs and useful examples are fairly thin (and approaching being woefully out of date) for the ODBC and ADO modules. This module has at least some useful example usage demonstrated. As far as performance goes, one should refer back to the original discussion segment where the author mentions his intended use, which is to aid in managing databases, ie., adding tables, adding users, simple queries to count rows, etc. I'm skeptical that the user of this module would suffer any meaningful performance penalty for that sort of use. But, if you're Amazon, you shouldn't use this module for your website transaction processing. Nor should you use this if you are NOAA crunching terabytes of sea-surface, air temps and humidity to issue hurricane forecasts. There isn't any way that this module will ever be compatible with Oracle, DB2, MySQL, PostGreSQL, SQLite, etc. But, if you're in a MS-SQL Server environment, who cares? If and when you transition to SQLServer 2005, you'll probably have to substitute for the planned deprecation of osql. This is certainly manageable. I also don't see a problem with maintainability if your use falls within the spectrum of use envisioned by the author. Don't use this to control nuclear power plants and don't think you can use this in a high availability mission-critical near real-time OLTP environment. There's so many other Python modules out there that make use of os.popen to great advantage, that I don't understand why one would object to this one. Why re-invent the wheel or bother with increased complexity if using popen meets your needs? It's not like the hardware you're likely to be operating on will collapse under the "burden". Do yourself a favor and skip the Daily WTF link. The postings there have so little relevance to this module. Unless you're in to gratuitous self-reference that's wholly devoid of useful content, you've seen all the critique specificity the prior respondent could muster. While I might quibble about the name of the module (IMO, it should be named msdblib), some non-idiomatic Python syntax, the extraneous HTML line-break tags on the ASPN page and other minor issues, this module can be useful. Depending on your environment and circumstances, the fact that it has no external dependencies (other than osql) may be reason enough to use this module. The 3 star rating is justified. Some performance tests by author - not bad. I agree with Kip that this dblib may not be suitable for some applications, but it is very useful for others. If you find yourself using in your system administration job a lot of calls to osql from scripts, it really simplifies your life. And the performance for this kind of use is not bad: the speed is comparable to ADO. I do not have an equivalent version of the dblib using ADO (one that conforms the output cursor like the dblib does), but I did some speed tests with this code, just to compare the plain speed of both (put it after the line (if __name__ == '__main__'): from time import time I run it several times, for different sized recordsets, and got results similar to this: Execute using dblib Elapsed time:11.719000101089478 Execute using ADO, no processing Elapsed time:0.125 Execute using plain osql, no processing Elapsed time:0.21799993515014648 It is to be expected in this test scenario for dblib to be the slowest, but this is due to the amount of text processing being done to configure the cursor to make it compatible with the Python cursor standard. I suspect that if anybody creates a compatible cursor like this dblib based in ADO, it will perform with a speed approximate to the one of dblib. Another plus is that with minor code changes it could be used with Sybase. I have not had time to test it extensively with SQL 2005's sqlcmd.exe, but it seems to work well with it (with better speed). And in reference to Nicolas Lehuen comment about the 10-foot pole, I can vouch for the safety of this program: I have never been electrocuted by it, not even mild shocks :-) OK for the no-dependency part. You have a point : this recipe may be interesting if you need a simple DBAPI implementation in a non-production context, for example to perform administrative tasks. Of course this should not be used in a high concurrency context, like in a Web application, but I guess this was not what the author intended. Sorry if I've been too harsh, but I've read this recipe a few hours after reading the Daily WTF article, and the similarity in concepts made me go ping. Regards, Nicolas 'Error: input query is too long\n' i'm using the module above and getting error message when trying to execute the proc. Any ideas I should change? The string sql="Execute [MyDB].[dbo].[MyProc] @var1=1, @var2=2.2, ...@var57=''" What do I do wrong and what should I change to avoid this error? I print this message in class Cursor def execute(self, s), basically self.records = [] lst = os.popen(self.constr + ' -s' + self.colseparator + " " + self.sqlfile + '"' + s + '"').readlines() print "lst",lst # prints the error message in the title if len(lst) == 0: return self.rowcount The rest of the code I use simple: c=Connection(...) if c.connected==1: sql="Execute [MyDB].[dbo].[MyProc] @var1=1, @var2=2.2, ...@var57=''" db = c.cursor ret = db.execute(sql) it doesn't fail but also doesn't execute by printing ['Error: input query is too long\n'] from the my inserted statement :( Any ideas or any other methods I could use? Many thanks!!! Katya SQL Server 2005 problem with simple test. Hi Jorge, when i run your script i get the following erros: Source Script code is: from dblib import * from dbcp import pp #Pretty Printer imported here c = Connection('frododb01', 'sa', 'xxxx','pkt110_IMCA','sql2005') #My micorsoft sql server 2005 parameters print c.constr #print the connection string print c.connected #prints 1 if connected OK cu = c.cursor #create the cursor lst = cu.execute('select * from comuni') print 'rowcount=' + str(cu.rowcount) #test print of record count rows = cu.fetchall() print pp(cu, rows, rowlens=1) c.close() where can i get it. please reply. thanks Giuseppe P. Try this please. Hi Giuseppe: Problem may be due to the use of the reserved word count in the lines count = lastline[1:spacepos] self.rowcount = int(count) Replace count by cnt: cnt = lastline[1:spacepos] self.rowcount = int(cnt) I will update the source code later.. Is the sybase implemented already? :) Hi Marco Not yet ready for Sybase
http://code.activestate.com/recipes/144183/
crawl-002
refinedweb
2,186
66.44
This pyplot command. By default this is usually the Axes.transData transform, going from data units to screen dots. We can use the offset_copy function to make a modified copy of this transform, where the modification consists of an offset. import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms import numpy as np from matplotlib.transforms import offset_copy xs = np.arange(7) ys = xs**2 fig = plt.figure(figsize=(5, 10)) ax = plt.subplot(2, 1, 1) # If we want the same offset for each text instance, # we only need to make one transform. To get the # transform argument to offset_copy, we need to make the axes # first; the subplot command above is one way to do this. trans_offset = mtransforms.offset_copy(ax.transData, fig=fig, x=0.05, y=0.10, units='inches') for x, y in zip(xs, ys): plt.plot((x,), (y,), 'ro') plt.text(x, y, '%d, %d' % (int(x), int(y)), transform=trans_offset) # offset_copy works for polar plots also. ax = plt.subplot(2, 1, 2, projection='polar') trans_offset = mtransforms.offset_copy(ax.transData, fig=fig, y=6, units='dots') for x, y in zip(xs, ys): plt.polar((x,), (y,), 'ro') plt.text(x, y, '%d, %d' % (int(x), int(y)), transform=trans_offset, horizontalalignment='center', verticalalignment='bottom') plt.show() Total running time of the script: ( 0 minutes 0.083 seconds) Gallery generated by Sphinx-Gallery
https://matplotlib.org/2.1.2/gallery/misc/transoffset.html
CC-MAIN-2022-05
refinedweb
229
54.39
Download presentation Presentation is loading. Please wait. 1 Getting Data into Your Program Let Me In Getting Data into Your Program 2 Ahh, Streams C++ views data as streams There are markers in the stream to indicate where you are The data travels past and you extract or insert as you want 3 Input Streams and Extraction #include <iostream> Input: cin >> //think sticking data in variable Output: cout << // think taking data out and into stream Extraction skips whitespace! ‘\n’, ‘\t’, ‘ ‘, ‘\r’, ‘\v’ 4 Newline Character Two ways to get a new line ‘\n’ endl; 5 Examples 25 A 16.9\n cin >> i; i = 25 cin >> ch; ch = A cin >> x; x = 16.9 25 A 16.9\n 6 One Character at a Time; Getting and Skipping get function example cin.get(someChar); ignore function cin.ignore(200, ‘\n’); Second parameter can be any character 7 Strings: How to read them getline function example getline(cin, myString); Defaults to the newline character Alternative getline(cin, myString, ‘\t’); Where the third parameter can be any character 8 Files: Let’s Use Them #include <fstream> Declare a file stream variable ifstream inFile; //input file stream ofstream outFile; //output file stream Open the files inFile.open(“MyInput.dat”); outFile.open(“MyOutput.dat”); 9 Alternative Declare and Open in one statement ifstream inFile(“MyInput.dat”); ofstream outFile(“MyOutput.dat”); 10 Were You Born in a Barn? Don’t forget to close the files when you are done with them inFile.close(); outFile.close(); 11 Using ifstreams and ofstreams Work just like cin and cout Extraction and Insertion get getline Read marker in read file Write marker in write file 12 I Don’t Know the Name of My File Declare it at run time Get from input statement in a string Use it to open the file ifstream inFile; inFile.open(myString); //won’t work Instead need to do this inFile.open( myString.c_str() ); //will work 13 FAILURE You can check for failure inFile.fail(); Example int i=10, j = 20, k=30; inFile >> i >> j >> k; // outFile << i << j << k; // Similar presentations © 2018 SlidePlayer.com Inc.
http://slideplayer.com/slide/3169290/
CC-MAIN-2018-47
refinedweb
354
59.74
Douglas Adams's Whale Ryan Palo Updated on ・6 min read Intro I think it is important to find ways that your background or experience specifically help you to stand out in any given group. If you can pinpoint those areas, the group can optimize its tool set and have a better idea of who would be best suited to a specific task. Personally, while programming is one of my favorite pastimes, I have a degree in Mechanical Engineering and some experience teaching Calculus and Physics. Because of this, I thought I would share some insight into an area that I know everyone has some questions about: the whale in Douglas Adams's Hitchhiker's Guide to the Galaxy. What whale, you ask? In chapter 18, two missiles get randomly transformed into a whale and a potted plant, respectively. Here's the excerpt:. This excerpt leads me to ask: can we simulate it? With a little help from Python, we can find out. I'm going to write this assuming the reader has a working knowledge of basic programming principles and what the difference between the Imperial and Metric system are, but has very little physics background beyond that. Although I'm generally more comfortable using Imperial units like feet and pounds, I'm going to stick to metric units this time, for the sanity of our international friends and because the math works out a little easier. The Forces Involved Let's start with the forces at play here. Basically, the only two I'm going to worry about are gravity acting on the whale and drag working against the whale as it falls. Let's assume this whale is falling from a geosynchronus orbit (orbit in space that would allow it to keep pace as the earth rotates) -- approximately 3.5786 x 107 meters elevation. For those that are interested, I'm going to plop the only real in-depth equation here. Turning the equations into code isn't super difficult. We just need to fill in some of the variables above first. Since getting data on an alien planet and alien whale is more difficult, let's use Earth and an Earthly Blue Whale. The mass of the earth is roughly 5.97 x 1024 kg, and its radius is approximately 6.37 million meters. Blue whales live in the region between about 80-120 metric tons. To make the math nice, let's use 100 (100,000 kg). Fun fact: the largest known dinosaur came in at around 90 metric tons! Anyways, with these constants, and the Universal Gravitational Constant -- 6.674 x 10-11 m3 /kg s2 -- let's turn this into code. def gravity(altitude): """Returns the force of gravity [N] at a given altitude [m]""" earth_mass = 5.972e24 # [kg] earth_radius = 6.367e6 # [m] whale_mass = 100000 # [kg] universal_grav_constant = 6.67384e-11 # [m^3/kg s^2] radius = altitude + earth_radius # [m] # Assumption: the 'radius' of the whale is negligible compared to # the other sizes involved # Here's the important bit: result = universal_grav_constant * whale_mass * earth_mass/(radius**2) return result Drag gets a little more interesting. Because there is a startling lack of data on the aerodynamic characteristics of belly-flopping whales, we'll assume the whale is diving towards the ground head-first. This article is chock-full of informational goodies, such as the drag coefficient of a swimming whale (0.05) and the approximate projected cross-sectional area (10 m2 ). The projected cross-sectional area is sort-of like the size of the shadow the whale would cast if light was shone on it head-on. It is important to note that the density of the atmosphere decreases with elevation, but not in a nice linear fashion. We'll need to model the following relationship in our code (approximately): In order to keep your interest, I'll do some handwaving and leave that code out. Here is the code for drag: def drag(altitude, velocity): """Given altitude [m] and velocity [m/s], outputs the force of drag [N]""" whale_drag_coefficient = 0.05 # [unitless] whale_crossectional_area = 10 # [m^2] result = .5 * whale_drag_coefficient * density(altitude) # VIGOROUS HAND-WAVING! result *= whale_crossectional_area * velociy**2 # Drag always is opposite of the direction of motion. # i.e. if whale falls down, drag is up and vice versa if velocity > 0: result *= -1 return result Great! Two more steps before we get results. First is to get acceleration of the whale. Good ole' F = m * a. def net_acceleration(altitude, velocity): """Sums all forces to calculate a net acceleration for next step.""" gravity_force = gravity(altitude) # [N] drag_force = drag(altitude, velocity) # [N] net_force = drag_force - gravity_force # [N] assuming gravity is down. # Since F=ma, a = F/m! acceleration = net_force / WHALE_MASS # [m/s^2] return acceleration The Simulation Now we need to simulate the whole fall. We'll do this by getting each data point one by one. If we know altitude and velocity at a given time, we can find acceleration with the function above. In order to get the next velocity and position from a given acceleration, we'll need the following function: def integrate(acceleration, current_velocity, current_altitude, timestep): """Gets future velocity and position from a given acceleration""" new_velocity = current_velocity + acceleration * timestep # Sort of a y = mx + b situation new_altitude = current_altitude + current_velocity * timestep # Same, but for altitude return new_velocity, new_position This set of code is probably the least intuitive, but it basically boils down to the idea that if you go 20 miles per hour for 6 hours, you will have travelled 120 total miles (20 * 6). Blah blah blah science handwaving. You can see the full code and comments here. I'm still working on cleaning it up and factoring out the constants. Let's get to the whale. The Results from matplotlib import pyplot as plt import pandas as pd results = pd.read_csv("results.csv", header=0) plt.plot(results["Time"], results["Height"]) plt.show() Looks pretty much like we would expect. First he was up. Then he came down and it was fast. So? Let's look at the forces he felt. results["Force"] = results["Acceleration"] * 100000 # whale mass [kg] plt.plot(results["Time"], results["Force"]) plt.show() Woah! Let's get a better look at that spike. Note that I'm plotting Force vs. the index this time instead of vs. Time. This is to get a more spread-out view of things. You can see he is feeling some crazy gravitational forces in the downward direction until WHAMMO! Checking the height of the whale right around this point shows that he's where we are splitting the upper and lower Stratosphere: ~25000 m. Basically, our whale is faceplanting onto our atmosphere. Realistically, I'm pretty sure that, if our whale hadn't burned up already, we would have a localized whale-splosion and whale-shower. So that's it for now. That's probably all you can stand. For future work, I recommend evaluating the heat generated from drag and estimating the ignition point of an airborne sea mammal to find out if he disintegrates or explodes first. Too gruesome? Yeah, probably. Don't worry. He had a very exciting time on the way down. Never mind, hey, this is really exciting, so much to find out about, so much to look forward to, I’m quite dizzy with anticipation! - The Whale What Advice Would You Give Your 20-year-old Self? If you could go back in time, what advice would you give your 20-year-old self? You calculated for earth, but wasn't it an alien planet? Sorry the math is a tad above me but curious about size of debris field should the remains reach earth. I started to type a response, and then realized that the math (and assumptions required) was a bit more complicated than I initially thought. I think I can come up with an answer, but it'll take blog post sequel. I did find this while researching, however, on this site: Gnarly!
https://practicaldev-herokuapp-com.global.ssl.fastly.net/rpalo/douglas-adamss-whale
CC-MAIN-2019-43
refinedweb
1,330
65.22
Simpson's Paradox Simpson’s Paradox is an interesting statistical property that arises when you arrive at misleading conclusions due to overlooking confounding variables in your data. Ultimately, the only way to overcome the paradox (should it even arise…) is a thorough understanding of your data and that it represents. Simple Overview This video was very helpful in helping me gain some intuition with simple examples. A More Concrete Example import requests import pandas as pd We’ll lean on a longitudinal dataset from South Africa. conn = requests.get('') df = pd.DataFrame.from_records(conn.text.split('\n')) df = df[[0, 2, 4]] df.columns = ['aid', 'traced', 'race'] df.drop(1590, inplace=True) df = df.applymap(int) df.head() The dataset is comprised of of three variables: aid: Whether or not the patient had insurance traced: Whether or not newborns had five-year follow appointments race: 1being White, 2Black A naive look at the mean traced proportions, suggests that having insurance makes you less likely to have a follow up appointment. df.groupby('aid')['traced'].agg(['mean', 'size']) However, when you also break out by race, we can see that this idea doesn’t hold. In fact, regardless of race, having insurance makes you objectively more likely to follow-up. df.groupby(['aid', 'race'])['traced'].mean().unstack() All told, through investigation, the more glaring isight this datset gives is the disproportionate level of care provided race-to-race. df.groupby('race')['aid'].mean() race 1 0.826087 2 0.087466 Name: aid, dtype: float64
https://napsterinblue.github.io/notes/stats/basics/simpsons/
CC-MAIN-2021-04
refinedweb
253
56.96
I have the word infinity appear in my output and I am trying to change its color when it becomes and actual number. So when I check to see if it isFinite it changes to orange, but then when it actually becomes a number- I cant get it to change to black. I am so close with this, am I writing this wrong? <span ng- Am I writing this wrong? Yes... several issues isFinite is function first off. Also it is in global namespace whereas angular expressions are evaluated against scope variables You would need to define isFinite(testValue) in angular scope (controller) to use it in the view // be sure to inject $window in controller $scope.isFinite = $window.isFinite And in view would be: ng-class="{'test3':isFinite(users2) , 'test2':!isFinite(users2)}" Reference MDN isFinite()
https://codedump.io/share/NeMgLlz0Kohu/1/angularjs-check-if-ng-model--isfinite
CC-MAIN-2017-43
refinedweb
136
63.8
Handling errors in GraphQL André König Feb 14 Updated on Mar 04, 2018 There has been some discussions recently about how to handle errors in GraphQL resolvers. I mentioned apollo-errors because I had very good experiences with it. In this article, I want to take the chance and describe my approach of handling errors in a GraphQL API. Anatomy of an error Before diving deep into how to establish a proper error handling, I would like to differentiate a little bit what kind of errors we are talking about here. Basically, as in all user-facing systems, there are two possible error types: Controlled errors: An exception which indicates that the user did something wrong (e.g. Wrong login credentials, etc.) Uncontrolled errors: The counterpart. An exception that indicates that something really bad happened (e.g. storage system not available, etc.) The ones we are most interested in are the controlled errors. These are the ones which you as the software engineer define and throw when the particular case has happened. Uncontrolled errors, as the name states, are the ones which can happen all the time. Even if they are not controllable, you will learn how to handle them gracefully as well. The common approach When reading about GraphQL, you will often see the following example: if (!areCredentialsValid) { throw new Error("Authentication required"); } This is a simple approach and might be sufficient in most cases. The downside here is that a respective client has a hard time figuring what kind of an error this actually is. A err.message === "Authentication required" in the client is not cool at all. It would be great to have a kind of error type, right? This is where apollo-errors comes to play. Let's go! A more robust approach Let's consider the following scenario: We have a login mutation and we want to throw an error when the user entered wrong credentials. A possible type could be WrongCredentialsError. The first step to do is creating the actual error type: // path: resolvers/mutation/login/errors/WrongCredentialsError.ts import { createError } from "apollo-errors"; const WrongCredentialsError = createError("WrongCredentialsError", { message: "The provided credentials are invalid." }); export { WrongCredentialsError } Now where we have our error type, we can throw it from our login mutation resolver: // path: resolvers/mutation/login/index.ts import { WrongCredentialsError } from "./errors/WrongCredentialsError"; interface LoginInput { username: string; password: string; } const login = await (parent, args: LoginInput, context: Context, info) { const user = await context.db.query.user({where: {username: args.username}}); const areCredentialsValid = checkCredentials(user, args.password); if (!areCredentialsValid) { throw new WrongCredentialsError(); } }; So when this mutation gets executed and the user entered wrong credentials the GraphQL API would respond with: { "data": {}, "errors": [ { "message":"The provided credentials are invalid.", "name":"WrongCredentialsError", "time_thrown":"2018-02-14T00:40:50.954Z", } ] } Pretty, isn't it? So, in theory the GraphQL API would respond with this. There is one missing puzzle piece. Due to the different error structure, we have to tell the GraphQL API endpoint that those errors should be formatted differently. But no worries, installing the formatter is an one-time shot and easily done. The following describes how to hook the formatter up on a graphql-yoga based application. import { GraphQLServer, Options } from "graphql-yoga"; import { formatError } from "apollo-errors"; const options: Options = { formatError }; const server = new GraphQLServer({ typeDefs, resolvers }) server.start(options, () => console.log('GraphQL API is running on localhost:4000')) That's it! You're able to throw named controlled errors now. Handling uncontrolled errors gracefully As promised above, I mentioned to give you an approach to handle uncontrolled errors gracefully as well. You may have read from the code snippets, that I use Prisma for interacting with my database. Let us assume that I've messed something up (e.g. sent a stuffy query to my database, etc.). In those cases, where something really bad happened, we want to inform the client that a FatalError occurred. How can we achieve this? One approach would be to put each Prisma interaction in a try / catch and throw the FatalError there. That would work, but is pretty cumbersome because you have to handle that in all your resolvers. The other approach could be to wrap all our resolvers into a wrapper that executes the actual resolver and checks if that resolver didn't throw an uncontrolled error. Let us call this wrapper helmet. It could look like: // path: resolvers/helmet.ts import { FatalError } from "./errors/FatalError"; const helmet = (resolver) => async (...args) => { try { // // Try to execute the actual resolver and return // the result immediately. // return await resolver(...args); } catch (err) { // // Due to the fact that we are using Prisma, we can assume // that each error from this layer has a `path` attribute. // // Note: The `FatalError` has been created before by // using `apollo-errors` `createError` function. // if (err.path) { throw new FatalError({ data: { reason: err.message } }); } else { throw err; } } }; export { helmet }; In order to actually handle the uncontrolled errors gracefully, you have to wrap your resolvers into that helmet function. Here for example, we use the login mutation described above: // path: resolvers/mutation/index.ts import { helmet } from "../helmet"; import { login } from "./login"; const Mutation = { login: helmet(login) // ... }; export { Mutation }; Conclusion Even when just throwing an Error object right away might be sane in some scenarios, I would suggest considering an approach like the one described in this post for larger applications. Remember, one of GraphQL's strengths is its expressiveness. Why shouldn't you treat your errors also like that? I hope you enjoyed the post and I'm happy to hear your thoughts :) Junior Dev Survival Guide: How to Communicate About Code A guide to clearly and effectively communicating about your code to your team mates, so you can solve problems together efficiently. Coincidentally I was reading through that exact part of the spec on errors yesterday and found a few neat things: There is only one requirement for the relationship between data and errors return value: if the query is null/empty there must be an error message The spec recommends that implementations provide a char index in the query in the error message where the error occurred. I don't think all servers I've tried follow this, but the major ones do IME Overall, the GraphQl spec doesn't enforce a whole lot with the response format - it doesn't even need to be JSON! I do like that the rules needed to have reliable interaction are pretty rigorously defined but it leaves room for extension of the protocol.
https://dev.to/andre/handling-errors-in-graphql--2ea3
CC-MAIN-2018-13
refinedweb
1,085
56.35
Lead2pass 2017 November New EC-Council 312-50v9 Exam Dumps! 100% Free Download! 100% Pass Guaranteed! 312-50v9 exam questions and answers provided by Lead2pass will guarantee you pass 312-50v9 exam, because Lead2pass is the top IT Certification study training materials vendor. Many candidates have passed exam with the help of Lead2pass. We offer the latest 312-50v9 PDF and VCE dumps with new version VCE player for free download, you can pass the exam beyond any doubt. Following questions and answers are all new published by EC-Council Official Exam Center: QUESTION 321 322 Which service in a PKI will vouch for the identity of an individual or company? A. KDC B. CA C. CR D. CBC Answer: B QUESTION 323 In IPv6 what is the major difference concerning application layer vulnerabilities compared to IPv4? A. Implementing IPv4 security in a dual-stack network offers protection from IPv6 attacks too. B. Vulnerabilities in the application layer are independent of the network layer. Attacks and mitigation techniques are almost identical. C. Due to the extensive security measures built in IPv6, application layer vulnerabilities need not be addresses. D. Vulnerabilities in the application layer are greatly different from IPv4. Answer: B QUESTION 324 In which phase of the ethical hacking process can Google hacking be employed? This is a technique that involves manipulating a search string with specific operators to search for vulnerabilities. Example: allintitle: root passwd A. Maintaining Access B. Gaining Access C. Reconnaissance D. Scanning and Enumeration Answer: C QUESTION 325 Which type of security feature stops vehicles from crashing through the doors of a building? A. Turnstile B. Bollards C. Mantrap D. Receptionist Answer: B QUESTION 326 ……..is an attack type for a rogue Wi-Fi access point that appears to be a legitimate one offered on the premises, but actually has been set up to eavesdrop on wireless communications. It is the wireless version of the phishing scam. An attacker fools wireless users into connecting a laptop or mobile phone to a tainted hotspot by posing as a legitimate provider. This type of attack may be used to steal the passwords of unsuspecting users by either snooping the communication link or by phishing, which involves setting up a fraudulent web site and luring people there. Fill in the blank with appropriate choice. A. Collision Attack B. Evil Twin Attack C. Sinkhole Attack D. Signal Jamming Attack Answer: B QUESTION 327 Which access control mechanism allows for multiple systems to use a central authentication server (CAS) that permits users to authenticate once and gain access to multiple systems? A. Role Based Access Control (RBAC) B. Discretionary Access Control (DAC) C. Windows authentication D. Single sign-on Answer: D QUESTION 328 What attack is used to crack passwords by using a precomputed table of hashed passwords? A. Brute Force Attack B. Hybrid Attack C. Rainbow Table Attack D. Dictionary Attack Answer: C QUESTION 329 Your next door neighbor, that you do not get along with, is having issues with their network, so he yells to his spouse the network’s SSID and password and you hear them both clearly. What do you do with this information? A. Nothing, but suggest to him to change the network’s SSID and password. B. Sell his SSID and password to friends that come to your house, so it doesn’t slow down your network. C. Log onto to his network, after all it’s his fault that you can get in. D. Only use his network when you have large downloads so you don’t tax your own network. Answer: A QUESTION 330 Shellshock had the potential for an unauthorized user to gain access to a server. It affected many internet- facing services, which OS did it not directly affect? A. Windows B. Unix C. Linux D. OS X Answer: D QUESTION 331 You want to analyze packets on your wireless network. Which program would you use? A. Wireshark with Airpcap B. Airsnort with Airpcap C. Wireshark with Winpcap D. Ethereal with Winpcap Answer: A QUESTION 332 It has been reported to you that someone has caused an information spillage on their computer. You go to the computer, disconnect it from the network, remove the keyboard and mouse, and power it down. What step in incident handling did you just complete? A. Containment B. Eradication C. Recovery D. Discovery Answer: A QUESTION 333 What is the code written for? #!/usr/bin/python import socket buffer=[“A”] counter=50 while len(buffer)<=100: buffer.apend (“A”*counter) counter=counter+50 commands=[“HELP”,“STATS.”,“RTIME.”,“LTIME.”,“SRUN.”,“TRUN.”,“GMON.”,“GDOG.”,“KSTET.”,“GTER.”,“HTER.”,“LTER.”,“KSTAN.”] for command in commands: for buffstring in buffer: print “Exploiting” +command+“:”+str(len(buffstring)) s=socket.socket(socket.AF_INET.socket.SOCK_STREAM) s.connect((‘127.0.0.1’,9999)) s.recv(50) s.send(command+buffstring) s.close() A. Buffer Overflow B. Encryption C. Bruteforce D. Denial-of-service (Dos) Answer: A Explanation: QUESTION 334 335 Which of the following is a serious vulnerability in the popular OpenSSL cryptographic software library. This weakness allows stealing the information protected, under normal conditions, by the SSL/TLS encryption used to secure the Internet. A. Heartbleed Bug B. POODLE C. SSL/TLS Renegotiation Vulnerability D. Shellshock Answer: A QUESTION 336 There are several ways to gain insight on how a cryptosystem works with the goal of reverse engineering the process. A term describes when two pieces of data result in the same value is? A. Collision B. Collusion C. Polymorphism D. Escrow Answer: C QUESTION 337 Which of the following security policies defines the use of VPN for gaining access to an internal corporate network? A. Network security policy B. Remote access policy C. Information protection policy D. Access control policy Answer: B QUESTION 338 One of the Forbes 500 companies has been subjected to a large scale attack. You are one of the shortlisted pen testers that they may hire. During the interview with the CIO, he emphasized that he wants to totally eliminate all risks. What is one of the first things you should do when hired? A. Interview all employees in the company to rule out possible insider threats. B. Establish attribution to suspected attackers. C. Explain to the CIO that you cannot eliminate all risk, but you will be able to reduce risk to acceptable levels. D. Start the Wireshark application to start sniffing network traffic. Answer: C QUESTION 339 Which of the following is an NMAP script that could help detect HTTP Methods such as GET, POST, HEAD, PUT, DELETE, TRACE? A. http-git B. http-headers C. http enum D. http-methods Answer: D QUESTION 340 Which of the following is the most important phase of ethical hacking wherein you need to spend considerable amount of time? A. Gaining access B. Escalating privileges C. Network mapping D. Footprinting Answer: D More free Lead2pass 312-50v9 exam new questions on Google Drive: Lead2pass is the leader in supplying candidates with current and up-to-date training materials for EC-Council certification and exam preparation. Comparing with others, our 312-50v9 exam questions are more authoritative and complete. We offer the latest 312-50v9 PDF and VCE dumps with new version VCE player for free download, and the new 312-50v9 dump ensures your exam 100% pass. 2017 EC-Council 312-50v9 (All 589 Q&As) exam dumps (PDF&VCE) from Lead2pass: [100% Exam Pass Guaranteed]
http://www.freepass4sure.net/lead2pass-new-312-50v9-exam-dump-free-updation-availabe-in-lead2pass-321-340.html
CC-MAIN-2019-26
refinedweb
1,238
57.57
Opened 9 years ago Closed 9 years ago #4320 closed (fixed) unicode-branch - admin select view doesn't work for localized field with choices Description I have this simple model: from django.db import models from django.utils.translation import ugettext_lazy as _ class MyModel(models.Model): my_field = models.CharField(choices=(('a', _('a')), ('b', _('b'))), maxlength=1) class Admin: list_display = ['my_field'] TypeError is thrown: TypeError at /admin/my_app/mymodel/ unicode.__cmp__(x,y) requires y to be a 'unicode', not a 'str' Request Method: GET Request URL: Exception Type: TypeError Exception Value: unicode.__cmp__(x,y) requires y to be a 'unicode', not a 'str' Exception Location: /usr/local/lib/python2.4/site-packages/django/contrib/admin/templatetags/admin_list.py in items_for_result, line 184 This problem can be solved by the attached patch. Attachments (1) Change History (4) Changed 9 years ago by anonymous comment:1 Changed 9 years ago by anonymous - Needs documentation unset - Needs tests unset - Patch needs improvement unset - Version changed from SVN to other branch comment:2 Changed 9 years ago by mtredinnick - Triage Stage changed from Unreviewed to Accepted comment:3 Changed 9 years ago by mtredinnick - Resolution set to fixed - Status changed from new to closed Note: See TracTickets for help on using tickets. smart_unicode() and ugettext_lazy() don't work properly together yet (#4295). This patch will stop working once that bug is fixed. I'll fix it properly once I've worked out a solution to #4295.
https://code.djangoproject.com/ticket/4320
CC-MAIN-2016-22
refinedweb
246
53.92
JavaScript in QML Like many features in Cascades, the implementation and use of JavaScript is based on the JavaScript implementation in Qt, but there are some differences. For more information about the Qt implementation, see Integrating JavaScript on the Qt website. Otherwise, continue reading the sections below to learn how to use JavaScript in Cascades. For a complete list of JavaScript objects and functions that are supported in QML, see ECMAScript Reference in the Qt documentation. JavaScript in signal handlers The most common use of JavaScript in QML is within signal handlers. Inside signal handlers, you use JavaScript to determine what you want your app to do in response to the signal. You can set values for properties of QML components, perform calculations, or call other JavaScript functions that you define. Here's how to create a button that, when it's clicked, changes the size of a colored container. Using basic JavaScript code, the container alternates between two sizes when the button is clicked: import bb.cascades 1.2 Page { Container { Button { text: "Change size" onClicked: { if (myContainer.preferredWidth == 200) { myContainer.preferredWidth = 400; myContainer.preferredHeight = 400; } else { myContainer.preferredWidth = 200; myContainer.preferredHeight = 200; } } } Container { id: myContainer preferredWidth: 200 preferredHeight: 200 background: Color.Blue } } } Notice the difference in syntax between JavaScript and QML. You set the values of properties in JavaScript by using an equal sign (=) and you set the values in QML by using a colon (:). For more information about signal handlers, see Signals and slots. Creating custom JavaScript functions You can write your own custom JavaScript functions in line in QML. These functions become part of the QML component that contains them and you can call them by using the id property of the component. These functions can accept parameters and even return values that you can use elsewhere in your app. Here's how to create a custom JavaScript function that calculates the Celsius equivalent of a Fahrenheit temperature value. You can type the Fahrenheit value in a text field, click a button, and the Celsius value appears as the text of a Label below the text field: import bb.cascades 1.2 Page { Container { id: root // The custom JavaScript function called convertTemp() function convertTemp(fahr) { fahr = parseInt(fahr); return ((fahr - 32) * 5) / 9; } Button { text: "Convert" onClicked: { tempOutput.text = "" + root } } } } Importing JavaScript code If you have multiple JavaScript functions that you want to use, you can place them in a separate file and then import them into your app instead of defining them in QML. You can define these functions in a .js file that's located in the assets folder of your project, and use the import statement in your .qml file to import them and make them available in your app. You must qualify the JavaScript files that you import by using the as keyword and providing a unique name for the file. This name can't be the same as any other modules that you import and can't be the same as any default JavaScript objects (such as Number or String). For example, let's say that you create a file called tempFunctions.js that includes the convertTemp() function from the sample code in the previous section. Here's how to import that file and use the function in QML: import bb.cascades 1.2 import "tempFunctions.js" as TemperatureFunctions Page { Container { Button { text: "Convert" onClicked: { // Call the convertTemp() function from the // imported JavaScript file tempOutput.text = "" + TemperatureFunctions } } } } Connecting signals to JavaScript functions In the previous sections, you learned how to call JavaScript functions from signal handlers (such as the onClicked signal handler for a Button) in QML. Instead of calling a JavaScript function explicitly, you can connect the function to a signal. When the signal is emitted, the function is called automatically. The JavaScript function acts as a slot and allows you to connect signals to it. Here's how to create a button that, when it's clicked, calls a custom JavaScript function that changes the text of a Label. To connect the signal to the JavaScript function, you use a signal handler for the Container control called onCreationCompleted. This signal handler is run in response to the creationCompleted() signal that's emitted after the container is created successfully and can be a good time to perform setup or initialization operations for your app: import bb.cascades 1.2 Page { Container { id: root // The custom JavaScript function called changeText() function changeText() { if (myLabel.text == "First text string") myLabel.text = "Second text string"; else myLabel.text = "First text string"; } Button { id: myButton text: "Change" } Label { id: myLabel text: "First text string" textStyle { base: SystemDefaults.TextStyles.BigText } } // When the container is created, connect the // button's clicked() signal to the custom JavaScript // function changeText() onCreationCompleted: { myButton.clicked.connect(root.changeText); } } } Last modified: 2015-03-31 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/documentation/dev/javascript/index.html
CC-MAIN-2017-22
refinedweb
819
55.74
flutter_login_vk 1.0.0 flutter_login_vk: ^1.0.0 copied to clipboard flutter_login_vk # Flutter Plugin to login via VK.com. Easily add VK login feature in your application. User profile information included. SDK version # VK SDK version, used in plugin: Minimum requirements # - iOS 9.0 and higher. - Android 4.1 and newer (SDK 16). ⚠️ If your project was create with Flutter pre 1.12 you should upgrade it to the Android embedding v2. See Getting Started # To use this plugin: - add flutter_login_vkas a dependency in your pubspec.yaml file; - create an app on VK.com - setup android; - setup ios; - additional VK.com app setup; - use plugin in application. See documentation on VK.com for full information: And here is instructions in Russian if it's your native language (русская версия). App on VK.com # Create an app on VK.com - Enter "Title". - Select Standalone app as "Platform". - Click "Connect app". An application will be created. Now select tab "Settings" and copy "App ID" (referenced as [APP_ID] in this readme). App settings for Android Set Package name for Android- your package name for Android application (attribute packagein AndroidManifest.xml). Set Main activity for Android- your main activity class (with package). By default it would be com.yourcompany.yourapp.MainActivity. To fill up Signing certificate fingerprint for Androidyou should create SHA1 fingerprint as described in the documentation (without SHA1:prefix). Add fingerprints for debug and release certificates. Note: if your application uses Google Play App Signing than you should get certificate SHA-1 fingerprint from Google Play Console. ⚠️ Important! You should add fingerprints for every build variants. E.g. if you have CI/CD which build APK for testing with it's own cerificate (it may be auto generated debug cetificate or some another) than you should add it's fingerprint too. Click "Save". App settings for iOS - Add your Bundle Identifier - set App Bundle ID for iOS(you can find it in Xcode: Runner - Target Runner - General, section Identity, field Bundle Identifier). - Also set App ID for iOS, it's you SKU(you can find it in App Store Connect: My Apps - {Your application} - App Store - App Information, section "General Information"). Mostly often is't the same as bundle ID. - Click "Save". Android # Edit AndroidManifest.xml ( android/app/src/main/AndroidManifest.xml): - Add the INTERNETpermission in the root of <manifest>, if you haven't (probably you have): <uses-permission android: - Add an activity to the section application: <activity android: See full AndroidManifest.xml in example. iOS # Configure Info.plist ( ios/Runner/Info.plist). You can edit it as a text file from your IDE, or you can open project ( ios/Runner.xcworkspace) in Xcode. - In Xcode right-click on Info.plist, and choose Open As Source Code. - Copy and paste the following XML snippet into the body of your file ( <dict>...</dict>), replacing [APP_ID]with your application id: <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>vk[APP_ID]</string> </array> </dict> </array> - Also add to Info.plistbody ( <dict>...</dict>): <key>LSApplicationQueriesSchemes</key> <array> <string>vk</string> <string>vk-share</string> <string>vkauthorize</string> </array> See full Info.plist in example. ⚠️ NOTE. Check if you already have CFBundleURLTypes or LSApplicationQueriesSchemes keys in your Info.plist. If you have, you should merge their values, instead of adding a duplicate key. If you want to use scope=nohttps, which we strongly do not recommend, you should also add NSAppTransportSecurity, see the documentation. Additional VK.com app setup # Go to My Apps and click "Manage" on your app. On tab "Information" you should: - Enter "Description". - Select a suitable "Category". - Upload small icon "32x32 icon". - Click "Save". - Upload "Square banner" and "A square banner for catalog" - user can see it. Setup other settings if you need it. Than go to "Setting" tab and turn on application: change "App status" from Application off to Application on and visible to all. Click "Save". Usage in application # First, you should create an instance of VKLogin. Than, before any method call or checking accessToken, you should initialize VK SDK with your application id ( [APP_ID]): final vk = VKLogin(); final appId = '7503887'; // Your application ID await vk.initSdk(appId); Now you can use the plugin. Features: - log in via VK.com; - get access token; - get user profile; - get user email; - check if logged in; Sample code: import 'package:flutter_login_vk/flutter_login_vk.dart'; // Create an instance of VKLogin final vk = VKLogin(); // Initialize await vk.initSdk('7503887'); // Log in final res = await vk.logIn(permissions: [ VKScope.email, VKScope.friends, ]); // Check result if (res.isValue) { // There is no error, but we don't know yet // if user loggen in or not. // You should check isCanceled final VKLoginResult data = res.asValue.value; if (res.isCanceled) { // User cancel log in } else { // Logged in // Send access token to server for validation and auth final VKAccessToken accessToken = res.accessToken; print('Access token: ${accessToken.token}'); // Get profile data final profile = await fb.getUserProfile(); print('Hello, ${profile.firstName}! You ID: ${profile.userId}'); // Get email (since we request email permissions) final email = await fb.getUserEmail(); print('And your email is $email'); } } else { // Log in failed final errorRes = res.asError; print('Error while log in: ${errorRes.error}'); } Initialization notes When you call initSdk(), plugin try to restore previous session. If token has been expired - it will be refreshed. Also, during restoring, log in screen may be shown to user (only if user was logged in). In additional, you can pass to initSdk() required scope, and if current user session doesn't provide it - user will be logged out. Also you can specify API version to use, but you shouldn't.
https://pub.dev/packages/flutter_login_vk
CC-MAIN-2021-21
refinedweb
927
52.36
To visualize the relationship between three variables, we generally need a three-dimensional graph. Surface plots are two-dimensional diagrams of three-dimensional data. Surface plots show the functional relationship between independent and dependent variables. 1. Import libraries We don’t need to import the entire matplotlib module, pyplot should be enough. Make sure to import numpy for any mathematics needed for the plot. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D 2. Introduce data This usually comprises of two independent-variable arrays and a dependent variable array. x = np.arange(0, 25, 1) y = np.arange(0, 25, 1) x, y = np.meshgrid(x, y) z = x + y 3. Draw a plot fig = plt.figure() axes = fig.gca(projection ='3d') axes.plot_surface(x, y, z) plt.show() import numpy as np # For mathematics, and making arrays import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Arrays x, y and z for data plot visualization x = np.arange(0, 25, 1) y = np.arange(0, 25, 1) # meshgrid makes a retangular grid out of two 1-D arrays. x, y = np.meshgrid(x, y) z = x**2 + y**2 # x^2+y^2 # surface plot for x^2 + y^2 fig = plt.figure() # creates space for a figure to be drawn # Uses a 3d prjection as model is supposed to be 3D axes = fig.gca(projection ='3d') # Plots the three dimensional data consisting of x, y and z axes.plot_surface(x, y, z) # show command is used to visualize data plot plt.show() RELATED TAGS View all Courses
https://www.educative.io/answers/how-to-create-surface-plots-in-python
CC-MAIN-2022-33
refinedweb
265
54.59
How to Adjust I.R.S. Tax Deductions (U.S.A.) Edited byDavjohn and 10 others! Edit (a PDF available at:) together. Read all of the forms thoroughly so you have a good idea of the information you will need before you do anything else. This includes the return (1040/A/EZ), and the supplemental forms (Schedule A, EIC form 596, Child Tax Credit form 972, Dependent Child Care Expenses form 2441, Additional Child Tax Credit form 8812). Take the time to get everything in order before you start doing anything. It will take a few minutes, but it will pay off later. Have. - 4taxes withheld from your paycheck in order to get the highest refund after you file. You can also claim the maximum allowance of 99, but be careful when doing so, as you may end up owing money at filing time. You can change this at any time during the year. Just file a new W-4 and your withholding will change. - 5refund, you may have to send some of it back. Form to File - 1 without printing out the whole thing. It's just as easy and it has all the same information. While you're at it, pull up the IRS Pub 17.[1] - 1040 and the Schedule A. - deductions and credits as with the 1040, but there's much less detail required. Just compare the back page of the 1040 and the 1040-A to make sure you didn't miss anything. Average expenses means that if you fill out and add all of the itemizations on Schedule A, and they are less than the standard deduction, the 1040-A is probably your form of choice. - - 2Depending upon your income sources, look for other appropriate schedules you might need to file: - For Self-Employment Tax, use Form 1040-SS. This is not the same as Self Employment Income. - For Non-Resident Tax, use Form 1040-NR. - For Interest and Ordinary Dividends, use Schedule B. - For Profit or Loss from Business (Sole Proprietorship), use Schedule C. - For Capital Gains and Losses, use Schedule D. - For Supplemental Income and Loss use, Schedule E. - For Farming, use Schedule F. - For Household Employment Taxes, use Schedule H. - For Self-Employment Tax, use Schedule SE. - For Estimated Tax, use Form ES. - 3Once you decide on your return form get the instructions and a copy of the Pub 17. The IRS wants you to do your own taxes; that's why they spend so much time and money to provide the instructions, Pub 17, worksheets, telephone help lines, etc. Don't let all this sound complicated. We've all been programmed to fear the IRS, but they actually go out of their way to make things easier. - 4Put the label from your booklet on the address area, or simply fill it in completely. Turn the form over and put your name(s) and Social Security Number in the head space at the top so you don't forget later. If your spouse passed away during the year, or you are filing as Qualifying Widow(er), write DECEASED after the name of your spouse. Most people forget this simple little step, but the IRS wants it, and it is helpful. Filing Status - 1Choose your filing status based on your marital status first, and then consider your household status. - Single--if you are unmarried and have no dependents, you will claim Single. on page 22.[2] - Married Filing Jointly-MFJ--if you are married, select Married Filing Jointly (MFJ). You are considered married if you have lived.[3] - Married Filing Separately-MFS--if you are married, but legally separated, you may have to file MFS. You can file MFS is this results in a lower tax liability than the joint return, or if you choose to file for only your.[4] - Under MFS, if your spouse files for deductions and credits due to you, because you have child custody, for example, you can claim the proper deductions and credits by filing the Innocent Spouse Relief form 8857.[5] - Qualifying Widow(er)-QW--If you are widowed during the year being reported you should still use the MFJ for that year. The following two years you can use the Qualified Widow(er) status or single, whichever gives you a lower tax liability. After that you will use Single, or Head of Household, if you qualify.[6] - Head of Household-HH--if you are unmarried, paid more than 50 percent of the cost of keeping a home, and have Qualifying person living with you, except your dependent parent doesn't have to fit the residency test, you may be able to file Head of Household.[7] - 2Death of a spouse: If your spouse died during the year being reported you would still file MFJ, but if your spouse died after the first of the year, but before the tax forms are signed, the administrator or executor of the will is to sign. Other exceptional criteria are found in the IRS Pub 17 on page 23.[8] Dependents - 1Once your filing status is determined, move on to your dependents. This part can be complicated and confusing. You will want to refer to the Pub 17 if you have anything but the standard dependents. To take an example, a single woman with a child lives with her mother. Both adults work and make enough to file, but the mother pays more than 50 percent of the household expenses. Under all the obvious conditions, she could claim both the daughter and the daughter's child. Not so. When the daughter files, only she can claim her child. - There are also separate rules for what are known as Qualifying Child and Qualifying Relative.[9] - There are 6 conditions that must be met in order for a child to be your Qualifying Child: see the IRS Pub 19 at page 29.[10] - Relationship--son, daughter, or their descendants, sibling or descendant of any, halves and adopted included. - Age--younger than 19 on December 31, younger than 24 if a full time student, younger than you or your spouse if you are MFJ, and/or permanently disabled (regardless of age). You can't claim a step-child that is older than you, even if s/he is 18. - Residency--must live with you 6 months out of the year. - Support--you pay more than half of his/her support. The Support Test is always the same. More than 50 percent. - Joint Return--the Qualifying Child cannot be married and filing a joint return. - Special Conditions for a Qualifying Child of more than one person. If another person can claim this dependent, the person who meets all of the first 5 tests claims the child. Tie breaker rules will identify who can take the exemption. Tie breaker rules are residency and support oriented. This is why detailed records are so important. If the child lived with you 183 days of the year, but you can't prove 50+ percent support, compared to the other parent, you may lose the exemption. - There are four conditions that must be met in order for a person to be a Qualifying Relative: - Cannot be a Qualifying Child, - Member of Household or Relationship--must be a member of the household or qualify by relationship. Some exceptions are allowed to this rule. The exemptions can be found on page 33 of the IRS Pub 17. These Qualifying Children are very often claimed with the Head of Household filing status. - Gross income--must be less than the established maximum for that year. - Support--must contribute more than 50 percent of his/her support. See Pub 17 for dollar and/or percentage amounts. If neither person contributes more than 50 percent of his or her support a Multiple Support Agreement, Form 2120, must be filed. - Note: A Qualifying Child or Qualifying Relative can work and file his/her own return, but s/he can not take any dependent exemption. The filing is only to claim income and receive a refund. Also, if someone else can claim you, you can file to report your own income and get a refund, but can not take any dependent exemptions. Adjustments - 1Insert your gross income on the first line after the dependent exemption section. Everything after this line, before the adjusted gross income, are adjustments. - Additions Of Taxable Interest, and Unemployment on the 1040-EZ; Taxable Interest, Dividends, Capital Gains, Ira Distributions, Pensions, Unemployment, SSA Benefits, And Deductions Of Educator Expenses, Ira Deductions, Student Loan Interest Deductions, Tuition And Fees Deductions on the 1040-A; and others on the 1040. - 2This is where the 972, 2441, & 596 Forms and Publications come into play. The majority of adjustments are available year to year, others are only available as passed. These are adjustments allowed only for certain qualified claimants that congress must approve on a yearly basis such as the Educator's Allowance for teachers. You can go to the IRS web site, usually in December, and the adjustments should be listed there. Be careful to look for them. The most common credits are: - For Earned Income Credit Schedule EIC, sometimes called the Earned Income Tax Credit, use the form with Pub 596, - Child Tax Credit (Publ 972), - Dependent Child Care Expenses (Publ 2441). - Additional Child Tax Credit (Publ 8812). Additional here doesn't mean more, it means another. The Additional Child Tax Credit is a refundable tax credit for people who have a qualifying child and did not receive the full amount of the Child Tax Credit. If you qualify for the full, regular Child Tax Credit, you can't claim the Additional Child Tax Credit. - 3Pay special attention to all the adjustments on the front of the 1040 form. There are some that are allowed even though you do not itemize. - 4Deductions for education that is required to keep your job, educator's supplies, business uniforms and necessary expendable supplies and other similar expenses that are not paid for by the employer are often missed in the itemization. - 5Claim the filing status and exemptions on page one, and the tax credits, and payments on page two. - 6Once you've gotten this far and if you're not itemizing, you're done here. Just do the math, check your figures, sign the form, and relax over a job well done. Itemizing - 1Regardless of which form you are using in addition to the 1040, aside from credits, it's itemizing. Keep detailed records for all itemizing expenses. Read through the instructions line by line. Don't get aead of yourself and you won't get confused. - Medical and dental expenses;[11] - Certain taxes you've paid; - Receipts for interest paid on home loan and for property tax including tax paid as part of your mortgage payments; (See 1040 Schedule A Worksheet) - Charitable and religious contributions;[12] - Casualty and theft losses; - Job expenses and miscellaneous deductions; - Required non-reimbursed job expenses including your business expenses such as: travel and temporary lodging (but not commuting expenses to your regular job location), required job training and education that is required to keep your employment, as well as professional dues;[13] - Special allowed deductions for damages in times of a theft, or local natural disaster where you have direct damages (including your personal costs of losses due to fire, storm, flood, for example: major natural disasters such as 2004 Sumatran Tsunami, 2005 for Hurricane Katrina, 2009 Haiti Earthquake, etc.).[14] - "Other Miscellaneous Deductions" for page A-11 of the Form 1040 Schedule A. - 2Read official IRS tax filing instructions for the schedule you've chosen to be sure that you know and understand the itemizations and the meanings of the IRS instructions.[15] Edit Video EditTips -, not so should you make unlawful claims. - All forms are searchable on the IRS Topical Index. [16] - Forms and Instructions are listed on the IRS Form Picklist. [17] - Publications are listed on the IRS Publication Picklist. [18] - Make sure all lines are filled in. - IRS Publication 17 is called the Preparer's Bible. If you have any questions about exemptions, deductions, or credits you will find all your answers here. - Many of the credits require separate forms to be included to support those claimed on side 2 of Form 1040.. - Because of the Special Rules, MFS would generally assess a higher tax. - For more forms that are commonly used in personal filing see the IRS Picklist. [19] - Don't get Common-Law and Community Property confused. - Common Law marriages must be dissolved or separated in the same means as marriages in all other states. EditWarnings -. - Putting furniture out on the curb is not a charitable contribution, even if someone takes it. - A section of a common room in the house cannot be claimed as an office, but a specific, isolated space clearly for your home business office may be allowed. -. EditRelated wikiHows Edit Sources and Citations - ↑ - ↑ - ↑ - ↑ – IRS Pub 17. p.23 - ↑ – IRS Pub 17. p.24. - ↑ – IRS Pub 17. p.24 - ↑ – IRS Pub 17. p.243 - ↑ - ↑ – IRS Pub 17 pages 28, 32 - ↑ - ↑ – IRS Pub 17. p.149 - ↑ – IRS Pub 17. p.18, 163, 171 - ↑ – IRS Pub 17. pp. 192, 194 - ↑ – IRS Pub 17. p.190 - ↑ - ↑ - ↑ - ↑ - ↑ Articles for You to Write Article Info Featured Article Last edited: April 25, 2012 by Jmuddy95 Categories: Featured Articles | Taxes and Fees Recent edits by: Howcast12345, Dvortygirl, Oliver (see all)
http://www.wikihow.com/Adjust-I.R.S.-Tax-Deductions-(U.S.A.)
crawl-003
refinedweb
2,232
64
Hi I'm having a lot of problems with this homework problem due tomorrow. The assignment is to make a program that can read data from a file and give out the wind chill, average temperature, average air speed, and average wind chill. It must also reject data that has a temperature (in fahrenheit) of larger than 50 or an air speed of larger the 120 mph. I haven't even written any function to calculate the average wind chill because I simply do not know how. There are definitely problems here, but I don't know how to correct or solve them. An example of some of the data from the file is: Temp Air speed 32 F 20 2 C 25 If a temperature is in Celsius the program must convert it back to fahrenheit. Any help is appreciated. #include <cstdlib> #include <cmath> #include <fstream> #include <iostream> using namespace std; ofstream outfile("WindChillOutfile.txt"); ifstream infile("/Users/richiemizrahi/Documents/C++/WindChill/weather.dat"); double Ta, V, Twc; double WindChill(); double AvgTemp(); double AvgAirSpeed(); int main() { double T, Ta, V, Twc; char scale; if (!infile.is_open() ) { cout << endl << "ERROR: Unable to open file" << endl; exit(1); } while (!infile.eof() ) { infile >> T >> scale >> V; if(!scale == 'F') { Ta = (T * 9 / 5) + 32; } if( !Ta > 50 || V > 120){ WindChill(); AvgTemp(); AvgAirSpeed(); }else ; outfile << "The temperature is " << Ta << " F, " << endl; outfile << "the air speed is " << V << " mph, " << endl; outfile << "and the wind chill index is " << Twc << " F." << endl; outfile << endl; outfile << AvgTemp << endl; outfile << AvgAirSpeed << endl; } return 0; } double WindChill() { Twc = 35.74 + (0.6215 * Ta) - (35.75 * pow(V,0.16)) + (.4275 * Ta * pow(V,0.16)); } double AvgTemp() { int counter; float average, number, sum; counter = 0; sum = 0; infile >> number; while ( !infile.eof() ){ ++counter; sum = sum + number; infile >> number; ; infile >> number; } average = sum / counter; outfile << "The average temperature is " << average << " F, " << endl; } double AvgAirSpeed() { int counter; float average, number, sum; counter = 0; sum = 0; infile >> number; while ( !infile.eof() ){ ; infile >> number; ++counter; sum = sum + number; infile >> number; } average = sum / counter; outfile << "the average air speed is " << average << " mph, " << endl; }
https://www.daniweb.com/programming/software-development/threads/385629/c-average-wind-chill
CC-MAIN-2018-43
refinedweb
349
63.59
Write an interactive C or C++ program to calculate the surface area of a cylinder. In the header comment of your code, write the pseudocode for the program. Include a screenshot showing that's you have tested your program. Write an interactive C or C++ program to calculate the surface area of a cylinder. In the header comment of your code, write the pseudocode for the program. Include a screenshot showing that's you have tested your program. cylinder surface area calculates with formula: 2*pi*R*h + 2*pi*R^2, so the input should be h and R values of cylinder. The program code: float area, R, h; area = 2*3.14*R*h + 2*3.14*R*R; that's all o thats it? thats all that i put in my complier? Of course, you need to write the other parts of the program to actually get it to compile and run. You also need to write the part that reads in input and prints the) Begin with the pseudo-code which apparently you have to write anyway. The formula for this only involves two variable, radius and height. You don't need <math.h>, but you do need pi, which you can just define this way: I would say the pseudo-code involves slightly more than just the formula, btwI would say the pseudo-code involves slightly more than just the formula, btwCode:#define PI 3.14 #include<stdio.h> #include<math.h> /*prompt the user for the radius get the radius prompt the user for the height get the height compute the surface area of the cylinder display the value of radius, height and the calculated surface area */ int main () { int r; int h; double sa; printf("Enter a value for the radius:"); scanf("%d",&r); printf("Enter a value for the height:"); scanf("%d",&h); sa= 2 * M_PI * (r * r) + 2 * M_PI * r * h; printf( "radius is %d\n", r); printf( "height is %d\n", h); printf( "surface area is %f\n", sa); return (0); is this right? I doubt if most cylinders would have a radius or a height, that would be an even integer. Better make them double. Either put a space before the % in your second scanf() line, or add a getchar() statement, after the first scanf() call, to pull the newline that scanf() will always leave behind, off the keyboard buffer. Second scanf() should be skipped unless you do. Also, use code tags on our forum, please. Just highlight the program code, and click on the "#" mark on the advanced reply window. Also, I'd add a getchar() or scanf() or something, on the line before the return, to hold the console window open long enough to get your screenshot, unless you redirect it, anyway. Last edited by Adak; 03-12-2009 at 09:55 AM.
https://cboard.cprogramming.com/c-programming/113212-helpp-do-not-know-where-start.html
CC-MAIN-2017-09
refinedweb
476
78.48
This site required JavaScript to be enabled. Click here to view a static menu. This page presents the FreeRTOS demo for the NEC 78K0R 16bit microcontroller. Note - since this page was written, NEC have merged with Renesas, and the links on this page have been updated accordingly. The demo project contains configurations for both the 78K0R/KG3 and 78K0R/KE3L target boards. A MINICUBE2 is used to interface between the IAR Embedded Workbench and the target boards. The MINICUBE2 is used for both flash programming and debugging. The 78K0R target boards allow for easy evaluation of the microcontroller by including the microcontroller itself along with the necessary reset, clock, power and debug circuitry on a board that routes all the microcontroller pins to connector mounting points along the edge of the PCB. 78K0R demo is called RTOSDemo.eww and can be located within the FreeRTOS\Demo\NEC_78K0R_IAR directory. The button is used to generate interrupts on INTP0. The demo project creates 22. The following demo specific tasks are created in addition to the standard demo tasks: Two register test tasks are created.. Most FreeRTOS demos demonstrate context switching from within an interrupt using a serial port loopback 'com test'. The 78K0R target board does not include an RS232 port so context switching from within interrupts is instead demonstrated using the interrupts generated by the button that is mounted directly onto the target board. Both the button push ISR and corresponding task are very basic. The ISR simply 'gives' a semaphore each time the button is pushed. The task simply blocks on the semaphore, then toggles an LED each time the semaphore is given by the ISR - effectively synchronising the task with the interrupt. When executing correctly the demo will behave as follows: There are also two constants that are specific to the NEC 78K0R port and demo: This must be set to match the selected compiler options. If the compiler options are set to use the 'near' code model and the 'near' data model then configMEMORY_MODE must be set to 0. If the compiler options are set to use the 'far' code model and the 'far' data model then configMEMORY_MODE must be set to 1. These are the only tested combinations of settings. Set configCLOCK_SOURCE to 0 to use an external clock source, or 1 to use the high speed internal clock source (typically 8MHz). include an assembly file wrapper. The simple button push interrupt is included in this demo to demonstrate the mechanism. The example is replicated below. First the assembly file wrapper. ; ISR_Support.h defines the portSAVE_CONTEXT and portRESTORE_CONTEXT ; macros. #include "ISR_Support.h" PUBLIC vButtonISRWrapper EXTERN vButtonISRHandler RSEG CODE:CODE ; The wrapper is the interrupt entry point. vButton vButtonIS C portion of the interrupt handler is just a standard C function. /* This standard C function is called from the assembly wrapper above. */ void vButtonISRHandler( void ) { short sHigherPriorityTaskWoken = pdFALSE; /* The code in this handler is just a copy of the button push interrupt code for demonstration only. */ /* 'Give' the semaphore to unblock the button task. */ xSemaphoreGiveFromISR( xButton.
https://www.freertos.org/NEC-78K-RTOS.html
CC-MAIN-2018-51
refinedweb
508
56.05
ECMAScript 6 standardizes the syntax of modules. A module is simply a Javascript file that you can load either on the application startup or lazily on the as-needed basis. ES6 modules give you complete control on what code to export to the external scripts and what to keep private to the module. Prepend a variable, a function, or a class definition with the keyword export, and all other scripts in your project can import the module’s API using the import keyword. For details of using modules, read this great post by Dr. Axel Rauschmayer. But the ECMAScript 6 specification doesn’t define module loaders, which can be used both in the browsers and in the standalone JavaScript engines. Eventually all Web browsers will support the System object that knows how to import modules, but meanwhile you can use the polyfill ES6 Module Loader or, if you want to go fancy and ensure that your AMD and/or CommonJS modules are also loaded in a standardized fashion, go with the universal system module loader called SystemJS. Since ES6 syntax is not fully supported by any of the modern browsers, you’d need to transpile the code from ES6 to ES5 using one of the transpilers such as Traceur or Babel. In this blog I’ll show you how to dynamically load ES6 modules in the Web browsers with auto-transpiling using Traceur. To run this example on your computer you’ll need to have node.js with npm installed. First, you need to download and install es6-module loader in any directory by running the following npm command: npm install es6-module-loader Then create an application folder and copy the file es6-module-loader.js there (this is a minimized version of the loader that was downloaded by npm). Our sample application will have two additional files: moduleLoader.html and shipping.js. For simplicity I’ll keep all these files in the same folder. Imagine that we develop an online store with a large code base. To avoid creating a monolithic application, we’ve split it into loadable modules. In particular, the module that handles shipping should be loaded only if the user clicks the Shipping button. Here’s the code of our “huge” shipping module: export function ship() { console.log("Shipping products..."); } function calculateShippingCost(){ console.log("Calculating shipping cost"); } Since I used the export keyword only in front of the ship() function, the function calculateShipptingCost() will remain private for the module and won’t be accessible from the outside. No need to implement the module design pattern with immediately-invoked function expressions, and no need to use a third-party framework like RequireJS. The file moduleLoader.html includes a script that loads and uses the shipping module. In this example I use Traceur for the on-the-fly transpiling of the ES6 code to ES5 so it can run in any browser. Here’s the file moduleLoader.html: <!DOCTYPE html> <html> <head> <title>modules.html</title> <script src=""></script> <script src="es6-module-loader.js"></script> </head> <body> <button id="shippingBtn">Load the Shipping Module</button> <script type="module"> let btn = document.querySelector('#shippingBtn'); btn.addEventListener('click', () =>{ System.import('shipping') .then(function(module) { console.log("Shipping module Loaded ", module); module.ship(); module.calculateShippingCost(); // will throw an error }) .catch(function(err){ console.log("In error handler", err); }); }); </script> </body> </html> In Line 5 we load the Traceur for transpiling. In line 6 we load es6-module-loader to support the System object that will load the shipping module using the import() call when the user clicks on the button. The import returns the ES6 Promise object, and when the module is loaded, the function specified in then() will be executed. In case of an error the control goes to the function catch().. To see this code in action you need to serve it using some Web server. I use WebStorm IDE for development, which comes with embedded Web server. Lets run moduleLoader.html in Google Chrome and open Chrome Developer Tools. This is my Chrome browser looks after I clicked on the button Load the Shipping Module: Look at the XHR tab in the middle of the window. The HTML page has loaded shipping.js after I clicked on the button. The size of this file is small and making an additional network call to get it seems like an overkill. But if the application consists of 10 modules 500KB each, modularization with lazy loading makes sense. At the bottom, on the console tab you see the message from the script in moduleLoader that the shipping module was loaded. Then it calls the function from ship() from the shipping module, and generates an error trying to call the function calculateShippingCost() as expected. In the real-world projects you should integrate transpiling in the project build, but I just wanted to illustrate the ease of the transpiling in the Web browser without any additional preparations. Transpilers allow you to start programming in ECMAScript today.
https://yakovfain.com/category/es6/
CC-MAIN-2021-49
refinedweb
835
55.54
- NAME - SYNOPSIS - DESCRIPTION - FEATURES AND CONVENTIONS - JUMP START FOR THE IMPATIENT - SEE ALSO - AUTHOR NAME Module::Build::WithXSpp - XS++ enhanced flavour of Module::Build SYNOPSIS In Build.PL: use strict; use warnings; use 5.006001; use Module::Build::WithXSpp; my $build = Module::Build::WithXSpp->new( # normal Module::Build arguments... # optional: mix in some extra C typemaps: extra_typemap_modules => { 'ExtUtils::Typemaps::ObjectMap' => '0', }, ); $build->create_build_script; DESCRIPTION This subclass of Module::Build adds some tools and processes to make it easier to use for wrapping C++ using XS++ (ExtUtils::XSpp). There are a few minor differences from using Module::Build for an ordinary XS module and a few conventions that you should be aware of as an XS++ module author. They are documented in the "FEATURES AND CONVENTIONS" section below. But if you can't be bothered to read all that, you may choose skip it and blindly follow the advice in "JUMP START FOR THE IMPATIENT". An example of a full distribution based on this build tool can be found in the ExtUtils::XSpp distribution under examples/XSpp-Example. Using that example as the basis for your Module::Build::WithXSpp-based distribution is probably a good idea. FEATURES AND CONVENTIONS XS files By default, Module::Build::WithXSpp will automatically generate a main XS file for your module which includes all XS++ files and does the correct incantations to support C++. If Module::Build::WithXSpp detects any XS files in your module, it will skip the generation of this default file and assume that you wrote a custom main XS file. If that is not what you want, and wish to simply include plain XS code, then you should put the XS in a verbatim block of an .xsp file. In case you need to use the plain-C part of an XS file for #include directives and other code, then put your code into a header file and #include it from an .xsp file: In src/mystuff.h: #include <something> using namespace some::thing; In xsp/MyClass.xsp #include "mystuff.h" %{ ... verbatim XS here ... %} Note that there is no guarantee about the order in which the XS++ files are picked up. Build directory When building your XS++ based extension, a temporary build directory buildtmp is created for the byproducts. It is automatically cleaned up by ./Build clean. Source directories A Perl module distribution typically has the module .pm files in its lib subdirectory. In a Module::Build::WithXSpp based distribution, there are two more such conventions about source directories: If any C++ source files are present in the src directory, they will be compiled to object files and linked automatically. Any .xs, .xsp, and .xspt files in an xs or xsp subdirectory will be automatically picked up and included by the build system. For backwards compatibility, files of the above types are also recognized in lib. Typemaps In XS++, there are two types of typemaps: The ordinary XS typemaps which conventionally put in a file called typemap, and XS++ typemaps. The ordinary XS typemaps will be found in the main directory, under lib, and in the XS directories (xs and xsp). They are required to carry the .map extension or to be called typemap. You may use multiple .map files if the entries do not collide. They will be merged at build time into a complete typemap file in the temporary build directory. The extra_typemap_modules option is the preferred way to do XS typemapping. It works like any other Module::Build argument that declares dependencies except that it loads the listed modules at build time and includes their typemaps into the build. The XS++ typemaps are required to carry the .xspt extension or (for backwards compatibility) to be called typemap.xsp. Detecting the C++ compiler Module::Build::WithXSpp uses ExtUtils::CppGuess to detect a C++ compiler on your system that is compatible with the C compiler that was used to compile your perl binary. It sets some additional compiler/linker options. This is known to work on GCC (Linux, MacOS, Windows, and ?) as well as the MS VC toolchain. Patches to enable other compilers are very welcome. Automatic dependencies Module::Build::WithXSpp automatically adds several dependencies (on the currently running versions) to your distribution. You can disable this by setting auto_configure_requires => 0 in Build.PL. These are at configure time: Module::Build, Module::Build::WithXSpp itself, and ExtUtils::CppGuess. Additionally there will be a build-time dependency on ExtUtils::XSpp. You do not have to set these dependencies yourself unless you need to set the required versions manually. Include files Unfortunately, including the perl headers produces quite some pollution and redefinition of common symbols. Therefore, it may be necessary to include some of your headers before including the perl headers. Specifically, this is the case for MSVC compilers and the standard library headers. Therefore, if you care about that platform in the least, you should use the early_includes option when creating a Module::Build::WithXSpp object to list headers to include before the perl headers. If such a supplied header file starts with a double quote, #include "..." is used, otherwise #include <...> is the default. Example: Module::Build::WithXSpp->new( early_includes => [qw( "mylocalheader.h" <mysystemheader.h> )] ) JUMP START FOR THE IMPATIENT There are as many ways to start a new CPAN distribution as there are CPAN distributions. Choose your favourite (I just do h2xs -An My::Module), then apply a few changes to your setup: Obliterate any Makefile.PL. This is what your Build.PL should look like: use strict; use warnings; use 5.006001; use Module::Build::WithXSpp; my $build = Module::Build::WithXSpp->new( module_name => 'My::Module', license => 'perl', dist_author => q{John Doe <john_does_mail_address>}, dist_version_from => 'lib/My/Module.pm', build_requires => { 'Test::More' => 0, }, extra_typemap_modules => { 'ExtUtils::Typemaps::ObjectMap' => '0', # ... }, ); $build->create_build_script; If you need to link against some library libfoo, add this to the options: extra_linker_flags => [qw(-lfoo)], There is extra_compiler_flags, too, if you need it. You create two folders in the main distribution folder: src and xsp. You put any C++ code that you want to build and include in the module into src/. All the typical C(++) file extensions are recognized and will be compiled to object files and linked into the module. And headers in that folder will be accessible for #include <myheader.h>. For good measure, move a copy of ppport.h to that directory. See Devel::PPPort. You do not write normal XS files. Instead, you write XS++ and put it into the xsp/ folder in files with the .xspextension. Do not worry, you can include verbatim XS blocks in XS++. For details on XS++, see ExtUtils::XSpp. If you need to do any XS type mapping, put your typemaps into a .map file in the xspdirectory. Alternatively, search CPAN for an appropriate typemap module (cf. ExtUtils::Typemaps::Default for an explanation). XS++ typemaps belong into .xspt files in the same directory. In this scheme, lib/ only contains Perl module files (and POD). If you started from a pure-Perl distribution, don't forget to add these magic two lines to your main module: require XSLoader; XSLoader::load('My::Module', $VERSION); SEE ALSO Module::Build upon which this module is based. ExtUtils::XSpp implements XS++. The ExtUtils::XSpp distribution contains an examples directory with a usage example of this module. ExtUtils::Typemaps implements progammatic modification (merging) of C/XS typemaps. ExtUtils::Typemaps was renamed from ExtUtils::Typemap since the original name conflicted with the core typemap file on case-insensitive file systems. ExtUtils::Typemaps::Default explains the concept of having typemaps shipped as modules. ExtUtils::Typemaps::ObjectMap is such a typemap module and probably very useful for any XS++ module. ExtUtils::Typemaps::STL::String implements simple typemapping for STL std::strings. AUTHOR Steffen Mueller <smueller@cpan.org> With input and bug fixes from: Mattia Barbon Shmuel Fomberg Florian Schlichting This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
https://metacpan.org/pod/Module::Build::WithXSpp
CC-MAIN-2016-36
refinedweb
1,321
57.47
Opened 6 years ago Closed 6 years ago Last modified 6 years ago #19384 closed Bug (fixed) Managers can no longer be used on abstract models Description Given the (contrived) models.py from django.db import models class ChoiceManager(models.Manager): def get_first_choice(self): return Choice1 class Choice(models.Model): choice = models.CharField(max_length=200) votes = models.IntegerField() choices = ChoiceManager() class Meta: abstract = True class Choice1(Choice): pass class Choice2(Choice): pass I get the following error when trying to access models.Choice.choices.get_first_choice() using 1.5 (master). Traceback (most recent call last): File "/home/mark/venvs/django-14/abstract_managers/demo/tests.py", line 20, in test_abstract_manager models.Choice.choices.get_first_choice() File "/home/mark/venvs/django-15/src/django/django/db/models/manager.py", line 244, in __get__ self.model._meta.object_name, AttributeError: Manager isn't available; Choice is abstract The code runs fine under 1.4. It appears that this behaviour was changed with this commit: Relating to this ticket: Change History (8) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by Thanks for taking the time to look at this. We're using the abstract class manager to access partitioned versions of the model. Some context to try and explain further: Our app runs many similar fantasy sports and tipping games. In these users make a series of choices for a round and compete with others over a number of phases. We have implemented a partition manager that allows very large tables such as tips and league standings to be partitioned over separate tables based on round or phase rather than simply have round or phase as a foreign key. During start-up (model generation phase) N models will be created based on how the abstract base model has been defined. For example if a game has 40 Rounds and the Tip model has been configured to partition by Round then Tip1 to Tip40 models will be created and the manager is then used to access these partitions, similarly if a game has 10 Phases LeagueStanding1 to LeagueStanding10 models will be created and the LeagueStanding partitions manager used to access them. If we weren't using a model manager then we'd probably need to use a mixin class instead to implement similar behaviour in all models that need it. comment:3 Changed 6 years ago by comment:4 Changed 6 years ago by Personally I think we need to document this as a backwards incompatible cleanup. I don't see what advantage manager methods have for the presented use case over a standard python method on the abstract base class that returns or calls the desired manager on the concrete subclass. comment:5 Changed 6 years ago by I agree with ptone. comment:6 Changed 6 years ago by I agree with ptone and aaugustin. Documentation patch incoming shortly. I'm marking this as a release blocker, because it's clearly a change in behavior between versions. However, I'm not completely convinced (yet) that the problem use case is a use case we intended to support. Calling a manager on the abstract isn't something that *should* be possible, AFAICT, because there's nothing for the abstract class to manage. You can't issue queries on the abstract model, for example. The use case here is to use the manager as a mechanism for getting at a specific class object -- but I'm not sure I see what that shouldn't be a normal class method, rather than a manager method. I appreciate that you've gone to the lengths of producing a simplified example here -- that definitely helps reproduce the problem. Can you elaborate some more on why you're using this approach in practice? I don't need to see code -- just an explanation of what you're putting on the abstract manager that needs to be accessed on the abstract base class.
https://code.djangoproject.com/ticket/19384
CC-MAIN-2019-18
refinedweb
655
53.92
Linear - Recursive formulations of linear-quadratic control problems and Kalman filtering problems both involve matrix Riccati equations. - Classical formulations of linear control and linear filtering problems make use of similar matrix decompositions (see for example this lecture). The Law of Motion¶ Let $ x_t $ be a vector describing the state of some economic system. Suppose that $ x_t $ follows a linear law of motion given by $$ x_{t+1} = A x_t + B u_t + C w_{t+1}, \qquad t = 0, 1, 2, \ldots \tag$$ a_{t+1} + c_t = (1 + r) a_t + y$$ a_{t+1} = (1 + r) a_t - c_t + \sigma w_{t $$ a_{t+1} = (1 + r) a_t - u_t - \bar c + \sigma w_{t+1} + \mu \tag{2} $$ $$ \left( \begin{array}{c} a_{t+1} \\ 1 \end{array} \right) = \left( \begin{array}{cc} 1 + r & -\bar c + \mu \\ 0 & 1 \end{array} \right) \left( \begin{array}{c} a_t \\ 1 \end{array} \right) + \left( \begin{array}{c} -1 \\ 0 \end{array} \right) u_t + \left( \begin{array}{c} \sigma \\ 0 \end{array} \right) w_{t+1} \tag{3} $$ then the first row is equivalent to (2). Moreover, the model is now linear and can be written in the form of (1) by setting $$ x_t := \left( \begin{array}{c} a_t \\ 1 \end{array} \right), \quad A := \left( \begin{array}{cc} 1 + r & -\bar c + \mu \\ 0 & 1 \end{array} \right), \quad B := \left( \begin{array}{c} -1 \\ 0 \end{array} \right), \quad C := \left( \begin{array}{c} \sigma \\ 0 \end{array} \right) \tag{4} $$ In effect, we’ve bought ourselves linearity by adding another state. Preferences¶ In the LQ model, the aim is to minimize flow of losses, where time-$ t $ loss is given by the quadratic expression $$ x_t' R x_t + u_t' Q u_t \tag{5} $$a] for details. Example 1¶ A very simple example that satisfies these assumptions is to take $ R $ and $ Q $ to be identity matrices so that current loss is$$ x_t' I x_t + u_t' I u_t = \| x_t \|^2 + \| u_t \|$$ x_t' R x_t + u_t' Q u_t = u_t^2 = (c_t - \bar c)^2 $$ Under this specification, the household’s current loss is the squared deviation of consumption from the ideal level $ \bar c $. The Objective¶ We will begin with the finite horizon case, with terminal time $ T \in \mathbb N $. In this case, the aim is to choose a sequence of controls $ \{u_0, \ldots, u_{T-1}\} $ to minimize the objective $$ \mathbb E \, \left\{ \sum_{t=0}^{T-1} \beta^t (x_t' R x_t + u_t' Q u_t) + \beta^T x_T' R_f x_T \right\} \tag{6} $$ backward$$ \min_u \{ x_{T-1}' R x_{T-1} + u' Q u + \beta \, \mathbb E J_T(A x_{T-1} + B u + C w_T) \} $$ At this stage, it is convenient to define the function $$ J_{T-1} (x) = \min_u \{ x' R x + u' Q u + \beta \, \mathbb E J_T(A x + B u + C w_T) \} \tag{7} $$$$ \min_u \{ x_{T-2}' R x_{T-2} + u' Q u + \beta \, \mathbb E J_{T-1}(Ax_{T-2} + B u + C w_{T-1}) \} $$ Letting$$ J_{T-2} (x) = \min_u \{ x' R x + u' Q u + \beta \, \mathbb E J_{T-1}(Ax + B u + C w_{T-1}) \} $$ the pattern for backward induction is now clear. In particular, we define a sequence of value functions $ \{J_0, \ldots, J_T\} $ via$$ J_{t-1} (x) = \min_u \{ x' R x + u' Q u + \beta \, \mathbb E J_{t}(Ax + B u + C w_t) \} \quad \text{and} \quad J_T(x) = x' R_f x $$ $$ J_{T-1} (x) = \min_u \{ x' R x + u' Q u + \beta \, \mathbb E (A x + B u + C w_T)' P_T (A x + B u + C w_T) \} \tag{8} $$ To obtain the minimizer, we can take the derivative of the r.h.s. with respect to $ u $ and set it equal to zero. Applying the relevant rules of matrix calculus, this gives $$ u = - (Q + \beta B' P_T B)^{-1} \beta B' P_T A x \tag{9} $$ Plugging this back into (8) and rearranging yields$$ J_{T-1} (x) = x' P_{T-1} x + d_{T-1} $$ where $$ P_{T-1} = R - \beta^2 A' P_T B (Q + \beta B' P_T B)^{-1} B' P_T A + \beta A' P_T A \tag{10} $$ and $$ d_{T-1} := \beta \mathop{\mathrm{trace}}(C' P_T C) \tag{11} $$ (The algebra is a good exercise — we’ll leave it up to you) If we continue working backwards in this manner, it soon becomes clear that $ J_t (x) = x' P_t x + d_t $ as claimed, where $ \{P_t\} $ and $ \{d_t\} $ satisfy the recursions $$ P_{t-1} = R - \beta^2 A' P_t B (Q + \beta B' P_t B)^{-1} B' P_t A + \beta A' P_t A \quad \text{with } \quad P_T = R_f \tag{12} $$ and $$ d_{t-1} = \beta (d_t + \mathop{\mathrm{trace}}(C' P_t C)) \quad \text{with } \quad d_T = 0 \tag{13} $$ Recalling (9), the minimizers from these backward steps are $$ u_t = - F_t x_t \quad \text{where} \quad F_t := (Q + \beta B' P_{t+1} B)^{-1} \beta B' P_{t+1} A \tag{14} $$ These are the linear optimal control policies we discussed above. In particular, the sequence of controls given by (14) and (1) solves our finite horizon LQ problem. Rephrasing this more precisely, the sequence $ u_0, \ldots, u_{T-1} $ given by $$ u_t = - F_t x_t \quad \text{with} \quad x_{t+1} = (A - BF_t) x_t + C w_{t+1} \tag{15} $$ for $ t = 0, \ldots, T-1 $ attains the minimum of (6) subject to our constraints. Implementation¶ We will use code from lqcontrol.py in QuantEcon.py to solve finite and infinite horizon linear quadratic control problems. In the module, the various updating, simulation and fixed point methods are wrapped in a class called LQ, which includes Instance data: The required parameters $ Q, R, A, B $ and optional parameters C, β, $$ \mathbb E \, \left\{ \sum_{t=0}^{T-1} \beta^t (c_t - \bar c)^2 + \beta^T q a_T^2 \right\} \tag{16} $$$$ Q := 1, \quad R := \left( \begin{array}{cc} 0 & 0 \\ 0 & 0 \end{array} \right), \quad \text{and} \quad R_f := \left( \begin{array}{cc} q & 0 \\ 0 & 0 \end{array} \right) $$ Now that the problem is expressed in LQ form, we can proceed to the solution by applying (12) and (14). After generating shocks $ w_1, \ldots, w_T $, the dynamics for assets and consumption can be simulated via (15). The following figure was computed using $ r = 0.05, \beta = 1 / (1+ r), \bar c = 2, \mu = 1, \sigma = 0.25, T = 45 $ and $ q = 10^6 $. The shocks $ \{w_t\} $ were taken to be IID and standard normal. import numpy as np import matplotlib.pyplot as plt from quantecon import LQ # == Model parameters == # r = 0.05 β = 1/(1 + r) T = 45 c_bar = 2 σ = 0.25 μ = 1 q = 1e6 # == Formulate as an LQ problem == # Q = 1 R = np.zeros((2, 2)) Rf = np.zeros((2, 2)) Rf[0, 0] = q A = [[1 + r, -c_bar + μ], [0, 1]] B = [[-1], [ 0]] C = [[σ], [0]] # == Compute solutions and simulate == # lq = LQ(Q, R, A, B, C, beta=β,() <Figure size 1200x1000 with 2 Axes>$$ z_t := \sum_{j=0}^t \sigma w. # == Compute solutions and simulate == # lq = LQ(Q, R, A, B, C, beta=0.96,() We now have a slowly rising consumption stream and a hump-shaped build-up of assets in the middle periods to fund rising consumption. However, the essential features are the same: consumption is smooth relative to income, and assets are strongly positively correlated with cumulative unanticipated income.a], section 2.4. Adding a Cross-Product Term¶ In some LQ problems, preferences include a cross-product term $ u_t' N x_t $, so that the objective function becomes $$ \mathbb E \, \left\{ \sum_{t=0}^{T-1} \beta^t (x_t' R x_t + u_t' Q u_t + 2 u_t' N x_t) + \beta^T x_T' R_f x_T \right\} \tag{17} $$ Our results extend to this case in a straightforward way. The sequence $ \{P_t\} $ from (12) becomes $$ P_{t-1} = R - (\beta B' P_t A + N)' (Q + \beta B' P_t B)^{-1} (\beta B' P_t A + N) + \beta A' P_t A \quad \text{with } \quad P_T = R_f \tag{18} $$ The policies in (14) are modified to $$ u_t = - F_t x_t \quad \text{where} \quad F_t := (Q + \beta B' P_{t+1} B)^{-1} (\beta B' P_{t+1} A + N) \tag{19} $$ The sequence $ \{d_t\} $ is unchanged from (13). We leave interested readers to confirm these results (the calculations are long but not overly difficult). Infinite Horizon¶ Finally, we consider the infinite horizon case, with cross-product term, unchanged dynamics and objective function given by $$ \mathbb E \, \left\{ \sum_{t=0}^{\infty} \beta^t (x_t' R x_t + u_t' Q u_t + 2 u_t' N x_t) \right\} \tag{20} $$. $$ P = R - (\beta B' P A + N)' (Q + \beta B' P B)^{-1} (\beta B' P A + N) + \beta A' P A \tag{21} $$ Equation (21) is also called the LQ Bellman equation, and the map that sends a given $ P $ into the right-hand side of (21) is called the LQ Bellman operator. The stationary optimal policy for this model is $$ u = - F x \quad \text{where} \quad F = (Q + \beta B' P B)^{-1} (\beta B' P A + N) \tag{22} $$ The sequence $ \{d_t\} $ from (13) is replaced by the constant value $$ d := \mathop{\mathrm{trace}}(C' P C) \frac{\beta}{1 - \beta} \tag{23} $$ the end of working life and falls more during retirement. In this section, we will model this rise and fall as a symmetric inverted “U” using a polynomial in age. As before, the consumer seeks to minimize $$ \mathbb E \, \left\{ \sum_{t=0}^{T-1} \beta^t (c_t - \bar c)^2 + \beta^T q a_T^2 \right\} \tag{24} $$ $$ a_{t+1} = (1 + r) a_t - u_t - \bar c + m_1 t + m_2 t^2 + \sigma w_{t+1} \tag{25} $$ $$ x_t := \left( \begin{array}{c} a_t \\ 1 \\ t \\ t^2 \end{array} \right), \quad A := \left( \begin{array}{cccc} 1 + r & -\bar c & m_1 & m_2 \\ 0 & 1 & 0 & 0 \\ 0 & 1 & 1 & 0 \\ 0 & 1 & 2 & 1 \end{array} \right), \quad B := \left( \begin{array}{c} -1 \\ 0 \\ 0 \\ 0 \end{array} \right), \quad C := \left( \begin{array}{c} \sigma \\ 0 \\ 0 \\ 0 \end{array} \right) \tag{26} $$ If you expand the expression $ x_{t+1} = A x_t + B u_t + C w_{t+1} $ using this specification, you will find that assets follow (25) as desired and that the other state variables also update appropriately. To implement preference specification (24) we take $$ Q := 1, \quad R := \left( \begin{array}{cccc} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{array} \right) \quad \text{and} \quad R_f := \left( \begin{array}{cccc} q & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{array} \right) \tag{27} $$ The next figure shows a simulation of consumption and assets computed using the compute_sequence method of lqcontrol.py $$ y_t = \begin{cases} p(t) + \sigma w_{t+1} & \quad \text{if } t \leq K \\ s & \quad \text{otherwise } \end{cases} \tag{28} $$ backward induction procedure, iterating back to the start of retirement. - take the start-of-retirement value function generated by this process, and use it as the terminal condition $ R_f $ to feed into the lq_workingspecification. - solve lq_workingby backward$$ p_t = a_0 - a_1 q_t + d_t $$ Here $ q_t $ is output, and the demand shock $ d_t $ follows$$ d_{t+1} = \rho d_t + \sigma w_{t+1} $$ where $ \{w_t\} $ is IID and standard normal. The monopolist maximizes the expected discounted sum of present and future profits $$ \mathbb E \, \left\{ \sum_{t=0}^{\infty} \beta^t \pi_t \right\} \quad \text{where} \quad \pi_t := p_t q_t - c q_t - \gamma (q_{t+1} - q_t)^2 \tag{29} $$$$ \bar q_t := \frac{a_0 - c + d_t}{2 a$$ \hat \pi_t = -a_1 (q_t - \bar q_t)^2 - \gamma u_t^2 $$ After negation to convert to a minimization problem, the objective becomes $$ \min \mathbb E \, \sum_{t=0}^{\infty} \beta^t \left\{ a_1 ( q_t - \bar q_t)^2 + \gamma u_t^2 \right\} \tag{30} $$). Exercise 1¶ Here’s one solution. We use some fancy plot commands to get a certain style — feel free to use simpler ones. The model is an LQ permanent income / life-cycle model with hump-shaped income$$ y_t = m_1 t + m_2 t^2 + \sigma w_{t+1} $$ where $ \{w_t\} $ is IID $ N(0, 1) $ and the coefficients $ m_1 $ and $ m_2 $ are chosen so that $ p(t) = m_1 t + m_2 t^2 $ has an inverted U shape with - $ p(0) = 0, p(T/2) = \mu $, and - $ p(T) = 0 $ # == Model parameters == # r = 0.05 β = 1/(1 + r) T = 50 c_bar = 1.5 σ = 0.15 μ = 2 q = 1e4 m1 = T * (μ/(T/2)**2) m2 = -(μ/(T/2)**2) # == Formulate as an LQ problem == # Q = 1 R = np.zeros((4, 4)) Rf = np.zeros((4, 4)) Rf[0, 0] = q A = [[1 + r, -c_bar, m1, m2], [0, 1, 0, 0], [0, 1, 1, 0], [0, 1, 2, 1]] B = [[-1], [ 0], [ 0], [ 0]] C = [[σ], [0], [0], [0]] # == Compute solutions and simulate == # lq = LQ(Q, R, A, B, C, beta=β, T=T, Rf=Rf) x0 = (0, 1, 0, 0) xp, up, wp = lq.compute_sequence(x0) # == Convert results back to assets, consumption and income == # ap = xp[0, :] # Assets c = up.flatten() + c_bar # Consumption time = np.arange(1, T+1) income = σ * wp[0, 1:] + m1 * time + m2 * time**2 # Income # ==), ap.flatten(), 'b-', label="assets", **p_args) axes[1].plot(range(T+1), np.zeros(T+1), 'k-') for ax in axes: ax.grid() ax.set_xlabel('Time') ax.legend(ncol=2, **legend_args) plt.show() # == Model parameters == # r = 0.05 β = 1/(1 + r) T = 60 K = 40 c_bar = 4 σ = 0.35 μ = 4 q = 1e4 s = 1 m1 = 2 * μ/K m2 = -μ/K**2 # == Formulate LQ problem 1 (retirement) == # Q = 1 R = np.zeros((4, 4)) Rf = np.zeros((4, 4)) Rf[0, 0] = q A = [[1 + r, s - c_bar, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0], [0, 1, 2, 1]] B = [[-1], [ 0], [ 0], [ 0]] C = [[0], [0], [0], [0]] # == Initialize LQ instance for retired agent == # lq_retired = LQ(Q, R, A, B, C, beta=β, T=T-K, Rf=Rf) # == Iterate back to start of retirement, record final value function == # for i in range(T-K): lq_retired.update_values() Rf2 = lq_retired.P # == Formulate LQ problem 2 (working life) == # R = np.zeros((4, 4)) A = [[1 + r, -c_bar, m1, m2], [0, 1, 0, 0], [0, 1, 1, 0], [0, 1, 2, 1]] B = [[-1], [ 0], [ 0], [ 0]] C = [[σ], [0], [0], [0]] # == Set up working life LQ instance with terminal Rf from lq_retired == # lq_working = LQ(Q, R, A, B, C, beta=β, T=K, Rf=Rf2) # == Simulate working state / control paths == # x0 = (0, 1, 0, 0) xp_w, up_w, wp_w = lq_working.compute_sequence(x0) # == Simulate retirement paths (note the initial condition) == # xp_r, up_r, wp_r = lq_retired.compute_sequence(xp_w[:, K]) # == Convert results back to assets, consumption and income == # xp = np.column_stack((xp_w, xp_r[:, 1:])) assets = xp[0, :] # Assets up = np.column_stack((up_w, up_r)) c = up.flatten() + c_bar # Consumption time = np.arange(1, K+1) income_w = σ * wp_w[0, 1:K+1] + m1 * time + m2 * time**2 # Income income_r = np.ones(T-K) * s income = np.concatenate((income_w, income), assets, 'b-', label="assets", **p_args) axes[1].plot(range(T+1), np.zeros(T+1), 'k-') for ax in axes: ax.grid() ax.set_xlabel('Time') ax.legend(ncol=2, **legend_args) plt.show() Exercise 3¶ The first task is to find the matrices $ A, B, C, Q, R $ that define the LQ problem. Recall that $ x_t = (\bar q_t \;\, q_t \;\, 1)' $, while $ u_t = q_{t+1} - q_t $. Letting $ m_0 := (a_0 - c) / 2a_1 $ and $ m_1 := 1 / 2 a_1 $, we can write $ \bar q_t = m_0 + m_1 d_t $, and then, with some manipulation$$ \bar q_{t+1} = m_0 (1 - \rho) + \rho \bar q_t + m_1 \sigma w_{t+1} $$ By our definition of $ u_t $, the dynamics of $ q_t $ are $ q_{t+1} = q_t + u_t $. Using these facts you should be able to build the correct $ A, B, C $ matrices (and then check them against those found in the solution code below). Suitable $ R, Q $ matrices can be found by inspecting the objective function, which we repeat here for convenience:$$ \min \mathbb E \, \left\{ \sum_{t=0}^{\infty} \beta^t a_1 ( q_t - \bar q_t)^2 + \gamma u_t^2 \right\} $$ Our solution code is # == Model parameters == # a0 = 5 a1 = 0.5 σ = 0.15 ρ = 0.9 γ = 1 β = 0.95 c = 2 T = 120 # == Useful constants == # m0 = (a0-c)/(2 * a1) m1 = 1/(2 * a1) # == Formulate LQ problem == # Q = γ R = [[ a1, -a1, 0], [-a1, a1, 0], [ 0, 0, 0]] A = [[ρ, 0, m0 * (1 - ρ)], [0, 1, 0], [0, 0, 1]] B = [[0], [1], [0]] C = [[m1 * σ], [ 0], [ 0]] lq = LQ(Q, R, A, B, C=C, beta=β) # == Simulate state / control paths == # x0 = (m0, 2, 1) xp, up, wp = lq.compute_sequence(x0, ts_length=150) q_bar = xp[0, :] q = xp[1, :] # == Plot simulation results == # fig, ax = plt.subplots(figsize=(10, 6.5)) # == Some fancy plotting stuff -- simplify if you prefer == # bbox = (0., 1.01, 1., .101) legend_args = {'bbox_to_anchor': bbox, 'loc': 3, 'mode': 'expand'} p_args = {'lw': 2, 'alpha': 0.6} time = range(len(q)) ax.set(xlabel='Time', xlim=(0, max(time))) ax.plot(time, q_bar, 'k-', lw=2, alpha=0.6, label=r'$\bar q_t$') ax.plot(time, q, 'b-', lw=2, alpha=0.6, label='$q_t$') ax.legend(ncol=2, **legend_args) s = f'dynamics with $\gamma = {γ}$' ax.text(max(time) * 0.6, 1 * q_bar.max(), s, fontsize=14) plt.show()
https://lectures.quantecon.org/py/lqcontrol.html
CC-MAIN-2019-35
refinedweb
2,931
63.43
Scan input from a wide-character string #include <wchar.h> int swscanf( const wchar_t * ws, const wchar_t * format, ... ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The swscanf() function scans input from the wide-character string ws, under control of the argument format. Following the format string is the list of addresses of items to receive values. The swscanf() function is the wide-character version of sscanf(). The number of input arguments for which values were successfully scanned and stored, or EOF when the scanning is terminated by reaching the end of the input string. It's safe to call this function in a signal handler if the data isn't floating point.
http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.neutrino.lib_ref/topic/s/swscanf.html
CC-MAIN-2018-47
refinedweb
124
66.64
Hello everyone at JPF! I am completey new to Java, in fact I am completely new to lower level languages full stop. I have a reasonable amount of experience with high level languages namely MatLab so I understand programming concepts but not the software engineering of it all. I tell you this so you go in knowing it's most probably a stupid question... Project Outline: I am building a turn based game for which I am laying down some foundations to get some understanding components of the project that are causing me problems: class unit subclass infantry extends unit class army public class unit { // vars public int posX,posY,posZ; public String type; // constructor public unit(int x, int y, int z, String t) { this.posX = x; this.posY = y; this.posZ = z; this.type = t; } // methods // movement public void move(int moveX, int moveY, int moveZ) { this.posX = this.posX + moveX; this.posY = this.posY + moveY; this.posZ = this.posZ + moveZ; } public void printStates() { System.out.println("unit type:"+this.type+"posX"+this.posX+" posY:"+this.posY+" posZ:"+this.posZ); } }public class infantry extends unit{ static String infantryType = "Infantry"; // stance 0=standing,1=crouch,2=prone public int stance,accuracy; // accuracy base describes the accuracy of a unit given a stance public int accuracyBase[] = new int[3]; public infantry(int x, int y, int z) { super(x, y, z, infantryType); this.accuracyBase[0]=1; this.accuracyBase[1]=2; this.accuracyBase[2]=3; // TODO Auto-generated constructor stub } public void changeStance(int newStance) { this.stance = newStance; } public void update() { this.accuracy = accuracyBase[this.stance]; } } public class army { public infantry[] armyInf; public infantry[] armyUni; public army(int ninf,int nveh) { infantry[] armyInf = new infantry[ninf]; unit[] armyUni = new unit[nveh]; for (int i = 0;i<ninf;i++) { armyInf[i] = new infantry(0,0,1); } for (int j = 0;j<nveh;j++) { armyUni[j] = new unit(0,0,0,"vehicle"); } } } so My main function is below. I will mention now that there are no compilation errors and the calls to unit classes and infantry classes work and the printstates works also. public class emwar { public static void main(String[] args) { army army1 = new army(3,1); unit unit1 = new unit(10,10,10,"foot"); unit unit2 = new unit(0,0,0,"foot"); unit1.move(1,1,1); unit1.printStates(); unit2.move(20,20,0); unit2.printStates(); infantry infant1 = new infantry(0,0,0); infant1.printStates(); army1.armyInf[0].printStates(); } The error when this is run is: Exception in thread "main" java.lang.NullPointerException at cis.emwar.main(emwar.java:30) Note: line 30 coincides with the army1.armyInf[0].printStates(); call I have seen the thread here and have made the modification in class army to match this, which [clearly] has not worked for me. All help greatly appreciated! Keep up the Fun!
https://www.javaprogrammingforums.com/whats-wrong-my-code/9525-exception-thread-help.html
CC-MAIN-2019-51
refinedweb
472
56.66
Updated on 18th January, 2006 - I received many positive comments about this article and several requests to add some descriptive code to the contents. Based on this feedback, I have reworked on the article to provide a more detailed discussion - with code - of the remoting server and client setup. Please enjoy! I have spent a lot of time learning how to create and use basic remoting services in my applications. Code Project has been very helpful in this. Although the various articles and tutorials provided me with the information I needed, I never did find a simple, bare bones, use-it today remoting example. This article will attempt to solve that problem. Once you have mastered the basics presented here, you can refer to the following Code Project articles for more detailed information: Many other interesting articles are also available at CodeProject. To provide you with a very simple, easy to understand implementation of a client/server system using .NET remoting. Once you understand this code, you can immediately enhance it for use in your own applications. I have left out everything except the minimum code required to setup and test a remoting client and server. The included zip file contains a Visual Studio .NET 2003 solution with three projects. Each project is described below: #defines at the top of MainForm.cs. #defineis set in the ServerStart.cs file. As configured, you should be able to build the solution and run the client and server on your local machine. To get started: The code is simple and well commented. You should look at it to get the big picture. A few items need closer examination. On the server side, you need to complete three key steps to get a server working. The steps are: Let us look at the ICalculatorImplemention class in the server project. It is small enough so that the whole thing can be shown here: public class ICalculatorImplementation: MarshalByRefObject, ICalculator { /// <summary> /// Default constructor /// </summary> public ICalculatorImplementation() { Console.WriteLine( "ICalculatorImplementation constructor."); } #region ICalculator Members public int Add(int A, int B) { Console.WriteLine("Calculator service: Add() called."); return (A + B); } #endregion } // class The most important thing is to inherit from MarshalByRefObject and to implement the interface you wish to provide to the client. MarshalByRefObject is the key to remoting in .NET; it provides the support needed to access an object across application domain boundaries - in other words, something running on the other end of a wire, or even in another process on your machine. For a simple service like this, you can pretty much ignore MarshalByRefObject. It is worth reading about when you are ready for more. Next, we need to create some type of application to hold our service. Any application is suitable; console, Windows and NT services are all useful in various situations. For this example, I used a standard C# console application created with the project wizard. All the work is done in the application entry point, static void Main(). Here is an excerpt from ServerStart.cs. I have removed some of the code and comments for clarity: [STAThread] static void Main(string[] args) { // HTTP or TCP connection setup go here. // See article section 3. // Register the Http/TCP channel we created above. ChannelServices.RegisterChannel(chan); // Start Calculator service. // Register calculator service Type iCalc = Type.GetType( "InterfaceTest.Server.ICalculatorImplementation"); // Configure the service RemotingConfiguration.RegisterWellKnownServiceType( iCalc, "ICalcEndPoint", WellKnownObjectMode.Singleton ); } I will look at the connection setup in a minute, so for now that section of the code has been removed. Once the connection (TCP or HTTP) has been setup, you register then configures the service. The code above is pretty much boiler plate so you can substitute your own interface implementations into the lines above. When you get the type of your interface implementation, you need to include the complete namespace as well as class name to get the correct type return. In this case, it is InerfaceTest.Server.ICalculatorImplementation. The RemotingConfiguration class is a static class that provides all the methods you need to configure your remoting service. When you move beyond this sample, you will want to investigate the WellKnownObjectMode enumeration. This enumeration controls how your service is started and shared among clients. Singleton mode indicates that a single instance of ICalculatorImplemention will be started and it will be shared among all the clients making requests. You could use WellKnownObjectMode.SingeCall if you want your service to be stateless and provide an instance per client call. Note: You can host multiple services in a single application. The provided sample code demonstrates this by hosting the ICalculatorImplemention and ITestImplementation classes as services. The two services share the same channel, port and communications method (TCP or HTTP). Each service URL differs by the end point. For example, the calculator service URL in the sample code is: TCP://LocalHost:65101/ICalcEndPoint And the test service URL is: TCP://LocalHost:65101/ITestEndPoint Remoting can use HTTP or TCP for communications. HTTP is very simple to setup. Here is an example for a remoting server: HttpChannel chan = new HttpChannel(65101); That's it! Create an HttpChannel instance and set a port number - in this case, 65101. A TCP channel is more complex to setup on the client and server. The performance benefits might be worth it depending on your application needs. TCP remoting is faster than HTTP remoting. Here is how you create a TCP channel on the server. See ServerStart.cs for all the details:(); props["port"] = 65101; props["typeFilterLevel"] = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; TcpChannel chan = new TcpChannel(props, clientProvider, serverProvider); Although there are many more steps required for TCP setup, you can use this code as boiler plate. Just replace the props["port"] = 65101 with a port of your choice. On the client side, when you want to gain access to a remote service you have to do two things. They are: Like the server, you need to create a TCP or HTTP channel. The steps are almost identical. For HTTP the statement: HttpChannel chan = new HttpChannel(0); is all that is required. Notice that you don't specify a port number. Since this is a client, it is not necessary. The TCP code is also similar to the server. Here is an excerpt from MainForm.cs in the client project:); Unlike the server code, this code creates BinartClient and BinaryServer sink providers. Like the HTTP example, it sets the port number to 0. Once you have created a communications channel you register the channel, setup remote access to the server using MarshalByRefObject and create a local instance of the remote class you wish to use. This excerpt demonstrates getting and using an instance of ICalculatorImplementation: // // Register the channel // ChannelServices.RegisterChannel(chan); // // Setup remote access to ICalc implementation // MarshalByRefObject calc = (MarshalByRefObject)RemotingServices.Connect( typeof(Interfaces.ITest), url + "ICalcEndPoint" ); // Set a reference to the service. calcReference = calc as Interfaces.ICalculator; // Test int test = calcReference.Add(10,20); Console.WriteLine("Add(10,20) returned " + test.ToString()); Once calcReference is created, you use it exactly like a regular instance of ICalculatorImplementation. This is the simplest remoting example I was able to create. The code is well commented and hopefully you can use it as is while you become more familiar with remoting concepts. The sections above highlight the most important remoting steps. Below I have listed a few key points and areas of interest that you should also think about when dealing with remoting. If you are not familiar with using interfaces, I suggest you review the topic. Interfaces are the mechanism I use to provide remote services to the client and as far as I know, it is the most common method in use. The interface allows you to treat a remote instance of some class as if it was a local object; it also decouples the client from the server. You will notice that I have created a separate interface class library to hold all interfaces shared by the client and server applications. Simply put, this means that changing the implementation of the client or server does not force you to rebuild the other. Interfaces also provide transparency. Once you create a communications channel to your server and create an interface instance of the service you want to use, the use of the remote object is completely transparent to your client's code. As you examine the code, you will see that, by far, the HTTP connection is the simplest to setup. This does come at some cost. The HTTP transport is much slower than the TCP/Binary connection. The advantage is that HTTP will work through a firewall and provide built-in security mechanisms if you need them. It is also compatible with non .NET code. The TCP connection is more complex, but faster and only compatible with other .NET applications. There is a wealth of information available on Code Project and other sites about TCP and HTTP remoting. Once you have the basics down you should spend some time reading these articles. See the links I have provided in the Overview section of this article. I have left out all error handling to simplify the code. In a real world application you should, at minimum, add some exception handling to the client. Many real world clients will wrap every call to a remote method in a try/ catch block. I do not generally do this. Instead, I place a try/ catch around the client code that creates a reference to the service. My servers always have an Init() or Test() method that the client can use to verify that the communication channel and the service are working. I wrap my Test() call in a try/ catch and report any exception to the user. I find that this technique makes the code easier to read and improves performance. However, my way is not the best way so use it at your own risk. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/IP/SimpleRemoting.aspx
crawl-002
refinedweb
1,655
57.37
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Martin Aspeli wrote: >> Easy or not doesn't matter: he flat refuses. > > To play devil's advocate: Why don't we just fork PIL entirely? > > I appreciate that a 1.1.7 came out recently, but before that 1.1.6 > lasted three years. I doubt it'd be hard to keep up with a fork. The > advantage is that we could package it appropriately, release the new > package on PYPI, and avoid all this confusion with names. > > We would need to come up with a new namespace (i.e. not PIL) and > adjust our code in Plone and elsewhere to use this new namespace. But > that's probably less work than having this debate every few months. Advertising You don't need to change the package name (the imports), just the distribution nname (the dependencies). Jim's 'PILwoTk' package already does this: Maybe we should just renew the request to push PILwoTk to PyPI[1] and update our dependencies. IjC0ACgkQ+gerLs4ltQ61HgCg0ppsEK/Y3YCDHb5EWzl4lmK5 EMcAnjubj/q26EpQkYMUmdWLhVXgWPsW =OHMv -----END PGP SIGNATURE----- _______________________________________________ Repoze-dev mailing list Repoze-dev@lists.repoze.org
https://www.mail-archive.com/repoze-dev@lists.repoze.org/msg02276.html
CC-MAIN-2017-51
refinedweb
185
67.15
I'm trying to get an input from the user for example like: "Tom", which is actually t = 20, o = 15 and m = 13. before I explain further I would like to add that I have assigned the characters in the alphabetical order for example a = 1, b = 2 and... My only problem is that how do I make the program to calculate the first and last character in the array, since I don't know what's the length of the word that user is going enter? In this case it's 20 + 13. BTW the code is mixed with c++ as I'm trying to translate it to c, please also tell me what's wrong with the first two printf? #include <iostream> #include <stdio.h> #include <string.h> #include <cctype> using namespace std; int main() { int vowelCount = 0; int unsigVowel = 0; int index = 0; int total = 0; char wordInput[28]; printf ("Please enter a word: "); gets (wordInput); printf ("-------------------"); for(int i = 0; i<strlen(wordInput);i++) { if(wordInput[i] == 'a' || wordInput[i] == 'A' || wordInput[i] == 'e' || wordInput[i] == 'E' || wordInput[i] == 'i' || wordInput[i] == 'I' || wordInput[i] == 'o' || wordInput[i] == 'O' || wordInput[i] == 'u' || wordInput[i] == 'U') { vowelCount++; } else unsigVowel++; } printf ("\nThere are %d vowels in the %c \n", vowelCount, wordInput); printf ("There are %d unsigned vowel in the %c \n", unsigVowel, wordInput); //cout << "\nThere are " << vowelCount << " vowels in the " << wordInput << "\n"; //cout << "There are " << unsigVowel << " unsigned vowel in the " << wordInput << "\n"; cout << "There are " << strlen(wordInput) << " characters in the " << wordInput << "\n\n"; for( int index = 0; index < strlen(wordInput);index++) { if ( ! std::isspace(wordInput[index])) { cout << "The value of character at position " << wordInput[index] << " is: "; cout << (int)(toupper(wordInput[index]) - 'A' + 1) <<"\n"; total += (int)(toupper(wordInput[index]) - 'A' + 1); } } cout << "The total is: " << total << "\n"; /* :(/> */ return 0; } Thank you
http://www.dreamincode.net/forums/topic/234313-calculating-first-and-last-character-in-an-array/
CC-MAIN-2017-04
refinedweb
304
58.35
This article will show an alternative of solving an error message exist upon executing a certain script which is part of the Django-based web application. In the application, there is an attempt to access a certain url of the Django-based web application. The definition exist actually not in the urls.py of the application. But it exist in the models.py file as follows : class MyModel(models.Model): attribute = models.CharField(max_length=100) def __str__(self): return self.attribite def get_absolute_url(self): return reverse('url-name', kwargs={'pk':self.pk}) Apparently, the url definition above in the get_absolute_url(self) function is invalid. The following is the image of the error message : The url is not accessible, although in order to reach out for the model, the definition has already exist in the models.py. The definition itself exist in the function of get_absolute_url(). But the main problem is, it is not accessible as in the above image. After checking the main urls.py file in the project of the Django-based web application, apparently there is no definition of the url itself. The definition of the url itself must be exist in the main urls.py file. Just define it as follows : from django.urls import path urlpatterns = [ path('url-name', MyModel.as_view() name='url-name'), ... ] So, the above definition is actually to load the model as a view. The url for accessing the model exist in the function of ‘get_absolute_url’. But off course the definition must also exist in the ‘urls.py’ file. By defining the url name in the urls.py file, the page with the url of ‘/url-name’ is accesible. In this context, the ‘/url-name’ is just an example. The urls.py itself can be the url definition in the main project or in the application itself. But the main concern is that the url in the models.py definition must also be exist also in the urls.py file as an url definition.
http://www.dark-hamster.com/application/how-to-solve-error-message-noreversematch-at-url-in-django/
CC-MAIN-2020-45
refinedweb
331
60.72
Demo: I have tried before and failed to make my page transtitions implemented in a way that we don't have to import the pageTransition component in each and every route. I have finally created a pageTransition component that can just be dropped in the $layout.svelte component (_layout.svelte in Sapper) and then be used by all existing or future routes. I am going to show you here the steps and the thought process for setting up the component and the changes along the way which was the natural steps that I evolved this component and hopefully they can help someone in understanding layout/route based Svelte reactivity better. There is also a github repo that I have committed all different phases if you need to know all the details. The tutorial is mostly focuses on inexperienced developers. For more experienced developers you can just skip to the last sections or go straight to the repo. I have chosen SvelteKit for this demonstration just to try it out and mostly because it seems to be the future of Svelte. If you are using Sapper the steps should be almost identical. Setup Svelte@next Inside an empty project directory run npm init svelte@next pnpm install pnpm run dev NOTE: Feel free to use npmwhere I use pnpm. The two have exactly the same syntax. After that you can browse to localhost:3000 and be presented with the demo route. Setup a 2nd route a Simple Navigation component and a $layout component Setup minimum routes and components to be able to navigate from one page to another. <!-- src/components/Nav.svelte --> <div> <a href="/">Home</a> <a href="/about">About</a> </div> <!-- src/routes/about.svelte --> <main> <h1>About Page</h1> <p>This is the about page</p> <p>More paragraphs of the about page</p> </main> <!-- src/routes/$layout.svelte --> <script> import Nav from '../components/Nav'; </script> <Nav/> <slot/> We should have now the two routes and be able to navigate between Home page and About page. The beauty of SvelteKit (the magic of snowpack) is that you should be able to see changes in your browser immediately after saving the files. Consistent styling of pages by creating global.css Some stylistic changes are due to make the styles consistent across all pages. We take all styles from index.svelte and add them to a new file static/global.css /* static/global.css */ :root { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; } main { text-align: center; padding: 1em; margin: 0 auto; } h1 { color: #ff3e00; text-transform: uppercase; font-size: 4rem; font-weight: 100; line-height: 1.1; margin: 4rem auto; max-width: 14rem; } p { max-width: 14rem; margin: 2rem auto; line-height: 1.35; } @media (min-width: 480px) { h1 { max-width: none; } p { max-width: none; } } Link css file from app.html by adding following line before %svelte.head% <!-- add to src/app.html --> <link rel="stylesheet" href="global.css"> Simple PageTransitions component Here is a simple PageTranstitions svelte component using svelte/transition package. <!-- src/component/PageTransitions.svelte --> <script> import { fly } from 'svelte/transition'; </script> <div in: <slot/> </div> It makes the page fly in and out from top of the viewport. We delay a bit on the in transition to avoid the in and out transitions from working at the same time. Perhaps if anyone know how to add crossfadeto it please do let me know in the comments. If you add it as a wrapper on any route it does work as expected and it is the way I have seen all tutorials use a page transition component. There might also be use cases where we only need it on certain routes and than this would be the way to use it. <!-- src/routes/about.svelte --> <script> import Counter from '$components/Counter.svelte'; import PageTransitions from '../components/PageTransitions.svelte'; </script> <PageTransitions> <main> <h1>About Page</h1> <p>This is the about page</p> <p>More paragraphs of the about page</p> </main> </PageTransitions> More versatile PageTransitions component For most use cases though I believe setting PageTransitions in the $layout.svelte component and than having all routes use it is the way to go as it we set it and forget it. First lets remove the component from all routes and bring them to their initial state (setup setps a little above). If we just put the PageTransitions component in $layout.svelte component without any modifications though we will not be able to see any transitions. <!-- src/routes/$layout.svelte --> <script> import Nav from '../components/Nav'; import PageTransitions from '../components/PageTransitions'; </script> <Nav/> <PageTransitions> <slot/> </PageTransitions> NOTE: I noticed that SvelteKit is not loading all changes automatically to the browser. Perhaps this is something that will be fixed in later versions so lets not focus on it just keep in mind to refresh the browser when you can't see any changes. The problem is that the component is not reactive as is. We should make it reactive to the change of the route. Reactive Nav component Lets first make the Nav component reactive by underlying the current route link. <!-- src/components/Nav.svelte --> <script> export let segment; </script> <style> a { text-decoration: none; } .current { text-decoration: underline; } </style> <div> <a href="/" class='{segment === "/" ? "current" : ""}'>Home</a> <a href="/about" class='{segment === "/about" ? "current" : ""}'>About</a> </div> Pass the $page.path as segment variable to $layout.svelte to make the Nav reactive. <!-- src/routes/$layout.svelte --> <script> import Nav from '../components/Nav'; import { page } from '@sveltejs/kit/assets/runtime/app/stores.js' </script> <Nav segment={$page.path}/> <slot/> Now if you change the Nav links the current route link should be underlined. Reactive PageTransition component We now need to make the component reactive by creating a refresh prop and using key directive which means that when the key changes, svelte removes the component and adds a new one, therefore triggering the transition. <!-- src/component/PageTransitions.svelte --> <script> import { fly } from 'svelte/transition'; export let refresh = ''; </script> {#key refresh} <div in: <slot/> </div> {/key} Also lets pass the $page.path variable to PageTransition component similar to how we did it with the Nav component. <!-- src/routes/$layout.svelte --> <script> import Nav from '../components/Nav'; import PageTransitions from '../components/PageTransitions'; import { page } from '@sveltejs/kit/assets/runtime/app/stores.js' </script> <Nav segment={$page.path}/> <PageTransitions refresh={$page.path}> <slot/> </PageTransitions> You should now have your smooth page transtitions without needing to add the component to every route. Improving the page transitions When the pages are longer in height the transition are not actually that smooth because it might cause the scrollbars to flicker creating an undesired moving effect on the contents of the page. For understanding the problem lets force each page to be a little bigger in height /* add in static/global.css */ main { min-height: 600px; } Depending on your viewport size you might need to adjust the height so that there is no scrollbars on when not transitioning (idle state). If you refresh your browser and navigate from page to page you should see the flickering effect. To mitigate this problem lets add the following css to your global.css. /* add in static/global.css */ body { overflow-y: scroll; } And now the scrollbars will be visible at all times but might not always have the scroll handle to drap up/down. This will prevent them from appearing and disappearing and eliminates the problem. Another alternative would be to use /* add in static/global.css */ html { margin-left: calc(100vw - 100%); } } Read more about the flickering scrollbar and the above solutions on css-tricks Conclusion Making a component reactive on the layout/routing level is easy enough as seen above. This technique can be used with any component we include in layout or any component that we want to be reactive when the route changes. Please post your thoughts on the comments below. I would be happy to improve on the above code if something is not considered right or best practice and I do welcome corrections. If you liked this tutorial or found it useful please share or like or give me a star on github. Any of the above gives me an incentive to dig deeper and write more useful tutorials. Discussion (18) I'm not sure in which version it happened... but the segmentprop no longer appears to be valid. I've yet to find what the appropriate replacement is. @skwasha I have updated the repo and replaced segmentwith $page.pathand updated also the tutorial to reflect this change. Let me know if this works for you. Hey, that's great! Thanks for the update. Where did you happen to find the location for the page stores? I tried searching and checking old messages on the Discord but never saw any mention of it. Do you know if that's going to be where these "built in" stores will be located moving forward with Svelte Kit? thanks again. @skwasha I started digging in the sveltekit node_modules/sveltejs/kit/assets/runtime/app/stores.jscode looking for $page.pathmentioned in the github.com/sveltejs/sapper/issues/824 and found it. Perhaps the import import { page } from '@sveltejs/kit/assets/runtime/app/stores.js';will get more elegant when sveltekit gets released (or I might be missing the correct way to do it) but this will be the way to use it again according to the issue/824. I searched the discord and found the right way to do it: import { page } from '$app/stores'; Thanks for this article, by the way, it's helping me get off the ground with svelte/kit. Another idea for a change, you can set the class="current"like this, it's a bit shorter: <a href="/" class:current={segment==="/"}>Home</a> <a href="/about" class:current={segment==="/about"}>About</a> Yes there is some talks about removing segment from sapper but nothing has been committed yet. In here github.com/sveltejs/sapper/issues/824 you can find the discussion and some alternatives (using $page store) Yes. I saw that discussion as well. I guess my point was that the above code is no longer functional (at least the bits that rely on segment). Somewhere along the way that proposed change seems to have made it into the current sveletkit branch. Does anyone know where the pagestore is in the Sveltekit world? Previously, it was in @sapper/app. import { page } from '$app/stores'; Good read! I think it would have been much better with short video clips of how the transitions are working with the changes. Sorry I don't understand why would you need a video when there is a live site demo amazing-kirch-8cb3f5.netlify.app/ ? No, I meant the difference in the transitions before and after making changes for improvement. Ok I see perhaps I can do it when I get a chance. In the meantime if you need to see the improvements you can toggle the last css changes on and off on your locally installed repo. @giorgosk did you manage to figure out how to handle routing from code ? in sapper for example you have the "goto" method for routing. i couldn't find this feature in sveltekit Sorry not done any further research on it If I try to use PageTransition in the layout instead of the component I get the following error, do you know why? Error: failed to load module for ssr: /Users/userName/Documents/GitRepos/project/src/lib/components/PageTransitions.svelt dang, this is what i need,, cool post,, thanks for the idea,, Great article Giorgos!! Congrats. Glad you liked it Pavlos, comments are always appreciated !!!
https://practicaldev-herokuapp-com.global.ssl.fastly.net/giorgosk/smooth-page-transitions-in-layout-svelte-with-sveltekit-or-sapper-4mm1
CC-MAIN-2021-21
refinedweb
1,953
65.32
Instance Scope¶ Instance scope determines how an instance is shared between requests for the same service. Note that you should be familiar with the concept of lifetime scopes to better understand what’s happening here. When a request is made for a service, Autofac can return a single instance (single instance scope), a new instance (per dependency scope), or a single instance within some kind of context, e.g. a thread or an HTTP request (per lifetime scope). This applies to instances returned from an explicit Resolve() call as well as instances created internally by the container to satisfy the dependencies of another component. Instance Per Dependency¶ Also called ‘transient’ or ‘factory’ in other containers. Using per-dependency scope, a unique instance will be returned from each request for a service. This is the default if no other option is specified. var builder = new ContainerBuilder(); // This... builder.RegisterType<Worker>(); // ...is the same as this: builder.RegisterType<Worker>().InstancePerDependency(); When you resolve a component that is instance per dependency, you get a new one each time. using(var scope = container.BeginLifetimeScope()) { for(var i = 0; i < 100; i++) { // Every one of the 100 Worker instances // resolved in this loop will be brand new. var w = scope.Resolve<Worker>(); w.DoWork(); } } Single Instance¶ This is also known as ‘singleton.’ Using single instance scope, one instance is returned from all requests in the parent and all nested scopes. var builder = new ContainerBuilder(); builder.RegisterType<Worker>().SingleInstance(); When you resolve a single instance component, you always get the same instance no matter where you request it. // It's generally not good to resolve things from the // container directly, but for singleton demo purposes // we do... var root = container.Resolve<Worker>(); // We can resolve the worker from any level of nested // lifetime scope, any number of times. using(var scope1 = container.BeginLifetimeScope()) { for(var i = 0; i < 100; i++) { var w1 = scope1.Resolve<Worker>(); using(var scope2 = scope1.BeginLifetimeScope()) { var w2 = scope2.Resolve<Worker>(); // root, w1, and w2 are always literally the // same object instance. It doesn't matter // which lifetime scope it's resolved from // or how many times. } } } Instance Per Lifetime Scope¶ This scope applies to nested lifetimes. A component with per-lifetime scope will have at most a single instance per nested lifetime scope. This is useful for objects specific to a single unit of work that may need to nest additional logical units of work. Each nested lifetime scope will get a new instance of the registered dependency. var builder = new ContainerBuilder(); builder.RegisterType<Worker>().InstancePerLifetimeScope(); When you resolve the instance per lifetime scope component, you get a single instance per nested scope (e.g., per unit of work). using(var scope1 = container.BeginLifetimeScope()) { for(var i = 0; i < 100; i++) { // Every time you resolve this from within this // scope you'll get the same instance. var w1 = scope1.Resolve<Worker>(); } } using(var scope2 = container.BeginLifetimeScope()) { for(var i = 0; i < 100; i++) { // Every time you resolve this from within this // scope you'll get the same instance, but this // instance is DIFFERENT than the one that was // used in the above scope. New scope = new instance. var w2 = scope2.Resolve<Worker>(); } } Instance Per Matching Lifetime Scope¶ This is similar to the ‘instance per lifetime scope’ concept above, but allows more precise control over instance sharing. When you create a nested lifetime scope, you have the ability to “tag” or “name” the scope. A component with per-matching-lifetime scope will have at most a single instance per nested lifetime scope that matches a given name. This allows you to create a sort of “scoped singleton” where other nested lifetime scopes can share an instance of a component without declaring a global shared instance. This is useful for objects specific to a single unit of work, e.g. an HTTP request, as a nested lifetime can be created per unit of work. If a nested lifetime is created per HTTP request, then any component with per-lifetime scope will have an instance per HTTP request. (More on per-request lifetime scope below.) In most applications, only one level of container nesting will be sufficient for representing the scope of units of work. If more levels of nesting are required (e.g. something like global->request->transaction) components can be configured to be shared at a particular level in the hierarchy using tags. var builder = new ContainerBuilder(); builder.RegisterType<Worker>().InstancePerMatchingLifetimeScope("myrequest"); The supplied tag value is associated with a lifetime scope when you start it. You will get an exception if you try to resolve a per-matching-lifetime-scope component when there’s no correctly named lifetime scope. // Create the lifetime scope using the tag. using(var scope1 = container.BeginLifetimeScope("myrequest")) { for(var i = 0; i < 100; i++) { var w1 = scope1.Resolve<Worker>(); using(var scope2 = scope1.BeginLifetimeScope()) { var w2 = scope2.Resolve<Worker>(); // w1 and w2 are always the same object // instance because the component is per-matching-lifetime-scope, // so it's effectively a singleton within the // named scope. } } } // Create another lifetime scope using the tag. using(var scope3 = container.BeginLifetimeScope("myrequest")) { for(var i = 0; i < 100; i++) { // w3 will be DIFFERENT than the worker resolved in the // earlier tagged lifetime scope. var w3 = scope3.Resolve<Worker>(); using(var scope4 = scope1.BeginLifetimeScope()) { var w4 = scope4.Resolve<Worker>(); // w3 and w4 are always the same object because // they're in the same tagged scope, but they are // NOT the same as the earlier workers (w1, w2). } } } // You can't resolve a per-matching-lifetime-scope component // if there's no matching scope. using(var noTagScope = container.BeginLifetimeScope()) { // This throws an exception because this scope doesn't // have the expected tag and neither does any parent scope! var fail = noTagScope.Resolve<Worker>(); } Instance Per Request¶ Some application types naturally lend themselves to “request” type semantics, for example ASP.NET web forms and MVC applications. In these application types, it’s helpful to have the ability to have a sort of “singleton per request.” Instance per request builds on top of instance per matching lifetime scope by providing a well-known lifetime scope tag, a registration convenience method, and integration for common application types. Behind the scenes, though, it’s still just instance per matching lifetime scope. What this means is that if you try to resolve components that are registered as instance-per-request but there’s no current request... you’re going to get an exception. There is a detailed FAQ outlining how to work with per-request lifetimes. var builder = new ContainerBuilder(); builder.RegisterType<Worker>().InstancePerRequest(); Instance Per Owned¶ The Owned<T> implicit relationship type creates new nested lifetime scopes. It is possible to scope dependencies to the owned instance using the instance-per-owned registrations. var builder = new ContainerBuilder(); builder.RegisterType<MessageHandler>(); builder.RegisterType<ServiceForHandler>().InstancePerOwned<MessageHandler>(); In this example the ServiceForHandler service will be scoped to the lifetime of the owned MessageHandler instance. using(var scope = container.BeginLifetimeScope()) { // The message handler itself as well as the // resolved dependent ServiceForHandler service // is in a tiny child lifetime scope under // "scope." Note that resolving an Owned<T> // means YOU are responsible for disposal. var h1 = scope.Resolve<Owned<MessageHandler>>(); h1.Dispose(); } Thread Scope¶ Autofac can enforce that objects bound to one thread will not satisfy the dependencies of a component bound to another thread. While there is not a convenience method for this, you can do it using lifetime scopes. var builder = new ContainerBuilder(); builder.RegisterType<MyThreadScopedComponent>() .InstancePerLifetimeScope(); var container = builder.Build(); Then, each thread gets its own lifetime scope: void ThreadStart() { using (var threadLifetime = container.BeginLifetimeScope()) { var thisThreadsInstance = threadLifetime.Resolve<MyThreadScopedComponent>(); } } IMPORTANT: Given the multithreaded scenario, you must be very careful that the parent scope doesn’t get disposed out from under the spawned thread. You can get into a bad situation where components can’t be resolved if you spawn the thread and then dispose the parent scope. Each thread executing through ThreadStart() will then get its own instance of MyThreadScopedComponent - which is essentially a “singleton” in the lifetime scope. Because scoped instances are never provided to outer scopes, it is easier to keep thread components separated. You can inject a parent lifetime scope into the code that spawns the thread by taking an ILifetimeScope parameter. Autofac knows to automatically inject the current lifetime scope and you can create a nested scope from that. public class ThreadCreator { private ILifetimeScope _parentScope; public ThreadCreator(ILifetimeScope parentScope) { this._parentScope = parentScope; } public void ThreadStart() { using (var threadLifetime = this._parentScope.BeginLifetimeScope()) { var thisThreadsInstance = threadLifetime.Resolve<MyThreadScopedComponent>(); } } } If you would like to enforce this even more heavily, use instance per matching lifetime scope (see above) to associate the thread-scoped components with the inner lifetime (they’ll still have dependencies from the factory/singleton components in the outer container injected.) The result of this approach looks something like: The ‘contexts’ in the diagram are the containers created with BeginLifetimeScope().
https://autofac.readthedocs.io/en/v3.5.2/lifetime/instance-scope.html
CC-MAIN-2021-31
refinedweb
1,487
50.12
Today one of my coworkers came and got me so that I could explain some weird Python code they’d found. It dealt with cmake, but since it was internal code, I won’t be able to show it here. Instead, I wrote up something that has the same issues so you can see what I consider bad, or at the very least, very obtuse code: class Config: def Run(self): print('Program Usage: blah blah blah') print(self.product) self.asset_tag = 'test' print(self.asset_tag) total = self.sub_total_a + self.sub_total_b When I first saw this, I was struck by how it was using attributes that weren’t initialized and I wondered how this could work. Then I realized they must be doing some kind of monkey patching. Monkey patching is where you write code to dynamically modify a class or module at run time. So I looked farther down the script and found some code that created an instance of the class and did something like this: def test_config(): cfg = Config() cfg.product = 'laptop' cfg.asset_tag = '12345ABCD' cfg.sub_total_a = 10.23 cfg.sub_total_b = 112.63 cfg.Run() if __name__ == '__main__': test_config() So basically whenever you create an instance of the class, you need to patch it so that the attributes exist before you call the Run method. While I think it’s pretty cool that Python can do this sort of thing, it is extremely confusing to someone who is not familiar with Python, especially when the code was as poorly documented as this was. As you can see, there are no comments or docstrings, so it took a bit of digging to figure out what was going on. Fortunately, all the code was in the same file. Otherwise this could have gotten really tricky to figure out. I personally thought this was a good example of bad coding. If I had written it, I would have created an __init__ method and initialized all those attributes there. Then there would have been no confusion about how the class worked. I am also a big believer in writing good docstrings and useful comments. Anyway, I hope you found this interesting. I also thought my readers should be aware of some of the oddball pieces of code you’ll see in the wild.
http://www.blog.pythonlibrary.org/2016/02/26/python-an-example-of-bad-monkey-patching/
CC-MAIN-2018-13
refinedweb
382
71.75
The .NET Platform was created by Microsoft and initially released in 2002. Supported by Microsoft, it is only available for Windows operating systems, but Unix-like environments can use an open source alternative called Mono. When Microsoft released the .NET Platform, they created a general guideline for the platform so anyone could implement it. In 2005, the ECMA approved the Common Language Infrastructure (CLI) and C# programming language specification, so from that point, anyone could follow the standard. The Mono project implements this standard and offers an alternative for non-Windows users. In 2015 Microsoft started to open-source all the .NET framework source code, which also helped the Mono project keep up with the new features of the platform. The .NET platform supports many programming languages, like VB.NET, J#, F# and C#, but C# is still the most widely adopted. The current stable version of the .NET platform is 4.6.1 and C# language is 6. In the image below you can see how the different features of the .NET platform were added on each version (image source: Wikipedia). The first part of the article covers features that were already introduced in .NET Framework 2.0. The next four topics (CLI, Metadata, CTS and VES) are all part of the Common Language Runtime, while BCL is marked as Framework Class Library on this diagram. What is CLI? CLI stands for Common Language Infrastructure. This is a standard approved by ECMA International and details how applications written in different high level programming languages (C#, VB.NET or J#) should generate executables, and what metadata needs to be added to the libraries so these can run on different CLI-compliant platforms. The CLI describes the CTS (Common Type System), CLS (Common Language Specification), and VES (Virtual Execution System), plus Metadata. What is Metadata? The metadata contains programming language-agnostic (different for each programming language) information which helps the VES identify the language and the execution flow for the program. It also maps the types used in the programming language to the ones defined in the CTS. Besides these, the metadata contains information related to the version of .NET Framework the source code was built with, such as the name, author and version of the assemblies. What is CTS (Common Type System)? The CTS defines the data types in the programming language and specifies how these should be used. The CTS ensures that using the common types the software can be executed and will run the same way on multiple platforms. The CTS also defines the rules and guidelines for programming languages on how to treat internal operations of types. Common Types in.NET are all the types that are written with capital letters in the source code, such as String, Int, Long, and Char. Each programming language usually has an internal type for each common type. For example, the C# has string type for storing character arrays, but CTS defines the String type (please note the difference between the first letters; the CTS type has capital S). You can read more about types below. What is VES? The Virtual Execution Environment is executing the code which was compiled to the common language. The VES can be available for every platform. Microsoft offers its own VES for Windows, Windows Server, Windows Phone, but if you are using a Unix based system then you can use Mono’s VES for code execution. What is the BCL (Base Class Library)? The Base Class Library (a.k.a Framework Class Library) is a set of classes and namespaces which offer the minimum support for writing high level applications using the .NET platform. The BLC includes the System, System.Collections, System.Collections.Generic, System.IO, System.Text namespaces. These namespaces contain classes like List, ArrayList, FileReader, FileWriter, Hashtable, Dictionary and so on, which have a support role when building a business application, and also helps speed up the development process. The BCL was released with the first version of .NET, and since the .NET Framework 2.0, it did not change at all. It was only optimized and ported to other platforms and new programming languages, like J#. Programming with C# C# is one of the most widely-used programming languages from the .NET platform. When appeared, it had a lot of elements from the Java programming language. This means that C# is C syntax based; it is an Object Oriented Programming language and does not support multiple inheritance. The source code files of C# have the .cs extension. C# is a statically typed programming language, but in .NET 4.0, the dynamic keyword has been added to the language which enables us to do some nice tricks, BUT please keep in mind that even if you are using a dynamic construct, the language is still statically typed, and behind the scenes there are Anonymous types created for the dynamically defined content too. Before you can start programming in C# you will need to make sure that you have the .NET Framework or Mono installed on your machine, depending on your OS. I am on MacOS X, so I installed the Mono package, which can be downloaded from the Mono website. Once the package is installed I need to make sure that I have the compiler available. On Windows you can check this if you type in the csc --version in the command line and it should display the version of the C# compiler. The Mono compiler can be accessed using the msc --version. Below you can see the simplest C# program, which will ask for your name and say hi to you plus it will tell the current time and date: using System; using System.Collections; namespace SayHello { public class SayHello { public static void Main (string[] args){ Console.WriteLine("Hi, I'm Nancy! What is your name?"); String name = Console.ReadLine(); Console.WriteLine("Hi {0}, pleased to meet you. The current time is {1} and the curent date is {2}", name, DateTime.Now.ToString("hh:mm:ss"), DateTime.Today.ToShortDateString()); } } } The program starts with the declaration of the using section, where we define all the necessary namespaces what we want to use in our program. After the using comes our namespace definition using the namespace keyword. The C# language has namespaces similar with the way C++ has. The next line contains the class declaration. The class should be public, because it will contain the Main method. The Main method needs to be a public static void method; it has to be static because we only have one Main method within a C# program. The Console class provides access to the command line of the operating system. Using this, you can write messages to the console and ask for input from the user. First, I write Hi, I’m Nancy! What is your name? to the console with the WriteLine method, then I read the input from the user, using the ReadLine method. In the next line, I write to the console the message for our user. In the string, we have numbers added between curly braces, like {0}, {1} and {2}. These are placeholders and will be substituted with the parameters coming after the string, in this case name (the input from the user), DateTime.Now.ToString() with formatting and the DateTime.Today.ToShortDateString(). The format string hh:mm:ss can be used in case of the DateTime type, this will display the time in format of hours, minutes and seconds, separated using a colon (:). Here is an image of the output of the program: Types in .NET In the source code above, I used two data types, DateTime and String. Now I will cover other types. In .NET there is an implicit initialization for each type. Types can be divided into value types and reference types. Value types are int, char, byte, long, decimal, float, double. The string type is a reference type. In the code below, I cover the int, long and decimal types. The int type is a 4byte (aka 32bits) big number. The long type is a 64bit value. The decimal type is 64bit floating point, with double precision. public static void Main (string[] args) { int number = 13; long bigNumber = long.Parse(Math.Pow(2, 36).ToString()); Console.WriteLine("Here is a big Number (larger than 2^32): {0}", bigNumber + number); Console.WriteLine("The same Decimal value is multiplied by PI is: {0}", (decimal)(bigNumber + number) * 3.1415m); var myPhrase = "The quick brown fox jumped over the lazy dog"; Console.WriteLine("The first occurence of q in the phrase: '{0}' is at index: {1}", myPhrase, myPhrase.IndexOf('q')); } In the Main method I declared an int variable (called number) initialized to the value 13. Then a number of type long (bigNumber) is declared, which has a value of 2^36. After the initialization, I write the numbers into the console. First by writing the sum of bigNumber and number, followed by the product of bigNumber and the value of Pi (3.1415). Then I declare a string. Please note that I am using the var keyword to declare a variable and I have not specified explicitly that I am declaring a string. The compiler can deduct that based on the value on the right side of the equal sign. The last line of the program displays the index of the first appearance of the q letter in the variable called myPhrase. The output of the code is: Custom Types The first custom type that I present is the Enum type. Enums can be declared by developers. Usually Enums are used when we can distinguish the elements based on a certain value. For this common element, we usually use an enum. public enum TireType { WET = 1, DRY = 2, INTER = 3 } We can assign integer values to enum values, and these do not have to be consecutive numbers. The TireType enum has three values, WET, DRY and INTER (which stands for intermediate). You will later how the enum type can be used. The next custom type is struct. Structs ideally should be used in case we want to create a composition of only value types. An example of a struct is this: public struct Car { public TireType tire {get; set;} public int nrOfLaps {get; set;} public int fuel {get; set;} public override string ToString() { return string.Format("My car has {0} tires, I raced {1} laps and I still have {2} liters of fuel.", tire, nrOfLaps, fuel); } } I created a struct called Car and it has three properties, tire, nrOfLaps and fuel. Each of the properties has a getter and a setter (in code this is defined using the get and set keywords). Please note that I have defined an override for the ToString() method. The ToString() method is defined on the Object level (base type in .NET), which can be overwritten. Here is a main method which uses the struct: public static void Main (string[] args){ var myRaceCar = new Car() { tire = TireType.DRY, nrOfLaps = 22, fuel = 13 }; Console.WriteLine(myRaceCar); } Here I create a new instance of the Car struct, I use the inline initialization, I set the tire to the DRY value, the nrOfLasp to 22 and the fuel to 13. In the last line of Main method, I write to the console the myRaceCar object. As you can see I did not invoke any method on myRaceCar, the WriteLine() method will invoke the ToString() method of the object it gets as parameter if that does not have the string type. The output of the program is: So there – we've covered the basics of the .NET framework and some basic C# features. I showed examples with the struct and enum custom types from C#, and it also shows how to overwrite the ToString() method, as well as how to use types and type conversion in the language.
https://www.fi.freelancer.com/community/articles/the-net-guide-for-new-programmers
CC-MAIN-2018-26
refinedweb
1,979
73.88
Introduction: Java Basics Learn to Use Java Step 1: Open Notepad Step 2: Enter the Code In writing a java program, it always begin with public class _________(Enter the name of your Program) Then Write the code provided public class Sample { public static void main(String args[]) { System.out.println("Hi...This is my First Java Program"); } } It is necessary that you should all the things given above or simply copy them Step 3: Saving It When you are going to save a java program, it is necessary to write the same name which you have written in the class name with a '.java' extension Step 4: Running a Program Then you have to open cmd For opening cmd just type it in the search box and do the following steps - Navigate to the place where you saved your program in cmd - Then type 'set path=C:\Program Files\Java\jdk1.8.0_101\bin' but change the version according to your jdk. - Press Enter - Then type 'javac' - Then type 'javac Sample.java' Where I have type Sample.java you have to replace it with your file name - If any errors were there then it would be shown on the screen. - After correcting those errors do the 5th step again. - Type 'java Sample' Where I have type Sample you have to replace it with your file name. - Your program is ready Step 5: Important Points - Your class name should start with a capital letter - While typing your message, you should add inverted commas or it will show errors - After typing your message, add a colon (;). I hope you like this ... Thanks Recommendations We have a be nice policy. Please be positive and constructive. 3 Comments Great first instructable. Very well written. Thanks Thanks
http://www.instructables.com/id/Java-Basics/
CC-MAIN-2018-22
refinedweb
293
69.62
DNA Sorting From Progteam DNA Sorting is problem number 1007 on the Peking University ACM site. The idea of the problem is to find the "unsortedness" of a given string, in this particular example, it happens to be a string of DNA, but the solution applies to any string. The unsortedness of a string is defined to be the number of pairs of entries that are out of order with respect to each other. More concretely: for every letter in the string, how many letters are there to the right of it, which should be to the left. After finding this figure, sort the strings by their disorder, and print them out. (Note: I believe the same figure is achieved when you reverse the words "left" and "right" but I have not proven this) Algorithm The obvious n^2 solution is in fact the correct one (n^2 is fine because each string has at most 50 letters). For each letter in the string, count through all the letters to it's right. Keep a count of all such letters that come before it lexicographically. After looping through each letter, the total count you have represents the disorder of the string. Find out the disorder for each entry, sort them though however means you like, and print them. Solution import java.util.*; public class Main{ public static Scanner in; public static StringBuilder out; public static int STRLEN; public static Entry[] ents; public static void main(String[] args){ in=new Scanner(System.in); out=new StringBuilder(); doStuff(); System.out.println(out); } public static void doStuff(){ //Read in the length of the string and how many there are STRLEN=in.nextInt(); int N=in.nextInt(); //ents is an array of pairs of Strings and Disorder ents=new Entry[N]; for(int i=0;i<N;i++){ ents[i]=new Entry(); //Solve the problem solve(i); } //They want the output sorted Arrays.sort(ents); //Prinnit! for(Entry e:ents){ System.out.println(e); } } public static void solve(int k){ ents[k].str=in.next(); ents[k].disorder=0; String tmp=ents[k].str; //n^2 is fine because the number of letters is small //For each letter in the string for(int i=0;i<tmp.length();i++) //Check each letter to its right for(int j=i+1;j<tmp.length();j++) //If it belongs on its left if(tmp.charAt(j)<tmp.charAt(i)) //Increase the counter ++ents[k].disorder; } } class Entry implements Comparable{ String str; int disorder; public int compareTo(Object o){ if(!(o instanceof Entry)) throw new AssertionError(); Entry e=(Entry) o; if(disorder==e.disorder) return 0; return (disorder>e.disorder)?1:-1; } public String toString(){ return str; } }
http://cs.nyu.edu/~icpc/wiki/index.php?title=DNA_Sorting&oldid=6179
CC-MAIN-2014-15
refinedweb
450
65.83
software-center crashed with AttributeError in __eq__ Bug Description Binary package hint: software-center Software Center version 3.1.7 I'm hitting the following crasher when clicking on various items in the viewswitcher (e.g "Provided by Ubuntu"): Traceback (most recent call last): File "/home/ self. File "/home/ self. File "/home/ self. File "/home/ return (self.supported AttributeError: 'NoneType' object has no attribute 'supported_only' This bug was fixed in the package software-center - 3.1.8 --------------- software-center (3.1.8) natty; urgency=low [ Michael Vogt ] backend/ restfulclient. py: plugin. py: view/appdetails view_gtk. py: * softwarecenter/ - honor UBUNTU_SSO_SERVICE * softwarecenter/ - ignore plugin init failures * softwarecenter/ - add helper to obtain xy position of the appicon in the view [ Gary Lasker ] view/appview. py: models/ appstore. py: * softwarecenter/ - fix crash in refresh_apps if previous model did not have a filter (LP: #690706) * softwarecenter/ - enable threaded listviews * <many>: - implement inline purchase flow (LP: #618817, LP: #625418) [ Kiwinote ] view/appview. py: view/historypan e.py: view/pendingvie w.py: models/ viewswitcherlis t.py for translation * softwarecenter/ - fix crash when switching from a specific channel in the available pane to the same channel in the installed pane * softwarecenter/ - use named arguments for history entries - thanks to dpm (LP: #690283) * softwarecenter/ - use a scrollbar when we have many transactions (LP: #642299) - display progress for transactions * po/POTFILES.in: - mark softwarecenter/ * data/ui/dialogs.py: - don't mark " " strings as translatable (LP: #691082) * debian/control: - use correct Vcs-Bzr url (LP: #690906) -- Michael Vogt <email address hidden> Tue, 21 Dec 2010 16:09:37 +0100
https://bugs.launchpad.net/ubuntu/+source/software-center/+bug/690706
CC-MAIN-2019-43
refinedweb
258
50.94
Practical .NET Some time back I wrote a post on a custom HtmlHelper that generated my typical block of HTML: A fieldset element containing a label, a textbox and a validation message element. Since then, in ASP.NET Core, tag helpers have come along as a replacement for (or complement to) HtmlHelpers. HtmlHelpers vs. Tag Helpers Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior. At compile time, the code in the tag helper's Process (or ProcessAsync) method manipulates the element the tag helper is attached to in order to create the HTML that appears in the Web page that goes to the user. While the way you invoke tag helpers is different than HtmlHelper, fundamentally, the goal is the same: Provide a convenient way to generate HTML in a View (or Razor Page) for those developers who don't want to have to write all the HTML themselves. If you have some HTML that you can see yourself repeating in multiple pages and (a) want to make yourself more efficient or (b) want to ensure consistency in your UI across those pages, tag helpers (like HtmlHelpers) can make a lot of sense. Tag helpers also centralize the generation of that HTML. If you should decide to change/update the HTML being generated, you don't have to touch each page -- you just rewrite your tag helper and roll it out to the Web sites that use it. And, because tag helpers are just a class, that's easy to do: You can create your tag help in a Class Library project and share the resulting class across multiple projects/sites. During processing your code can modify both the element it's attached to and any content inside the element's open and close tags. You can add or remove attributes and even change the tag's name. You can also add HTML immediately before or after the element that your helper is attached to. Tag helpers are especially good news for page designers. Because tag helpers attach themselves to HTML elements, page designers get to work with tags they actually understand (unlike HtmlHelpers that are, essentially, opaque to anyone with HTML and CSS knowledge). That IntelliSense support for tag helpers is better than what you get with HtmlHelpers is just icing on the cake. Attaching to a Tag There are two ways to attach a tag helper class to an HTML-compliant element. The most straightforward way is to give the class the same name as the tag. A tag helper must inherit from the TagHelper class, so a tag helper that attaches itself to the Label tag would look like this: public class Label: TagHelper { However, you don't need to create tag helpers that attach just to existing HTML elements -- your helper will attach itself to any HTML-compliant element. For example, every one of your sites probably has a contact e-mail address on it. Odds are that the contact person varies from site to site but that the domain name (your organization) remains the same. As a result, it would be convenient to have a tag helper that would attach itself to a tag that looks like this: <contact domain-phvogel</contact> And then, at compile time, deliver this anchor tag to the browser: <a href="mailto:[email protected]">Contact</a> You can do that simply by creating a tag helper called Contact. The rules for names in C# are different from the rules for HTML tag and attribute names. As a result, when you use your tag helper's class and property names in your HTML-compliant tags you have to convert those C# names to valid HTML names. That's done by following the rules of kebab-naming. These rules are simple: So a class called ContactEmail would become a tag called <contact-email>. There are other benefits to creating tag helpers. If, for example, you change your mind and decide you want your mailto Contact element to be replaced with an anchor tag that takes the user to a page filled with contact options (e-mail, online chat, phone numers and so on) ... well, all you have to do is rewrite your tag helper to generate the new tag. Enhancing Multiple Tags But there's more flexibility here than just attaching your helper to specific tags. There's nothing stopping you from creating a tag helper that attaches itself to any element that meets criteria that you set. You do that by decorating your tag helper class with the HtmlTargetElement attribute. That attribute lets you specify some combination of element name, attributes and attribute values that will be used when attaching your tag helper to an element. This code, for example, attaches itself to any element with a tag name of input and an attribute called type that's set to "email": [HtmlTargetElement("input", attributes="[type=email]")] public class Contact : TagHelper Now, you can piggyback your tag helper with its domain-name attribute onto an HTML element that looks like this: <input type="email" domain- The output would be the same: an anchor tag that replaces this input tag. I don't even have to specify a tag name -- using the HtmlTargetElement, my tag helper can extend any HTML-compliant element I want based solely on what attributes that element has. Unfortunately, as fond as I am of tag helpers, I have to regard them as a complement to HtmlHelpers rather than a replacement. There's at least one limitation to tag helpers that makes recreating my HtmlHelper as a tag helper impossible and I'm not willing to give that HtmlHelper up. To explain why that is, I'll have to drag you through the ugly details of creating a tag helper, starting
https://visualstudiomagazine.com/articles/2019/05/01/custom-tag-helpers.aspx
CC-MAIN-2020-34
refinedweb
1,000
63.43
villus A small and fast GraphQL client for Vue.js 3.x This is forked from my previous work at vue-gql before they decide to go for a different direction with this library. Features - ? Minimal: Its all you need to query GQL APIs - ? Tiny: Very small footprint - ? Caching: Simple and convenient query caching by default - ? TypeScript: Written in Typescript and Supports GraphQL TS tooling - ? Composable: Built for the Composition API - ⚡️ Suspense: Supports the <Suspense>API in Vue 3 - ? Plugins: Use existing plugins and create custom ones - Higher-order components available Why use this GraphQL is just a simple HTTP request. This library is meant to be a tiny client without all the bells and whistles attached to Apollo and its ecosystem which subsequently means it is faster across the board due to it's smaller bundle size and reduced overhead. villus offers simple strategies to cache and batch, dedup your GraphQL requests. villus also supports file uploads and subscriptions without compromising bundle size through plugins. Quick Start First install villus: yarn add villus graphql # or npm npm install villus graphql --save Or because villus is so simple, you can use it via CDN: <!-- Import Vue 3 --> <script src="[email protected]/dist/vue.global.js"></script> <!-- Villus --> <script src="[email protected]/dist/villus.min.js"></script> You can now use it with either the new Vue composition API or higher order components. Usage Configure the GraphQL client for your root component: import { useClient } from 'villus'; export default { name: 'App', setup() { useClient({ url: '', }); }, }; Then you can use useQuery in any child component: <template> <div> <div v- <pre>{{ data }}</pre> </div> </div> </template> <script> import { useQuery } from 'villus'; export default { setup() { const AllPosts = ` query AllPosts { posts { title } } `; const { data } = useQuery({ query: AllPosts, }); return { data }; }, }; </script>
https://vuejsexamples.com/a-fast-graphql-client-for-vue-js-3/
CC-MAIN-2022-40
refinedweb
293
62.48
[Charles Cazabon] > >> Perhaps py3k could have a py2compat module. Importing it could have the > >> effect of (for instance) putting compile, id, and intern into the global > >> namespace, making print an alias for writeln, [Greg Ewing] > > There's no way importing a module could add something that > > works like the old print statement, unless some serious > > magic is going on... [Reinhold Birkenfeld] > You'd have to enclose print arguments in parentheses. Of course, the "trailing > comma" form would be lost. And good riddance! The print statement harks back to ABC and even (unvisual) Basic. Out with it! A transitional strategy could be to start designing the new API and introduce it in Python 2.x. Here's my strawman: (1) Add two new methods the the stream (file) API and extend write(): stream.write(a1, a2, ...) -- equivalent to map(stream.write, map(str, [a1, a2, ...])) stream.writeln(a1, a2, ...) -- equivalent to stream.write(a1, a2, ..., "\n") stream.writef(fmt, a1, a2, ...) -- equivalent to stream.write(fmt % (a1, a2, ...)) (2) Add builtin functions write(), writeln(), writef() that call the corresponding method on sys.stdout. (Note: these should not just be the bound methods; assignment to sys.stdout should immediately affect those, just like for print. There's an important use case for this.) -- --Guido van Rossum (home page:)
http://mail.python.org/pipermail/python-dev/2005-September/055968.html
crawl-002
refinedweb
216
78.45
A while back, the OpenXmlDeveloper.org website offered an example of how to create a WordProcessingML document from within Java code. I even referenced it briefly here. Remember, WordProcessingML is the document format produced and consumed by Microsoft Word 2007, and the format will also be supported by back versions of Word via the freely downloadable compatibility pack. I looked into that post, and found it to be pretty simplistic. Essentially, it is a guide for using the java.util.zip.* packages that are part of Java, to create a valid .docx file. The content of the document itself - the formatted text, the embedded image - in the post I referenced, all that content is manually constructed via text editors. So the post is not so much about "creating" a document, as it is about zipping up the existing parts of a WordProcessingML document. I think a better, more thorough approach for Java is required. What is needed is a class library for Java that parallels the System.IO.Packaging namespace in .NET 3.0. Something that allows a Java application to define the parts of a document, the relationships, and so on... programmatically, much as this article describes for a .NET application. Given the support for zip compression already in Java, and the fairly clear packaging rules for OpenXML, this extra step shouldn't be too hard to do. Once you have the packaging utility classes, then you can use the template approach I described a while ago, for WordML (the XML format from Word 2003), to create the content that gets zipped up. What does this get you? the ability to quickly generate OpenXML docs from Java, using a higher-level API that correctly models the packaging metaphor in the OpenXML spec. In theory you would be able to do this from any Java application, whether a thick client, a server-side app, or an agent or batch job that runs with no UI at all. Sorry, no example code, yet. I'll look into either creating a sample or finding someone else to do it. Any volunteers? -D If you would like to receive an email when updates are made to this post, please register here RSS jQuery Spy [Via: Dion Almaer ] What's in a name? "Generate..." [Via: CWeyer ] Inline XSD in WSDL with... Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page. Connecting .NET to just about anything else
http://blogs.msdn.com/dotnetinterop/archive/2006/10/03/WordProcessingML-doc-creation-in-Java.aspx
crawl-002
refinedweb
418
64.71
Code. Collaborate. Organize. No Limits. Try it Today. This article's aim is to provide material for modern day decompiling of applications written in C++. We assume you have a solid understand of C++, X86 Assembly, and windows. Each compiler is different, such as their CrtlStartUp routines, their statement assemblies (switch , if, while), and numerous other things make each compiler generate different code, even if you compile the same C++ code on two compilers, the end result will be different, because of this I will stick with one and only one compiler, which is the Visual C++ Compiler. CrtlStartUp switch if while Visual C++ is produce by Microsoft and currently delivers the fastest and most optimized code available. Not to say all the information provided in this book only applies to Visual C++, I just saying some of the information presented in this book may only work on Visual C++. If you don’t have Visual C++ that is fine, there are many other compilers available, and most of this information is also accurate for them I been ask many times is C++ decompiling even possible not only due to the complexity of a compiler but for the mass about of information loss in compiling, such as comments , include files, macros just to name a few. So one often wonders is this even worth pursing. Well I wanted to start out with the topic of what is totally loss when you compile a program and what stays there, refer to table 1.1.1 to see what we loses and remains. What is lost What remains templates Function calls classes Dynamic linking calls Marcos Switch statements Include files Local Variables Parameters Not to say everything that is in the “What remains” sections is 100% there, it just means it is very simple and practical to reverse engineer. Because of this fact I choose to deal with the “What remains” section first because it’s much easier. As we progress though this book keep in mind reverse engineering is almost never practical and takes lots of practice. It’s harder to reverse engineer something created than to create it in the first place. A good way to start out with reverse engineering is to decompile your own programs and see how each C++ function specifically works, then apply that knowledge in other areas because looking at thousands of lines of assembly code is not really fun. Now when your reading this book you might start to think that , “anything translated info a different language can be retranslated back into the same language” right, well this is not the case in reverse engineering a lot of things will be lost, and a lot of things you must make up(assume) along the way. So I wanted to make sure a provided some practical examples for reverse engineering at the beginning of the book, to give you a sense of hope. To begin reverse engineering, I decided to start with the main C++ statement Int main(int argc, char * argv[]) Now we can easily find this statement in any executable file due to the PE format which tells us the start of the executable, because of this we can simply read the PE format in a specific executable and get its start address. Or can we? This is where the Common Runtime Library comes in at (CRTL), you see when you compile a C++ program most compilers (because this is compiler specific stuff) will execute in the following order CrtlStartUp(); CrtlCleanUp (); this means we can’t look into the PE file and get the start of our code, we can only get the start of the CrtlStartUp()’s code. We have to choices, reverse engineer the CrtStartup Code or skip over it, I like the latter, and we will deal with the Common Runtime Library later. One of the main reason C++ is so well design is because it has a strict protocols use in its assemblies. C++ has some very static assemblies such as when you return values, it is always put in the EAX register, and function calling usually always use the stack because of this reverse engineers can attack this static assemblies and get a head start The first thing we should deal with is Global Variables because if you’re coming from a lot of high level languages you might have some miss conceptions. You know how many books say Memory is stored random on the computer, well this is true for the most part, but your application memory allocation for global variables is quite static. That’s right each time you run your program, your static allocated variables will always end up in the same place. Another interesting fact is variables don’t hold data, they pointer to where the data is stored. Here is a C++ Example: #include "stdafx.h" #include "windows.h" char * globalvar = "Whats Up"; int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. globalvar = (char *)0x400000; return 0; } Here is a in depth look at the disassemblies 00405030: global_var dd 405034h 00405034: global_var_value db 'Whats Up',0 mov global_var,400000h OK, this proves that variables do not hold data, as you can see, the compiler automatically initialize our global_var pointer to the address of global_var_value. global_var_value OK, so far we know that variables are just pointers to values, so we can change were the variable is pointer right? Yes we can, with mov global_var, 400000h so whenever the compiler accesses global_var, it will look into the value stored at 405030h and come up with 400000h mov global_var, 400000h global_var 405030h 400000h If you’re confused remember global_var is stored at 405030h, and refer to the picture 2. 405030h This picture is pretty self explanatory and if you’re still confused how everything works then I suggest you get a good assembly book and learn what indirect addressing is. We have just dealt with a pointer variable lets deal with just a variable, because this is much more simple. #include "stdafx.h" #include "windows.h" char globalvar[] = "Whats Up"; int APIENTRY WinMain(HINSTANCE hInstance, INSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { globalvar[0] = 'A'; globalvar[5] = ‘U’; return 0; } Which when compiled becomes 00405030 global_var db “Whats up”,0 mov global_var, ‘A’ mov global_var + 5 , ‘U’ When instantly see that regular variables or a lot simpler than global variables, all we have to do is refer to a address in memory which holds or data , of course in machine code we can’t see pretty names like global_var, so here is a pure disassembly 00405030 “Whats Up”,0 mov 00405030,’A’ mov 00405035,’U’ As you can see, we aren’t doing anything special just modifying the values store at 00405030 and 00405035. 00405030 00405035 You should have variables and pointer variables down pack, since this information will not be explain again, if there is something you don’t understand, read it over. OK, as we all know C++ has near English like syntax and which we can program in. Well X86 assembly code doesn’t, for example take a look at the following statement Int s = 3 + 4 + 1 + 5 + 9; How can we calculate this in assembly? simple, look at the following C++ example #include "stdafx.h" #include "windows.h" int s1 = 3; int s2 = 4; int s3 = 1; int s4 = 13; int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. s1 = s2 + s3 –s4 + 34; return 0; } 00405030 s1 dd 3 00405034 s2 dd 4 00405038 s3 dd 1 0040503C s4 dd 1 mov eax, s2 00401008 add eax, s3 0040100E sub eax, s4 00401014 add eax, 34 00401017 mov s1, eax OK the compiler optimizes the code a little bit, but it’s still very easy to understand. eax mov eax, s2 eax 4, s3 5 s4 4 34 38 s1 You will often see the compiler use registers instead of variables in expression because registers are faster. From this we can conclude that for each mathematical operator the compiler maps it with a specific X 86 Instructions, here is a table C++ Operator X86 Instruction * (Multiply) Mul , (use fmul for floating point) / (Division) Div (use fdiv for floating point) - (Subtraction) Sub +(Addition) Add As you can see, we can easily decipher most statements in C++ using the table above. For a test we will look at a sample disassembly dump and decompile it by hand to C++. 0000000 2 0000001 3 0000002 4 0000003 0 0000004 1 0000005 mov al, [00000000] add al, [00000001] mov ch, [00000002] mul ch mov [000000003],ax OK the first thing we do is try to figure out what type of variables they are using And from what we can see they our using al and ch, which are 8 bit registers, so that means whenever they reference anything with 8 bit registers, it means the variable is a Char type. On down you see that they do a “mov [000000003], ax”, and since ax is a 16 bit register the variable type is short int. mov [000000003], ax Here is a small table, so you can map registers to variable types X86 Registers C++ Type Variables 8 bit registers ( AL , AH) Char 16 bit registers (AX) Short int 32 bit registers (EAX) Int So far we see 4 references to memory addresses, because of this we know we have 4 variables, the first one [000000000] is obviously an char type variable since we see, mov al, [00000000]” and since al is an 8 bit register. So lets give [0000000] the name of s1, we also see that [0000000] though[00000002] is all reference by 8 bit variables meaning they are also char type, and the last one [00000003] which’s use like “mov [000000003] , ax” is a short int type since ax is 16 bits [0000000] [00000002] [00000003] mov [000000003] , ax OK let’s create another table one which will hold variable names or alias for the addresses Although we can never get the original variable name we can also create our own. Addresses Variable names/alias’s Variable size 0000:0000 S1 0000:0001 S2 0000:0002 S3 0000:0003 S4 You might be confused why 00000004 holds 1 and 00000003 doesn’t, well this is because Intel is a little edian machine, that stores values in reverse word order. 00000004 00000003 Now the next thing we should do is rewrite the code above with our alias’s we created s1 db 2 s2 db 3 s3 db 4 s4 dw 1 mov al, s1 add al, s2 mov ch, s3 mul ch mov s4,ax Now the first thing we do is mov al, s1 mov al, s1 OK al now holds a value of 2, the next thing we do is “add al, s2” al add al, s2 Now al has a value of 5, since s2 had a value of 3 in it the next thing we want to do is mov ch, s3? s2 mov ch, s3 Now ch has a value of 4, after that we mul ch, now ax has the value of al * ch, ch al * ch And since al had a value of 5 in it and ch had a value of 4 in at, ax has the value of 20. at ax OK we can start to decipher the C++ statement which is s1 + s2 * s3 After that we see that we see, “mov s4, ax” so the complete C++ statement is mov s4, ax S4 = s1 + s2 * s3; As you can see we just went though a whole bunch of mess to come up with a simple C++ statement, and this only works for global variables. Not local variables or structure members. So things will only get harder, due to this I suggest you read carefully and if you don’t understand something read it over and over until you do. One of the major fundamentals of C++ is returning values from function call. This is actually a very simple procedure, because it simple involves placing a value into the eax register. So when you have a statement like this c = (char *) malloc (0xFF); The first thing the compiler does is call malloc and then it assigns c to eax like “mov c, eax” malloc mov c, eax For example if you have a statement that returns 5; what you our really saying is __asm { Mov eax, 5 Ret } Let’s have a little practice with a full disassembly dump Mov eax,5 Add eax,2 Sub eax,1 Ret And the C++ equivalent is return 5 + 2 – 1; This although simple is one of the most important concepts a C++ reverse engineer can learn. Now its time to get to the blood and guts of C++ with function calls. Function calls are fairly simple for the most part because they our just labels for assembly programmers example. Int func () {return 1 ;} Func(); Would compile into Func: Mov eax, 1 Ret Call Func From this we can conclude two things, the first is: Function’s name or like variables, they are just references to some address which is the same as a label Here is a full disassembly dump for practice 0000:0000 0 0000:0001 0 0000:0002 0 0000:0003 0 0000:0005 mov eax,1 0000:0009 ret 0000:0010 call 0000:0005 ‘code starts here 0000:0015 mov [0000:0000],eax OK the first thing we see is that at address 0000:0015 , we our assign a 32 bit memory address to the value of a 32 bit register which’s mean that we have a 32 bit variable at hand or a int type variable to be more exact. 0000:0015 So let’s create an alias for the address’s 0000:0000 – 0000:0003, which will be s1. 0000:0000 s1 Now let’s create a new disassembly with this added information S1 dw0 0000:0005 mov eax,1 0000:0009 ret 0000:0010 call 0000:0005 ‘code starts here 0000:0015 mov S1,eax OK the second thing we see is that code start at 0000:0010 and the first instruction is call 0000:0005. 0000:0010 0000:0005 Now we’re at 0000:0015 we can see that the code is moving a value into eax then returning. Now we our at address 0000:0015 and we just moved s1 into eax 0000:0015 So we can now reverse engineer this whole program back into C++ Int s1 = 0; //dw 0 Int some_function() { return 1; //mov eax ,1 : ret } s1 = some_function(); //mov s1 , eax Now what do we do when functions have parameters, well things get pretty complicated because the compiler uses the stack to handle parameters. It pushes in parameters right to left, meaning the last parameter goes in first, and the first parameter goes in lest. For example, C++ Function: Func (1, 2); Push 2 Push 1 Call func Now let’s have an imaginary stack frame, which has a size of 32 Now the first thing we realize is that ESP = 32, with that in mind look at the table below ESP = 32 Memory address stored at Stack Frame Pointer value Push 2 [32] ESP = 28 Push 1 [28] ESP = 24 Call func [24] ESP = 20 Push ebp [20] ESP = 16 Remember when you issue a call instruction on the X86 machines, the Processor stores the current address on the stack so it can know the location it should return to. Now that the parameters are on the stack lets look at the function itself Int func (int a, int b) { return a + b; } Mov eax, [ESP + 8] ESP add eax, [esp + 12] ret So the full compilation would be Func: Mov eax, [ESP + 8] Add eax, [ESP + 12] Ret A neat little reverse engineering tip is to remember that sense the stack has a fix width of 4 bytes, you can easily tell what parameter they our accessing. [EBP] = Stack [EBP +4] = Return address [EBP + 8] = First [EBP + 12] = Second [EBP + 16] = Third [EBP + 20] = Fourth And so on…. We just learn that parameters are stored on the stack, now it time to learn about local variables which are also stored on the stack, but local variables are stored quite different. Here is an example Int func () { int a = 5; return a; } OK to compile this code, the compiler must first reserve space on the stack by going Sub ESP, 4. Since 4 bytes is the size of an int variable. Of course the compiler must first back up the esp register , and it does this by “mov ebp,esp” , but wait, the compiler must first back up ebp, and it does this by “push ebp” so the very first thing the compiler does is Sub ESP, 4 int mov ebp,esp ebp push ebp : Setting up the stack frame Push ebp; back up ebp Mov ebp, ESP; back up ESP in ebp Sub ESP, 4; reverse some space on the stack Note: C++ always compiles code like “Setting up the stack frame” in any function, even if you use or don’t use local variables, and the compiler always uses ebp to reference parameters and local variables. In the “Function Calls and the Stack” section I use esp to reference parameters and skip Setting up the stack frame code this out for clarity sake. Now the second thing the compiler does is Mov [ebp – 4], 5 Mov eax, [ebp -4] If we had a second local variable we could simple go Mov [ebp – 8], 5, or course the compiler would use sub ESP, 8 Instead of sub ESP, 4. Mov [ebp – 8], 5, sub ESP, 8 sub ESP, 4 The last thing the compiler does is restore the stack frame and return ; Cleaning up the stack frame Mov ESP, ebp; restore stack pointer Pop ebp; restore ebp Ret Note: The compiler always execute the “Cleaning up the stack frame” code, in every function, due to this we can detect a function by looking for similar code. I also skip this in “functions call and the stack” section for clarity sake. Here is a full disassembly dump, for practice 0000:0000 0 0000:0004 push ebp 0000:0003 mov ebp,esp 0000:0005 sub esp, 8 0000:0010 mov [ebp -4], 5 0000:0015 add [ebp – 4] , [ebp + 8] 0000:0016 mov eax,[ebp – 4] 0000:0018 mov esp, ebp 0000:0020 pop ebp 0000:0021 ret 0000:0022 push ebp 0000:0023 mov ebp,esp 0000:0025 add [ebp + 8] , [0000:0000] 0000:0030 add [ebp + 8] , [ebp + 12] 0000:0031 mov eax,[ebp +8] 0000:0032 mov esp, ebp 0000:0035 pop ebp 0000:0036 ret 0000:0037 push ebp ;code start 0000:0038 mov esp, ebp 0000:0040 push 1 0000:0044 call 0000:0002 0000:0049 mov [0000:0000],eax 0000:0050 push 4 0000:0051 push 3 0000:0052 call 0000:0022 0000:0056 add [0000:0000],eax 0000:0058 mov esp, ebp 0000:0059 pop ebp OK the first thing we is that memory address [0000:000] is being reference by eax a lot, meaning we have a 32 bit variable which is an int type. The next thing we notice is we set up the stack frame 3 times and clean it up 3 times, which means we have 3 functions(and yes int main(…) also sets up the stack frame and cleans it up). [0000:000] main(…) So we have Func1 () Func2 () Main () Next we see Func1 address is at 0000:0004 and accept one 32 bit parameter Func1 address 0000:0004 Because we see at address 0000:0040 we push 1 into the stack and then at address 0000:0044 we are calling 0000:0004 so we can setup func1 declaration 0000:0044 00000:00002 Func1 (int a) Now whenever func1, does anything to [ebp + 8] we know that it is doing something to its first parameter. So look into func1 code, and we see that it has 1 local variable because it references [ebp – 4]. ebp – 4 Now lets take a lot at address 0000:0049, which is mov [0000:000], eax so we know that the original C++ code is something like mov [0000:000], eax [0000:0000] = func1 (1); Next when see at address 0000:0051 that we are pushing 4 onto the stack then after that we are pushing 3 onto the stack then we all 0000:0022. 0000:0051 0000:0022 Now we can setup Func2 declarations Func2 0000:0022 Func2(int a, int b) At address 0000:0056 we see add [0000:0000],eax , means the original C++ code is something like 0000:0056 add [0000:0000],eax [0000:0000] += Func2(3,4) Remember we pushed 4 onto the stack first, and 3 onto the stack second, because parameters or passed right to left. Now that we have a lot of information lets make a new disassembly one with alias for all local variables and parameters in Func1 and Func2. Since we know that whenever they use code like [ebp +…] it’s a parameter, and when they use code like [ebp -...] it’s a local variable. [ebp +…] [ebp -...] 0000:0000 s1 dw 0 0000:0004 func1(int param_1): push ebp { local : local_var_1} OK I know, I made up a little assembly syntax such as func1(int param_1) and {Local : local_var_1 } This is for clarity sake that’s all. Now let’s start with func1 at address 0000:0010 we see that it is moving local_var_1 to 5, which in C++ it's saying 0000:0010 local_var_1 int local_var_1 = 5; next we see add local_var_1, param_1 which in C++ its saying local_var_1 +=param_1 The last thing we see before we clean up the stack is mov eax,local_var_1 which in C++ its saying mov eax,local_var_1 return local_var_1; So the full reversed engineered function is Int func1(int param1) { int local_var_1 = 5; local_var_1 += param1; return local_var_1; Now lets go to func2 at address 0000:0025 we see add param_1, s1, which in C++ its saying 0000:0025 param_1 +=s1; after that we see add param_1, param_2, which in C++ its saying param_1 += param_2; the last thing we see before we clean up the stack is mov eax, param_1, which in C++ its saying mov eax, param_1 return param_1; Int func2(int param_1 int param_2) { param_1 += s1; param_1 += param_2; return param_1; } Now we our able to reverse engineer the whole program Int s1 = 0; Int func1(int param1) { int local_var_1 = 5; local_var_1 += param1; return local_var_1; } Int func2(int param_1 int param_2) { param_1 += s1; param_1 += param_2; return param_1; } int main() { s1 = func1(1); s1 += func2(3,4); } This Chapter might be a little hard to comprehend at first since I presented a lot of “straight to the point” information, again if you don’t understand anything read it over, and if you still don’t understand email vbmew@hotmail.com with your question What we been doing so far is the easy stuff, its time to deal with C++ keywords complex expression, and some practical real world examples. One of the main statements people use is this if statement which logically compares values. Using this function we can choose which path of execution our program should take. If statement can also be very , very complex and very simple Take a look at the following examples. If(I ==0) //do function //continue Now what if we had something like this If(I==0) { int i2 = 0; } i2 = 3; //error can’t access i2 because it’s not in your scope // it’s in the if statements scope Because of this we know that compiler generates a stack frame for each If statement with brackets right? Wrong!. I2 is accessible to main in reality but the compiler keeps it hidden, the reason I ‘m telling you this is because to reverse engineer if statements you must completely understand them. The second example is If( (I ==0) || ( ( I2 == 1) && (i3 ==2) ) ) The logic for this is if I = 0 or if i2 = 1 andi3 = 2 I = 0 i2 = 1 i3 = 2 Another Example would be If( (c = (char *) malloc(0xFF) ) == NULL) This is saying c = malloc(0xFF) and if malloc return NULL this condition is true. c = malloc(0xFF) NULL Yet another example is If(malloc(0xFF)) //this is saying call malloc(0xFF) and if it returns //anything not equal to 0 then This condition is true The last but not least example is If(!malloc(0xFF)) //this is saying call malloc(0xFF) and if it returns // value is equal to zero then this condition is true Thankfully all these if statement can be reverse engineer in turn back into just the way they are(almost). Now the if statement maps directly to the X86 instruction cmp with this in mind take a lot at the following C++ program int main() { int I = 0; if(I == 34) i+= 23; return 1; } This compiles into the following push ebp mov ebp,esp ;setup the stack frame sub esp, 4 mov [ebp – 4],0 cmp [ebp – 4], 34 ; jnz continue_program add [ebp – 4],23 continue_program: mov eax,1 mov esp, ebp ;restore the stack frame pop ebp ret Yes I know I decided to give you a complete binary disassembly to see if you remember about the stack frame and the [ebp -4] which means the first local variable created and yes int main has to setup the stack frame like every other function. Now let’s learn how to turn this program back into C++ The first thing we do is look at the compare mov [ebp – 4],0 which is telling us that the program is initilize a variable to 0. Next we see a cmp instruction that is comparing [ebp -4],34 , because of this we know the program is using a if statement, you know “if [ebp -4] = 34” what we should do now is create some alias for [ebp -4] we will use local_var_1. next we see the instruction jnz, which is the same as jne which is saying if[ebp -4] or local_var_1 is not 34 then skip over this if statement and jump to continue_program. Add [ebp -4], 34 or add local_var_1, 34 is saying local_var_1 += 34; After that we “mov eax,1”, clean up the stack frame and then return. Add [ebp -4], 34 add local_var_1, 34 local_var_1 += 34; mov eax,1 Now lets look for a multiple logical if statements If( (i==0) || (i2 == 23) && (i3 ==21) ) If_block_check1: Cmp I,0 Jne if_block_check2: Jmp do_if If_block_check2: Cmp i2,23 Jne skip_if Cmp i3,21 Jne skip_if Do_if: ; actions here skip_if: OK the first thing we see is that on multi logical if statements when one condition fails it jumps to the next logical expression to see if that will evaluate to true, as shown in figure 3.2.1 So if we have a multi logical if statement, and part of the expression succeeds we continue to evaluate the expression until something is false. Of course this is only true for a && operator. For a || operator if one part of the expression is true we quit that entire expression and the if statement evaluates as true. && || The for Loop is not only one of the most interesting things about C++ it is one of the most use statements. The interesting factor for the for loop comes in its ability to evaluate 3 expressions For( <expression 1>; <expression 2>; <expression 3>) The Expression our usually For( <assignment>; <conditional>; <increment| decrement>) Reverse engineering the for statement is not hard, because it’s really a if statement in most cases If(I < 4) { i++; //do actions } Now for the for loop equivalent for(int I =0;i<4;i++) { //do actions } OK lets look at a simple reverse disassembly for the for loop Mov [ebp – 4],0 ;initilize the local variable Jmp condition Increment: Add [ebp -4],1 Condition: Cmp [ebp -4],4 Jge done Loop: ;do actions Jmp increment Done: As you can see the for loop is nothing more than a high level if statement, the first thing we do is initilize the local variable on the stack , after that check the condition statement. Then we go to the loop, then at last we jump back to increment then we jump yet again to the condition label and again until the condition is true. Structures are very useful in C++ because of there ability to contain members. A structure lets you define a variable of any size , example Struct test1 { int member1; int member2; }; This creates a 64 bit , 8 byte variable in memory. So in a sense structures or regular variables but allow us to access certain parts of that variable independently from others This makes it very useful Because if you were to use char test1[8]; you would be create the exact same in memory as Struct test1, only it would be much harder to access 4 byte members individually in char test[8]; Here is a example of using test1 as a local variable Sub ESP, 8 ;reverse 8 bytes on the local stack Mov [ESP -4], 45 ;move member2 to 45 Mov [ebp -8], 12 ;move member1 to 1 As you can see structures are stored reverse in memory, because you would think That member one would be the last on the stack, but it turns out it is the first on the stack For a global variable the compiler would simply reverse 8 bytes in the executable in reference those each individually base on the member you have chosen. I am providing some algorithms to prove and help you understand some of the theory I presented in this book. This following example proves that variables inside a if block our truly accessible to the whole function. #include "stdafx.h" #include "iostream.h" int main(int argc, char* argv[]) { __asm mov dword ptr [ebp -4], 23 if(true) { int i; cout << i << endl; } return 1; } The output should be 23 even though we never initialize I , if your confused remanber that since I is the first variable and the only variable its location is [ebp -4]. This next example proves that structures are just regular variables with the given ability to be access in parts instead of wholes. #include "stdafx.h" #include "iostream.h" struct test1 { int member1; int member2; int member3; }; int main(int argc, char* argv[]) { test1 local_struct; local_struct.member1 = 1; local_struct.member2 = 1; local_struct.member3 = 1; __asm { add dword ptr [ ebp - 12],55 ; structure 1 add dword ptr [ ebp - 8] , 100 ; structure 2 add dword ptr [ ebp - 4] , 23 ; structure 3 } cout << "member 1: " << local_struct.member1 << endl; cout << "member 2: " << local_struct.member2 << endl; cout << "member 3: " << local_struct.member3 << endl; return 1; } Output should be member 1: 56 member 2: 101 member 3: 24 This Chapter aims to provide knowledge of practical decompiling, in this chapter we will learn to use a disassembler, and learn to decompile real world applications. 4.1 Intro to Windows decompiling Windows decompiling is not that difficult since all windows programmers follow a strict programming method such as CreateWindowEx, or CreateDialog, and All windows have message loops which you can easily find. Before we really start getting into decompiling lets go over the basic. In the vast world of windows there are many types of application, and many more types of technology. CreateWindowEx CreateDialog Therefore all of it is too much to cover in one tutorial. On top of that, this information only applies to application that uses the basic window functions, such as CreateWindowEx, and CreateDialog. Applications made in visual basic, or Delphi use there own engine, and there engines will not be cover. Also there is MFC, which is simply a class wrapper to API calls, but can greatly complex things. We will be working on an application I made in pure win32 API, All it does is show a window, but we all know showing a window requires a significant amount of work. 1. Create the window class From this we can get the Window Procedure Method, in which all message are handle. lpfnWndProc of the WNDCLASSEX structure contains the address to the Window procedure method. lpfnWndProc WNDCLASSEX 2. Create the Window itself. We can retrieve every single const by name, and most of the time the exact C/C++ equivalent. 3. The message Loop All we have to do is look for a reference to GetMessage(…). GetMessage(…) We start with the basic skeletons first, then move on to more complex stuff, its import to learn the basic first because They give you an ideal of how the application is design. We will be using the PVdasm, which you can get from my site - This is a very nice free disassembler which we will be using. 4.2 Decompiling a sample application First load up PvDasm, and your screen should look similar to Figure 4.2.1 (Figure 4.2.1) Grab CreateWindow2 (the program we are going to decompile by hand) and Open it in the disassembler, your screen should look similar to figure 4.2.2 (Figure 4.2.2) We see are entry point, but this is CRTL code (Common Runtime library), how can we find WinMain Function? By references. We know that in WinMain functions we have a CreateWindowEx, or a RegisterClassEx, if we can find where the program is calling these functions, we can than begin to map out the program. You see when you compile a program a linker links it with libraries or DLL (Dynamic linking libraries). The functions you get from these WinMain RegisterClassEx DLL’s are called imports. The PVdasm can list all the imports a program has, and show you the address from where they are called. To use this feature press Crtl+N or press the import button. Your screen should look similar to figure 4.2.3 Now we must find the start of the function, this is pretty easy, if we follow the following rules. push ebp mov esp,ebp sub esp, <X> 2. Right after a mov esp,ebp pop ebp ret <X> Well if we scroll up to address 0040104C and you should see 0040104C push ebp 0040104D mov ebp, esp 0040104F sub esp, 50h After that we see mov dword ptr ss:[ebp- 30],0000030 mov dword ptr ss:[ebp-2c],0000000003 Ok, so we know we have local variables, and it mostly looks like a structure, to find the WNDCLASSEX structure we need a reference point. A good reference to look for is LoadCursor. About every single application uses the call, so simply press the import button or Crtl+N, and select LoadCursor. WNDCLASSEX LoadCursor Once you have selected LoadCursor you should then see something similar to 00401092 call ds:LoadCursorA 00401098 mov [ebp-14], eax Ok, now we all know the return value for functions are stored in the eax register, and we know that the hCursor member of WNDCLASSEX is being used (because we are loading a cursor). Now what position is hCursor in memory, well its ebp-14h(yes that’s 14 HEX no decimal), with this information we can figure out where all the other member are to. If we take a quick look at the WNDCLASSEX structure hCursor typedef struct WNDCLASSEX { UINT cbSize; //30h UINT style; // 2ch WNDPROC lpfnWndProc; //28h int cbClsExtra; //24h int cbWndExtra; //20h HINSTANCE hInstance; //1ch/ HICON hIcon; //18h HCURSOR hCursor; // ebp -14h ß--Start calculation here -> HBRUSH hbrBackground; //ebp -10h LPCSTR lpszMenuName; //ebp – 0ch LPCSTR lpszClassName; //ebp - 8 HICON hIconSm; //ebp -4 }; As you can see its easy to calculate structure member addresses, simply add the size of the variable for each member above you and subtract the size of the variable for each member below you. Now that we know the memory location of every structure we can begin to really understand how the program is created. The first thing we do is get the value of all the members in the structure, starting with the cbSize member. 1. cbSize The first thing we see is mov dword ptr ss:[ebp- 30],0000030 and we all know that ebp – 30h is the location of cbSize. So what we are really saying is mov dword ptr ss:[cbSize],30h. Of course we can go a step further since we know that 30h is the size of WNDCLASSEX, and cbSize is suppose to hold the size of WNDCLASSEX, so we can fully decompile this line to mov dword ptr ss:[ebp- 30],0000030 cbSize mov dword ptr ss:[cbSize],30h wc.cbSize = sizeof(WNDCLASSEX); 2. style mov dword ptr ss:[ebp-2c],0000000003 Ok, what style is the program using, well, to figure this out we need to look into windows.h and get all style values. Now we could do a bit by bit compare by hand, but we don’t have time for that, so I made a small program call WinDasmRef. All we need to do is choose the type of section we want to look up, in our case its style from WNDCLASSEX, then enter a value, and bam it returns exactly what the user entered. Refer to screen shot 4.2.5 for more information You can get this program from This program is no where near finish, but it is more than enough for this book. 3. lpfnWndProc mov dword ptr ss:[ebp-28],00401000 This is the most important and interesting structure, because this holds the address to the message loop from this we can tell that the message loop is located at address 00401000(in hex of course) 4. cbClsExtra mov dword ptr ss:[ebp -24],0 We are simply setting wc.cbClsExtra to 0000000 wc.cbClsExtra 5. cbWndExtra mov dword ptr ss:[ebp-20],0000000 we are simply setting wc.cbWndExtra to 0 wc.cbWndExtra 6. hInstance mov eax,dword ptr ss:[ebp+8] //local variable hInstance mov dword ptr ss:[ebp-1C],eax //Hinstance Remember the declaration for the main function is WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine , int nCmdShow) and the first parameter (hInstance) is stored at ebp + 8, and the second parameter (hPrevInstance) is stored at ebp + 12 ebp + 8 ebp + 12 Now that eax holds the value of holds hinstance, we simply transfer that value to [ebp-1C] or hinstance. So in other words we are saying wc.hInstance = hInstance 7. hIcon mov dword ptr ss:[ebp-18],00000000 we are simply setting wc.hIcon to 0 wc.hIcon 8. hCursor push 00007F00 mov ecx,DWORD ptr SS:[ebp+08] push ecx mov dword ptr ss:[ebp-14],eax Ok, the first thing we do is look at the declaration of LoadCursorA and find that it is LoadCursorA LoadCursor (HINSTANCE hInstance, LPSTR cursorname); and the last parameter is push first, so cursorname is the first parameter being bush which is the value 7F00. If the user is not using a custom cursor (most don’t) we can retrieve its value in WinDasmRef and yes, you can enter hex values in WinDasmRef, just make sure you put a 0x7F00 not 7F00 refer to figure 4.2.6 (Figure 4.2.6) Note: If your wondering why LoadCursor.cursorname wasn’t in the first picture, it is because I’m writing this program as I’m typing this book. LoadCursor.cursorname mov ecx,DWORD ptr SS:[ebp+08] push ecx Next we move ecx, to SS:[ebp+8] which is hInstance, and then we push ecx to the stack, hInstance the stack currently contains then we see call USER32!LoadCursorA , we can turn this back into the complete original line of source which is USER32!LoadCursorA LoadCursor(hInstance,IDC_ARROW); now we all know that LoadCursor returns the handle to the cursor in the eax register so mov dword ptr ss:[ebp-14],eax , ebp-14 is the position of hCursor. Now lets decompile the entire statement mov dword ptr ss:[ebp-14],eax , ebp-14 wc.hCursor = LoadCursor(hInstance,IDC_ARROW); 9. hbrBackground push 01 CALL GDI32!GetStockObject mov dword ptr ss:[ebp-10],eax Ok , first we push 01 into the stack and call GetStockObject, now if we look at the declaration of GetStockObject which is GetStockObject(int brush) , we know that the 01 is specifying a brush so load up WinDasmRef, and type 1 in , refer to figure 4.2.7 for more information GetStockObject GetStockObject(int brush) So we know the call is like GetStockObject(LTGRAY_BRUSH), after that we see mov dword ptr ss:[ebp-10],eax and eax holds the handle to the brush return by GetStockObject, and ebp-10, is the memory location of hbrBackground, so the full decompile statement is GetStockObject(LTGRAY_BRUSH) hbrBackground wc.hbrBackground = GetStockObject(LTGRAY_BRUSH); 10. lpszMenuName mov dword ptr ss:[ebp-0C],0000000 we simply set lpszMenuName to 0 lpszMenuName 11. lpszClassName mov edx,dword ptr ds:[0040603C] mov dword ptr ss:[ebp-08],edx at the address of 0040603C, is a pointer to are class name, how can i tell ? , easy because it is surrounding the address in brackets, so it is getting a value from 0040603C, we can easily use any hex editor to look at the address 0040603C, as long as we know the image base. The image base is the location the program is loaded into memory, to see the image base press CRTL+P in PvDasm A window similar to Figure 4.2.8 should come up (Figure 4.2.8) We subtract the image base with is 400000 in hex from 0040603C, and we are left with 603C, now if we go to offset 603C in a file we will see 30, we must read 3 more bytes because Intel uses 32 bit address, so the full address is 30604000 Now 30604000 is in little endian order, which the X86 uses, we must convert it to big endian by reverse every hex byte, like this 00406030, now if we subtract the image base from that we get 6030, and we look at address 6030, we will see a ‘D’, if we keep reading to a null terminator like everyone else does we will see DECOMPILE. Now that we have the name of are class, we can fully decompile the statement like this static char * szClass = “DECOMPILE”; wc.lpszClassName = szClass; since we are going mov dword ptr ss:[ebp-08],edx and edx wc.lpszClassName = szClass; mov dword ptr ss:[ebp-08],edx and edx holds the address of szClass, and ebp-8 is the memory location of lpszClassName szClass lpszClassName 12. hIcon mov dword ptr ss:[ebp-4],0000000 this is simply setting hIcon to 0 Now that we are done with are whole window class, lets have a overview of all the values WNDCLASSEX wc; //we don’t know the exact name but it has to be something wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra =0; wc.hInstance = hInstance; wc.hIcon =0; wc.hCursor = LoadCursor(hInstance,IDC_ARROW); wc.hbrBackground = (HBRUSH) GetStockObject(LTGRAY_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = szClass; wc.hIconSm = NULL; As you can see we practically decompile this back to exact source code. Now we see the following code lea eax,dword ptr ss:[ebp-30] push eax and eax,0000FFFF test eax,eax jnz 004010E4 push 0 push 00406054 ; ASCIIZ Crap push 0040605C ; ASCIIZ Can’t register class push 0 xor eax,eax jmp 00401172 lets first begin with lea eax,dword ptr ss:[ebp-30] push eax now ss:[ebp-30] holds the address of the WNDCLASSEX structure, because [ebp-30] is the first member of the structure which is cbSize, now that eax holds the address of the structure we push it into the stack and call USER32!RegisterClassExA; if we look at the Declaration of RegisterClassEx, USER32!RegisterClassExA; ATOM WINAPI RegisterClassExA(CONST WNDCLASSEX *); We see that it returns the type ATOM, which is 16 bits, and because of that we see and eax,0000FFFF, which is masking off the upper 16 bits, so we don’t read a 32 bit value, after that we see test eax,eax jnz 004010E4 this is simply saying if eax is not zero then jump to 004010E4, the exact c++ code for this is if(!RegisterClassEx(&wc)) { //bad code here } //else continue (004010E4 Remember the ‘!’ is saying if RegisterClassEx returns the value of 0 execute the bad code. Now as we continue on we see that it is going to display a message box if it fails push 0 push 00406054 ; ASCIIZ Crap push 0040605C ; ASCIIZ Can’t register class and if we look at the declaring of MessageBox MessageBox MessageBoxA(HWND hWnd , LPCSTR lpText, LPCSTR lpCaption, UINT uType); Lets crack open WinDasmRef Refer to figure 4.2.9 for more information So we can decompile the whole line into MessageBox(NULL,”Can’t register class”,”crap”,MB_OK); after that we see xor eax,eax jmp 00401172 xor eax,eax clears 0 and if we go see what’s at address 00401172, we will find xor eax,eax mov esp,ebp pop ebp ret 10 which is exit code, so we can decompile this line to return 0. The full original code is MessageBox(NULL,"Can't register class","Crap",MB_OK); return 0; } As you can see decompiling is quite simple for this basic windows stuff, so I not going to bore you with the rest. If you have any questions , please check out are forums at Visual basic 6.0 is next This paper is made possible by a grant from your donation, if you would like to continue to support Opcodevoid, then please donate. This book is provided as is; no warranty is applied nor granted information. What is presented in this book is copyrighted by Opcodevoid with all rights respected. All information, algorithms can not be copied, reproduce nor distributed in anyway, without written permission from Opcodevoid or Opcodevoid Inc. This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here :~ :| X| X| :suss::suss::(:( General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/4210/C-Reverse-Disassembly?msg=520555
CC-MAIN-2014-23
refinedweb
7,764
56.83
- Part 1 - Getting Started - Part 2 - App Service with dotnet (this post) - Part 3 - Serverless with JavaScript - Part 4 - CosmosDB and GraphQL - Part 5 - Can We Make GraphQL Type Safe in Code? In my introductory post we saw that there are many different ways in which you can host a GraphQL service on Azure and today we’ll take a deeper look at one such option, Azure App Service, by building a GraphQL server using dotnet. If you’re only interested in the Azure deployment, you can jump forward to that section. Also, you’ll find the complete sample on my GitHub. Getting Started For our server, we’ll use the graphql-dotnet project, which is one of the most common GraphQL server implementations for dotnet. First up, we’ll need an ASP.NET Core web application, which we can create with the dotnet cli: dotnet new web Next, open the project in an editor and add the NuGet packages we’ll need: At the time of writing graphql-dotnet v3 is in preview, we’re going to use that for our server but be aware there may be changes when it is released. These packages will provide us a GraphQL server, along with the middleware needed to wire it up with ASP.NET Core and use System.Text.Json as the JSON seralizer/deserializer (you can use Newtonsoft.Json if you prefer with this package). We’ll also add a package for GraphiQL, the GraphQL UI playground, but it’s not needed or recommended when deploying into production. With the packages installed, it’s time to setup the server. Implementing a Server There are a few things that we need when it comes to implementing the server, we’re going to need a GraphQL schema, some types that implement that schema and to configure our route engine to support GraphQL’s endpoints. We’ll start by defining the schema that’s going to support our server and for the schema we’ll use a basic trivia app (which I’ve used for a number of GraphQL demos in the past). For the data, we’ll use Open Trivia DB. .NET Types First up, we’re going to need some generic .NET types that will represent the underlying data structure for our application. These would be the DTOs (Data Transfer Objects) that we might use in Entity Framework, but we’re just going to run in memory. As you can see, it’s a fairly generic C# class. We’ve added a few serialization attributes to help converting the JSON to .NET, but otherwise it’s nothing special. It’s also not usable with GraphQL yet and for that, we need to expose the type to a GraphQL schema, and to do that we’ll create a new class that inherits from ObjectGraphType<Quiz> which comes from the GraphQL.Types namespace: The Name and Description properties are used provide the documentation for the type, next we use Field to define what we want exposed in the schema and how we want that marked up for the GraphQL type system. We do this for each field of the DTO that we want to expose using a lambda like q => q.Id, or by giving an explicit field name ( incorrectAnswers). Here’s also where you control the schema validation information as well, defining the nullability of the fields to match the way GraphQL expects it to be represented. This class would make a GraphQL type representation of: Finally, we want to expose a way to query our the types in our schema, and for that we’ll need a Query that inherits ObjectGraphType: Right now there is only a single type in our schema, but if you had multiple then the TriviaQuery would have more fields with resolvers to represent them. We’ve also not implemented the resolver, which is how GraphQL gets the data to return, we’ll come back to that a bit later. This class produces the equivalent of the following GraphQL: Creating a GraphQL Schema With the DTO type, GraphQL type and Query type defined, we can now implement a schema to be used on the server: Here we would also have mutations and subscriptions, but we’re not using them for this demo. Wiring up the Server For the Server we integrate with the ASP.NET Core pipeline, meaning that we need to setup some services for the Dependency Injection framework. Open up Startup.cs and add update the ConfigureServices: The most important part of the configuration is lines 8 - 13, where the GraphQL server is setup and we’re defining the JSON seralizer, System.Text.Json. All the lines above are defining dependencies that will be injected to other types, but there’s a new type we’ve not seen before, QuizData. This type is just used to provide access to the data store that we’re using (we’re just doing in-memory storage using data queried from Open Trivia DB), so I’ll skip its implementation (you can see it on GitHub). With the data store available, we can update TriviaQuery to consume the data store and use it in the resolvers: Once the services are defined we can add the routing in: I’ve put the inclusion GraphiQL. within the development environment check as that’d be how you’d want to do it for a real app, but in the demo on GitHub I include it every time. Now, if we can launch our application, navigate to and run the queries to get some data back. Deploying to App Service With all the code complete, let’s look at deploying it to Azure. For this, we’ll use a standard Azure App Service running the latest .NET Core (3.1 at time of writing) on Windows. We don’t need to do anything special for the App Service, it’s already optimised to run an ASP.NET Core application, which is all this really is. If we were using a different runtime, like Node.js, we’d follow the standard setup for a Node.js App Service. To deploy, we’ll use GitHub Actions, and you’ll find docs on how to do that already written. on ASP.NET Core using graphql-dotnet and deploy it to an Azure App Service. When it comes to the Azure side of things, there’s nothing different we have to do to run the GraphQL server in an App Service than any other ASP.NET Core application, as graphql-dotnet is implemented to leverage all the features of ASP.NET Core seamlessly. Again, you’ll find the complete sample on my GitHub for you to play around with yourself.
https://www.aaron-powell.com/posts/2020-07-21-graphql-on-azure-part-2-app-service-with-dotnet/
CC-MAIN-2021-04
refinedweb
1,124
68.6
A relaxed chat room about all things Scala (2 & 3 both). Beginner questions welcome. applies ... = Tis intended to be a type parameter, in scala 2, you can't do that, and in scala 3, there is special syntax for that Tis defined when you call it inline, and not if you don't def foo[T](f: T => Int), you can do foo((t: T) => 7)because Tis defined there toStringon it, which you can always do Tof a type you don't know Any, you can't do anything more with it def foo[T](t: T): T = t List(1, 2, 3).map(foo) @ def foo(f: Int => Int = _ + 1): Int = f(42) defined function foo @ foo() res1: Int = 43 @ foo(_ * 2) res2: Int = 84
https://gitter.im/scala/scala?at=60ad4c149d18fe19982666a3
CC-MAIN-2021-49
refinedweb
129
76.59
In this topic - Using add-ins - Implementing interfaces - Inheriting ArcGIS base classes - Using ArcGIS item templates - Creating a command or tool Using add-ins Creating an add-in is the easiest and recommended way to create simple commands (buttons) and tools. Add-ins are fully documented in Building add-ins for ArcGIS Desktop. Implementing interfaces A custom command can be created by implementing ICommand. By implementing ICommand, you define a command's appearance, state, and behavior. A command is plugged into an application by registering itself in to the appropriate command component categories. When the command is used by the application framework, the OnCreate method is called to initialize and hook to the application or control. A tool is a type of command that allows interaction with a display canvas in an ArcGIS application. To create a custom tool, implement both the ICommand and ITool interfaces. By implementing ITool, you define the cursor, mouse, or keystroke interaction performed by a tool. You must stub out and provide implementation code for each interface member in the source code. You are also responsible for registering the class to the appropriate component category. Using the ArcGIS Add Class Wizard to extend ArcObjects will help you accomplish these development tasks. Inheriting ArcGIS base classes The BaseCommand and BaseTool classes simplify the creation of custom commands and tools for ArcGIS. They provide a default implementation for each member of ICommand and ITool. Instead of stubbing out each member and providing implementation code, you have to override the members that your custom command or tool requires. The exception is ICommand.OnCreate; this member must be overridden in your derived class. The following table shows the members that have a significant base class implementation, along with a description of that implementation. Override these members when the base class behavior is not consistent with your customization. For example, enabled is set to true by default; if you want your custom command enabled only when a specific set of criteria has been met, you must override this property in your derived class. Using ArcGIS item templates The Base Command and Base Tool item templates are available to help you create commands and tools more efficiently than directly implementing the interfaces. The advantages of using the item templates are listed as follows: - The ArcGIS Base Command and Base Tool templates inherit from the BaseCommand and BaseTool abstract classes. Instead of implementing the Bitmap, Caption, Category, Name, Message, and ToolTip properties individually, you can set the values to be returned from these read-only properties in the class constructor and rely on the BaseCommand or BaseTool class to provide the implementation for these methods. The other members are left to return the default values. - The templates also add the necessary resource file or files, bitmap images, and cursor files to the project. - The templates override the OnCreate method that is passed a handle or hook to the ArcGIS Engine control or ArcGIS Desktop application that the command works with—for example, MapControl, PageLayoutControl, ToolbarControl, or ArcMap. The templates process the incoming hook object and set the initial state of the command or tool appropriately. - The IApplication interface is used to hold on to the application object if the command only works in an ArcGIS Desktop application. - The HookHelper object is used to hold on to the hook, and the IHookHelper interface it implements can return the ActiveView, PageLayout, and Map regardless of the type of hook that is passed. - The GlobeHookHelper object is used to hold on to the hook, and the IGlobeHookHelper interface it implements can return the Camera, Globe, GlobeDisplay, and ActiveViewer regardless of the type of hook that is passed. - The SceneHookHelper object is used to hold on to the hook, and the ISceneHookHelper interface it implements can return the SceneViewer, Scene, SceneGraph, and Camera regardless of the type of hook that is passed. - All custom commands or tools must be exposed to the Component Object Model (COM). The templates insert the COM related attributes and required globally unique identifiers (GUIDs) to expose a .NET class to COM. - Visual Studio provides the ability to specify functions that execute when an assembly exposed to COM is registered and unregistered on a system. This allows the class to be registered in the appropriate command component category. The ArcGIS Base Command and Base Tool templates provide these COM component category registration functions. Creating a command or tool Follow these general steps to add a command or tool implementation to an existing project: - Select Base Command or Base Tool from the Add New Item dialog box and click Add to add the item to your Visual Studio project. For information on how to access the dialog box, see Using item templates to extend ArcObjects. - After you click Add, the ArcGIS New Item Wizard Options dialog box opens. Select the type of command or tool you want to create and click OK. The type of command or tool you choose depends on the ArcGIS Engine control or ArcGIS Desktop application you want the command or tool to work with. See the following screen shot: A Universal Command or Universal Tool works with the ArcGIS Engine MapControl, PageLayoutControl, GlobeControl, and SceneControl, as well as the ArcGIS Desktop ArcMap, ArcGlobe, and ArcScene applications. A Blank Command or Blank Tool does not contain any component category registration code or implementation in the OnCreate method; you need to provide this. - Modify the code below the TODO comment lines in the constructor of the generated class. Review the code in the overridden OnCreate method, which is responsible for initializing the command or tool with the hook control or application. - In the case of a command, provide implementation within the OnClick method. In the case of a tool, provide implementation within the OnMouseDown, OnMouseMove, or OnMouseUp methods. - If necessary, override other methods or properties from the base class. Using the autocompletion feature in Visual Studio, type public override (C#) or Public overrides (VB.NET) and press the spacebar to get a list of the available members to override. - If necessary, edit the command bitmap or tool cursor file. These files have the same name as the class file. See Also:Working with ArcGIS base classes ESRI.ArcGIS.ADF.BaseClasses namespace How to create a command or tool to work with the controls Using item templates to extend ArcObjects
http://help.arcgis.com/en/sdk/10.0/arcobjects_net/conceptualhelp/0001/000100000066000000.htm
CC-MAIN-2018-05
refinedweb
1,059
52.19
When you want to draw something on a form you need a Graphics object. But a Graphics constructor isn’t public and if that is not enough the Graphics class is also sealed! This means you can’t create a Graphics object via the new keyword nor can you derive from the Graphics class. One way to get a Graphics object is through a Paint event handler of a Form via the PaintEventArgs class. OK now you can use an array of Points, pass it with a Pen object to DrawLines and it draws your function! This is not what I want here. I want my functions to plot a single dot, not connected by a line. That seems hard to do in GDI+, if anyone knows a better answer then what I got here please let me know. The PlotPixel method of my Plot class is something I found on the internet, which I feed with transformed pixelcoordinates so it looks nice on the screen. I exercice my Plot class in a DrawIt class which is derived from Form. In the DrawWindow_Paint event handler two functions are plotted: a classic sine function and a function which simulates the trajectories of particles in a cyclotron. Change some of the values a,b,c,x and y to get amazing results! Also notice the same minimalistic approach as used in a previous entry in code snippets. using System; using System.Drawing; namespace SimpleDrawProject { class Plot { //class to plot x and y values on a form // //because on the form coordinates start at the upper left corner with 0,0 //with the y coordinate going down, a little transformation is done here //so that x,y coordinates act as normal carthesian coordinates, with 0,0 //in the center of the form struct PlotPort { public int minX; public int maxX; public int minY; public int maxY; }; private PlotPort _PlotW; //"window" of carthesian coordinates private Size _ClientArea; //keeps the pixels info private double _Xspan; private double _Yspan; public Plot(){} public Plot(Size Plotarea) { _ClientArea = Plotarea; } public Size ClientArea { set { _ClientArea = value; } } public void SetPlotPort(int minx, int maxx, int miny, int maxy) { //set the bounderies of the form(screen) to real coordinates. _PlotW.minX = minx; _PlotW.maxX = maxx; _PlotW.minY = miny; _PlotW.maxY = maxy; _Xspan = _PlotW.maxX - _PlotW.minX; _Yspan = _PlotW.maxY - _PlotW.minY; } public void PlotPixel(double X, double Y, Color C, Graphics G) { //workhorse of this class Bitmap bm = new Bitmap(1, 1); bm.SetPixel(0, 0, C); G.DrawImageUnscaled(bm, TX(X), TY(Y)); } private int TX(double X) //transform real coordinates to pixels for the X-axis { double w; w = _ClientArea.Width / _Xspan * X + _ClientArea.Width / 2; return Convert.ToInt32(w); } private int TY(double Y) //transform real coordinates to pixels for the Y-axis { double w; w = _ClientArea.Height / _Yspan * Y + _ClientArea.Height / 2; return Convert.ToInt32(w); } } } //--------------------------------------------------------------------------- using System; using System.Drawing; using System.Windows.Forms; namespace SimpleDrawProject { class DrawWindow : Form { public DrawWindow() //this constructor draws the form { InitializeComponent(); } static void Main() { Application.Run(new DrawWindow()); //start the application } private void InitializeComponent() { this.SuspendLayout(); // DrawWindow this.ClientSize = new System.Drawing.Size(800, 800); this.Location = new System.Drawing.Point(10, 10); this.Name = "DrawWindow"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.DrawWindow_Paint); this.ResumeLayout(false); } private void DrawWindow_Paint(object sender, PaintEventArgs e) { Graphics Grf = e.Graphics; MiraPlot(Grf); SinusPlot(Grf); } private void SinusPlot(Graphics Grf) { Plot MyPlot = new Plot(); double x = 0.0; double y = 0.0; MyPlot.ClientArea = this.ClientSize; MyPlot.SetPlotPort(-10, 10, -5, 5); for (x = -7.0; x < 10.0; x += 0.025) { y = Math.Sin(x); MyPlot.PlotPixel(x ,y , Color.BlueViolet, Grf); } } private void MiraPlot(Graphics Grf) { Plot MyPlot = new Plot(); double a = -0.46; double b = 0.99; double c = 2.0 - 2.0 * a; double x = 12.0; //start value double y = 0.0; //start value double z; double w = a * x + c * x * x / (1 + x * x); MyPlot.ClientArea = this.ClientSize; MyPlot.SetPlotPort(-20, 20, -20, 20); for (int n = 0; n < 20000; n++) { MyPlot.PlotPixel(x, y, Color.BlueViolet, Grf); z = x; x = b * y + w; w = a * x + c * x * x / (1 + x * x); y = w - z; } } } } skatamatic 371 ddanbe commented: Fine positive remarks! +14
https://www.daniweb.com/programming/software-development/code/217204/function-plotting-in-c
CC-MAIN-2019-51
refinedweb
709
60.41
Transparent Persistence, Fault-Tolerance and Load-Balancing for Java Systems. Orders of magnitude FASTER and SIMPLER than a traditional DBMS. No pre or post-processing required, no weird proprietary VM required, no base-class inheritance or clumsy interface definition required: just PLAIN JAVA CODE. How is this possible? Question: RAM is getting cheaper every day. Researchers are announcing major breakthroughs in memory technology. Even today, servers with multi-gigabyte RAM are commonplace. For many systems, it's already feasible to keep all business objects in RAM. Why can't I simply do that and forget all the database hassle? Answer: You can, actually. Are you crazy? What if there's a system crash? To avoid losing data, every night your system server saves a snapshot of all business objects to a file using plain object serialization. What about the changes occurred since the last snapshot was taken? Won't the system lose those in a crash? No. How come? All commands received from the system's clients are converted into serializable objects by the server. Before being applied to the business objects, each command is serialized and written to a log file. During crash recovery, first, the system retrieves its last saved state from the snapshot file. Then, it reads the commands from the log files created since the snapshot was taken. These commands are simply applied to the business objects exactly as if they had just come from the system's clients. The system is then back in the state it was just before the crash and is ready to run. Does that mean my business objects have to be deterministic? Yes. They must always produce the same state given the same commands. Doesn't the system have to stop or enter read-only mode in order to produce a consistent snapshot? No. That is a fundamental problem with transparent or orthogonal persistence projects like PJama () but it can be solved simply by having all system commands queued and routed through a single place. This enables the system to have a replica of the business logic on another virtual machine. All commands applied to the "hot" system are also read by the replica and applied in the exact same order. At backup time, the replica stops reading the commands and its snapshot is safely taken. After that, the replica continues reading the command queue and gets back in sync with the "hot" system. Doesn't that replica give me fault-tolerance as a bonus? Yes it does. I have mentioned one but you can have several replicas. If the "hot" system crashes, any other replica can be elected and take over. Of course, you must be able to afford a machine for every replica you want. Does this whole scheme have a name? Yes. It is called system prevalence. It encompasses transparent persistence, fault-tolerance and load-balancing. If all my objects stay in RAM, will I be able to use SQL-based tools to query my objects' attributes? No. You will be able to use object-based tools. The good news is you will no longer be breaking your objects' encapsulation. What about transactions? Don't I need transactions? No. The prevalence design gives you all transactional properties without the need for explicit transaction semantics in your code. How is that? DBMSs tend to support only a few basic operations: INSERT, UPDATE and DELETE, for example. Because of this limitation, you must use transaction semantics (begin - commit) to delimit the operations in every business transaction for the benefit of your DBMS. In the prevalent design, every transaction is represented as a serializable object which is atomically written to the queue (a simple log file) and processed by the system. An object, or object graph, is enough to encapsulate the complexity of any business transaction. What about business rules involving dates and time? Won't all those replicas get out of sync? No. If you ask the use-case gurus, they will tell you: "The clock is an external actor to the system.". This means that clock ticks are commands to the business objects and are sequentially applied to all replicas, just like all other commands. Is object prevalence faster than using a database? The objects are always in RAM, already in their native form. No disk access or data marshalling is required. No persistence hooks placed by preprocessors or postprocessors are required in your code. No "isDirty" flag. No restrictions. You can use whatever algorithms and data-structures your language can support. Things don't get much faster than that. Besides being deterministic and serializable, what are the coding standards or restrictions my business classes have to obey? None whatsoever. To issue commands to your business objects, though, each command must be represented as a serializable object. Typically, you will have one class for each use-case in your system. How scalable is object prevalence? The persistence processes run completely in parallel with the business logic. While one command is being processed by the system, the next one is already being written to the log. Multiple log files can be used to increase throughput. The periodic writing of the snapshot file by the replica does not disturb the "hot" system in the slightest. Of course, tests must be carried out to determine the actual scalability of any given implementation but, in most cases, overall system scalability is bound by the scalability of the business classes themselves. Can't I use all those replicas to speed things up? All replicas have to process all commands issued to the system. There is no great performance gain, therefore, in adding replicas to command-intensive systems. In query-intensive systems such as most Web applications, on the other hand, every new replica will boost the system because queries are transparently balanced between all available replicas. To enable that, though, just like your commands, each query to your business logic must also be represented as a serializable object. Isn't representing every system query as a serializable object a real pain? That's only necessary if you want transparent load-balancing, mind you. Besides, the queries for most distributed applications arrive in a serializable form anyway. Take Web applications for example: aren't HTTP request strings serializable already? Does prevalence only work in Java? No. You can use any language for which you are able to find or build a serialization mechanism. In languages where you can directly access the system's memory and if the business objects are held in a specific memory segment, you can also write that segment out to the snapshot file instead of using serialization. Is there a Java implementation I can use? Yes. You will find Prevayler - The Open-Source Prevalence Layer, an example application and more information at. It does not yet implement automatic load-balancing but it does implement transparent business object persistence and replication is in the oven. Is Prevayler reliable? Prevayler's robustness comes from its simplicity. It is orders of magnitude simpler than the simplest RDBMS. Although I wouldn't use Prevayler to control a nuclear plant just yet, its open-source license ensures the whole of the software developing community the ability to scrutinize, optimize and extend Prevayler. The real questions you should bear in mind are: "How robust is my Java Virtual Machine?" and "How robust is my own code?". Remember: you will no longer be writing feeble client code. You will now have the means to actually write server code. It's the way object orientation was intended all along; but it's certainly not for wimps. You said Prevayler is open-source software. Do you mean it's free? That's right. It's licensed under the Lesser General Public License. But what if I'm emotionally attached to my database? For many applications, prevalence is a much faster, much cheaper and much simpler way of preserving your objects for future generations. Of course, there will be all sorts of excuses to hang on to "ye olde database", but at least now there is an option. --------------------------------------------------------------------- ABOUT THE AUTHOR KlausWuestefeld enjoys writing good software and helping other people do the same. He has been doing so for 17 years now. He can be contacted at klaus@objective.com.br. --------------------------------------------------------------------- "PREVAYLER" and "OPEN-SOURCE PREVALENCE LAYER" are trademarks of Klaus Wuestefeld. Unmodified, verbatim copies of this text including this copyright notice can be freely made. There are still quite a few things we really need transactions for: There's a reason that databases are written by career professionals. A simple object database can be really useful, but that doesn't make it a substitute for the real thing. That's part of why so many "object database" companies failed some ten years back.There's a reason that databases are written by career professionals. A simple object database can be really useful, but that doesn't make it a substitute for the real thing. That's part of why so many "object database" companies failed some ten years back. -. To get much concurrency, you need to snapshot the state before the first change. - If you get halfway through a series of changes and crash, the system had better come back up without the changes you made, because you're not going to be equipped to continue where you left off. - If you get halfway through a series of changes and discover some condition that keeps you from finishing, you had better be able to just drop the changes and pick up with the original snapshot. - If N processes make a series of conflicting changes concurrently, (N-1) of them had better be told that their changes have failed, and that they must try again. Actually, transactions are not so important in the external interface of an OODBMS. In an RDBMS, a manipulation typically involves several SQL statements (e.g. insert, update, remove) each of which can act on only one table at a time. So if a transaction needs to manipulate more than one table, you need to ensure that the set of statements is atomic by issuing a transaction. In an OODBMS, where manipulation methods can operate on more than one class, the need is reduced somewhat. Internally, you can just queue up the command logs until the method is complete, then write them out together. Then the problem becomes entirely one of synchronisation. It's not quite ACID, but it'll do for most business applications. You (ncm) are right, however, in that this solution, while no doubt excellent for many purposes (e.g. if you're happy with the robustness and performance of MySQL, you'll probably be happy with this, too), won't scale to many critical applications. For example, it would be quite hard to handle replication in any sane manner. Klaus, as a matter of interest, how did you manage to get Java to force flushing to disk? Is it just me, or prevayler isn't useful in anything else but a uniprocessor machine as is? You process requests one at a time, which means that there can't be 2 different requests being processed at the same time in different processors. And when you have several replicas you have to have some coordination between all replicas to insure the order of the requests. Or am I missing something here ? Thank you (Klaus Wuestefeld) for your nice write-up. I mostly agree to the points made by the other repliers. Let me discuss/ask some further points: distributed systems? if a systen-prevalence-deployed application contacts other services resp. other servers you have a synchronization problem. How do you handle that? I guess, that you end up doing a 2PC-like synchronization between your prevalence servers. fine grained tx-model versus all or nothing? with big BOs -systems there are actually lots of small transactions. the system prevalence paradigma doesn't give you a fine grained application side control, or does it? Note though that you can adapt (extended) 2PC-transactions to efficiently work RAM-based while retaining persistent storage properties (by using RAM-based subtransactions and files or RDBMS in the root transaction). scalabity? having all "commands queued and routed through a single place" doesn't scale very well. consider one of these big 64 processor multigigabyte machines using a gigabit card: you wouldn't want all requests to be serialized through a single bottleneck which involves IO. With fine grained distributed transactions you don't need this "single place" or even a single server. I appreciate the "do it in background" approach, though, as an advance to requiring requests to be queued while saving the state. It's quite neccesary for 24/7 systems. In my oppinion the complexity of 2PC-systems comes from shortcomings of the commercial products (BEA WLE, Websphere, Oracle etc.). They impose big clumsy quite old fashioned development schemes where the developer is restricted and has to keep track of many conditions. This partly stems from the pain with underspecified and often incorrectly implemented XA-interfaces. (e.g. writing multithreaded programs with XA-adapters from the main RDBMs is a desaster). I think that system prevalence would help implementing web applications which are located on single systems. It is a simple enough paradigm to be used and understood by companies which often fail or are very slow with 2pc-transaction systems. Handling of error conditions (pointed out by ncm) might still be a big problem. just my 2 (soon to be) eurocent and best wishes! holger THANKS A LOT for the FEEDBACK! This is the first forum outside of my working group to actually get the idea and give me some positive feedback. I am just leaving on a trip right now (my wife is calling me ;) for Christmas and will be back on wednesday. Then, I will address all concerns: ACID properties, error-condition recovery, scalability, the works... Just a note on scalability and concurrency to think about over Christmas: Suppose we have a subscriber management system that receives a file from a bank with 100000 (one-hundred-thousand) payment records. A prevalent server running on a regular desktop machine can handle a command/transaction for this in less than a millisecond and be ready for the next command. Merry Christmas! See you soon. I used to be a professional SmallTalk programmer, I also was a professional Lisp programmer. Both of those languages use the concept of a saved memory image as part of their normal development environment. contrast, the impedence mismatch between OO systems and RDBMSs provides a natural boundary and conceptual bottleneck for testing and debugging. It is realtively easy to compare 2 database dumps to see what is different, or to populate the database with test data, or to see which INSERT statement introduced a particular row into the database. You could have test data consisting of a long set of commands, but that "algebraic" approach to testing does not scale well, and allows defects in mutators to mask defects in accessors. One thing that I learned while trying to actually sell ST-80 systems to other divisions in a large company is that IS organizations see a standard RDBMS as an integration point. If your system uses an RDMBS, they can plan capacity on a shared database machine: they can generate ad-hoc reports, they can use standard tools for disk backups and such on the database machine only. Also, in the event that your system eventaully dies (is no longer maintained, or the license is not extended or whatever) they will at least have the data in a format that they can get out of your system's tables and into some other system.. I'll take the opposite tack for variety: If you're going this far, why bother with a disk at all? Just attach a battery to your RAM. If you want reliability, keep replicas. If a replica is lost, "clone" another one by freezing its message queue and copying the frozen image; the two clones can then "catch up" with the queued messages in parallel. Copy-on-write VM tricks may soften the need to entirely freeze a replica during checkpointing. I suspect the points raised in most of the comments can be fixed. (After all, suppose we were looking the other way. Compared to modern programming languages, databases and middleware systems have lots of horrible misfeatures, starting with bad syntax and ending with fundamentally broken models of (non-)encapsulation and (non-)reuse and (non-)genericity; the complaints in the other direction seem relatively trivial by comparison. How can any self-respecting software engineer stand to use today's RDBMS systems without feeling dirty all over?) jrobbins's notes are the most interesting. It's worth noting that these are basically software engineering problems having to do with how to maintain long-running systems, not issues with the physical architecture proposed here. Is an RDBMS the best way to solve those software engineering problems? It's hard to believe. Are these problems worth solving for other domains? You betcha. I'd love to be able to upgrade my applications without restarting them. (Thanks to Debian, I can mostly upgrade my operating system without restarting it -- something users of e.g. Windows may have difficulty imagining.) Data persistence is definitely not a new idea. In fact, if I remember correctly, persistent storage (ferrite cores) actually predate volatile storage. I guess it somehow faded away, only to emerge recently under the guise of persistent OSs such as EROS, persistent architectures such as Prevayler which we now discuss, and so on. It's hard to see how relational algebra or persistence compare with each other. After all, relational algebra was supposed to be simple anyway -- data are nothing more than just lots of mathematical relations, right? We now know however that this `simple' idea is fraught with practical problems. Will the same happen for persistence? Maybe, or maybe not. As jrobbins mentioned, changing the `shape' of objects is a problem, and there are probably many other problems. I might be taking a bit of a simplistic view on the subject but couldn't alot of the issues raised by jrobbins relating to testing and having data in a useful format if a system is retired; be addressed by XML serialization. If we are going to be able to serialize all the commands and business objects why not have an option or feature to dump this information to a XML file. Then when tracking states you could do a dump at each command and compare the XML output to see where things are going wrong. XML serialization also has the advantage of being self describing rather than in a group of tables in binary format on a database server. I mean what happens if your RDBMS company goes bust and you can't get at the data because of a licence timeout for example... Obviously XML serialization will implement another overhead to the system, but if implemented correctly you could serialize in binary format to boost performance, and then you should you need to restore the state for investigative/testing/export purposes load the objects through an Object to XML parsing engine and look at the output. Yes, you are right: in RAM a desktop machine may be able to process your 100.000 records in less than a second or something (I don't think that's representative for anything though), but I do not think that makes the system necessarily more consistent or bullet-proof. What happens if you (or any of your client applications) run into a deadlock within a millisecond? How consistent will the rest of the system and data be without an ACID paradigm to rely on? Correct me, if I'm just not getting the point, but I believe such an issue is not addressed in this approach. Minor point, but '"PREVAYLER" and "OPEN-SOURCE PREVALENCE LAYER" are trademarks of Klaus Wuestefeld'? I'm curious on trademarking a few things of my own, so I checked the USPTO. Neither marks are listed. Given the email address of ".br", are they only trademarked in Brazil? I agree that the Prevayler implementation, as it is today, is robust, fast and scalable enough for most applications. In the company where I work there are 7 people working on two projects using Prevayler to be released in January. I am also glad to help any other early Prevayler adopters. I would like to share some thoughts, though, on the use of prevalence "in the large" to make sure that we are not missing out on some very interesting possibilities. First, I will give a few very quick, specific and UNJUSTIFIED answers, and then, in a separate comment, I will give a more complete explanation in an attempt to clarify all concerns so far... There are still quite a few things we really need transactions for: -- ncm I apologize. Prevayler does have transactions. Although a prevalent system can define transactions (commands) and provide them for a client to use, there is NO TRANSACTION SCHEME the client can use to arbitrarily define new TYPES of transactions (new atomic sets of business operations) whenever it fancies. The last thing we need is another transaction scheme allowing clients to bring business logic into their own hands. I realize the article is confusing in this respect. I have corrected the "oficial" version of the article to make this clear.. Yes. In the prevalence scheme, the other processes shall wait. To get much concurrency, you need to snapshot the state before the first change. Hmmm. What if the waiting time for each transaction is only a few microseconds? (I shall explain...) If you get halfway through a series of changes and crash, the system had better come back up without the changes you made, because you're not going to be equipped to continue where you left off. Yes. The article already covers this well, though. Are there any doubts? If you get halfway through a series of changes and discover some condition that keeps you from finishing, you had better be able to just drop the changes and pick up with the original snapshot. "You" (the system server, I presume) will never be halfway through a series of changes and discover some condition that keeps "you" from finishing. (I shall explain...) If N processes make a series of conflicting changes concurrently, (N-1) of them had better be told that their changes have failed, and that they must try again. There are no concurrent changes in a prevalent scheme. All changes are sequenced. There's a reason that databases are written by career professionals. Yes. Databases are way too complex. ;) A simple object database can be really useful, but that doesn't make it a substitute for the real thing. That's part of why so many "object database" companies failed some ten years back. Prevalence is a persistence scheme, and, like OODBMSs, Prevayler will guarantee a logically crash-free object space for your business objects. Prevayler is not an object database manager, as I see it, though. It does not provide any sort of language for data storage or retrieval (ODBMSs normally provide some OQLish thing). Database managers are also worried, among other things, about how they will store chunks of data from RAM to disk and how they will retrieve those chunks later. When you have enough RAM for all your system data, you need no longer worry about that. When you have enough RAM (the prevalence hypothesis) and a crash-free object space, many database career professionals' assumptions no longer hold. Interesting but ... one has to free one's mind. New possibilities are waiting. (e.g. if you're happy with the robustness and performance of MySQL, you'll probably be happy with this, too) Of course you will be happy! Prevayler is much more robust* and much faster** than MySQL. ;) * Robustness, as I understand it, is related to failure. The less failures something presents, the more robust it is - as simple as that. Prevayler's robustness is bounded by the robustness of the VM and its serialization algorithm. Prevayler is so simple (564 lines including comments, javadoc and blank lines) you could probably write a formal proof for it. ** I have tried both but please don't take my word. Try them out too. "Since Prevayler is also simpler to use, what is the advantage of MySQL?" Some people like SQL and the relational model. MySQL is a relational database manager with an SQL interface. Prevayler is not. Klaus, as a matter of interest, how did you manage to get Java to force flushing to disk? FileOutputStream.getFD().sync() Thank you (Klaus Wuestefeld) for your nice write-up. You are welcome. Let me discuss/ask some further points: distributed systems? if a systen-prevalence-deployed application contacts other services resp. other servers you have a synchronization problem. How do you handle that? I guess, that you end up doing a 2PC- like synchronization between your prevalence servers. I didn't understand the question very well. Fine grained tx-model versus all or nothing? with big BOs - systems there are actually lots of small transactions. the system prevalence paradigma doesn't give you a fine grained application side control, or does it? No it doesn't. I believe that to be inefficient and unnecessary. Maybe we could discuss an example where you think it might be necessary. Note though that you can adapt (extended) 2PC-transactions to efficiently work RAM-based while retaining persistent storage properties (by using RAM-based subtransactions and files or RDBMS in the root transaction). Yes. I know. Three years ago, I wrote an object-relational persistence layer for Java that had nested transactions in RAM and an optional* RDBMS in the root transaction. * You could run everything in RAM if you wanted. That was good for presentations, developing without database configuration hassle and running test scripts very fast. Scalabity? having all "commands queued and routed through a single place" doesn't scale very well. We should better consider one of these big 64 processor multigigabyte machines using a gigabit card: you wouldn't want all requests to be serialized through a single bottleneck which involves IO. Make sure you let the people using ORACLE (and its redo log files) know about that. ;) With fine grained distributed transactions you don't need this "single place" or even a single server. Sounds interesting. Could you elaborate and give an example? I appreciate the "do it in background" approach, though, as an advance to requiring requests to be queued while saving the state. It's quite neccesary for 24/7 systems. Was it clear to you, from the article, that your prevalent system DOES NOT have to stop in order to save its state? I used to be a professional SmallTalk programmer, ... Me too, for 5 years. :) the prevalent scheme, with some daily system snapshots, you can retrieve the system's state before it "got bad"; and with the command logs you can actually replay your commands one-by-one until you get to the rotten one. Of course, I am supposing you have a decent "object encapsulation breaker" FOR DEBUGGING PURPOSES ONLY. I know there aren't many of those around (compared to SQL-based tools) but that is more of a cultural problem, I believe. As you say, people are used to rows and columns. They like to break their systems' encapsulation with SQL tools and, at the same time, they like to complain: "Where are all the benefits object orientation has promised us?". ;) What can you do? I expect things like Prevayler to gradually break this vicious circle.. Me and my team would always do our migrations in Smalltalk (I wrote an object-relational persistence layer for Smalltalk 6 years ago). We would only use SQL or PL as a last resort and for performance reasons. With all your objects in RAM, that is a different story... ;) You can certainly go for RAM all the way and have several replicas, if you can afford it. I could not agree more with egnor. Just a comment on the "Copy-on-write VM tricks" to "soften the need to entirely freeze a replica during checkpointing.": It is a bit complicated dealing with executing threads because your memory might never be in a consistent state at any given moment in time. The orthogonal persistence guys (like the guys mentioned in the article) have not figured how to solve this problem. With prevalence, the problem simply doesn't exist. There is a colleague of mine fiddling with several XML-serialization libraries because he wants to include that in Prevayler. The point about speed is that, if every transaction is extremely fast, you do not have to handle concurrent transactions. That makes life MUCH easier. I am not only talking about sheer RAM processing speed increase, mind you. I am talking about a design change. I shall explain it in one of the following comments. The ACID properties do remain. "PREVAYLER" and "OPEN-SOURCE PREVALENCE LAYER" are trademarks of Klaus Wuestefeld in the same way that "Linux" is a trademark of Linus Torvalds. They are not REGISTERED trademarks though. Much like a copyright, you do not have to register it to be entitled to a trademark. Of course, the suits will always tell you that it is better to register. How fast does serialization run on your machine? import java.io.*; public class SerializationThroughput { static public void main(String[] args) { try { FileOutputStream fos = new FileOutputStream(new File ("tmp.tmp"));} catch (Exception e) { ObjectOutputStream oos = new ObjectOutputStream(fos); Thread.sleep(5000); //Wait for any disk activity to stop. long t0 = System.currentTimeMillis(); int max = 10000; int i = 0; while (i++ < max) { oos.writeObject(new Integer(i));} oos.reset(); oos.flush(); fos.getFD().sync(); //Forces flushing to disk. :) System.out.println("This machine can serialize " + max * 1000 / (System.currentTimeMillis() - t0) + " Integers per second."); e.printStackTrace(); } } } My 450MHz K6II running windows98 with a 3 year old IDE hard drive gives me the following result: "This machine can serialize 576 Integers per second." Does anyone give me more? :) OK, here we go: I shall leave automatic load-balancing aside for now and concentrate on the concerns we already have. Atomicity and Crash-Recovery This is already covered in the article. Consistency and Error-Conditions Every command is executed on its own. The business system must either check for inconsistencies before it starts executing any command or be able to undo whatever changes were done if it runs into an inconsistency. In my designs I prefer the first approach. The demo application included with Prevayler has good examples. Isolation While a client is preparing a command to be executed, no other client can see what that command is all about. Durability The snapshots and command logs guarantee your persistence. If you use replicas, as described in the article, your system shall not only persist, it shall prevail. Scalability and Performance Suppose we have a multi-threaded system in which all threads do all of the three following things: 1) Client stuff - Waiting for an HTTP request; Waiting for an RMI request; Reading a file; Preparing a command to be executed; Writing a file; Generating HTML; Painting a GUI screen; etc... 2) Prevayler stuff - Logging a command to a file. (This is the only thing Prevayler does on the hot system during execution. The snapshot is taken by the replica and has no impact here.) 3) Business stuff - Processing a command; Evaluating a query. For simplicity, Prevayler's implementation, today, will synchronize "Logging a command" and "Processing a command" in a single go. That is not necessary though. The only conditions we have to meet are: - All commands are logged. - All commands are executed after they are logged. - All commands are executed in the same order as they are logged. Using two producer-consumer queues would already alleviate that a little. The main problems, though, are still: - It might take a long time to serialize certain large commands and Prevayler doesn't serialize and log more than one command at a time. - The business system cannot process more than one command at a time. The first problem is easy to solve. 4096 (or more) "slave" log files could be used to serialize and log up to 4096 (or more) SIMULTANEOUS COMMANDS. There must only be a "master" log file indicating in which "slave" log file the last command was serialized (it is not even necessary that the first command that started being logged be the first one to finish). In terms of scalability and throughput, this is as much as you can get even in an RDBMS like ORACLE because of its redo log files. Take a look at the "Serialization Throughput Test" above, to see how well your machine would do as a "master logger". :) All these performance enhancements are already scheduled for future Prevayler releases. If anyone is considering using Prevayler on a project for a system that actually needs them already, I will be glad to implement them sooner (or integrate someone else's implementation) and help out on the project design. All other thread activities, including query evaluation, mind you, can already be processed in parallel. So, you can have as many processors as your VM, OS and hardware will support. On to the second problem: "The business system cannot process more than one command at a time.". To overcome that, then, we will establish a simple rule: "The business system cannot take more than a few MICROSECONDS to run any single command." "Oh no! I knew it! This guy is crazy!", some might think, "How can I possibly process 100000 payment records in only a few microseconds?". For 99% of your commands, like changing a person's name, you check for inconsistencies (invalid name, duplicate name, etc), and then you just execute it normally. With your objects in RAM, that will only take a few microseconds anyway. For 1% of your commands (the hairy ones), like processing a batch payment with 100000 payments, lazy evaluation is the key: your system simply doesn't process the command. Instead, it just keeps the command in the "batch payments" list for future evaluation. The command will be processed bit-by-bit whenever a query is evaluated regarding that command. It is important to note that, while the client is building the command, the command is internally preparing its structure to be kept in the system without further processing. Remeber: a prevalent command is much more than an atomic set of operations. It is a full-fledged object and can be responsible for much of the system's business intelligence! The batch payment command, for example, would keep all payment records internally in a HashMap with contract id as the key. Suppose you then query the payment status of any given contract. The contract will see "When was the last time I updated my payment status?". It will then look at the "batch payments" list (there are two or three batch payments a month): "Were there any batch payments since my last update?". If there were, the contract updates itself accordingly (one HashMap lookup per batch). Then, the contract simply returns its payment status. This all takes only a few microsecond too. You could have a query, though, that actually depends on the processing of ALL the payments (e.g. "Total Monthly Revenue"). In this case, the query AND ONLY THIS QUERY will take about 2 seconds* to execute. All the rest of the system continues working at full speed and with full availability. *Today, my company has an ORACLE based billing system running on big solaris boxes that takes 62.5 machine hours to process 100000 payment records. We estimate that doing it all in RAM would take no more than 2 seconds (on my desktop machine, mind you). Are there any more doubts or are all your systems already prevalent? ;) They are not REGISTERED trademarks though. Much like a copyright, you do not have to register it to be entitled to a trademark. Ahh, thank you. The USPTO link for that is:. Do I need to register my trademark? No.. Also, What are the benefits of federal trademark registration? -. "PREVAYLER" and "OPEN-SOURCE PREVALENCE LAYER" are trademarks of Klaus Wuestefeld in the same way that "Linux" is a trademark of Linus Torvalds. Umm, except that Linus owns the registered trademark on Linux, serial number 74560867 at uspto.gov. There was a big hoorah about this some five years ago when someone other than Linus registered the term for himself. Some of the links about the topic are mentioned at . Of course, the suits will always tell you that it is better to register. Most "suits" would say that if you have the $325/10 years and don't want to go through the hassle of defending your mark if your work becomes popular, then it's worth it. I'm using prevayler at a beta system I'm developing, and I think the main problem when you expose this kind of system is that you don't have studies saying it's right or not. Of course a lot of people thought about this before Klaus, but anyone really made a serious study about what are the more commom actions (procedures) perfomed for each category of application?. What is the best application category for prevayler?. Anybody knows what is the REAL consystency of the systems at the market?. Don't you think inconsystency at 99% of the cases are just result of bad code at the top layer? Can't we just make a fault-tolerant system and keep the system working, no matter how bad coder is the guy?. New java implementation (1.3 and 1.4) has news classes that allows high speed messaging pipes between applications. Can you imagine a better use to these pipes?. I agree that XML serialization is a good thing, mainly for debugging purposes and it's atomicity, but how can you compress it? And if you compress, why keep it as XML?. I think that just a better serialization scheme should do the trick, with compression, cryptography, and a hierarquical system that could allow easily XML translation. Externalize methods do the job. Any volunteer?. One easy question. Is it a framework? Is there a planned plugin structure? Everything will be done through interfaces? No register classes or similar approaches?. []s, gandhi. One easy question. Is it a framework? Not at present. Is there a planned plugin structure? No. Can there be a plugin structure in the future? Yes. There is no design trait in Prevayler based on predictions for the future. Prevayler's design, at any point in time, will be the simplest design that we can achieve and that satisfies all CURRENT requirements. The goal is anticlimactic simplicity. Don't worry. Thanks to simplicity, the day you write the first plug-in for Prevayler, we will easily find a way to "plug it in". The day you write your third Prevayler plug-in, there will certainly be a "plug-in structure" in place. That is the beauty of open-source and that is the beauty of simple design. Anyone interested in knowing more about prevalence or in further discussing the subject (but not necessarily having Advogato certification) take a look at the Prevayler Forum. See you there, Klaus. Askemos has a simillar take on persistense. Just not "all in memory" but "allways saved to file" - after each transaction in any of your objects. I generalized the throughput test to write records of various size. For small records the time is dominated by the flush; for large ones, transfer time. I found the knee of this classic curve to be at about 300 Integers (3k bytes) on a Windows platform and 100 Integers on a Linux. All but one machine I tested showed other behaviour that I cannot explain. I've written a short note with graphs and the revised test source code. I designed and implemented a RAM-based, transactional database in Java years ago for Ganymede, and I can attest that keeping everything in memory works splendidly. Add a transaction log for recovery, and you're cooking with gas. At least, that is, for reasonably small datasets. The big open question for Ganymede, and for any memory-resident Java database systems, is how big a cost does Garbage Collection become when you scale up? Using the operating system's native VM subsystem to handle disk paging works fine, but when the Garbage Collector has to sweep through everything periodically in order to clean up garbage, that sweep has presumably to do a good bit of paging to take care of things. Do you have any insight into how serious a problem this is? Ganymede works fantastically well for us at the scale we need it to, but I've always imagined (but not tested) that putting a gigabyte of directory data into it would probably not work so terribly well. I ran a few tests creating huge arrays of Integers and serializing them to stress the limits of some VMs. Everytime we increased the size of the array to a point where the system started paging, we simply had to abort the test after a few hours because we couldn't stand waiting any longer. 55 million was the max we reached without paging, running on an HP-UX machine (Thanks to the guys at HP/PortoAlegre/Brazil). The prevalence hypothesis, though, is that you have enough RAM for all your data so, even when the garbage collector kicks in, your system shouldn't have to page to disk. Even if you have enough RAM, the garbage collector can be a nuisance in many large systems and a real show-stopper for time-sensitive critical systems. I am not an expert but it seems that most VMs use a mix of generational garbage collection and traditional mark-and-sweep. I really would like to see some three-colouring going on anytime soon (if you know of anything about this please post here). A very popular VM's heap size won't even reach 1GB. (It will allow you to set the parameter but will shamelessly ignore it if it is above a certain limit). It seems that VMs like that one are targeted only at feeble client code. I believe that projects using Prevayler will actually raise the bar for VM robustness, heap size and garbage collection!
http://www.advogato.org/article/398.html
crawl-002
refinedweb
7,113
64.61
- Before or after? No, don't answer that. It just had to be said. Admin However, "it's" is shorthand for "it is", while the possessive case is written "its". It's one of the many little quirks of the English language. I would guess (not being one) that this is one of the things a native speaker would learn in elementary school. Admin Not anymore. :( Doom. How apropos. Bwahahahaha Admin Possibly it does have some element of rocket science in it, since a reasonably intelligent person such as you is unaware that "one's" does have an apostrophe in it. Admin Admin ok, thanks a lot. now the cognitive dissonance is going to have me boggle-eyed and slack-jawed all day. Admin Just remember Strong Bad's song! o/~ Oh, if it's supposed to be posessive, then it's just i-t-s/But, if it's supposed to be a contraction then it's i-t-apostrophe-s! Scalawag! o/~ Admin If you didn't know about perlfunc, you could read the perl man page, which directs you to many resources including perlfunc. If you didn't know about the man page, you could read the perl FAQ which directs you to the man page, as well as the perldoc perl page in case you don't have man installed. (The perldoc perl page also directs you to perlfunc.) So yeah, if you're just blindly hammering on the keyboard, you're not going to find the reference material you need, but if you have 12 seconds to look for the information in one of several different ways, you'll find what you need. Or you can be a copy/paste cargo cult programmer, and end up featured on this site. Admin your_prompt> perldoc -f -s HTH Admin ObRuby: mysize = File.new(filename).stat.size I gave up Perl for Ruby. It's worth the performance drop to be able to avoid Perl syntax, and the performance thing will be addressed in 1.9 anyway... Admin First of all, by using >0 instead of >=0, you make this class worthless with streams that are open and still transmitting data -- network streams, for example. Second, you miss entirely the point that this still requires you to copy the bytes into memory and then write them. Java provides four gazillion classes, and they don't have one to abstract this process for the programmer?Those classes work in the opposite direction than you typically want. Normally you're looking to take something from an InputStream, and put it out to an OutputStream. These classes take everything written to the output and provide it to the input. Also, if you use them both in a single thread, you could make the entire universe collapse on itself. Or maybe you'll just deadlock your thread; I don't know, I stopped paying attention. Admin links to Online Documentation, and to FAQs. Perhaps from the FAQ page you could learn about perlfaq2: Obtaining and Learning about Perl and ask Where can I get information on Perl?. It would tell you about, among other things. And if you have a copy of the Llama book or the Camel book from O'Reilly, you'll find some assistance there as well. And if you read 'man perl', it saysand then presents you with an index to a variety of topics, including perlfunc. Now, I realize that there are a variety of valid complaints against Perl, but a) you honestly cannot expect to be able to sit down in front of a programming language and know everything you need to know in five minutes, so you should expect a need to consult with at least minimal documentation, and b) there are a wide variety of ways to stumble upon the proper documentation. I have no respect for programmers who would claim that this is an undue burden upon them. Admin that's called PHP -- and if you want to talk about what sucks, go look at the PHP ref docs for a while. Bottom line, if you're going to write in any language, at least have the decency to scan a language reference to get a feel for the types of functions, operators, etc. Admin Admin Admin Otherwise, it had to be a backup script to be statting that many files at once. Admin It's wide use does not mean that it doesn't suck. It's wide use is because it's been around for long enough, and prior to better languages that have come along since. So, just 'cause it's used on X number of web sites, does NOT mean you should use it for yours. Admin Not true. Perl is a language that supports scripting, true. It does not impose scripting. I have Perl programs that run to the thousands of lines, in which there are fewer than 10 lines in the global namespace [things like use directives], and no single sub that can not be viewed in its entirety in a single screen. It's not the tool, it's the design decisions made by those using the tool. Admin rjnewton wins this thread. The end. Admin What's wrong with a 24 hour perl script run? If it's doing a lot of IO (like reading the whole file and flushing the cache in order to get its size), then going to C won't be much faster. for a 2G file, the piped command could take 10-20 seconds to complete. 500 calls to it = about 75 minutes. Admin This is actually fine, because when "9112cra" is interpreted in a numeric context, the letters will be dropped. It's only a problem if your filename begins with digits or the letter 'e', and since no one ever does that, there can't possibly be any problem. :D Admin Bzzzt. Sorry, try again: If reading from a network socket which does not have any data available, read() will block. Admin You're right. I'm thinking of SocketChannel's read, not InputStream's. Admin The secret? I'm smart enough to know that I don't know everything, so I, uh, read the fucking manual instead of jumping in and assuming I would know how to do everything without having to learn. I think that gives me the right to sneer. Admin This is supposed to be more intuitive? Do you really believe "stat" is more transparent to the average newbie than "-s" is? That's like giving up herpes for rabies. I tried Ruby once, and liked the syntax even less than Perl's. Pretending that everything should be an object is stupid - numbers are abstract concepts, not objects. And treating things like string literals as objects is just plain ugly. Admin I've got a password cracker that will take just shy of 14 months to exhaust all reasonable passwords for older *nix systems. Would you consider a 75-minute speedup to be worthwhile? Admin No, you'll have to read a real manual - especially for perl. If you try to google for it, you'll end up with answers from a bunch of wannabe's saying "I know the answer to this problem, but it's way below my skills to give you the answer." or "I found this problem solved after 2 sleepless weeks, and I'm not going to give you the answer such quick" ... I call such boardmembers of any programming board or even newsgroup the RTFM BASTARDS ;) ... They'll never give you any helpful answer. BTW. I'm always wondering about the energy such BASTARDS invest to write lengthy articles why not to give the answer ... Admin Lurk moar. Admin Well, as mentioned before, with Perl and File::stat you could write $mysize = stat($filename)->size and that looks quote similar to your code. OTOH, in Ruby you could also do it like this: mysize = test(?s, filename) Admin This is proof that programmers should be shot on sight, and the ones who survive should be promoted to super-geekdom. Too many "programmers" are just imbeciles who read the first chapter of "Sams Teach yourself Minesweeper in 24 hours" and got their certificate. Any half-wit with any experience using ANY language would look for a file size function as one of the first steps of learning a new language. Frig even MS Batch files can fetch the file size, how ghetto is that ? Admin Some of Perl's shortcut test operators evolved from shell test operators and the test command. And, if you prefer a more verbose way, someone has already mentioned that you can use the stat function. What the hell is wrong with being concise, anyway? It's not my problem that you can't read it and can't take the time to learn. Admin Actually, it won't work for file sizes over 8 digits. Perl will happily turn "9112cra" into the number 9112 as soon as you try to do a numeric operation on it. Don't believe me, try this: or There are also several versions of wc out there. The one included with Solaris 10 puts the number in an 8-character field padded with spaces (if it <= 8 digits). Thus for any file with a size <= 8 digits work perfectly with this particular wc. Admin perl inexperience is beside the point. the code is bad in any language. a coder's inner "ridiculously inefficient" alarms should go off when they see this kind of code. O(n^2) alarms. alarms that tell you that this only ok if you do it once in a while. even if the coder was using bash, he'd have to sense the evil caused by this piece of code. somewhere deep in his gut, some voice should be telling him, "there has got to be a better way." The multiplication of the code indicates that the coder had no idea what the runtime cost of this code was. or perhaps didn't care. Admin [snip] diaphanein: If that's the only set you consider, then yes. There are (other) scripting languages that don't suck, that aren't cryptic, that don't inherently lend themselves unreadable, unmaintainable code. Sure, but do they have the advantages perl has? -regular expressions -C-like syntax for easy adoption -large user base -large installed base on random machines The only one that comes close is Python, which isn't any more maintainable or readable than Perl. I've been programming in Perl for close to 10 years and I have yet to see code that I can't read except for an obfuscation contest. [/snip] I agree. If you take the time to LEARN how to use a language, it is not "mysterious" or "non-intuitave" to use. It is only difficult to read or maintain if you are a "one language wonder" and the language you know is not the one in use... Admin That, and CPAN. Admin PERL... The problem I have with perl is that its conciseness is confusing. If I needed to edit perl on a daily or even weekly basis, I might look into 'just finding the documentation' and then reading it, rereading it, trying it, failing, and trying again to understand what it's supposed to be doing. So, for me, it's not a problem of finding how to write something (I can do that!) but a problem of trying to decipher what others' 'simply concise' code actually means. So: writing in perl...easy reading perl...difficult maintaining perl...can be really difficult or really easy! Oh, on an aside: I hate Python. Admin I confess to using that. Not because I think that it's the best way,but because it's quicker to type than using perl's built-in. However, I wouldn't use it on a production system. Admin Admin PHP sucks for some reasons but its popularity is not hard to understand ... a PHP application is easy to deploy (easier than with Perl, Python, Java, whatever), it is cheap to deploy because of PHP's nature (compared to Java and .NET which are quite expensive), the PHP interpreter has a reasonable speed, it can be easily extended by C modules ... thus it can connect to a wide variety of services, there are countless of open-source applications and framerworks already built for it ... and put simply ... It Gets The Job Done in most cases. PHP is quite a mature, stable and robust platform for web apps ... and if you can't see that from your ivory tower that doesn't mean the rest of us are blind too. Admin Admittedly, I did have to do a bit of digging to locate strftime() the first time I wanted it, but I wouldn't consider it that much slower to type... I guess having to add the use() to your preamble makes it forgivable. ;] But not, as you say, on production systems. Admin I'm sure you are a joy to work with. We can only hope that whoever inherits your code knows about thedailywtf. Admin Hold your horses man, "man perl" will refer the reader to "man perlfunc". Admin Indeed, I lose. "One's" isn't a personal possessive, it's an indefinite possessive. But it must be somewhere between middle school & rocket science. Admin or even better: $filesize = filesize($file); Admin I would say he was ignorant of hashes, but he used them at the start of every script to grab the CGI parameters. He also used a whopping 4 subroutines in the 2 dozen scripts I've rebuilt. One script included an entire cut & paste of the tax calc code 4 times. Admin I really liked this thread, nice how folks come up with an example in there favorite language. From experience i can tell: if a job falls in all other environments, it can be done in perl. When switching between languages, switching to perl takes the most adjustment of one's mind. one's ... every board has it's Captain Pedantic. The end. Admin Admin Yes, that stuff about being faster is clearly bollocks. :P Admin Hear, hear!
https://thedailywtf.com/articles/comments/The_UNIX_Philosophy/3
CC-MAIN-2018-51
refinedweb
2,375
72.66
History | View | Annotate | Download (33.9 KB) //---------------------------------------------------------------------- // File: ANN.h // Programmer: Sunil Arya and David Mount // Last modified: 05/03/05 (Release 1.1) // Description: Basic include file for approximate nearest // neighbor searching. // Copyright (c) 1997-2005 University of Maryland and Sunil Arya and // // This software and related documentation is part of the Approximate // Nearest Neighbor Library (ANN). This software is provided under // the provisions of the Lesser GNU Public License (LGPL). See the // file ../ReadMe.txt for further information. // The University of Maryland (U.M.) and the authors make no // representations about the suitability or fitness of this software for // any purpose. It is provided "as is" without express or implied // warranty. // History: // Revision 0.1 03/04/98 // Initial release // Revision 1.0 04/01/05 // Added copyright and revision information // Added ANNcoordPrec for coordinate precision. // Added methods theDim, nPoints, maxPoints, thePoints to ANNpointSet. // Cleaned up C++ structure for modern compilers // Revision 1.1 05/03/05 // Added fixed-radius k-NN searching // ANN - approximate nearest neighbor searching // ANN is a library for approximate nearest neighbor searching, // based on the use of standard and priority search in kd-trees // and balanced box-decomposition (bbd) trees. Here are some // references to the main algorithmic techniques used here: // // kd-trees: // Friedman, Bentley, and Finkel, ``An algorithm for finding // best matches in logarithmic expected time,'' ACM // Transactions on Mathematical Software, 3(3):209-226, 1977. // Priority search in kd-trees: // Arya and Mount, ``Algorithms for fast vector quantization,'' // Proc. of DCC '93: Data Compression Conference, eds. J. A. // Storer and M. Cohn, IEEE Press, 1993, 381-390. // Approximate nearest neighbor search and bbd-trees: // Arya, Mount, Netanyahu, Silverman, and Wu, ``An optimal // algorithm for approximate nearest neighbor searching,'' // 5th Ann. ACM-SIAM Symposium on Discrete Algorithms, // 1994, 573-582. #ifndef ANN_H #define ANN_H // basic includes #include <cstdlib> // exit(int) #include <cmath> // math includes #include <iostream> // I/O streams // Limits // There are a number of places where we use the maximum double value as // default initializers (and others may be used, depending on the // data/distance representation). These can usually be found in limits.h // (as LONG_MAX, INT_MAX) or in float.h (as DBL_MAX, FLT_MAX). // Not all systems have these files. If you are using such a system, // you should set the preprocessor symbol ANN_NO_LIMITS_H when // compiling, and modify the statements below to generate the // appropriate value. For practical purposes, this does not need to be // the maximum double value. It is sufficient that it be at least as // large than the maximum squared distance between between any two // points. #ifdef ANN_NO_LIMITS_H // limits.h unavailable #include <cvalues> // replacement for limits.h const double ANN_DBL_MAX = MAXDOUBLE; // insert maximum double #include <climits> #include <cfloat> const double ANN_DBL_MAX = DBL_MAX; #define ANNversion "1.1.1" // ANN version and information #define ANNversionCmt "" #define ANNcopyright "David M. Mount and Sunil Arya" #define ANNlatestRev "Aug 4, 2006" // ANNbool // This is a simple boolean type. Although ANSI C++ is supposed // to support the type bool, some compilers do not have it. enum ANNbool {ANNfalse = 0, ANNtrue = 1}; // ANN boolean type (non ANSI C++) // ANNcoord, ANNdist // ANNcoord and ANNdist are the types used for representing // point coordinates and distances. They can be modified by the // user, with some care. It is assumed that they are both numeric // types, and that ANNdist is generally of an equal or higher type // from ANNcoord. A variable of type ANNdist should be large // enough to store the sum of squared components of a variable // of type ANNcoord for the number of dimensions needed in the // application. For example, the following combinations are // legal: // ANNcoord ANNdist // --------- ------------------------------- // short short, int, long, float, double // int int, long, float, double // long long, float, double // float float, double // double double // It is the user's responsibility to make sure that overflow does // not occur in distance calculation. typedef double ANNcoord; // coordinate data type typedef double ANNdist; // distance data type // ANNidx // ANNidx is a point index. When the data structure is built, the // points are given as an array. Nearest neighbor results are // returned as an integer index into this array. To make it // clearer when this is happening, we define the integer type // ANNidx. Indexing starts from 0. // // For fixed-radius near neighbor searching, it is possible that // there are not k nearest neighbors within the search radius. To // indicate this, the algorithm returns ANN_NULL_IDX as its result. // It should be distinguishable from any valid array index. typedef int ANNidx; // point index const ANNidx ANN_NULL_IDX = -1; // a NULL point index // Infinite distance: // The code assumes that there is an "infinite distance" which it // uses to initialize distances before performing nearest neighbor // searches. It should be as larger or larger than any legitimate // nearest neighbor distance. // On most systems, these should be found in the standard include // file <limits.h> or possibly <float.h>. If you do not have these // file, some suggested values are listed below, assuming 64-bit // long, 32-bit int and 16-bit short. // ANNdist ANN_DIST_INF Values (see <limits.h> or <float.h>) // ------- ------------ ------------------------------------ // double DBL_MAX 1.79769313486231570e+308 // float FLT_MAX 3.40282346638528860e+38 // long LONG_MAX 0x7fffffffffffffff // int INT_MAX 0x7fffffff // short SHRT_MAX 0x7fff const ANNdist ANN_DIST_INF = ANN_DBL_MAX; // Significant digits for tree dumps: // When floating point coordinates are used, the routine that dumps // a tree needs to know roughly how many significant digits there // are in a ANNcoord, so it can output points to full precision. // This is defined to be ANNcoordPrec. On most systems these // values can be found in the standard include files <limits.h> or // <float.h>. For integer types, the value is essentially ignored. // ANNcoord ANNcoordPrec Values (see <limits.h> or <float.h>) // -------- ------------ ------------------------------------ // double DBL_DIG 15 // float FLT_DIG 6 // long doesn't matter 19 // int doesn't matter 10 // short doesn't matter 5 #ifdef DBL_DIG // number of sig. bits in ANNcoord const int ANNcoordPrec = DBL_DIG; const int ANNcoordPrec = 15; // default precision // Self match? // In some applications, the nearest neighbor of a point is not // allowed to be the point itself. This occurs, for example, when // computing all nearest neighbors in a set. By setting the // parameter ANN_ALLOW_SELF_MATCH to ANNfalse, the nearest neighbor // is the closest point whose distance from the query point is // strictly positive. const ANNbool ANN_ALLOW_SELF_MATCH = ANNtrue; // Norms and metrics: // ANN supports any Minkowski norm for defining distance. In // particular, for any p >= 1, the L_p Minkowski norm defines the // length of a d-vector (v0, v1, ..., v(d-1)) to be // (|v0|^p + |v1|^p + ... + |v(d-1)|^p)^(1/p), // (where ^ denotes exponentiation, and |.| denotes absolute // value). The distance between two points is defined to be the // norm of the vector joining them. Some common distance metrics // include // Euclidean metric p = 2 // Manhattan metric p = 1 // Max metric p = infinity // In the case of the max metric, the norm is computed by taking // the maxima of the absolute values of the components. ANN is // highly "coordinate-based" and does not support general distances // functions (e.g. those obeying just the triangle inequality). It // also does not support distance functions based on // inner-products. // For the purpose of computing nearest neighbors, it is not // necessary to compute the final power (1/p). Thus the only // component that is used by the program is |v(i)|^p. // ANN parameterizes the distance computation through the following // macros. (Macros are used rather than procedures for // efficiency.) Recall that the distance between two points is // given by the length of the vector joining them, and the length // or norm of a vector v is given by formula: // |v| = ROOT(POW(v0) # POW(v1) # ... # POW(v(d-1))) // where ROOT, POW are unary functions and # is an associative and // commutative binary operator mapping the following types: // ** POW: ANNcoord --> ANNdist // ** #: ANNdist x ANNdist --> ANNdist // ** ROOT: ANNdist (>0) --> double // For early termination in distance calculation (partial distance // calculation) we assume that POW and # together are monotonically // increasing on sequences of arguments, meaning that for all // v0..vk and y: // POW(v0) #...# POW(vk) <= (POW(v0) #...# POW(vk)) # POW(y). // Incremental Distance Calculation: // The program uses an optimized method of computing distances for // kd-trees and bd-trees, called incremental distance calculation. // It is used when distances are to be updated when only a single // coordinate of a point has been changed. In order to use this, // we assume that there is an incremental update function DIFF(x,y) // for #, such that if: // s = x0 # ... # xi # ... # xk // then if s' is equal to s but with xi replaced by y, that is, // s' = x0 # ... # y # ... # xk // then the length of s' can be computed by: // |s'| = |s| # DIFF(xi,y). // Thus, if # is + then DIFF(xi,y) is (yi-x). For the L_infinity // norm we make use of the fact that in the program this function // is only invoked when y > xi, and hence DIFF(xi,y)=y. // Finally, for approximate nearest neighbor queries we assume // that POW and ROOT are related such that // v*ROOT(x) = ROOT(POW(v)*x) // Here are the values for the various Minkowski norms: // L_p: p even: p odd: // ------------------------- ------------------------ // POW(v) = v^p POW(v) = |v|^p // ROOT(x) = x^(1/p) ROOT(x) = x^(1/p) // # = + # = + // DIFF(x,y) = y - x DIFF(x,y) = y - x // L_inf: // POW(v) = |v| // ROOT(x) = x // # = max // DIFF(x,y) = y // By default the Euclidean norm is assumed. To change the norm, // uncomment the appropriate set of macros below. // Use the following for the Euclidean norm #define ANN_POW(v) ((v)*(v)) #define ANN_ROOT(x) sqrt(x) #define ANN_SUM(x,y) ((x) + (y)) #define ANN_DIFF(x,y) ((y) - (x)) // Use the following for the L_1 (Manhattan) norm // #define ANN_POW(v) fabs(v) // #define ANN_ROOT(x) (x) // #define ANN_SUM(x,y) ((x) + (y)) // #define ANN_DIFF(x,y) ((y) - (x)) // Use the following for a general L_p norm // #define ANN_POW(v) pow(fabs(v),p) // #define ANN_ROOT(x) pow(fabs(x),1/p) // Use the following for the L_infinity (Max) norm // #define ANN_SUM(x,y) ((x) > (y) ? (x) : (y)) // #define ANN_DIFF(x,y) (y) // Array types // The following array types are of basic interest. A point is // just a dimensionless array of coordinates, a point array is a // dimensionless array of points. A distance array is a // dimensionless array of distances and an index array is a // dimensionless array of point indices. The latter two are used // when returning the results of k-nearest neighbor queries. typedef ANNcoord* ANNpoint; // a point typedef ANNpoint* ANNpointArray; // an array of points typedef ANNdist* ANNdistArray; // an array of distances typedef ANNidx* ANNidxArray; // an array of point indices // Basic point and array utilities: // The following procedures are useful supplements to ANN's nearest // neighbor capabilities. // annDist(): // Computes the (squared) distance between a pair of points. // Note that this routine is not used internally by ANN for // computing distance calculations. For reasons of efficiency // this is done using incremental distance calculation. Thus, // this routine cannot be modified as a method of changing the // metric. // Because points (somewhat like strings in C) are stored as // pointers. Consequently, creating and destroying copies of // points may require storage allocation. These procedures do // this. // annAllocPt() and annDeallocPt(): // Allocate a deallocate storage for a single point, and // return a pointer to it. The argument to AllocPt() is // used to initialize all components. // annAllocPts() and annDeallocPts(): // Allocate and deallocate an array of points as well a // place to store their coordinates, and initializes the // points to point to their respective coordinates. It // allocates point storage in a contiguous block large // enough to store all the points. It performs no // initialization. // annCopyPt(): // Creates a copy of a given point, allocating space for // the new point. It returns a pointer to the newly // allocated copy. DLL_API ANNdist annDist( int dim, // dimension of space ANNpoint p, // points ANNpoint q); DLL_API ANNpoint annAllocPt( int dim, // dimension ANNcoord c = 0); // coordinate value (all equal) DLL_API ANNpointArray annAllocPts( int n, // number of points int dim); // dimension DLL_API void annDeallocPt( ANNpoint &p); // deallocate 1 point DLL_API void annDeallocPts( ANNpointArray &pa); // point array DLL_API ANNpoint annCopyPt( ANNpoint source); // point to copy //Overall structure: ANN supports a number of different data structures //for approximate and exact nearest neighbor searching. These are: // ANNbruteForce A simple brute-force search structure. // ANNkd_tree A kd-tree tree search structure. ANNbd_tree // A bd-tree tree search structure (a kd-tree with shrink // capabilities). // At a minimum, each of these data structures support k-nearest // neighbor queries. The nearest neighbor query, annkSearch, // returns an integer identifier and the distance to the nearest // neighbor(s) and annRangeSearch returns the nearest points that // lie within a given query ball. // Each structure is built by invoking the appropriate constructor // and passing it (at a minimum) the array of points, the total // number of points and the dimension of the space. Each structure // is also assumed to support a destructor and member functions // that return basic information about the point set. // Note that the array of points is not copied by the data // structure (for reasons of space efficiency), and it is assumed // to be constant throughout the lifetime of the search structure. // The search algorithm, annkSearch, is given the query point (q), // and the desired number of nearest neighbors to report (k), and // the error bound (eps) (whose default value is 0, implying exact // nearest neighbors). It returns two arrays which are assumed to // contain at least k elements: one (nn_idx) contains the indices // (within the point array) of the nearest neighbors and the other // (dd) contains the squared distances to these nearest neighbors. // The search algorithm, annkFRSearch, is a fixed-radius kNN // search. In addition to a query point, it is given a (squared) // radius bound. (This is done for consistency, because the search // returns distances as squared quantities.) It does two things. // First, it computes the k nearest neighbors within the radius // bound, and second, it returns the total number of points lying // within the radius bound. It is permitted to set k = 0, in which // case it effectively answers a range counting query. If the // error bound epsilon is positive, then the search is approximate // in the sense that it is free to ignore any point that lies // outside a ball of radius r/(1+epsilon), where r is the given // (unsquared) radius bound. // The generic object from which all the search structures are // dervied is given below. It is a virtual object, and is useless // by itself. class DLL_API ANNpointSet { public: virtual ~ANNpointSet() {} // virtual distructor virtual void annkSearch( // approx k near neighbor search ANNpoint q, // query point int k, // number of near neighbors to return ANNidxArray nn_idx, // nearest neighbor array (modified) ANNdistArray dd, // dist to near neighbors (modified) double eps=0.0 // error bound ) = 0; // pure virtual (defined elsewhere) virtual int annkFRSearch( // approx fixed-radius kNN search ANNdist sqRad, // squared radius int k = 0, // number of near neighbors to return ANNidxArray nn_idx = NULL, // nearest neighbor array (modified) ANNdistArray dd = NULL, // dist to near neighbors (modified) virtual int theDim() = 0; // return dimension of space virtual int nPoints() = 0; // return number of points // return pointer to points virtual ANNpointArray thePoints() = 0; }; // Brute-force nearest neighbor search: // The brute-force search structure is very simple but inefficient. // It has been provided primarily for the sake of comparison with // and validation of the more complex search structures. // Query processing is the same as described above, but the value // of epsilon is ignored, since all distance calculations are // performed exactly. // WARNING: This data structure is very slow, and should not be // used unless the number of points is very small. // Internal information: // --------------------- // This data structure bascially consists of the array of points // (each a pointer to an array of coordinates). The search is // performed by a simple linear scan of all the points. class DLL_API ANNbruteForce: public ANNpointSet { int dim; // dimension int n_pts; // number of points ANNpointArray pts; // point array ANNbruteForce( // constructor from point array ANNpointArray pa, // point array int n, // number of points int dd); // dimension ~ANNbruteForce(); // destructor void annkSearch( // approx k near neighbor search double eps=0.0); // error bound int annkFRSearch( // approx fixed-radius kNN search int theDim() // return dimension of space { return dim; } int nPoints() // return number of points { return n_pts; } ANNpointArray thePoints() // return pointer to points { return pts; } // kd- and bd-tree splitting and shrinking rules // kd-trees supports a collection of different splitting rules. // In addition to the standard kd-tree splitting rule proposed // by Friedman, Bentley, and Finkel, we have introduced a // number of other splitting rules, which seem to perform // as well or better (for the distributions we have tested). // The splitting methods given below allow the user to tailor // the data structure to the particular data set. They are // are described in greater details in the kd_split.cc source // file. The method ANN_KD_SUGGEST is the method chosen (rather // subjectively) by the implementors as the one giving the // fastest performance, and is the default splitting method. // As with splitting rules, there are a number of different // shrinking rules. The shrinking rule ANN_BD_NONE does no // shrinking (and hence produces a kd-tree tree). The rule // ANN_BD_SUGGEST uses the implementors favorite rule. enum ANNsplitRule { ANN_KD_STD = 0, // the optimized kd-splitting rule ANN_KD_MIDPT = 1, // midpoint split ANN_KD_FAIR = 2, // fair split ANN_KD_SL_MIDPT = 3, // sliding midpoint splitting method ANN_KD_SL_FAIR = 4, // sliding fair split method ANN_KD_SUGGEST = 5}; // the authors' suggestion for best const int ANN_N_SPLIT_RULES = 6; // number of split rules enum ANNshrinkRule { ANN_BD_NONE = 0, // no shrinking at all (just kd-tree) ANN_BD_SIMPLE = 1, // simple splitting ANN_BD_CENTROID = 2, // centroid splitting ANN_BD_SUGGEST = 3}; // the authors' suggested choice const int ANN_N_SHRINK_RULES = 4; // number of shrink rules // kd-tree: // The main search data structure supported by ANN is a kd-tree. // The main constructor is given a set of points and a choice of // splitting method to use in building the tree. // Construction: // ------------- // The constructor is given the point array, number of points, // dimension, bucket size (default = 1), and the splitting rule // (default = ANN_KD_SUGGEST). The point array is not copied, and // is assumed to be kept constant throughout the lifetime of the // search structure. There is also a "load" constructor that // builds a tree from a file description that was created by the // Dump operation. // Search: // ------- // There are two search methods: // Standard search (annkSearch()): // Searches nodes in tree-traversal order, always visiting // the closer child first. // Priority search (annkPriSearch()): // Searches nodes in order of increasing distance of the // associated cell from the query point. For many // distributions the standard search seems to work just // fine, but priority search is safer for worst-case // performance. // Printing: // --------- // There are two methods provided for printing the tree. Print() // is used to produce a "human-readable" display of the tree, with // indenation, which is handy for debugging. Dump() produces a // format that is suitable reading by another program. There is a // "load" constructor, which constructs a tree which is assumed to // have been saved by the Dump() procedure. // Performance and Structure Statistics: // ------------------------------------- // The procedure getStats() collects statistics information on the // tree (its size, height, etc.) See ANNperf.h for information on // the stats structure it returns. // The data structure consists of three major chunks of storage. // The first (implicit) storage are the points themselves (pts), // which have been provided by the users as an argument to the // constructor, or are allocated dynamically if the tree is built // using the load constructor). These should not be changed during // the lifetime of the search structure. It is the user's // responsibility to delete these after the tree is destroyed. // The second is the tree itself (which is dynamically allocated in // the constructor) and is given as a pointer to its root node // (root). These nodes are automatically deallocated when the tree // is deleted. See the file src/kd_tree.h for further information // on the structure of the tree nodes. // Each leaf of the tree does not contain a pointer directly to a // point, but rather contains a pointer to a "bucket", which is an // array consisting of point indices. The third major chunk of // storage is an array (pidx), which is a large array in which all // these bucket subarrays reside. (The reason for storing them // separately is the buckets are typically small, but of varying // sizes. This was done to avoid fragmentation.) This array is // also deallocated when the tree is deleted. // In addition to this, the tree consists of a number of other // pieces of information which are used in searching and for // subsequent tree operations. These consist of the following: // dim Dimension of space // n_pts Number of points currently in the tree // n_max Maximum number of points that are allowed // in the tree // bkt_size Maximum bucket size (no. of points per leaf) // bnd_box_lo Bounding box low point // bnd_box_hi Bounding box high point // splitRule Splitting method used // Some types and objects used by kd-tree functions // See src/kd_tree.h and src/kd_tree.cpp for definitions class ANNkdStats; // stats on kd-tree class ANNkd_node; // generic node in a kd-tree typedef ANNkd_node* ANNkd_ptr; // pointer to a kd-tree node class DLL_API ANNkd_tree: public ANNpointSet { protected: int dim; // dimension of space int n_pts; // number of points in tree int bkt_size; // bucket size ANNpointArray pts; // the points ANNidxArray pidx; // point indices (to pts array) ANNkd_ptr root; // root of kd-tree ANNpoint bnd_box_lo; // bounding box low point ANNpoint bnd_box_hi; // bounding box high point void SkeletonTree( // construct skeleton tree int dd, // dimension int bs, // bucket size ANNpointArray pa = NULL, // point array (optional) ANNidxArray pi = NULL); // point indices (optional) ANNkd_tree( // build skeleton tree int n = 0, // number of points int dd = 0, // dimension int bs = 1); // bucket size ANNkd_tree( // build from point array int bs = 1, // bucket size ANNsplitRule split = ANN_KD_SUGGEST); // splitting method ANNkd_tree( // build from dump file std::istream& in); // input stream for dump file ~ANNkd_tree(); // tree destructor void annkPriSearch( // priority k near neighbor search ANNpoint q, // the query point ANNdist sqRad, // squared radius of query ball int k, // number of neighbors to return virtual void Print( // print the tree (for debugging) ANNbool with_pts, // print points as well? std::ostream& out); // output stream virtual void Dump( // dump entire tree virtual void getStats( // compute tree statistics ANNkdStats& st); // the statistics (modified) }; // Box decomposition tree (bd-tree) // The bd-tree is inherited from a kd-tree. The main difference // in the bd-tree and the kd-tree is a new type of internal node // called a shrinking node (in the kd-tree there is only one type // of internal node, a splitting node). The shrinking node // makes it possible to generate balanced trees in which the // cells have bounded aspect ratio, by allowing the decomposition // to zoom in on regions of dense point concentration. Although // this is a nice idea in theory, few point distributions are so // densely clustered that this is really needed. class DLL_API ANNbd_tree: public ANNkd_tree { ANNbd_tree( // build skeleton tree int bs = 1) // bucket size : ANNkd_tree(n, dd, bs) {} // build base kd-tree ANNbd_tree( // build from point array ANNsplitRule split = ANN_KD_SUGGEST, // splitting rule ANNshrinkRule shrink = ANN_BD_SUGGEST); // shrinking rule ANNbd_tree( // build from dump file // Other functions // annMaxPtsVisit Sets a limit on the maximum number of points // to visit in the search. // annClose Can be called when all use of ANN is finished. // It clears up a minor memory leak. DLL_API void annMaxPtsVisit( // max. pts to visit in search int maxPts); // the limit DLL_API void annClose(); // called to end use of ANN
http://roboticsclub.org/redmine/projects/quadrotor/repository/revisions/9240aaa3a4a7b485cc52b9bc21036ad83821ceee/entry/rgbdslam/gicp/ann_1.1.1/include/ANN/ANN.h
CC-MAIN-2013-48
refinedweb
3,872
52.49
Hello, i have to create a java program that calculates a polynomial, kinda. the key question i have is i dont understand what this is asking me right here, and if i am understanding it right, why is it not working? this is what it is asking me Create a constructor that takes three parameters of type MyDouble representing coefficients a, b, and c (in that order) for the Polynomial being constructed. The data members a, b, and c are to be initialized with these values resulting in the polynomial: "a*x^2 + b*x + c". this is what i have understood so far, though it gives me an error public class Polynomial { private final MyDouble a; private final MyDouble b; private final MyDouble c; public Polynomial (double tempA, double tempB, double tempC){ } } i realize there is nothing inside the constructor, but im not exactly sure what to put inside. and without putting anything inside, i get an error that says "The blank final field c may not have been initialized" Thank You for your help!
https://www.daniweb.com/programming/software-development/threads/270236/understanding-constructor-request
CC-MAIN-2018-05
refinedweb
176
50.7
eichin at metacarta.com wrote: > > (as for the other part, Python's XML story is wierd - when PyXML is > > installed it drops some new things into the xml namespace, so having > > "import xml" work doesn't actually tell you anything useful.) Ah, thanks for the clarification. Bob Ippolito <bob at redivi.com> wrote: > import _xmlplus is the correct way to detect the presence of PyXML. I tried this, which didn't work on my system, so I guess PyXML is not part of the Panther Python distribution. I don't really want to fuss with distributing this to all our Macs if I can avoid it. Bob Ippolito <bob at redivi.com> wrote: > If this doesn't work with Python 2.4's plistlib, then the output of > system profiler is not correct. I'm at least 90% sure that Python > 2.4's plistlib correctly reads and writes all valid plists. Well, you may be right. I don't have an XML validator handy at the moment, but I tried your updated, bug-fixed plistlib on the full output of system_profiler -xml. It failed, but I didn't get the same traceback as eichin. Also, plistlib worked beautifully on partial output of system_profiler, such as system_profiler -SPNetworkDataType -xml. Here's what I did: At the bash prompt, ran: system_profiler -xml > /Users/ballen/system_profiler_output.plist In Python: import pyDesktopConfig.plistlibTest as plistlib plistDict = plistlib.readPlist('/Users/ballen/system_profiler_output.plist') ....after which I received the following error: oms-ballen:/OMS/IT_Tools/scripts/managedScript/pythonTools ballen$ python tester2.py Traceback (most recent call last): File "tester2.py", line 60, in ? plistDict = plistlib.readPlist('/Users/ballen/spoutput.txt') File "/OMS/IT_Tools/scripts/managedScript/pythonTools/pyDesktopConfig/plistlibTest.py", line 79, in readPlist rootObject = p.parse(pathOrFile) File "/OMS/IT_Tools/scripts/managedScript/pythonTools/pyDesktopConfig/plistlibTest.py", line 383, in parse parser.ParseFile(fileobj) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 13031, column 15 Next, I tried: In Bash: system_profiler SPNetworkDataType -xml > spNetwork.plist In Python: plistDict = plistlib.readPlist('/Users/ballen/spNetwork.plist') print plistDict [{'_timeStamp': Date('2004-11-12T35:16:00Z'), '_detailLevel': -1, '_items': [{'domain': 'omsdal.com', 'dns_servers': ['10.100.1.48', '10.100.1.35'], 'router_address': '10.100.32.1', 'broadcast_address': ['10.100.32.255'], 'type': 'Ethernet', 'ethernet_address': '00:0a:93:9d:76:f8', '_name': 'Built-in Ethernet', 'subnet_mask': ['255.255.255.0'], 'interface': 'en0', 'ip_address': ['10.100.32.81']}, {'interface': 'modem', 'type': 'PPP (PPPSerial)', '_name': 'Internal Modem'}, {'interface': 'en1', 'type': 'AirPort', 'ethernet_address': '00:31:62:0b:47:34', '_name': 'AirPort'}], '_dataType': 'SPNetworkDataType', '_properties': {'domain': {'_order': '80'}, 'dns_servers': {'_order': '70'}, 'router_address': {'_order': '60'}, 'broadcast_address': {'_order': '50'}, 'type': {'_order': '20', '_isColumn': 'YES', '_width': '100'}, 'ethernet_address': {'_order': '90'}, '_name': {'_order': '0', '_isColumn': 'YES', '_width': '100'}, 'subnet_mask': {'_order': '40'}, 'interface': {'_order': '10', '_isColumn': 'YES', '_width': '100'}, 'destination_address': {'_order': '35'}, 'ip_address': {'_order': '30', '_isColumn': 'YES', '_width': '100'}}}] Very nice!
https://mail.python.org/pipermail/pythonmac-sig/2004-November/012070.html
CC-MAIN-2016-30
refinedweb
474
52.26
1 1 Across 4. Given that distance rate time, what is the distance from Oklahoma City to Boston if it takes 28 hr of driving 60 mph? 5. What is the sum of the measures of the angles of a triangle? 6. What number is twice 6249? 8. If the measure of an angle is 48, what is the measure of its supplement? 10. If a rectangle has an area of 8670 ft2 and a width of 85 ft, what is its length? Down 1. What is the next consecutive 2. If the measure of an angle is complement? 3. What is 25% of 25,644? 5. What is the next consecutive 7. What is 10% of 87,420? 9. What is the next consecutive even integer after 4308? 2, what is the measure of its 8 9 Section 1.1 Concepts 1. 2. 3. 4. 5. Set of Real Numbers Inequalities Interval Notation Union and Intersection of Sets Translations Involving Inequalities the set of all x such that the set of all x such that. Each point on the number line corresponds to exactly one real number, and for this reason, the line is called the real number line (Figure 1-1). 5 4 3 2 1 0 1 2 3 4 Negative numbers Positive numbers Figure 1-1 5 Several sets of numbers are subsets (or part) of the set of real numbers. These are The The The The The set set set set set of of of of of natural numbers whole numbers integers rational numbers irrational numbers The set of rational numbers is 5 q 0 p and q are integers and q does not equal zero}. p Example 1 Show that each number is a rational number by finding two integers whose ratio equals the given number. a. 4 7 b. 8 c. 0.6 d. 0.87 Solution: a. is a rational number because it can be expressed as the ratio of the integers 4 and 7. 4 7 b. 8 is a rational number because it can be expressed as the ratio of the integers 8 and 1 1 8 8 1 2 . In this example we see that an integer is also a rational number. c. 0.6 represents the repeating decimal 0.6666666 and can be expressed as the ratio of 2 and 3 1 0.6 2 3 2 . In this example we see that a repeating decimal is a rational number. 87 d. 0.87 is the ratio of 87 and 100 1 0.87 100 2 . In this example we see that a terminating decimal is a rational number. TIP: Any rational number can be represented by a terminating decimal or by a repeating decimal. Skill Practice Show that the numbers are rational by writing them as a ratio of integers. 2. 0 3. 0.3 4. 0.45 1. 98 Some real numbers such as the number p (pi) cannot be represented by the ratio of two integers. In decimal form, an irrational number is a nonterminating, nonrepeating decimal. The value of p, for example, can be approximated as p 3.1415926535897932. However, the decimal digits continue indefinitely with no pattern. Other examples of irrational numbers are the square roots of nonperfect squares, such as 13 and 111. The set of irrational numbers is {x 0 x is a real number that is not rational}. Note: An irrational number cannot be written as a terminating decimal or as a repeating decimal. The set of real numbers consists of both the rational numbers and the irrational numbers. The relationships among the sets of numbers discussed thus far are illustrated in Figure 1-2. Real numbers Rational numbers 2 7 0.25 0.3 Irrational numbers 2 17 Figure 1-2 Example 2 Check the set(s) to which each number belongs. The numbers may belong to more than one set. Whole Numbers Integers Rational Numbers Irrational Numbers Real Numbers Solution: Natural Numbers 6 1 23 2 7 3 2.35 Whole Numbers Rational Numbers Irrational Numbers Real Numbers Integers Skill Practice 2. Inequalities The relative size of two numbers can be compared by using the real number line. We say that a is less than b (written mathematically as a b) if a lies to the left of b on the number line. a ab b We say that a is greater than b (written mathematically as a b) if a lies to the right of b on the number line. b ab a Table 1-1 summarizes the relational operators that compare two real numbers a and b. Table 1-1 Mathematical Expression a 6 b a 7 b ab ab ab a b ab Translation a is less than b a is greater than b a is less than or equal to b a is greater than or equal to b a is equal to b a is not equal to b a is approximately equal to b Other Meanings b exceeds a b is greater than a a exceeds b b is less than a a is at most b a is no more than b a is no less than b a is at least b The symbols , , , , and are called inequality signs, and the expressions a 6 b, a 7 b, a b, a b, and a b are called inequalities. Example 3 b. a. 2 7 5 4 7 6 5 4 3 2 1 3 5, b. To compare and write the fractions as equivalent fractions with a common denominator. 20 4 5 7 5 35 and 21 3 7 5 7 35 4 7 3 5 Because 21 4 20 6 , then 35 35 7 6 1.3 3 5 6 5 4 3 2 1 c. 1.3 2.8 6 5 4 3 2 1 3 2.8 Skill Practice Fill in the blanks with the appropriate symbol, or . 7. 1 2 ______ 4 9 8. 7.2 ______ 4.6 6. 2 ______ 12 3. Interval Notation The set {x 0 x 3} represents all real numbers greater than or equal to 3. This set can be illustrated graphically on the number line. 5 4 3 2 1 0 1 2 3 4 5 5 4 3 2 1 By convention, a closed circle or a square bracket [ is used to indicate that an endpoint (x 3) is included in the set. This interval is a closed interval because its endpoint is included. The set {x 0 x 3} represents all real numbers strictly greater than 3. This set can be illustrated graphically on the number line. 5 4 3 2 1 5 4 3 2 1 0 1 2 3 4 5 By convention, an open circle or a parenthesis ( is used to indicate that an endpoint (x 3) is not included in the set. This interval is an open interval because its endpoint is not included. Notice that the sets {x 0 x 3} and {x 0 x 3} consist of an infinite number of elements that cannot all be listed. Another method to represent the elements of such sets is by using interval notation. To understand interval notation, first consider the real number line, which extends infinitely far to the left and right. The symbol is used to represent infinity. The symbol is used to represent negative infinity. Skill Practice Answers 6. 7. 8. 0 To express a set of real numbers in interval notation, sketch the graph first, using the symbols ( ) or [ ]. Then use these symbols at the endpoints to define the interval. Example 4 a. {x 0 x 3} Graph the sets on the number line, and express the set in interval notation. Solution: a. Set-Builder Notation {x 0 x 3} Graph Interval Notation 3 3, 2 5 4 3 2 1 0 1 2 3 [3 4 , 5 ) The graph of the set {x 0 x 3} begins at 3 and extends infinitely far to the right. The corresponding interval notation begins at 3 and extends to . Notice that a square bracket [ is used at 3 for both the graph and the interval notation to include x 3. A parenthesis is always used at (and at ) because there is no endpoint. b. Set-Builder Notation {x 0 x 3} Graph Interval Notation 1 3, 2 5 4 3 2 1 4 , 5 ) (3 c. Set-Builder Notation {x 0 x 3 26 3 2 5 4 3 2 1 , 3 2] Graph Interval Notation 1 , 3 24 0 1 2 3 4 5 The graph of the set {x 0 x 3 2 6 extends infinitely far to the left. Interval notation is always written from left to right. Therefore, is written first, followed by a comma, and then followed by the right-hand endpoint 3 2. Skill Practice 9. 5 w 0 w 7 6 Graph and express the set, using interval notation. 10. 5 x 0 x 6 0 6 11. 5 y 0 y 7 3.5 6 10. 11. ( 3.5 Table 1-2 summarizes the solution sets for four general inequalities. Table 1-2 Set-Builder Notation 5x 0 x 7 a6 5x 0 x a6 5x 0 x 6 a6 5x 0 x a6 Graph Interval Notation 1 a, 2 3 a, 2 1 , a 2 1 , a 4 ( a a ( a a Example 5 Find: a. A B b. A B c. A C Solution: a. A B {a, b, c, d, e, f, g, i, k} The union of A and B includes all the elements of A along with all the elements of B. Notice that the elements a, c, and e are not listed twice. The intersection of A and B includes only those elements that are common to both sets. Because A and C share no common elements, the intersection of A and C is the empty set or null set. b. A B {a, c, e} TIP: The empty set may be denoted by the symbol { } or by the symbol . Skill Practice 13. A B 14. A C Example 6 B {x 0 x 2} c. A B C {x 0 x 5} Graph the following sets. Then express each set in interval notation. d. A C It is helpful to visualize the graphs of individual sets on the number line before taking the union or intersection. ( a. Graph of A {x 0 x 3} 6 5 4 3 2 1 0 1 2 3 4 5 6 Graph of B {x 0 x 2} Graph of A B (the overlap) Interval notation: [2, 3) Note that the set A B represents the real numbers greater than or equal to 2 and less than 3. This relationship can be written more concisely as a compound inequality: 2 x 3. We can interpret this inequality as x is between 2 and 3, including x 2. b. Graph of A {x 0 x 3} Graph of C {x 0 x 5} Graph of A C Interval notation: ( , 3) [5, ) ( 0 0 0 1 1 1 2 2 2 3 3 4 4 4 5 5 5 6 6 6 6 5 4 3 2 1 6 5 4 3 2 1 0 0 1 1 2 2 3 4 4 5 5 6 6 ( 3 6 5 4 3 2 1 6 5 4 3 2 1 6 5 4 3 2 1 ( 3 A C includes all elements from set A along with the elements from set C. 10 6 5 4 3 2 1 6 5 4 3 2 1 6 5 4 3 2 1 ( 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 A B includes all elements from set A along with the elements of set B. This encompasses all real numbers. d. Graph of A {x 0 x 3} Graph of C {x 0 x 5} Graph of A C (the sets do not overlap) A C is the empty set { }. Skill Practice 6 5 4 3 2 1 6 5 4 3 2 1 6 5 4 3 2 1 ( 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 15. 5 x 0 x 1 6 5 x 0 x 6 10 6 17. 5 x 0 x 7 2 6 5 x 0 x 6 3 6 Find the intersection or union by first graphing the sets on the real number line. Write the answers in interval notation. 16. 5 x 0 x 2 6 5 x 0 x 7 3 6 18. 5 x 0 x 6 1 6 5 x 0 x 7 5 6 Translating Inequalities The intensity of a hurricane is often defined according to its maximum sustained winds for which wind speed is measured to the nearest mile per hour. Translate the italicized phrases into mathematical inequalities. a. A tropical storm is updated to hurricane status if the sustained wind speed, w, is at least 74 mph. b. Hurricanes are categorized according to intensity by the Saffir-Simpson scale. On a scale of 1 to 5, a category 5 hurricane is the most destructive. A category 5 hurricane has sustained winds, w, exceeding 155 mph. c. A category 4 hurricane has sustained winds, w, of at least 131 mph but no more than 155 mph. Solution: a. w 74 mph Skill Practice b. w 155 mph 19. The gas mileage, m, for a Honda Civic is at least 30 mpg. 20. The gas mileage, m, for a Harley Davidson motorcycle is more than 45 mpg. 21. The gas mileage, m, for a Ford Explorer is at least 10 mpg, but not more than 20 mpg. 11 Section 1.1 Boost your GRADE at mathzone.com! Practice Exercises Practice Problems Self-Tests NetTutor e-Professors Videos m. Union 6 5 4 3 2 1 For Exercises 59, show that each number is a rational number by finding a ratio of two integers equal to the given number. 5. 10 8. 0.1 6. 1 9. 0 1 2 7. 3 5 12 Integers Integers Concept 2: Inequalities For Exercises 1217, fill in the blanks with the appropriate symbol: 6 or 7 . 12. 9 ___ 1 16. 10 5 ___ 3 7 13. 0 ___ 6 17. 21 17 ___ 5 4 14. 0.15 ___ 0.04 15. 2.5 ___ 0.6 19. ( 5 6 20. 0 21. 9 22. 23. 0 1 15 24. 1 25. 12.8 13 For Exercises 2643, graph the sets and express each set in interval notation. 26. 5 x 0 x 7 3 6 27. 5 x 0 x 6 3 6 29. 5 z 0 z 4 6 32. 5 x 0 2.5 6 x 4.5 6 35. All real numbers greater than 2.34. 30. 5 w 0 w 6 9 26 33. 5 x 0 6 x 6 0 6 4 36. All real numbers greater than 5 2 . 37. All real numbers less than 7 . 38. All real numbers not less than 2. 41. All real numbers between 7 and 1. 40. All real numbers between 4 and 4. 43. All real numbers between 1 and 6, inclusive. For Exercises 4451, write an expression in words that describes the set of numbers given by each interval. (Answers may vary.) 44. ( , 4) 48. [180, 90] 45. [2, ) 49. ( , ) 46. (2, 7] 50. (3.2, ) 47. (3.9, 0) 51. ( , 1] Let A 5 x 0 x 7 3 6, B 5 x 0 x 0 6, C 5 x 0 1 x 6 4 6, and D 5 x 0 1 6 x 6 3 6. For Exercises 5461, graph the sets described here. Then express the answer in set-builder notation and in interval notation. 54. A B 55. A B 56. B C 57. B C 58. C D 59. C D 60. B D 61. A D 14 Let X 5 x 0 x 10 6, Y 5 x 0 x 6 1 6 , Z 5 x 0 x 7 1 6, and W 5 x 0 x 3 6. For Exercises 6267, find the intersection or union of the sets X, Y, Z, and W. Write the answers in interval notation. 62. X Y 65. Y Z 63. X Y 66. Z W 64. Y Z 67. Z W For Exercises 6872, write an inequality using the variable p that represents each condition. 68. Normal systolic blood pressure 70. High normal range for systolic pressure 72. Normal diastolic blood pressure A pH scale determines whether a solution is acidic or alkaline. The pH scale runs from 0 to 14, with 0 being the most acidic and 14 being the most alkaline. A pH of 7 is neutral (distilled water has a pH of 7). For Exercises 7377, write the pH ranges as inequalities and label the substances as acidic or alkaline. 73. Lemon juice: 2.2 through 2.4, inclusive 75. Carbonated soft drinks: 3.0 through 3.5, inclusive 77. Milk of magnesia: 10.0 through 11.0, inclusive 74. Eggs: 7.6 through 8.0, inclusive 76. Milk: 6.6 through 6.9, inclusive 69. Diastolic pressure in hypertension 71. Systolic pressure in hypertension 15 Section 1.2 Concepts 1. Opposite and Absolute Value 2. Addition and Subtraction of Real Numbers 3. Multiplication and Division of Real Numbers 4. Exponential Expressions 5. Square Roots 6. Order of Operations 7. Evaluating Expressions 6 5 4 3 2 1 1 3 2 3 2 Opposites The absolute value of a real number a, denoted 0 a 0 , is the distance between a and 0 on the number line. Note: The absolute value of any real number is nonnegative. For example: 05 0 5 and 0 5 0 5 |5| 5 5 units 0 1 2 3 4 5 6 |5| 5 5 units 6 5 4 3 2 1 Example 1 Calculator Connections Some calculators have an absolute value function. For example, 4 5 6 a. 0 2.5 0 2.5 b. 0 5 40 c. 0 4 0 1 4 2 4 Skill Practice 5 4 4 units 6 5 4 3 2 1 0 units 2.5 units 1. 0 92 0 Simplify. 2. 0 7.6 0 3. 0 2 0 The absolute value of a number a is its distance from zero on the number line. The definition of 0 a 0 may also be given algebraically depending on whether a is negative or nonnegative. Skill Practice Answers 1. 92 2. 7.6 3. 2 16 This definition states that if a is a nonnegative number, then 0 a 0 equals a itself. If a is a negative number, then 0 a 0 equals the opposite of a. For example, 0 7 0 7 09 0 9 Because 7 is negative, 0 7 0 equals the opposite of 7, which is 7. Because 9 is positive, 0 9 0 equals the number 9 itself. Example 2 1 11 42 a. 2 1 6 2 12 62 First find the absolute value of the addends. 0 2 0 2 and 0 6 0 6 Add their absolute values and apply the common sign (in this case, the common sign is negative). 8 b. 10.3 13.8 First find the absolute value of the addends. 0 10.3 0 10.3 and 0 13.8 0 13.8 The absolute value of 13.8 is greater than the absolute value of 10.3. Therefore, the sum is positive. Subtract the smaller absolute value from the larger absolute value. 1 13.8 10.3 2 Apply the sign of the number with the larger absolute value. 3.5 17 c. 1 5 a 1 b 6 4 5 5 a b 6 4 52 53 a b 62 43 10 15 a b 12 12 1 Write 1 as an improper fraction. 4 The LCD is 12. Write each fraction with the LCD. Find the absolute value of the addends. 10 10 15 15 ` ` and ` ` 12 12 12 12 The absolute value of 15 12 is greater than the absolute value of 10 12. Therefore, the sum is negative. a 15 10 b 12 12 Subtract the smaller absolute value from the larger absolute value. Apply the sign of the number with the larger absolute value. Skill Practice 4. 4 1 1 2 Subtraction of real numbers is defined in terms of the addition process. To subtract two real numbers, add the opposite of the second number to the first number. Example 3 b. 2.7 (3.8) c. a. 13 5 13 15 2 18 Add the opposite of the second number to the first number. Add. Skill Practice Answers 4. 5 5. 0.8 6. 10 7 18 b. 2.7 13.8 2 Add the opposite of the second number to the first number. Add. c. 2 5 4 2 3 2 5 a 4 b 2 3 5 14 a b 2 3 15 28 a b 6 6 13 1 or 2 6 6 Subtract. 8. 5 1 2 2 9. 1 3 6 4 Add the opposite of the second number to the first number. Write the mixed number as a fraction. Get a common denominator and add. Skill Practice 7. 1.1 3 Example 4 19 3 1 c. a 3 b a b 3 10 a 30 30 3 10 b a b 3 10 Write the mixed number as a fraction. Same signs. The product is positive. Simplify to lowest terms. Multiply. 2 11. 1 4 2a b 3 8 b 12. 1 51 4 2a 3 1 Skill Practice 10. 1 5 2 1 11 2 3 Notice from Example 4(c) that 1 10 3 2 1 10 2 1. If the product of two numbers is 1, then the numbers are said to be reciprocals. That is, the reciprocal of a real 1 1 number a is a . Furthermore, a a 1. TIP: A number and its reciprocal have the same sign. For example: a 10 3 b a b 1 3 10 and 3 1 1 3 Recall that subtraction of real numbers was defined in terms of addition. In a similar way, division of real numbers can be defined in terms of multiplication. To divide two real numbers, multiply the first number by the reciprocal of the second number. For example: Multiply 10 5 2 or equivalently Reciprocal 10 1 2 5 Because division of real numbers can be expressed in terms of multiplication, the sign rules that apply to multiplication also apply to division. 1 10 1 2 2 10 a b 5 2 10 2 10 1 5 2 Dividing two numbers of the same sign produces a positive quotient. Skill Practice Answers 10. 55 11. 8 3 12. 14 20 1 10 1 2 2 10 a b 5 2 10 2 10 1 5 2 0. a b is positive. a b is negative. 0. is undefined. The relationship between multiplication and division can be used to investigate properties 3 and 4 in the preceding box. For example, 0 0 6 6 is undefined 0 Because 6 0 0 Note: The quotient of 0 and 0 cannot be determined . Evaluating an expression of the form 0 0 ? is equivalent to asking, What number times zero will equal 0? That is, (0)(?) 0. Any real number will satisfy this requirement; however, expressions involving 0 0 are usually discussed in advanced mathematics courses. Example 5 Divide the real numbers. Write the answer as a fraction or whole number. a. 42 7 b. c. d. 3 Solution: a. 42 6 7 TIP: Recall that multiplication may be used to check a division problem. For example: TIP: If the numerator and denominator are both negative, then the fraction is positive: 5 5 7 7 42 6 7 1 1 7 2 1 6 2 42 b. c. 96 2 144 3 5 5 7 7 Same signs. The quotient is positive. Simplify. Same signs. The quotient is positive. 21 d. 3 1 2 a b 10 5 31 5 a b 10 2 1 Write the mixed number as an improper fraction, and multiply by the reciprocal of the second number. 31 5 a b 10 2 2 31 4 TIP: If the numerator and denominator of a fraction have opposite signs, then the quotient will be negative. Therefore, a fraction has the same value whether the negative sign is written in the numerator, in the denominator, or in front of a fraction. 31 31 31 4 4 4 Skill Practice 13. 28 4 4. Exponential Expressions To simplify the process of repeated multiplication, exponential notation is often used. For example, the quantity 3 3 3 3 3 can be written as 35 (3 to the fifth power). Definition of b n Let b represent any real number and n represent a positive integer. Then bn b b b b b n factors of b b is read as b to the nth power. b is called the base and n is called the exponent, or power. b2 is read as b squared, and b3 is read as b cubed. Example 6 22 Solution: a. 53 5 5 5 125 b. 1 2 2 4 1 2 21 2 2 1 2 21 2 2 16 c. 24 3 2 2 2 2 4 16 The base is 2, and the exponent is 4. The exponent 4 applies to the entire contents of the parentheses. The base is 2, and the exponent is 4. Because no parentheses enclose the negative sign, the exponent applies to only 2. 24 1 24 1 1 2 2 2 2 2 16 1 2 1 1 d. a b a b a b 3 3 3 1 9 Calculator Connections On many calculators, the x 2 key is used to square a number. The ^ key is used to raise a base to any power. Skill Practice 17. 23 5. Square Roots The inverse operation to squaring a number is to find its square roots. For example, finding a square root of 9 is equivalent to asking, What number when squared equals 9? One obvious answer is 3, because 1 3 2 2 9. However, 3 is also a square root of 9 because 1 3 2 2 9. For now, we will focus on the principal square root which is always taken to be nonnegative. The symbol 1 , called a radical sign, is used to denote the principal square root of a number. Therefore, the principal square root of 9 can be written as 19. The expression 164 represents the principal square root of 64. Example 7 a. 181 b. c. 116 23 Solution: a. 181 9 b. 5 25 A 64 8 because because (9)2 81 5 2 25 a b 8 64 Calculator Connections The 1 key is used to find the square root of a nonnegative real number. c. 116 is not a real number because no real number when squared will be negative. Evaluate, if possible. 22. 49 B 100 23. 14 Skill Practice 21. 125 Example 7(c) illustrates that the square root of a negative number is not a real number because no real number when squared will be negative. 6. Order of Operations When algebraic expressions contain numerous operations, it is important to evaluate the operations in the proper order. Parentheses ( ), brackets [ ], and braces { } are used for grouping numbers and algebraic expressions. It is important to recognize that operations must be done first within parentheses and other grouping symbols. Other grouping symbols include absolute value bars, radical signs, and fraction bars. Order of Operations 1. First, simplify expressions within parentheses and other grouping symbols. These include absolute value bars, fraction bars, and radicals. If embedded parentheses are present, start with the innermost parentheses. 2. Evaluate expressions involving exponents, radicals, and absolute values. 3. Perform multiplication or division in the order in which they occur from left to right. 4. Perform addition or subtraction in the order in which they occur from left to right. Example 8 24 Solution: a. 10 5 1 2 5 2 2 6 3 216 7 10 5 1 3 2 2 6 3 29 Simplify inside the parentheses and radical. Simplify exponents and radicals. Do multiplication and division from left to right. Do addition and subtraction from left to right. TIP: Dont try to do too many steps at once. Taking a shortcut may result in a careless error. For each step rewrite the entire expression, changing only the operation being evaluated. 10 5 1 9 2 6 3 3 10 45 2 3 35 2 3 33 3 30 0 1 3 2 3 1 52 3 2 0 15 1 3 2 1 2 2 0 1 3 2 3 1 25 3 2 0 5122 0 1 3 2 3 1 22 2 0 10 0 27 22 0 10 b. Numerator: Simplify inner parentheses. Denominator: Do multiplication and division (left to right). Numerator: Simplify inner parentheses. Denominator: Multiply. Simplify exponents. Add within the absolute value. Evaluate the absolute value. 0 5 0 10 1 5 or 10 2 Calculator Connections To evaluate the expression 0 1 3 2 3 1 52 3 2 0 15 1 3 2 1 2 2 on a graphing calculator, use parentheses to enclose the absolute value expression. Likewise, it is necessary to use parentheses to enclose the entire denominator. Skill Practice 24. 36 22 3 1 18 5 2 2 6 0 5 7 0 11 1 1 2 2 2 25 7. Evaluating Expressions The order of operations is followed when evaluating an algebraic expression or when evaluating a geometric formula. For a list of common geometry formulas, see the inside front cover of the text. It is important to note that some geometric formulas use Greek letters (such as p) and some formulas use variables with subscripts. A subscript is a number or letter written to the right of and slightly below a variable. Subscripts are used on variables to represent different quantities. For example, the area of a trapezoid is given by A 1 2 1 b1 b2 2 h. The values of b1 and b2 (read as b sub 1 and b sub 2) represent the two different bases of the trapezoid (Figure 1-5). This is illustrated in Example 9. b2 h b1 Figure 1-5 Subscripts Example 9 A homeowner in North Carolina wants to buy protective film for a trapezoidshaped window. The film will adhere to shattered glass in the event that the glass breaks during a bad storm. Find the area of the window whose dimensions are given in Figure 1-6. Solution: 1 1 b b2 2 h 2 1 Substitute b1 4.0 ft, b2 2.5 ft, and h 5.0 ft. Simplify inside parentheses. Multiply from left to right. TIP: Subscripts should not be confused with superscripts, which are written above a variable. Superscripts are used to denote powers. b2 b2 16.25 ft2 26. Use the formula given in Example 9 to find the area of the trapezoid. b2 5 in. h 10 in. b1 12 in. 26 Section 1.2 Boost your GRADE at mathzone.com! Practice Exercises Practice Problems Self-Tests NetTutor e-Professors Videos Review Exercises For Exercises 36, describe the set. 3. Rational numbers Integers 5. Natural numbers {0} 4. Rational numbers Irrational numbers 6. Integers Whole numbers 27 For Exercises 1320, fill in the blank with the appropriate symbol 1 6 , 7 , 2 . 13. 0 6 0 ______ 0 6 0 14. 1 5 2 ______ 0 5 0 16. 0 2 0 ______ 1 2 2 19. 0 2 1 5 2 0 ______ 0 2 0 0 5 0 17. 0 1 0 ______ 1 20. 0 4 3 0 ______ 0 4 0 0 3 0 15. 0 4 0 ______ 0 4 0 18. 3 _______ 0 7 0 28 86. 89. 90. 1 2 64 2 52 2 91. a b a b a b 2 5 10 92. a 2 8 1 2 2 2 23 b a b 2 1 32 For Exercises 9394, find the average of the set of data values by adding the values and dividing by the number of values. 93. Find the average low temperature for a week in January in St. Johns, Newfoundland. (Round to the nearest tenth of a degree.) Day Mon. Tues. Wed. Thur. Fri. Sat. Sun. 94. Find the average high temperature for a week in January in St. Johns, Newfoundland. (Round to the nearest tenth of a degree.) Day High temperature 2C 6C 7C 96. The formula F 9 5 C 32 converts Celsius temperatures to Fahrenheit temperatures. Find the equivalent Fahrenheit temperature for each Celsius temperature. a. 5C b. 0C c. 37C d. 40C 29 Use the geometry formulas found in the inside front cover of the book to answer Exercises 97106. For Exercises 97100, find the area. 97. Trapezoid 5 in. 2 in. 4 in. 98. Parallelogram 8.5 m 6m 99. Triangle 100. Rectangle 3.1 cm 7 6 yd 5.2 cm 1 3 4 yd For Exercises 101106, find the volume. (Use the key on your calculator, and round the final answer to 1 decimal place.) 101. Sphere 102. Right circular cone 103. Right circular cone r 1.5 ft h 12 cm r 5 cm h 4.1 ft r 2.5 ft 104. Sphere r1 2 yd h 5 in. h 9.5 m r4m r 3 in. 108. Which expression when entered into a graphing calculator will yield the correct value of or 24 63 24 6 3 ? 109. Verify your solution to Exercise 85 by entering the expression into a graphing calculator: 1 1 1 102 82 2 2 32 110. Verify your solution to Exercise 86 by entering the expression into a graphing calculator: 1 1 1 16 7 2 32 2 1 1 1 16 2 1 1 4 2 2 30 Section 1.3 Concepts 1. Recognizing Terms, Factors, and Coefficients 2. Properties of Real Numbers 3. Simplifying Expressions Simplifying Expressions 1. Recognizing Terms, Factors, and Coefficients An algebraic expression is a single term or a sum of two or more terms. A term is a constant or the product of a constant and one or more variables. For example, the expression 6x2 5xyz 11 or 6x2 5xyz 1 11 2 consists of the terms 6x2, 5xyz, and 11. The terms 6x2 and 5xyz are variable terms, and the term 11 is called a constant term. It is important to distinguish between a term and the factors within a term. For example, the quantity 5xyz is one term, but the values 5, x, y, and z are factors within the term. The constant factor in a term is called the numerical coefficient or simply coefficient of the term. In the terms 6x2, 5xyz, and 11, the coefficients are 6, 5, and 11, respectively. A term containing only variables such as xy has a coefficient of 1. Terms are called like terms if they each have the same variables and the corresponding variables are raised to the same powers. For example: Like Terms 6t and 1.8ab and 1 2 3 d and c 2 4 and Example 1 4t 3ab c2d3 6 Unlike Terms 6t and 1.8xy and 1 2 3 c d and 2 4p and 4s 3x c2d 6 (different (different (different (different variables) variables) powers) variables) a. List the terms of the expression. b. Identify the coefficient of the term. c. Identify the pair of like terms. Solution: 1 6c b. The term yz3 can be written as 1yz3; therefore, the coefficient is 1. c. 1 6 c are like terms because they have the same variable raised to the same power. 1 2 c, Skill Practice Given: 2x 2 5x 1 y2 2 1a. List the terms of the expression. b. Which term is the constant term? c. Identify the coefficient of the term y2. Section 1.3 Simplifying Expressions 31 Table 1-3 Property Name Algebraic Representation Example 5335 152 132 132 152 12 32 7 2 13 72 12 327 213 72 315 22 3532 Description/Notes The order in which two real numbers are added or multiplied does not affect the result. The manner in which two real numbers are grouped under addition or multiplication does not affect the result. A factor outside the parentheses is multiplied by each term inside the parentheses. Commutative property a b b a of addition Commutative property a b b a of multiplication Associative property of addition Associative property of multiplication Distributive property of multiplication over addition 1a b2 c a 1b c2 1a b2 c a 1b c2 a1b c2 ab ac 5 0 0 5 5 Any number added 0 is the identity element for to the identity addition because element 0 will a00aa remain unchanged. 1 is the identity 51155 element for multiplication because a11aa Any number multiplied by the identity element 1 will remain unchanged. The sum of a number and its additive inverse (opposite) is the identity element 0. The product of a number and its multiplicative inverse (reciprocal) is the identity element 1. 1 1 a and 1 a1 a (provided a 0) The properties of real numbers are used to multiply algebraic expressions. To multiply a term by an algebraic expression containing more than one term, we apply the distributive property of multiplication over addition. Example 2 a. 4 1 2x 5 2 2 3 d. a 9x y 5 b 3 8 32 Solution: a. 4 1 2x 5 2 4 1 2x 2 4 1 5 2 8x 20 Apply the distributive property. Simplify, using the associative property of multiplication. The negative sign preceding the parentheses can be interpreted as a factor of 1. 1 1 3.4q 2 1 1 21 5.7r 2 3 1 a 2 1 3 21 2b 2 1 3 21 5c 2 3a 6b 15c 2 3 d. a 9x y 5 b 3 8 2 2 3 2 1 9x 2 a b a y b a b 1 5 2 3 3 8 3 6 10 18 x y 3 24 3 1 10 6x y 4 3 Skill Practice 2. 10 1 30y 40 2 4. 2 1 4x 3y 6 2 3. 1 7t 1.6s 9.2 2 5. Notice that the parentheses are removed after the distributive property is applied. Sometimes this is referred to as clearing parentheses. Two terms can be added or subtracted only if they are like terms. To add or subtract like terms, we use the distributive property, as shown in Example 3. Example 3 a. 8x 3x Section 1.3 Simplifying Expressions 33 Solution: a. 8x 3x x 1 8 3 2 x 1 5 2 5x 6. 4y 7y Although the distributive property is used to add and subtract like terms, it is tedious to write each step. Observe that adding or subtracting like terms is a matter of combining the coefficients and leaving the variable factors unchanged. This can be shown in one step. This shortcut will be used throughout the text. For example: 4w 7w 11w 8ab2 10ab2 5ab2 13ab2 3. Simplifying Expressions Clearing parentheses and combining like terms are important tools to simplifying algebraic expressions. This is demonstrated in Example 4. Example 4 Simplify by clearing parentheses and combining like terms. a. 4 3 1 2x 8 2 1 c. 2 3 1.5x 4.7 1 x2 5.2x 2 3x 4 Solution: a. 4 3 1 2x 8 2 1 4 6x 24 1 4 24 1 6x 27 6x 6x 27 Apply the distributive property. Group like terms. Combine like terms. TIP: The expression 27 6x is equal to 6x 27. However, it is customary to write the variable term first. Skill Practice Answers 6. 3y 7. 2a 2 34 b. 1 3s 11t 2 5 1 2t 8s 2 10s 3s 11t 10t 40s 10s 3s 40s 10s 11t 10t c. 2 3 1.5x 4.7 1 x2 5.2x 2 3x 4 53s t Apply the distributive property. Group like terms. Combine like terms. Apply the distributive property to inner parentheses. Group like terms. Combine like terms. Apply the distributive property. 51.88x 9.4x 2 can also be written as 9.4x 2 1 51.88x 2 or simply 9.4x 2 51.88x. Although the expressions are all equal, it is customary to 1 1 d. 1 3w 6 2 a w 4 b 3 4 3 6 1 w w4 3 3 4 1 w 2 w 4 4 1 4 w w24 4 4 5 w2 4 Skill Practice Apply the distributive property. Reduce fractions to lowest terms. Group like terms and find a common denominator. Combine like terms. 8. 7 2 1 3x 4 2 5 9. 1 6z 10y 2 4 1 3z y 2 8y Section 1.3 Simplifying Expressions 35 Section 1.3 Boost your GRADE at mathzone.com! Practice Exercises Practice Problems Self-Tests NetTutor e-Professors Videos Review Exercises For Exercises 34, a. Classify the number as a whole number, natural number, rational number, irrational number, or real number. (Choose all that apply.) b. Write the reciprocal of the number. c. Write the opposite of the number. d. Write the absolute value of the number. 3. 4 For Exercises 58, write the set in interval notation. 5. 5 x 0 x 7 0 3 0 6 7. e w 0 5 6 w 29 f 2 4 6. e x 0 x ` ` f 3 8. e z 0 2 z 6 11 f 3 4. 0 36 1 53. 2 c 5a a 3 b 1 a2 a 2 4 d 2 55. 3 1 2y 5 2 2 1 y y2 2 4 3y 2 54. 3 c 3a b b 2 1 b 4 2 6b2 d 3 56. 3 1 x 6 2 3 1 x2 1 2 4 2x 58. 3.2 5 6.1y 4 3 9 1 2y 2.5 2 4 7y 6 60. 4 1 1 1 25a 20b 2 1 21a 14b 2 2 5 7 7 Section 1.4 37 yz a. Write an expression for the area of region A. (Do not simplify.) b. Write an expression for the area of region B. c. Write an expression for the area of region C. d. Add the expressions for the area of regions B and C. e. Show that the area of region A is equal to the sum of the areas of regions B and C. What property of real numbers does this illustrate? Section 1.4 Concepts 1. Definition of a Linear Equation in One Variable 2. Solving Linear Equations 3. Clearing Fractions and Decimals 4. Conditional Equations, Contradictions, and Identities All equations have an equal sign. Furthermore, notice that the equal sign separates the equation into two parts, the left-hand side and the right-hand side. A solution to an equation is a value of the variable that makes the equation a true statement. Substituting a solution to an equation for the variable makes the righthand side equal to the left-hand side. 38 Equation x 4 Solution 4 Check x 4 4 4 Substitute 4 for x. Right-hand side equals lefthand side. Substitute 8 for p. Right-hand side equals lefthand side. Substitute 10 for z. Right-hand side equals lefthand side. p 3 11 p 3 11 8 3 11 2z 20 10 2z 20 2 1 10 2 20 Throughout this text we will learn to recognize and solve several different types of equations, but in this chapter we will focus on the specific type of equation called a linear equation in one variable. Notice that a linear equation in one variable has only one variable. Furthermore, because the variable has an implied exponent of 1, a linear equation is sometimes called a first-degree equation. Linear equation in one variable 4x 3 0 4 5p 3 10 3 10 q Section 1.4 39 Example 1 c. 4 d. x 6 a. 12 x 40 12 12 x 40 12 x 28 Check: 12 1 28 2 40 40 40 12 x 40 To isolate x, subtract 12 from both sides. Simplify. Check the solution in the original equation. True statement b. 1 p2 5 1 5 a p b 5 1 2 2 5 p 10 Check: 1 p2 5 1 1 10 2 2 5 22 True statement To isolate p, multiply both sides by 5. Simplify. Check the solution in the original equation. c. w 2.2 w b 2.2 2.2 To isolate w, multiply both sides by 2.2. Simplify. w 2.2 Check the solution in the original equation. 2.2 1 4 2 a 8.8 w Check: 4 40 Check: 1 6 2 6 x 6 66 True statement Skill Practice 1. x 5 11 For more complicated linear equations, several steps are required to isolate the variable. Example 2 a. 11z 2 5 1 z 2 2 a. 11z 2 5 1 z 2 2 11z 2 5z 10 Clear parentheses. Subtract 5z from both sides. Combine like terms. Subtract 2 from both sides. 6z 12 6 6 z 2 Section 1.4 41 Check: 11 1 2 2 2 5 1 2 2 2 22 2 5 1 4 2 20 20 11z 2 5 1 z 2 2 True statement b. 3 1 x 4 2 2 7 1 x 1 2 3x 12 2 7 x 1 3x 14 x 6 3x x 14 x x 6 2x 14 6 2x 14 14 6 14 2x 8 2x 8 2 2 Check: 3 1 x 4 2 2 7 1 x 1 2 3 1 4 4 2 2 7 1 4 1 2 3 1 0 2 2 7 1 5 2 022 c. 4 3 y 3 1 y 5 2 4 2 1 6 5y 2 4 3 y 3y 15 4 12 10y 4 3 2y 15 4 12 10y 8y 60 12 10y 8y 10y 60 12 10y 10y 18y 60 12 18y 60 60 12 60 18y 72 72 18y 18 18 Check: 4 3 y 3 1 y 5 2 4 2 1 6 5y 2 4 3 4 3 1 1 2 4 2 1 6 20 2 4 3 4 3 4 2 1 14 2 4 1 7 2 28 28 28 y4 To isolate y, divide both sides by 18. Simplify. 22 True statement x4 To isolate x, divide both sides by 2. Simplify. Check the solution in the original equation. Clear parentheses. Combine like terms. Add x to both sides of the equation. Combine like terms. Subtract 14 from both sides. Clear parentheses. Combine like terms. Clear parentheses. Add 10y to both sides of the equation. Combine like terms. Add 60 to both sides of the equation. 4 3 4 3 1 4 5 2 4 2 1 6 5 1 4 22 True statement 42 Skill Practice 5. 7 2 1 y 3 2 6y 3 7. 3 3 p 2 1 p 2 2 4 4 1 p 3 2 6. 4 1 2t 2 2 6 1 t 1 2 6 t 1 1 1 w w 1 1w 42 4 3 2 1 1 1 w w1 w2 4 3 2 1 1 1 12 a w w 1 b 12 a w 2 b 4 3 2 Apply the distributive property to clear parentheses. Multiply both sides of the equation by the LCD of all terms. In this case, the LCD is 12. Apply the distributive property. Subtract 6w 3 4 1 1 1 16 2 2 True statement 8 8 Section 1.4 43 TIP: The fractions in this equation can be eliminated by multiplying both sides of the equation by any common multiple of the denominators. For example, multiplying both sides of the equation by 24 produces the same solution. 1 1 1 24 a w w 1 b 24 1 w 4 2 4 3 2 6w 8w 24 12 1 w 4 2 14w 24 12w 48 2w 24 w 12 Skill Practice 8. 3 1 2 1 a a 4 2 3 3 Example 4 Solve. x2 x4 x4 2 5 2 10 Solution: x2 x4 2 x4 5 2 1 10 The LCD of all terms in the equation is 10. Multiply both sides by 10. 10 a 2 x2 x4 2 x4 b 10 a b 5 2 1 10 5 1 10 x2 10 x4 10 2 10 x4 a b a b a b a b 1 5 1 2 1 1 1 10 2 1 x 2 2 5 1 x 4 2 20 1 1 x 4 2 2x 4 5x 20 20 x 4 3x 16 x 24 3x x 16 x x 24 4x 16 24 4x 16 16 24 16 4x 8 Clear fractions. Apply the distributive property. Simplify both sides of the equation. Subtract x from both sides. 44 8 4x 4 4 x 2 Skill Practice Solve. 9. 1 x3 3x 2 8 4 2 The same procedure used to clear fractions in an equation can be used to clear decimals. Example 5 Solve the equation. Solution: Recall that any terminating decimal can be written as a fraction. Therefore, the equation 0.55x 0.6 2.05x is equivalent to 55 6 205 x x 100 10 100 A convenient common denominator for all terms in this equation is 100. Multiplying both sides of the equation by 100 will have the effect of moving the decimal point 2 places to the right. 100 1 0.55x 0.6 2 100 1 2.05x 2 55x 60 205x 55x 55x 60 205x 55x 60 150x 60 150x 150 150 60 x 150 2 x 0.4 5 Check: 0.55 1 0.4 2 0.6 2.05 1 0.4 2 0.22 0.6 0.82 0.82 0.82 Skill Practice True statement Section 1.4 45 No solution III. Identities An equation that has all real numbers as its solution set is called an identity. For example, consider the equation x 4 x 4. Because the left- and righthand sides are identical, any real number substituted for x will result in equal quantities on both sides. If we solve the equation, we get the identity 4 4. In such a case, the solution is the set of all real numbers. x 4x4 xx4xx4 44 Example 6 1 identity 2 Solve the equations. Identify each equation as a conditional equation, a contradiction, or an identity. a. 3 3 x 1 x 1 2 4 2 c. 4x 3 17 Solution: a. 3 3 x 1 x 1 2 4 2 3 3 1 4 2 3 2 3 3 x x 1 4 2 46 b. 5 1 3 c 2 2 2c 3c 17 15 5c 2 5c 17 5c 17 5c 17 00 This equation is an identity. The solution is the set of all real numbers. c. 4x 3 17 4x 3 3 17 3 4x 20 4x 20 4 4 x5 Skill Practice Answers 11. The equation is a contradiction. There is no solution. 12. The equation is an identity. The solution is the set of all real numbers. 13. The equation is conditional. The solution is x 1. Solve the equations. Identify each equation as a conditional equation, an identity, or a contradiction. 12. 2 1 3x 1 2 6 1 x 1 2 8 Section 1.4 Boost your GRADE at mathzone.com! Practice Exercises Practice Problems Self-Tests NetTutor e-Professors Videos Review Exercises For Exercises 36, clear parentheses and combine like terms. 3. 8x 3y 2xy 5x 12xy 5. 2 1 3z 4 2 1 z 12 2 4. 5ab 5a 13 2a 17 6. 1 6w 5 2 3 1 4w 5 2 Section 1.4 47 20. 21. a 36. 1 5 1 p 2 2 2 1 p 13 2 48. 50. 51. 52. 48 Mixed Exercises For Exercises 6596, solve the equations. 65. 5b 9 71 68. 15 12 9x 71. 12b 15b 8 6 4b 6 1 74. 2x 3 1 x 5 2 15 2 77. 0.75 1 8x 4 2 1 6x 9 2 3 80. 6 1 z 2 2 3z 8 3z 3 83. 3 x 9 4 86. 2 x2 5x 2 3 6 2 66. 3x 18 66 69. 10c 3 3 12c 72. 4z 2 3z 5 3 z 4 75. c 3c c 1 2 4 8 67. 16 10 13x 70. 2w 21 6w 7 73. 5 1 x 2 2 2x 3x 7 76. d d 5d 7 5 10 20 10 79. 7 1 p 2 2 4p 3p 14 82. 1 1 1 1 x 3 2 1 2x 5 2 3 6 6 y3 2y 1 5 4 8 2 2 5 1 x x3 x5 3 6 2 85. 87. 88. 7 1 1 3 95. y a 5 y b 8 4 2 4 96. 5x 1 8 x 2 2 3 4 1 3 5x 2 13 4 49 Section 1.5 Concepts 1. Introduction to Problem Solving 2. Applications Involving Consecutive Integers 3. Applications Involving Percents and Rates 4. Applications Involving Principal and Interest 5. Applications Involving Mixtures 6. Applications Involving Distance, Rate, and Time Step 2 Step 3 Step 4 Replace the verbal model with a mathematical equation using x or another variable. Step 5 Solve for the variable, using the steps for solving linear equations. Once youve obtained a numerical value for the variable, recall what it represents in the context of the problem. Can this value be used to determine other unknowns in the problem? Write an answer to the word problem in words. Step 6 Example 1 The sum of two numbers is 39. One number is 3 less than twice the other. What are the numbers? Solution: Step 1: Read the problem carefully. Step 2: Let x represent one number. Let 2x 3 represent the other number. Step 3: (One number) (other number) 39 Step 4: Replace the verbal model with a mathematical equation. (One number) (other number) 39 x (2x 3) 39 50 x 1 2x 3 2 39 3x 3 39 3x 42 3x 42 3 3 x 14 Step 6: Interpret your results. Refer back to step 2. One number is x: The other number is 2x 3: 2(14) 3 Answer: The numbers are 14 and 25. Skill Practice 14 25 1. One number is 5 more than 3 times another number. The sum of the numbers is 45. Find the numbers. Example 2 The sum of two consecutive odd integers is 172. Find the integers. Solution: Step 1: Read the problem carefully. Step 2: Label unknowns: Let x represent the first odd integer. Let x 2 represent the next odd integer. 51 Step 3: Write an equation in words: (First integer) (second integer) 172 Step 4: Write a mathematical equation based on the verbal model. (First integer) (second integer) 172 x Step 5: Solve for x. (x 2) 172 Step 6: Interpret your results. One integer is x: The other integer is x 2: 85 2 Answer: The numbers are 85 and 87. Skill Practice 85 87 TIP: After completing a word problem, it is always a good idea to check that the answer is reasonable. Notice that 85 and 87 are consecutive odd integers, and the sum is equal to 172 as desired. 2a. If the first integer is represented by x, write expressions for the next two integers. b. Write a mathematical equation that describes the verbal model. c. Solve the equation and find the three integers. The following models are used to compute sales tax, commission, and simple interest. In each case the value is found by multiplying the base by the percentage. Sales tax (cost of merchandise)(tax rate) Commission (dollars in sales)(commission rate) Simple interest (principal)(annual interest rate)(time in years) I Prt Skill Practice Answers 2a. x 1 and x 2 b. x 1 x 1 2 1 x 2 2 66 c. The integers are 21, 22, and 23. 52 Example 3 A realtor made a 6% commission on a house that sold for $172,000. How much was her commission? Solution: Let x represent the commission. (Commission) (dollars in sales)(commission rate) x ($172,000)(0.06) x $10,320 The realtors commission is $10,320. Skill Practice Label the variables. Verbal model Mathematical model Solve for x. Interpret the results. 3. The sales tax rate in Atlanta, Georgia, is 7%. Find the amount of sales tax paid on an automobile priced at $12,000. Example 4 A woman invests $5000 in an account that earns 5 1 4 % simple interest. If the money is invested for 3 years, how much money is in the account at the end of the 3-year period? Solution: Let x represent the total money in the account. P $5000 r 0.0525 t3 (principal amount invested) (interest rate) (time in years) Label variables. The total amount of money includes principal plus interest. (Total money) (principal) (interest) x P Prt x $5000 ($5000)(0.0525)(3) x $5000 $787.50 x $5787.50 The total amount of money in the account is $5787.50. Skill Practice Verbal model Mathematical model Substitute for P, r, and t. Solve for x. Interpret the results. 4. A man earned $340 in 1 year on an investment that paid a 4% dividend. Find the amount of money invested. As consumers, we often encounter situations in which merchandise has been marked up or marked down from its original cost. It is important to note that percent increase and percent decrease are based on the original cost. For example, suppose a microwave originally priced at $305 is marked down 20%. 53 The discount is determined by 20% of the original price: (0.20)($305) $61.00. The new price is $305.00 $61.00 $244.00. Example 5 A college bookstore uses a standard markup of 22% on all books purchased wholesale from the publisher. If the bookstore sells a calculus book for $103.70, what was the original wholesale cost? Solution: The selling price of the book is based on the original cost of the book plus the bookstores markup. (Selling price) (original price) (markup) (x)(0.22) Verbal model (Selling price) (original price) (original price markup rate) 103.70 x Mathematical model 103.70 x 0.22x 103.70 1.22x 103.70 x 1.22 x $85.00 Simplify. Combine like terms. The original wholesale cost of the textbook was $85.00. Interpret the results. Skill Practice 5. An online bookstore gives a 20% discount on paperback books. Find the original price of a book that has a selling price of $5.28 after the discount. Miguel had $10,000 to invest in two different mutual funds. One was a relatively safe bond fund that averaged 8% return on his investment at the end of 1 year. The other fund was a riskier stock fund that averaged 17% return in 1 year. If at the end of the year Miguels portfolio grew to $11,475 ($1475 above his $10,000 investment), how much money did Miguel invest in each fund? Solution: This type of word problem is sometimes categorized as a mixture problem. Miguel is mixing his money between two different investments. We have to determine how the money was divided to earn $1475. Skill Practice Answers 5. $6.60 54 The information in this problem can be organized in a chart. (Note: There are two sources of money: the amount invested and the amount earned.) Because the amount of principal is unknown for both accounts, we can let x represent the amount invested in the bond fund. If Miguel spends x dollars in the bond fund, then he has (10,000 x) left over to spend in the stock fund. The return for each fund is found by multiplying the principal and the percent growth rate. To establish a mathematical model, we know that the total return ($1475) must equal the growth from the bond fund plus the growth from the stock fund: (Growth from bond fund) (growth from stock fund) (total growth) 0.08x 0.17(10,000 x) 1475 0.08x 0.17(10,000 x) 1475 8x 17(10,000 x) 147,500 8x 170,000 17x 147,500 9x 170,000 147,500 9x 22,500 22,500 9x 9 9 x 2500 Solve for x and interpret the results. Combine like terms. Subtract 170,000 from both sides. The amount invested in the bond fund is $2500. The amount invested in the stock fund is $10,000 x, or $7500. Skill Practice 6. Winston borrowed $4000 in two loans. One loan charged 7% interest, and the other charged 1.5% interest. After 1 year, Winston paid $225 in interest. Find the amount borrowed in each loan account. How many liters (L) of a 60% antifreeze solution must be added to 8 L of a 10% antifreeze solution to produce a 20% antifreeze solution? Skill Practice Answers 6. $3000 was borrowed at 7% interest, and $1000 was borrowed at 1.5% interest. 55 Solution: x L of solution 8 L of solution (8 x) L of solution 60% Antifreeze Number of liters of solution Number of liters of pure antifreeze x 0.60x Notice that an algebraic equation is derived from the second row of the table which relates the number of liters of pure antifreeze in each container. The amount of pure antifreeze in the final solution equals the sum of the amounts of antifreeze in the first two solutions. a pure antifreeze pure antifreeze Pure antifreeze b ba ba in the final solution from solution 2 from solution 1 0.60x 0.10(8) 0.20(8 x) Mathematical model Apply the distributive property. Subtract 0.2x from both sides. 0.60x 0.10(8) 0.20(8 x) 0.6x 0.8 1.6 0.2x 0.6x 0.2x 0.8 1.6 0.2x 0.2x 0.4x 0.8 1.6 0.4x 0.8 0.8 1.6 0.8 0.4x 0.8 0.4x 0.8 0.4 0.4 x2 Answer: 2 L of 60% antifreeze solution is necessary to make a final solution of 20% antifreeze. Skill Practice 7. Find the number of ounces (oz) of 30% alcohol solution that must be mixed with 10 oz of a 70% solution to obtain a solution that is 40% alcohol. Skill Practice Answers 7. 30 oz of the 30% solution is needed. 56 A hiker can hike 21 2 mph down a trail to visit Archuletta Lake. For the return trip back to her campsite (uphill), she is only able to go 11 2 mph. If the total time for the round trip is 4 hr 48 min (4.8 hr), find a. The time required to walk down to the lake b. The time required to return back to the campsite c. The total distance the hiker traveled Solution: Column 2: The rates of speed going to and from the lake are given in the statement of the problem. Column 3: There are two unknown times. If we let t be the time required to go to the lake, then the time for the return trip must equal the total time minus t, or (4.8 t) Column 1: To express the distance in terms of the time t, we use the relationship d rt. That is, multiply the quantities in the second and third columns. To create a mathematical model, note that the distances to and from the lake are equal. Therefore, (Distance to lake) (return distance) 2.5t 1.5(4.8 t) 2.5t 7.2 1.5t 2.5t 1.5t 7.2 1.5t 1.5t 4.0t 7.2 4.0t 7.2 4.0 4.0 t 1.8 Solve for t and interpret the results. Verbal model Mathematical model Apply the distributive property. Add 1.5t to both sides. 57 Answers: a. Because t represents the time required to go down to the lake, 1.8 hr is required for the trip to the lake. b. The time required for the return trip is (4.8 t) or (4.8 hr 1.8 hr) 3 hr. Therefore, the time required to return to camp is 3 hr. c. The total distance equals the distance to the lake and back. The distance to the lake is (2.5 mph)(1.8 hr) 4.5 mi. The distance back is (1.5 mph) (3.0 hr) 4.5 mi. Therefore, the total distance the hiker walked is 9.0 mi. Skill Practice 8. Jody drove a distance of 320 mi to visit a friend. She drives part of the time at 40 mph and part at 60 mph. The trip took 6 hr. Find the amount of time she spent driving at each speed. Section 1.5 Boost your GRADE at mathzone.com! Practice Exercises Practice Problems Self-Tests NetTutor e-Professors Videos Review Exercises For Exercises 311, solve the equations. 3. 7a 2 11 6. 3(y 5) 4 1 9. 3 3 3 p p 8 4 2 4. 2z 6 15 7. 5(b 4) 3(2b 8) 3b 10. 1 2x 5 4 5. 4(x 3) 7 19 8. 12c 3c 9 3(4 7c) c 11. 0.085(5)d 0.075(4)d 1250 For the remaining exercises, follow the steps outlined in the Problem-Solving Flowchart found on page 49. 58 14. The sum of 3 times a number and 2 is the same as the difference of the number and 4. Find the number. 15. Twice the sum of a number and 3 is the same as 1 subtracted from the number. Find the number. 16. The sum of two integers is 30. Ten times one integer is 5 times the other integer. Find the integers. (Hint: If one number is x, then the other number is 30 x.) 17. The sum of two integers is 10. Three times one integer is 3 less than 8 times the other integer. Find the integers. (Hint: If one number is x, then the other number is 10 x.) 59 31. In the 1996 presidential election, a third party candidate received a significant number of votes. The figure illustrates the number of votes received for Bill Clinton, Bob Dole, and Ross Perot in that election. Compute the percent of votes received by each candidate. (Round to the nearest tenth of a percent.) 32. The total bill (including a 6% sales tax) to have a radio installed in a car came to $265. What was the cost before tax? 33. Wayne County has a sales tax rate of 7%. How much does Mikes Honda Civic cost before tax if the total cost of the car plus tax is $13,888.60? 34. The price of a swimsuit after a 20% markup is $43.08. What was the price before the markup? 35. The price of a used textbook after a 35% markdown is $29.25. What was the original price? 36. In 2006, 39.6 million people lived below the poverty level in the United States. This represents an 80% increase from the number in 2002. How many people lived below the poverty level in 2002? 37. In 2006, Americans spent approximately $69 billion on weddings. This represents a 50% increase from the amount spent in 2001. What amount did Americans spend on weddings in 2001? 60 61 Section 1.6 Concepts 1. Applications Involving Geometry 2. Literal Equations The length of a rectangular corral is 2 ft more than 3 times the width. The corral is situated such that one of its shorter sides is adjacent to a barn and does not require fencing. If the total amount of fencing is 774 ft, then find the dimensions of the corral. Solution: 3x 2 x 3x 2 Figure 1-8 Label variables. To create a verbal model, we might consider using the formula for the perimeter of a rectangle. However, the formula P 2L 2W incorporates all four sides of the rectangle. The formula must be modified to include only one factor of the width. a 1 times 2 times Distance around b ba ba the width the length three sides 774 2(3x 2) Solve for x. Apply the distributive property. Combine like terms. Subtract 4 from both sides. Divide by 7 on both sides. x Verbal model Mathematical model Because x represents the width, the width of the corral is 110 ft. The length is given by 3x 2 or 3 1 110 2 2 332 Interpret the results. The width of the corral is 110 ft, and the length is 332 ft. (To check the answer, verify that the three sides add to 774 ft.) 62 Skill Practice 1. The length of Karens living room is 2 ft longer than the width. The perimeter is 80 ft. Find the length and width. The applications involving angles utilize some of the formulas found in the front cover of this text. Example 2 Two angles are complementary. One angle measures 10 less than 4 times the other angle. Find the measure of each angle (Figure 1-9). (4x 10) Solution: Let Let x 4x 10 Figure 1-9 Recall that two angles are complementary if the sum of their measures is 90. Therefore, a verbal model is x 1 4x 10 2 90 1 One angle 2 1 the complement of the angle 2 90 Verbal model Mathematical equation Solve for x. 5x 10 90 5x 100 x 20 2. Two angles are supplementary, and the measure of one is 16 less than 3 times the other. Find their measures. 2. Literal Equations Literal equations (or formulas) are equations that contain several variables. For example, the formula for the perimeter of a rectangle P 2L 2W is an example of a literal equation. In this equation, P is expressed in terms of L and W. However, in science and other branches of applied mathematics, formulas may be more useful in alternative forms. For example, the formula P 2L 2W can be manipulated to solve for either L or W: Solve for L P 2L 2W P 2W 2L Skill Practice Answers 1. The length is 21 ft, and the width is 19 ft. 2. 49 and 131 P 2W L 2 L P 2W 2 63 To solve a literal equation for a specified variable, use the addition, subtraction, multiplication, and division properties of equality. Example 3 The formula for the volume of a rectangular box is V LWH. a. Solve the formula V LWH for W. b. Find the value of W if V 200 in. , L 20 in., and H 5 in. (Figure 1-10). 3 Solution: a. V LWH V LWH LH LH V W LH W V LH The goal is to isolate the variable W. Divide both sides by LH. Simplify. b. W W 2 in. Skill Practice 3a. Solve the formula for h. b. Find the value of h when A 40 in. 2 and b 16 in. Example 4 The formula to find the area of a trapezoid is given by A 1 2 1 b1 b2 2 h, where b2 b1 and b2 are the lengths of the parallel sides and h is the height. Solve this formula for b1. h Solution: A1 2 1 b1 b2 2 h The goal is to isolate b1. Multiply by 2 to clear fractions. Apply the distributive property. b1 64 Skill Practice 4. The formula for the volume of a right circular cylinder is V pr 2h. Solve for h. r TIP: When solving a literal equation for a specified variable, there is sometimes more than one way to express your final answer. This flexibility often presents difficulty for students. Students may leave their answer in one form, but the answer given in the text looks different. Yet both forms may be correct. To know if your answer is equivalent to the form given in the text you must try to manipulate it to look like the answer in the book, a process called form fitting. The literal equation from Example 4 may be written in several different forms. The quantity 1 2A b2h 2 h can be split into two fractions. b1 b2h 2A b2h 2A 2A b2 h h h h Example 5 2x 3y 5 3y 2x 5 3y 2x 5 3 3 y Skill Practice 2x 5 3 Solve for y. 5. 5x 2y 11 Example 6 Buckingham Fountain is one of Chicagos most familiar landmarks. With 133 jets spraying a total of 14,000 gal (gallons) of water per minute, Buckingham Fountain is one of the worlds largest fountains. The circumference of the fountain is approximately 880 ft. a. The circumference of a circle is given by C 2pr. Solve the equation for r. b. Use the equation from part (a) to find the radius and diameter of the fountain. (Use the p key on the calculator, and round the answers to 1 decimal place.) 65 Solution: a. C 2pr C 2pr 2p 2p C r 2p r C 2p Substitute C 880 ft and use the p key on the calculator. b. r 880 ft 2p r 140.1 ft The radius is approximately 140.1 ft. The diameter is twice the radius (d 2r); therefore the diameter is approximately 280.2 ft. Skill Practice The formula to compute the surface area S of a sphere is given by S 4pr 2. Skill Practice Answers 6a. p S 4r 2 b. 3.14 6a. Solve the equation for p. b. A sphere has a surface area of 113 in.2 and a radius of 3 in. Use the formula found in part (a) to approximate p. Round to 2 decimal places. Section 1.6 Boost your GRADE at mathzone.com! Practice Exercises Practice Problems Self-Tests NetTutor e-Professors Videos Review Exercises For Exercises 2 5, solve the equations. 2. 7 5x 1 2x 6 2 6 1 x 1 2 21 4. 3 3 z 1 2 3z 2 4 4 z 7 3. 3 y 3 2y 5 5 5. 2a 4 8a 7a 8 3a 66 House 11 1 2 yd Dog run 11. George built a rectangular pen for his rabbit such that the length is 7 ft less than twice the width. If the perimeter is 40 ft, what are the dimensions of the pen? 12. Antoine wants to put edging in the form of a square around a tree in his front yard. He has enough money to buy 18 ft of edging. Find the dimensions of the square that will use all the edging. 13. Joanne wants to plant a flower garden in her backyard in the shape of a trapezoid, adjacent to her house (see the figure). She also wants a front yard garden in the same shape, but with sides one-half as long. What should the dimensions be for each garden if Joanne has only a total of 60 ft of fencing? 14. The measures of two angles in a triangle are equal. The third angle measures 2 times the sum of the equal angles. Find the measures of the three angles. 15. The smallest angle in a triangle is one-half the size of the largest. The middle angle measures 25 less than the largest. Find the measures of the three angles. 16. Two angles are complementary. One angle is 5 times as large as the other angle. Find the measure of each angle. 17. Two angles are supplementary. One angle measures 12 less than 3 times the other. Find the measure of each angle. 2x x Back x House Front 67 In Exercises 1825, solve for x, and then find the measure of each angle. 18. (7x 1) (2x 1) 19. 20. 21. (2x 3) (x 2.5) [3(x 7)] (2x 5) 22. (2 x) 23. (3x 3) [3(5x 1)] (5x 1) (x 35) 24. [4(x 6)] (2 x 2) 25. (10x) (x 2) (20x 4) 68 For Exercises 3047, solve for the indicated variable. 30. A lw for l for b for C 31. C1 5 2R for R for K1 for F for a for w for B 32. I Prt for P for x for v2 for b2 for y for h 35. y mx b 2 38. K 1 2 mv 42. w p 1 v2 v1 2 45. P 2L 2W for v2 for L 43. A lw 1 46. V Bh 3 In Chapter 2 it will be necessary to change equations from the form Ax By C to y mx b. For Exercises 4859, express each equation in the form y mx b by solving for y. 48. 3x y 6 51. 4x 5y 25 54. 3x 3y 6 1 57. 4x y 5 3 49. x y 4 52. 6x 2y 13 55. 2x 2y 8 2 58. x y 0 3 50. 5x 4y 20 53. 5x 7y 15 4 56. 9x y 5 3 1 59. x y 0 4 For Exercises 6061, use the relationship between distance, rate, and time given by d rt. 60. a. Solve d rt for rate r. b. In 2006, Sam Hornish won the Indianapolis 500 in 3 hr, 10 min, 59 sec 1 3.183 hr 2 . Find his average rate of speed if the total distance is 500 mi. Round to the nearest tenth of a mile per hour. 61. a. Solve d rt for time t. b. In 2006, Jimmie Johnson won the Daytona 500 with an average speed of 141.734 mph. Find the total time it took for him to complete the race if the total distance is 500 miles. Round to the nearest hundredth of an hour. For Exercises 6263, use the fact that the force imparted by an object is equal to its mass times acceleration, or F ma. 62. a. Solve F ma for mass m. b. The force on an object is 24.5 N (newtons), and the acceleration due to gravity is 9.8 m/sec2. Find the mass of the object. (The answer will be in kilograms.) 63. a. Solve F ma for acceleration a. b. Approximate the acceleration of a 2000-kg mass influenced by a force of 15,000 N. (The answer will be in meters per second squared, m/sec2.) 69 74. ax by cx z Section 1.7 Concepts 1. Solving Linear Inequalities 2. Inequalities of the Form axb 3. Applications of Inequalities Now consider the inequality x 3. The solution set to an inequality is the set of real numbers that makes the inequality a true statement. In this case, the solution set is all real numbers less than or equal to 3. Because the solution set has an infinite number of values, the values cannot be listed. Instead, we can graph the solution set or represent the set in interval notation or in set-builder notation. Graph 5 4 3 2 1 0 1 2 3 4 5 Interval Notation 1 , 3 4 Set-Builder Notation 5x 0 x 36 The addition and subtraction properties of equality indicate that a value added to or subtracted from both sides of an equation results in an equivalent equation. The same is true for inequalities. 70 Example 1 Solve the inequality. Graph the solution and write the solution set in interval notation. 3x 7 7 2 1 x 4 2 1 Solution: 3x 2x 7 7 2x 2x 9 x 7 7 9 x 7 7 7 9 7 x 7 2 Graph 4 3 2 1 Interval Notation 1 2, 2 Skill Practice 1. Solve the inequality. Graph the solution and write the solution in interval notation. 4 1 2x 1 2 7 7x 1 Multiplying both sides of an equation by the same quantity results in an equivalent equation. However, the same is not always true for an inequality. If you multiply or divide an inequality by a negative quantity, the direction of the inequality symbol must be reversed. For example, consider multiplying or dividing the inequality 4 6 5 by 1. Multiply/divide by 1: 45 4 5 6 5 4 3 2 1 4 5 0 1 2 3 4 5 6 45 ( 5 The number 4 lies to the left of 5 on the number line. However, 4 lies to the right of 5. Changing the signs of two numbers changes their relative position on the number line. This is stated formally in the multiplication and division properties of inequality. 71 The second statement indicates that if both sides of an inequality are multiplied or divided by a negative quantity, the inequality sign must be reversed. *These properties may also be stated for a b, a 7 b, and a b. Example 2 Solve the inequalities. Graph the solution and write the solution set in interval notation. a. 2x 5 6 2 Solution: a. 2x 5 6 2 2x 5 5 6 2 5 2x 6 7 7 2x 7 2 2 x 7 Graph 7 2 7 2 5 4 3 2 1 TIP: The inequality 2 x 5 6 2 could have been solved by isolating x on the right-hand side of the inequality. This creates a positive coefficient on the x term and eliminates the need to divide by a negative number. 2x 5 6 2 5 6 2x 2 7 6 2x 7 2x 6 2 2 Add 2x to both sides. Subtract 2 from both sides. Divide by 2 (because 2 is positive, do not reverse the inequality sign). 7 (Note that the inequality 7 2 6 x is equivalent to x 7 2 . 2 7 6 x 2 72 b. 6 1 x 3 2 2 2 1 x 8 2 6x 18 2 2x 16 6x 18 18 2x 6x 2x 18 18 2x 2x 4x 18 18 4x 18 18 18 18 4x 0 4x 0 4 4 x0 Graph 5 4 3 2 1 0 1 2 3 4 5 Apply the distributive property. Combine like terms. Add 2x to both sides. Interval Notation 1 , 0 4 Skill Practice Solve the inequalities. Graph the solution and write the solution in interval notation. 3. 5 1 3x 1 2 6 4 1 5x 5 2 2. 4x 12 20 Example 3 5x 2 7 x 2. Graph the solution and write the 3 solution set in interval notation. Solve the inequality Solution: Multiply by 3 to clear fractions (reverse the inequality sign). Add 3x to both sides. Graph 3 2 1 0 1 2 3 4 5 6 3. 1 , 8 4 1 5, 2 73 Skill Practice Solve the inequality. Graph the solution and write the solution in interval notation. 4. x1 x 1 3 In Example 3, the inequality sign was reversed twice: once for multiplying the inequality by 3 and once for dividing by 2. If you are in doubt about whether you have the inequality sign in the correct direction, you can check your final answer by using the test point method. That is, pick a point in the proposed solution set, and verify that it makes the original inequality true. Furthermore, any test point picked outside the solution set should make the original inequality false. 3 2 1 0 1 2 3 4 5 1 0 2 2 ? 7 102 2 3 2 ? 7 2 3 False 5 1 5 2 2 ? 7 152 2 3 23 ? 7 7 3 72 3 7 7 ? True Because a test point to the right of x 4 makes the inequality true, we have shaded the correct part of the number line. a 6 x and x 6 b The solution to the compound inequality a 6 x 6 b is the intersection of the inequalities a 6 x and x 6 b. To solve a compound inequality of this form, we can actually work with the inequality as a three-part inequality and isolate the variable x. Skill Practice Answers 4. 3 2, 2 2 74 Example 4 Solve the inequality 2 3x 1 6 5. Graph the solution and express the solution set in interval notation. Solution: To solve the compound inequality 2 3x 1 6 5, isolate the variable x in the middle. The operations performed on the middle portion of the inequality must also be performed on the left-hand side and right-hand side. 2 3x 1 6 5 2 1 3x 1 1 6 5 1 3 3x 6 4 3x 4 3 6 3 3 3 1 x 6 Graph 4 3 Subtract 1 from all three parts of the inequality. Simplify. Divide by 3 in all three parts of the inequality. Simplify. Interval Notation 4 3 4 3 2 1 ( 0 1 2 3 4 4 c 1, b 3 Skill Practice 5. Solve the compound inequality. Graph the solution and express the solution set in interval notation. 8 6 5x 3 12 3. Applications of Inequalities Example 5 Beth received grades of 87%, 82%, 96%, and 79% on her last four algebra tests. To graduate with honors, she needs at least a B in the course. a. What grade does she need to make on the fifth test to get a B in the course? Assume that the tests are weighted equally and that to earn a B the average of the test grades must be at least 80% but less than 90%. b. Is it possible for Beth to earn an A in the course if an A requires an average of 90% or more? Solution: a. Let x represent the score on the fifth test. Skill Practice Answers 5. 1 87 82 96 79 x 5 1 1, 3 4 75 Verbal model Mathematical model Multiply by 5 to clear fractions. Simplify. Subtract 344 from all three parts. Simplify. 400 344 x 6 450 400 344 344 344 x 6 450 344 56 x 6 106 To earn a B in the course, Beth must score at least 56% but less than 106% on the fifth exam. Realistically, she may score between 56% and 100% because a grade over 100% is not possible. b. To earn an A, Beths average would have to be greater than or equal to 90%. 1 Average of test scores 2 90 Verbal model Mathematical equation Clear fractions. Simplify. Solve for x. 87 82 96 79 x 90 5 5a 87 82 96 79 x b 5 1 90 2 5 344 x 450 x 106 It would be impossible for Beth to earn an A in the course because she would have to earn at least a score of 106% on the fifth test. It is impossible to earn over 100%. Skill Practice 6. Jamie is a salesman who works on commission, so his salary varies from month to month. To qualify for an automobile loan, his salary must average at least $2100 for 6 months. His salaries for the past 5 months have been $1800, $2300, $1500, $2200, and $2800. What amount does he need to earn in the last month to qualify for the loan? Example 6 The number of registered passenger cars N (in millions) in the United States has risen between 1960 and 2005 according to the equation N 2.5t 64.4, where t represents the number of years after 1960 (t 0 corresponds to 1960, t 1 corresponds to 1961, and so on) (Figure 1-11). 76 Number of Registered Passenger Cars, United States, 1960 2005 N 2.5t 64.4 40 a. For what years after 1960 was the number of registered passenger cars less than 89.4 million? b. For what years was the number of registered passenger cars between 94.4 million and 101.9 million? c. Predict the years for which the number of passenger cars will exceed 154.4 million. Solution: 6 89.4 Substitute the expression 2.5t 64.4 for N. Subtract 64.4 from both sides. 2.5t 64.4 6 89.4 2.5t 64.4 64.4 6 89.4 64.4 2.5t 6 25 25 2.5t 6 2.5 2.5 t 6 10 Before 1970, the number of registered passenger cars was less than 89.4 million. b. We require 94.4 6 N 6 101.9. Hence 94.4 6 2.5t 64.4 6 101.9 Substitute the expression 2.5t 64.4 for N. Subtract 64.4 from all three parts of the inequality. 30.0 6 2.5t 6 37.5 30.0 2.5t 37.5 6 6 2.5 2.5 2.5 12 6 t 6 15 Divide by 2.5. t 12 corresponds to 1972 and t 15 corresponds to 1975. Between the years 1972 and 1975, the number of registered passenger cars was between 94.4 million and 101.9 million. 77 c. We require N 7 154.4. 2.5t 64.4 7 154.4 2.5t 7 90 2.5t 90 7 2.5 2.5 t 7 36 Substitute the expression 2.5t 64.4 for N. Subtract 64.4 from both sides. Divide by 2.5. t 36 corresponds to the year 1996. After the year 1996, the number of registered passenger cars exceeded 154.4 million. Skill Practice 7. The population of Alaska has steadily increased since 1950 according to the equation P 10t 117, where t represents the number of years after 1950 and P represents the population in thousands. For what years after 1950 was the population less than 417 thousand people? Section 1.7 Boost your GRADE at mathzone.com! Practice Exercises Practice Problems Self-Tests NetTutor e-Professors Videos Review Exercises 3. Solve for v. 4. Solve for x. d vt 16t2 4 5 1 4 2x 2 2 1 x 1 2 4 5. Five more than 3 times a number is 6 less than twice the number. Find the number. 6. Solve for y. 5x 3y 6 0 7. a. The area of a triangle is given by A 1 2 bh. Solve for h. b. If the area of a certain triangle is 10 cm2 and the base is 3 cm, find the height. 8. Solve for t. 1 1 1 2 3 1 t t t 5 2 10 5 10 2 78 12. 6z 3 7 16 13. 8w 2 13 14. 2 t 6 8 3 2 1 2x 1 2 7 10 5 15. 1 p 3 1 5 16. 3 1 8y 9 2 6 3 4 17. 20. 5x 7 6 22 3k 2 4 5 21. 3w 6 7 9 5 3 22. x 6 4 23. 24. 3p 1 7 5 2 3 21 25. y 7 2 16 29. 1 6 3 4 1 3b 1 2 For Exercises 3445, solve the compound inequalities. Graph the solution and write the solution set in interval notation. 34. 0 3a 2 6 17 35. 8 6 4k 7 6 11 36. 5 6 4y 3 6 21 37. 7 3m 5 6 10 1 38. 1 x 12 13 5 y 3 8 6 1 39. 5 a 1 6 9 4 40. 4 7 2x 8 5 2 41. 5 42. 6 2b 3 7 6 79 43. 4 7 3w 7 2 44. 8 7 w 4 7 1 80 55. Between the years 1960 and 2006, the average gas mileage (miles per gallon) for passenger cars has increased. The equation N 12.6 0.214t approximates the average gas mileage corresponding to the year t, where t 0 represents 1960, t 1 represents 1961, and so on. a. For what years after 1960 was the average gas mileage less than 14.1 mpg? (Round to the nearest year.) b. For what years was the average gas mileage between 17.1 and 18.0 mpg? (Round to the nearest year.) Mixed Exercises For Exercises 5673, solve the inequalities. Graph the solution, and write the solution set in interval notation. Check each answer by using the test point method. 56. 6p 1 7 17 57. 4y 1 11 58. 3 x81 4 2 59. a 3 7 5 5 62. 1 6 3 1 2t 4 2 12 63. 4 2 1 5h 3 2 6 14 for c 7 0 for c 6 0 81 Section 1.8 Concepts 1. Properties of Exponents 2. Simplifying Expressions with Exponents 3. Scientific Notation Properties of Exponents* Description Multiplication of like bases Division of like bases Power rule Power of a product Power of a quotient m Property b b b n mn 2 Example b b b b6 4 24 b b 1b b2 1b b b b2 b6 2 4 Details/Notes bm bm n bn 1 bm 2 n bm n 1 ab 2 m ambm a m am a b m b b b5 b5 2 b2 b3 1 ab 2 3 a3b3 a 3 a3 a b 3 b b 1 b4 2 2 b4 2 b8 bbbbb b5 2 bb b b3 1 b4 2 2 1 b b b b 2 1 b b b b 2 b8 a 3 a a a a b a ba ba b b b b b aaa a3 3 bbb b 1 ab 2 3 1 ab 2 1 ab 2 1 ab 2 1 a a a 2 1 b b b 2 a3b3 In addition to the properties of exponents, two definitions are used to simplify algebraic expressions. b0 and bn Let n be an integer, and let b be a real number such that b 1. b 1 0 0. 1 n 1 2. bn a b n b b The definition of b0 is consistent with the properties of exponents. For example, if b is a nonzero real number and n is an integer, then bn 1 bn The expression b0 1 bn bn n b0 bn 82 The definition of bn is also consistent with the properties of exponents. If b is a nonzero real number, then b3 bbb 1 2 5 bbbbb b b The expression b2 b3 b3 5 b2 b5 Example 1 a. 1 2 2 4 1 b2 Solution: a. 1 2 2 4 1 2 2 1 2 21 2 2 1 2 2 b. 24 1 2 2 2 2 2 16 c. 24 1 24 1 12 2 2 22 1 16 1 16 because b0 1 16 d. 1 7x 2 0 1 e. 7x0 7 x0 7 1 7 Skill Practice 1. 1 3 2 2 4. 1 8y 2 0 5. 6 0 Simplify the following expressions. Write the final answer with positive exponents only. Skill Practice Answers 1. 9 4. 1 2. 9 5. 1 3. 1 9 83 Solution: a. 1 x7x3 2 2 1 x7 132 2 2 1 x4 2 2 x 8 Multiply like bases by adding exponents. Apply the power rule. Multiply exponents. 1 3 b. a b 1 2 2 2 30 5 1 2 53 a b 30 2 125 c. a 1 1 4 Simplify negative exponents. Evaluate the exponents. Write the expressions with a common denominator. Simplify. Work within the parentheses first. Divide like bases by subtracting exponents. Simplify within parentheses. 6 1 1 4 500 4 4 4 503 4 4 y3w10 yw 5 1 y3 5w10 4 2 1 1 y2w6 2 1 2 1 1y 2 1w 2 y2w6 y2 a d. a y 1 b or 6 6 w w Simplify negative exponents. Subtract exponents within first 2 1 parentheses. Simplify 8 to 4 . In the second parentheses, replace b0 by 1. Simplify inside parentheses. Apply the power rule. Multiply exponents. Simplify negative exponents. Multiply factors in the numerator and denominator. Simplify. a6b6 b 1 6 2 2a2 43 a2 d 1 6 2 2 84 Skill Practice Simplify the expressions. Write the final answers with positive exponents only. 2 1 1 0 7. a b 4 1 a b 3 4 9. 1 x 3y 4 2 2 1 x 2y 2 4 6. 1 a5b 3 2 4 8. a 2b 3c 3 3 b 4b 2c 3. Scientific Notation Scientists in a variety of fields often work with very large or very small numbers. For instance, the distance between the Earth and the Sun is approximately 93,000,000 mi. The national debt in the United States in 2004 was approximately $7,380,000,000,000. The mass of an electron is 0.000 000 000 000 000 000 000 000 000 000 911 kg. Scientific notation was devised as a shortcut method of expressing very large and very small numbers. The principle behind scientific notation is to use a power of 10 to express the magnitude of the number. Consider the following powers of 10: 100 1 101 10 102 100 103 1000 104 10,000 101 102 103 104 1 1 0.1 1 10 10 1 1 0.01 2 100 10 1 1 0.001 1000 103 1 1 0.0001 10,000 104 Each power of 10 represents a place value in the base-10 numbering system. A number such as 50,000 may therefore be written as 5 10,000 or equivalently 1 as 5.0 104. Similarly, the number 0.0035 is equal to 3.5 1000 or, equivalently, 3 3.5 10 . A number expressed in the form a 10n, where 1 0 a 0 6 10 and n is an integer, is said to be written in scientific notation. Consider the following numbers in scientific notation: The distance between the Sun and the Earth: 93,000,000 mi 9.3 107 mi 7 places The national debt of the United States in 2004: $7,380,000,000,000 $7.38 1012 Skill Practice Answers a 20 b 12 1 8. 8b 3c12 6. 3 4 x 14 9. 12 y 7. 12 places 0.000 000 000 000 000 000 000 000 000 000 911 kg 9.11 1031 kg 31 places 85 In each case, the power of 10 corresponds to the number of place positions that the decimal point is moved. The power of 10 is sometimes called the order of magnitude (or simply the magnitude) of the number. The order of magnitude of the national debt is 1012 dollars (trillions). The order of magnitude of the distance between the Earth and Sun is 107 mi (tens of millions). The mass of an electron has an order of magnitude of 1031 kg. Example 3 Fill in the table by writing the numbers in scientific notation or standard notation as indicated. Quantity Number of NASCAR fans Width of an influenza virus Cost of hurricane Andrew Probability of winning the Florida state lottery Approximate width of a human red blood cell Profit of Citigroup Bank, 2003 0.000007 m $1.53 1010 Standard Notation 75,000,000 people 0.000000001 m $2.65 1010 4.35587878 10 8 Scientific Notation Solution: Quantity Number of NASCAR fans Width of an influenza virus Cost of hurricane Andrew Probability of winning the Florida state lottery Approximate width of a human red blood cell Profit of Citigroup Bank, 2003 Standard Notation 75,000,000 people 0.000000001 m $26,500,000,000 0.0000000435587878 0.000007 m $15,300,000,000 Scientific Notation 7.5 107 people 1.0 10 9 m $2.65 1010 4.35587878 10 8 7.0 10 6 m $1.53 1010 Skill Practice Calculator Connections Calculators use scientific notation to display very large or very small numbers. To enter scientific notation in a calculator, try using the EE key or the EXP key to express the power of 10. 86 Example 4 a. The U.S. national debt in 2005 was approximately $7,830,000,000,000. Assuming there were approximately 290,000,000 people in the United States at that time, determine how much each individual would have to pay to pay off the debt. b. The mean distance between the Earth and the Andromeda Galaxy is approximately 1.8 106 light-years. Assuming 1 light-year is 6.0 1012 mi, what is the distance in miles to the Andromeda Galaxy? Solution: a. Divide the total U.S. national debt by the number of people: 7.83 1012 2.9 108 a 7.83 1012 ba 8b 2.9 10 Divide 7.83 by 2.9 and subtract the powers of 10. 2.7 104 In standard notation, this amounts to approximately $27,000 per person. b. Multiply the number of light-years by the number of miles per light-year. 1 1.8 106 21 6.0 1012 2 1 1.8 21 6.0 2 1 106 2 1 1012 2 10.8 1018 Multiply 1.8 and 6.0 and add the powers of 10. The number 10.8 1018 is not in proper scientific notation because 10.8 is not between 1 and 10. Rewrite 10.8 as 1.08 101. Apply the associative property of multiplication. Calculator Connections Use a calculator to check the solutions to Example 4. 1.08 1019 The distance between the Earth and the Andromeda Galaxy is 1.08 1019 mi. Skill Practice 14. The thickness of a penny is 6.1 102 in. The height of the Empire State Building is 1250 ft (1.5 104 in.). How many pennies would have to be stacked on top of each other to equal the height of the Empire State Building? Round to the nearest whole unit. 15. The distance from Earth to the nearby star, Barnards Star, is 7.6 light years (where 1 light year 6.0 1012 mi). How many miles away is Barnards Star? 87 Section 1.8 Boost your GRADE at mathzone.com! Practice Exercises Practice Problems Self-Tests NetTutor e-Professors Videos Review Exercises For Exercises 36, solve the equation or inequality. Write the solutions to the inequalities in interval notation. 3. 3a 2 1 a2 3 4 2 4. y 2 2y 6 3 5 2 5. 6x 2 1 x 3 2 7 1 x 1 2 4 6. 5c 3 1 c 2 2 7 6c 8 For Exercises 78, solve the equation for the indicated variable. 7. 5x 9y 11 for x 8. 2x 3y 8 for y For Exercises 1116, write two examples of each property. Include examples with and without variables. (Answers may vary.) 11. bn bm bn m 14. bn bn m bm 1b 02 12. 1 ab 2 n anbn 13. 1 bn 2 m bnm 1b a n an 15. a b n b b 1b 02 0 16. b 1 02 2 2 17. Simplify: a b 3 1 2 18. Simplify: a b 3 For Exercises 1934, simplify. 19. 52 23. 1 5 2 2 3 4 27. a b 2 31. 1 10ab 2 0 20. 82 24. 1 8 2 2 1 2 28. a b 9 32. 1 13x 2 0 21. 52 1 3 25. a b 4 2 3 29. a b 5 33. 10ab0 22. 82 3 1 26. a b 8 1 5 30. a b 2 34. 13x0 88 51. 52. 53. 54. 55. 56. 60. 32 31 66. m1n3 m4n2 67. 48ab10 32a4b3 68. 25x2y12 10x5y7 69. 1 3x4y5z2 2 4 73. 1 p2q 2 3 1 2pq4 2 2 77. 1 8a2b2 2 4 1 16a3b7 2 2 2x3y0 4x6y b 5 2 70. 1 6a2b3c 2 2 74. 1 mn3 2 2 1 5m2n2 2 78. 1 3x2y3 2 2 1 2xy4 2 3 a3b2c0 2 b a1b2c3 81. a 82. a 83. 3xy5 a 2x4y 6x5y b 3 84. 7x3y4 a 89 87. Write the numbers in standard notation. a. The number of $20 bills in circulation in 2004 was 5.2822 109. b. The dissociation constant for acetic acid is 1.8 105. c. In 2004, the population of the world was approximately 6.378 109. 88. Write the numbers in standard notation. a. The proposed budget for the 2006 federal government allocated $5.6 1010 for the Department of Education. b. The mass of a neutron is 1.67 1024 g. c. The number of $2 bills in circulation in 2004 was 6.8 108. For Exercises 8994, determine which numbers are in proper scientific notation. If the number is not in proper scientific notation, correct it. 89. 35 104 92. 8.12 101 90. 0.469 107 93. 9 101 91. 7.0 100 94. 6.9 100 For Exercises 95102, perform the indicated operations and write the answer in scientific notation. 95. 1 6.5 103 2 1 5.2 108 2 99. 1 8.5 102 2 1 2.5 1015 2 100. 1 3 109 2 1 1.5 1013 2 102. 1 0.0000000002 2 1 8,000,000 2 96. 1 3.26 106 21 8.2 109 2 97. (0.0000024)(6,700,000,000) 103. If one H2O molecule contains 2 hydrogen atoms and 1 oxygen atom, and 10 H2O molecules contain 20 hydrogen atoms and 10 oxygen atoms, how many hydrogen atoms and oxygen atoms are contained in 6.02 1023 H2O molecules? 104. The star named Alpha Centauri is 4.3 light-years from the Earth. If there is approximately 6 109 mi in 1 light-year, how many miles away is Alpha Centauri? 105. The county of Queens, New York, has a population of approximately 2,200,000. If the area is 110 mi2, how many people are there per square mile? 106. The county of Catawba, North Carolina, has a population of approximately 150,000. If the area is 400 mi2, how many people are there per square mile? 110. 111. 112. 113. At one count per second, how many days would it take to count to 1 million? (Round to 1 decimal place.) 114. Do you know anyone who is more than 1.0 109 sec old? If so, who? 115. Do you know anyone who is more than 4.5 105 hr old? If so, who? 90 Chapter 1 Section 1.1 Key Concepts SUMMARY Sets of Numbers and Interval Notation Examples Natural numbers: 5 1, 2, 3, . . . 6 Whole numbers: 5 0, 1, 2, 3, . . . 6 Integers: 5 . . . , 3, 2, 1, 0, 1, 2, 3, . . . 6 p Rational numbers: e 0 p and q are integers and q q does not equal 0 f Irrational numbers: {x x is a real number that is not rational} Real numbers: 5 x 0 x is rational or x is irrational 6 a a a a a b b b b xb a a a a x is is is is is less than b greater than b less than or equal to b greater than or equal to b between a and b Example 1 Some rational numbers are: 1 7, Example 2 Set-Builder Notation Interval Notation 5x 0 x 7 36 5x 0 x 36 5x 0 x 6 36 5x 0 x 36 1 3, 2 Graph ( 3 3 3 3, 2 1 , 3 2 1 , 3 4 Intersection B A B ( 3 3 Example 3 A B is the union of A and B and is the set of elements that belong to set A or set B or both sets A and B. A B is the intersection of A and B and is the set of elements common to both A and B. AB AB Union A Summary 91 Section 1.2 Key Concepts The reciprocal of a number a 0 is The opposite of a number a is a. The absolute value of a, denoted 0 a 0 , is its distance from zero on the number line. Addition of Real Numbers Same Signs: Add the absolute values of the numbers, and apply the common sign to the sum. Unlike Signs: Subtract the smaller absolute value from the larger absolute value. Then apply the sign of the number having the larger absolute value. Subtraction of Real Numbers Add the opposite of the second number to the first number. Multiplication and Division of Real Numbers Same Signs: Product or quotient is positive. Opposite Signs: Product or quotient is negative. The product of any real number and 0 is 0. The quotient of 0 and a nonzero number is 0. The quotient of a nonzero number and 0 is undefined. Example 2 3 1 4 2 7 5 7 2 3 0 is undefined Exponents and Radicals b b b b b (b is the base, 4 is the exponent) 1b is the principal square root of b (b is the radicand, 1 is the radical sign). 4 Order of Operations 1. Simplify expressions within parentheses and other grouping symbols first. 2. Evaluate expressions involving exponents, radicals and absolute values. 3. Perform multiplication or division in order from left to right. 4. Perform addition or subtraction in order from left to right. 10 5 1 4 2 4 10 20 4 10 4 6 92 Section 1.3 Key Concepts Simplifying Expressions Examples Example 1 2x xy 6 2 A term is a constant or the product of a constant and one or more variables. A variable term contains at least one variable. A constant term has no variable. The coefficient of a term is the numerical factor of the term. Like terms have the same variables, and the corresponding variables are raised to the same powers. Distributive Property of Multiplication over Addition a 1 b c 2 ab ac Variable term has coefficient 2. Variable term has coefficient 1. Constant term has coefficient 6. Example 2 4ab3 and 2ab3 are like terms. Example 3 1 a 6b 5c 2 a 6b 5c Example 4 4d 12d d 9d Example 5 2 3 w 4 1 w 2 2 4 3 2 3 w 4w 8 4 3 2 1 x 4y 2 2x 8y Two terms can be added or subtracted if they are like terms. Sometimes it is necessary to clear parentheses before adding or subtracting like terms. 2 3 3w 8 4 3 6w 16 3 6w 13 Summary 93 Section 1.4 Key Concepts A linear equation in one variable can be written in the form ax b 0 1 a 0 2 . Steps to Solve a Linear Equation in One Variable 1. Simplify both sides of the equation. Clear parentheses. Consider clearing fractions or decimals (if any are present) by multiplying both sides of the equation by a common denominator of all terms. Combine like terms. 2. Use the addition or subtraction property of equality to collect the variable terms on one side of the equation. 3. Use the addition or subtraction property of equality to collect the constant terms on the other side. 4. Use the multiplication or division property of equality to make the coefficient on the variable term equal to 1. 5. Check your answer. An equation that has no solution is called a contradiction. Example 1 3 1 1 1x 42 1x 22 2 4 4 1 3 3 1 x2 x 2 4 2 4 1 3 3 1 4a x 2 x b 4a b 2 4 2 4 2x 8 3x 6 1 x 14 1 x 15 x 15 Example 2 3x 6 3 1 x 5 2 3x 6 3x 15 6 15 Contradiction There is no solution. An equation that has all real numbers as its solutions is called an identity. Example 3 1 5x 12 2 3 5 1 x 3 2 5x 12 3 5x 15 5x 15 5x 15 15 15 Identity 94 Section 1.5 Key Concepts Problem-Solving Steps for Word Problems 1. 2. 3. 4. 5. 6. Read the problem carefully. Assign labels to unknown quantities. Develop a verbal model. Write a mathematical equation. Solve the equation. Interpret the results and write the final answer in words. Sales tax: (Cost of merchandise)(tax rate) Commission: (Dollars in sales)(commission rate) Simple interest: I Prt Distance (rate)(time) d rt 3. a 4. 0.06x 0.10 1 8500 x 2 750 5. 6x 10 1 8500 x 2 75,000 6x 85,000 10x 75,000 4x 10,000 x 2500 x 2500 8500 x 6000 $2500 was invested at 6% and $6000 was invested at 10%. 6. Summary 95 Section 1.6 Key Concepts Some useful formulas for word problems: Perimeter Rectangle: P 2l 2w Area Rectangle: Square: Triangle: Trapezoid: Angles Two angles whose measures total 90 are complementary angles. Two angles whose measures total 180 are supplementary angles. Vertical angles have equal measure. m 1 a 2 m 1 c 2 A lw A x2 1 A bh 2 1 A 1 b1 b2 2 h 2 2x 25.5 2 1 2x 2 2 1 x 2 25.5 4x 2x 25.5 6x 4.25 x The width is 4.25 ft, and the length is 2(4.25) ft or 8.5 ft. P 2l 2w m 1 b 2 m 1 d 2 a d c b Literal equations (or formulas) are equations with several variables. To solve for a specific variable, follow the steps to solve a linear equation. 96 Section 1.7 Key Concepts Properties of Inequalities 1. If a 6 b, then a c 6 b c. 2. If a 6 b, then a c 6 b c. 3. If c is positive and a 6 b, then ac 6 bc and b a 1c 02. 6 c c 4. If c is negative and a 6 b, then ac 7 bc and a b 1c 02. 7 c c Properties 3 and 4 indicate that if we multiply or divide an inequality by a negative value, the direction of the inequality sign must be reversed. The inequality a 6 x 6 b is represented by or, in interval notation, (a, b). ( ( a b 3 4, 2 2 Review Exercises 97 Section 1.8 Key Concepts Let a and b 1 b 0 2 represent real numbers and m and n represent positive integers. bm bn bm n 1 bm 2 n bmn a m am a b m b b 1 bn a b b n 1 ab 2 m ambm b0 1 b bm n bn b 1 x4y0 2 23x6y3 z3 z3 b1 x 4 1 2 or A number expressed in the form a 10n, where 1 0 a 0 6 10 and n is an integer, is written in scientific notation. Example 2 0.0000002 35,000 1 2.0 107 21 3.5 104 2 7.0 103 or 0.007 Chapter 1 Section 1.1 Review Exercises 10. Explain the difference between the union and intersection of two sets. You may use the sets C and D in the following diagram to provide an example. 1. Find a number that is a whole number but not a natural number. For Exercises 23, answers may vary. 2. List three rational numbers that are not integers. 3. List five integers, two of which are not whole numbers. For Exercises 49, write an expression in words that describes the set of numbers given by each interval. (Answers may vary.) 4. (7, 16) 6. 3 6, 3 4 8. 1 , 13 4 5. 1 0, 2.6 4 7. 1 8, 2 9. 1 , 2 Let A 5 x 0 x 6 2 6, B 5 x 0 x 0 6, and C 5 x 0 1 6 x 6 5 6. For Exercises 1116, graph each set and write the set in interval notation. 11. A 12. B 13. C 98 14. A B Section 1.3 For Exercises 3538, apply the distributive property and simplify. 35. 3 1 x 5y 2 37. 1 4x 10y z 2 x 6 3 is equivalent to 3 7 x 2 x 6 5 is equivalent to For Exercises 3942, clear parentheses if necessary, and combine like terms. 39. 5 6q 13q 19 41. 7 3 1 y 4 2 3y 42. 3 1 1 8x 4 2 1 6x 4 2 4 2 40. 18p 3 17p 8p 36. 1 1 x 8y 5 2 2 15. B C 16. A B 38. 1 13a b 5c 2 Section 1.2 For Exercises 1920, find the opposite, reciprocal, and absolute value. 19. 8 20. 4 9 For Exercises 4344, answers may vary. 43. Write an example of the commutative property of addition. 44. Write an example of the associative property of multiplication. For Exercises 2122, simplify the exponents and the radicals. 21. 42, 14 22. 252, 125 For Exercises 2332, perform the indicated operations. 23. 6 1 8 2 25. 8 1 2.7 2 27. 5 13 a b 8 40 2 413 72 4 5 1 1 3 2 24. 1 2 2 1 5 2 26. 1 1.1 2 1 7.41 2 1 11 28. a b a b 4 16 30. 12 1 2 2 8 4 1 3 2 2 1 5 2 Section 1.4 45. Describe the solution set for a contradiction. 46. Describe the solution set for an identity. For Exercises 4756, solve the equations and identify each as a conditional equation, a contradiction, or an identity. 47. x 27 32 49. 7.23 0.6x 0.2x 51. 1 4 3m 2 9 1 3 m 2 52. 2 1 5n 6 2 3 1 n 3 2 53. 2x 1 x3 1 5 2 48. y 7 1 8 29. 34. Find the area of a parallelogram with base 42 in. and height 18 in. 54. 3 1 x 3 2 2 3x 2 18 in. 42 in. Review Exercises 99 55. 10 7 3 m 18 m m 25 8 8 8 2 1 1 1 m 1 m 1 2 m 1 4m 1 2 3 3 3 3 68. a. Cory made $30,403 in taxable income in 2007. If he pays 28% in federal income tax, determine the amount of tax he must pay. b. What is his net income (after taxes)? 56. Section 1.5 57. Explain how you would label three consecutive integers. 58. Explain how you would label two consecutive odd integers. 59. Explain what the formula d rt means. 60. Explain what the formula I Prt means. 61. To do a rope trick, a magician needs to cut a piece of rope so that one piece is one-third the length of the other piece. If she begins with a 22 3-ft rope, what lengths will the two pieces of rope be? 62. Of three consecutive even integers, the sum of the smallest two integers is equal to 6 less than the largest. Find the integers. 63. Pat averages a rate of 11 mph on his bike. One day he rode for 45 min (3 4 hr) and then got a flat tire and had to walk back home. He walked the same path that he rode and it took him 2 hr. What was his average rate walking? 64. How much 10% acid solution should be mixed with a 25% acid solution to produce 3 L of a solution that is 15% acid? 65. Sharyn invests $2000 more in an account that earns 9% simple interest than she invests in an account that earns 6% simple interest. How much did she invest in each account if her total interest is $405 after 1 year? 66. In 2003, approximately 7.2 million men were in college in the United States.This represents an 8% increase over the number of men in college in 2000. Approximately how many men were in college in 2000? (Round to the nearest tenth of a million.) 67. In 2002, there were 17,430 deaths due to alcoholrelated accidents in the United States. This was a 5% increase over the number of alcohol-related deaths in 1999. How many such deaths were there in 1999? Section 1.6 69. The length of a rectangle is 2 ft more than the width. Find the dimensions if the perimeter is 40 ft. For Exercises 7071, solve for x, and then find the measure of each angle. 70. x a 1b 2 (x 25) 71. (x 1) (2x 1) For Exercises 7275, solve for the indicated variable. 72. 3x 2y 4 73. 6x y 12 74. S 2pr pr2h 1 75. A bh 2 for b for y for y for h 76. a. The circumference of a circle is given by C 2pr. Solve this equation for p. b. Tom measures the radius of a circle to be 6 cm and the circumference to be 37.7 cm. Use these values to approximate p. (Round to 2 decimal places.) 100 Section 1.7 For Exercises 7785, solve the inequality. Graph the solution and write the solution set in interval notation. 77. 6x 2 7 6 78. 10x 15 79. 2 3x 9 15 80. 5 7 1 x 3 2 7 19x 81. 4 3x 10 1 x 5 2 82. 5 4x 9 8 3 2x 8 4 4q 1 2 2 95. Write the numbers in scientific notation. a. The population of Asia was 3,686,600,000 in 2000. b. A nanometer is 0.000001 of a millimeter. 96. Write the numbers in scientific notation. a. A millimeter is 0.001 of a meter. b. The population of Asia is predicted to be 5,155,700,000 by 2040. 97. Write the numbers in standard form. a. A micrometer is 1 103 of a millimeter. b. A nanometer is 1 109 of a meter. 98. Write the numbers in standard form. a. The total square footage of shopping centers in the United States is approximately 5.23 109 ft2. b. The total sales of those shopping centers is $1.091 1012. (Source: International Council of Shopping Centers.) For Exercises 99102, perform the indicated operations. Write the answer in scientific notation. 99. 2,500,000 0.0004 0.0005 25,000 83. 84. 3 7 85. 11 6 5z 2 0 86. One method to approximate your maximum heart rate is to subtract your age from 220. To maintain an aerobic workout, it is recommended that you sustain a heart rate of between 60% and 75% of your maximum heart rate. a. If the maximum heart rate h is given by the formula h 220 A, where A is a persons age, find your own maximum heart rate. (Answers will vary.) b. Find the interval for your own heart rate that will sustain an aerobic workout. (Answers will vary.) 100. Section 1.8 For Exercises 8794, simplify the expression and write the answer with positive exponents. 87. 1 3x 2 3 1 3x 2 2 89. 24x5y3 8x y 4 Test 101 Chapter 1 Test For Exercises 1013, solve the equations. 10. x 1 20 7 1. a. List the integers between 5 and 2, inclusive. b. List three rational numbers between 1 and 2. (Answers may vary.) 2. Explain the difference between the intervals 1 3, 4 2 and 3 3, 4 4 . 3. Graph the sets and write each set in interval notation. a. All real numbers less than 6 b. All real numbers at least 3 4. Given sets A 5 x 0 x 6 2 6 and B 5 x 0 x 5 6, graph A B and write the set in interval notation. 14. Label each equation as a conditional equation, an identity, or a contradiction. a. 1 5x 9 2 19 5 1 x 2 2 b. 2a 2 1 1 a 2 5 c. 1 4w 3 2 4 3 1 5 w 2 15. The difference between two numbers is 72. If the larger is 5 times the smaller, find the two numbers. 16. Jolle is determined to get some exercise and walks to the store at a brisk rate of 4.5 mph. She meets her friend Yun Ling at the store, and together they walk back at a slower rate of 3 mph. Jolles total walking time was 1 hr. a. How long did it take her to walk to the store? b. What is the distance to the store? 17. Shawnna banks at a credit union. Her money is distributed between two accounts: a certificate of deposit (CD) that earns 5% simple interest and a savings account that earns 3.5% simple interest. Shawnna has $100 less in her savings account than in the CD. If after 1 year her total interest is $81.50, how much did she invest in the CD? 18. A yield sign is in the shape of an equilateral triangle (all sides have equal length). Its perimeter is 81 in. Find the length of the sides. For Exercises 1920, solve the equations for the indicated variable. 19. 4x 2y 6 for y 20. x m zs for z 5. Write the opposite, reciprocal, and absolute value for each of the numbers. a. 1 2 b. 4 c. 0 6. Simplify. 7. Given z , find z when n 16, x 18, s/ 2n s 1.8, and m 17.5. (Round the answer to 1 decimal place.) a. 1 x y 2 2 2 1 x y 2 is an example of the associative property of addition. xm 0 8 0 4 1 2 3 2 2 14 8. True or false? 102 For Exercises 2123, solve the inequalities. Graph the solution and write the solution set in interval notation. 21. x 8 7 42 23. 2 6 3x 1 5 24. An elevator can accommodate a maximum weight of 2000 lb. If four passengers on the elevator have an average weight of 180 lb each, how many additional passengers of the same average weight can the elevator carry before the maximum weight capacity is exceeded? 3 22. x 6 x 3 2 For Exercises 2528, simplify the expression, and write the answer with positive exponents only. 25. 20a7 4a6 3x6 2 b 5y7 26. x6x3 x2 1 2 1xy2 2 3 1 x4y 2 1 x0y5 2 1 27. a 28. 29. Multiply.
https://id.scribd.com/document/135285375/Ch01-SE
CC-MAIN-2019-35
refinedweb
21,292
76.62
How to transpose a DataFrame in Pandas In this tutorial, we will learn how to transpose a DataFrame in Python using a library called pandas. Pandas library in Python is a very powerful tool for data manipulation and analysis used by data scientists and analysts across the globe. With the help of pandas, we can create a data structure called DataFrame. A DataFrame is a tabular form of the data present in CSV, excel, etc types of files. Creating a DataFrame using pandas eases out the process of data cleaning and sorting. Let us first install pandas. pip install pandas This command installs pandas in our computer. Now, we need to import it in our IDE or text editor. import pandas as pd Now, pandas is imported and ready to use. Let us make a DataFrame which we wish to transpose. name = ['John', 'Paul', 'George', 'Ringo'] rno = ['2', '3', '1', '4'] mks = ['60', '80', '90', '75'] dict = {'Name':name, 'Rollno':rno, 'Marks':mks} This is the data which we want to convert into a DataFrame. To do that, we use the pandas.Dataframe() method which is in-built in pandas. df = pd.Dataframe(dict) print(df) Output: Name Rollno Marks 0 John 2 60 1 Paul 3 80 2 George 1 90 3 Ringo 4 75 Here, we have created a DataFrame and stored it in a variable called df. Moving on, to transpose this DataFrame we need to use another in-built pandas function Dataframe.transpose(). transposed_df = df.transpose() print(transposed_df) Output: 0 1 2 3 Name John Paul George Ringo Rollno 2 3 1 4 Marks 60 80 90 75 As a result, we have successfully transposed our DataFrame using in-built pandas functions.
https://www.codespeedy.com/transpose-a-dataframe-in-pandas/
CC-MAIN-2020-45
refinedweb
286
71.04
User:Carlfk/meeting notes Aug 15 2019 - Wiki fixi day. SMW sucks!!! remove SMW, install Cargo. or make a new box with no SMW but yes Cargo We should stop using Categories and start using disambiguation and redirects. 106 Category pages each needs to be looked at to see if there is content that needs to be moved to main name space overview page. of them need to be broken we have 1382 pages with content. 600 pages are member meeting notes. 400 board meetings 360 pages that have a tools info box, so we can assume those are most of the tools. leaving 30-100 pages of users and special interest group pages. There are also 1200+images, like red ticket items. And 4000 redirects to meeting notes. there are 4 ways to get to the same page, times 1000. Bring up a new MW instance. import all the pages, start with everything in the archive namespace, this will break all the links between pages, but that's ok. We will move all the pages that meet some patterns, like "meeting*" or stuff with inforbox tool. mass import the pages we want. To figure out what we want: Each area needs a curator to grind though the process of searching and tagging pages "move me"
https://wiki.pumpingstationone.org/index.php?title=User:Carlfk/meeting_notes&oldid=40508
CC-MAIN-2020-29
refinedweb
216
83.46
Comment on Tutorial - File read and write - sample program in C By Norman Chap Comment Added by : Techbymak Comment Added at : 2013-01-08 09:51:54 Comment on Tutorial : File read and write - sample program in C By Norman Chap Thank you sir this is a. Imports Excel = Microsoft.Office.Interop.Excel View Tutorial By: Nilesh at 2014-12-01 13:45:25 2. This is starting program for me in j2me.This will View Tutorial By: Surya at 2010-07-26 03:29:47 3. I liked it. View Tutorial By: savitha at 2011-05-06 02:23:46 4. can any plz tell me how to create a calculator in View Tutorial By: sam at 2010-11-13 06:53:04 5. import gnu.io.*; import java.io.*; < View Tutorial By: Anonymous at 2013-03-29 02:39:00 6. Thanks a lot this thing was very importent for me! View Tutorial By: Andrew at 2010-05-23 01:47:04 7. HELP! HELP! HELP! i got an time out at step View Tutorial By: sumit at 2009-04-03 20:19:51 8. java.lang.IllegalArgumentException means usually t View Tutorial By: Seink at 2008-11-12 11:03:00 9. Please give me a example of regionMatches(). View Tutorial By: A. K. M. Saleh Sultan at 2009-10-05 14:52:25 10. i need help for my study, i need an algorithm for View Tutorial By: Vincent at 2011-08-17 13:37:52
https://java-samples.com/showcomment.php?commentid=38769
CC-MAIN-2022-33
refinedweb
250
76.62
Demonstrates querying a corpus for similar documents. import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) First, we need to create a corpus to work with. This step is the same as in the previous tutorial; if you completed it, feel free to skip to the next section. from collections import defaultdict", ] # remove common words and tokenize stoplist = set('for a of the and to in'.split()) texts = [ [word for word in document.lower().split() if word not in stoplist] for document in documents ] # remove words that appear only once frequency = defaultdict(int) for text in texts: for token in text: frequency[token] += 1 texts = [ [token for token in text if frequency[token] > 1] for text in texts ] dictionary = corpora.Dictionary(texts) corpus = [dictionary.doc2bow(text) for text in texts]). To follow Deerwester’s example, we first use this tiny corpus to define a 2-dimensional LSI space: from gensim import models lsi = models.LsiModel(corpus, id2word=dictionary, num_topics=2) For the purposes of this tutorial, there are only two things you need to know about LSI. First, it’s just another transformation: it transforms vectors from one space to another. Second, the benefit of LSI is that enables identifying patterns and relationships between terms (in our case, words in a document) and topics. Our LSI space is two-dimensional (num_topics = 2) so there are two topics, but this is arbitrary. If you’re interested, you can read more about LSI here: Latent Semantic Index) Out: [(0, 0.4618210045327158), (1, 0.07002766527900064)]. from gensim import similarities Out: [(0, 0.998093), (1, 0.93748635), (2, 0.9984453), (3, 0.9865886), (4, 0.90755945), (5, -0.12416792), (6, -0.10639259), (7, -0.09879464), (8, 0.050041765)]]) for i, s in enumerate(sims): print(s, documents[i]) Out: (2, 0.9984453) Human machine interface for lab abc computer applications (0, 0.998093) A survey of user opinion of computer system response time (3, 0.9865886) The EPS user interface management system (1, 0.93748635) System and human system engineering testing of EPS (4, 0.90755945) Relation of user perceived response time to error measurement (8, 0.050041765) The generation of random binary unordered trees (7, -0.09879464) The intersection graph of paths in trees (6, -0.10639259) Graph minors IV Widths of trees and well quasi ordering (5, -0.12416792) Graph minors A survey Reference, see the Experiments on the English Wikipedia or perhaps check out Distributed Computing in gensim. Gensim is a fairly mature package that has been used successfully by many individuals and companies, both for rapid prototyping and in production. That doesn’t mean it’s perfect though: there are parts that could be implemented more efficiently (in C, for example), or make better use of parallelism (multiple machines cores) new algorithms are published all the time; help gensim keep up by discussing them and contributing code your feedback is most welcome and appreciated (and it’s not just the code!): bug reports or user stories and general questions. Gensim has no ambition to become an all-encompassing framework, across all NLP (or even Machine Learning) subfields. Its mission is to help NLP practitioners try out popular topic modelling algorithms on large datasets easily, and to facilitate prototyping of new algorithms for researchers. import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('run_similarity_queries.png') imgplot = plt.imshow(img) plt.axis('off') plt.show() Out: /Volumes/work/workspace/gensim_misha/docs/src/gallery/core/run_similarity_queries.py:194: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. plt.show() Total running time of the script: ( 0 minutes 0.663 seconds) Estimated memory usage: 6 MB Gallery generated by Sphinx-Gallery
https://radimrehurek.com/gensim/auto_examples/core/run_similarity_queries.html
CC-MAIN-2019-47
refinedweb
624
51.44
In my django project I want to store an email in the database to be able to retrieve it later and send it. I'm implementing a throttling mechanism for sending emails to many users. I thought it would be as easy as storing 'to, from, subject, body' but then I realized there are attachments, multipart emails, etc, there is at least two classes pickle can't pickle lock objects I'm going to make a guess based on your can't pickle lock objects message that you may be trying to pickle your objects with the default SMTP connection included. Try it without it - grepping through the source it is the smtp module that has a self._lock. Pass connection=None to the constructor of the messages. On Django 1.9, this works for me (Python2): from django.core.mail import EmailMessage from django.core.mail import EmailMultiAlternatives import pickle email = EmailMessage( 'Hello', 'Body goes here', 'from@example.com', ['to1@example.com', 'to2@example.com'], ['bcc@example.com'], reply_to=['another@example.com'], headers={'Message-ID': 'foo'}, connection=None, ) email.attach("foo", [l for l in open(__file__)], 'text') print len(pickle.dumps(email)) subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to], connection=None) msg.attach_alternative(html_content, "text/html") print len(pickle.dumps(msg)) According to the Django code in messages.py, later when you call send() it will attempt to use get_connection() from django.core.mail to get your default connection if None. ....Alternatively, if you want to use json, this also worked with connection=None: import json print json.dumps(msg.__dict__) print json.dumps(email.__dict__) This means you could fairly easily write a JSONEncoder and JSONDecoder to serialize/deserialize your objects as well by basically using the __dict__ of the object. More on JSON: As I showed above, encoding the __dict__ makes the encoding easy. You could do msg.__dict__ = json.load(...), but what makes it difficult is the EmailMessage object must be created before you change its values. So you could initialize msg with an __dict__, or decode the JSON and construct the object explicitly by passing the arguments (...and functions) stored in the JSON to the constructor. This requires you to know the internals, though. I'd go with pickle, although there are security implications. This SO question covers some other alternatives as well.
https://codedump.io/share/VYIvFCZjiWwS/1/django---persisting-an-email-to-database-to-be-able-to-send-it-later
CC-MAIN-2017-04
refinedweb
414
51.04
sec_rgy_pgo_get_next-Returns the next PGO item in the registry database #include <dce/pgo.h> void sec_rgy_pgo_get_next( sec_rgy_handle_t context, sec_rgy_domain_t name_domain, sec_rgy_name_t scope, sec_rgy_cursor_t *item_cursor, sec_rgy_pgo_item_t *pgo_item, sec_rgy_name_t Returns the next principal item. - sec_rgy_domain_group Returns the next group item. - sec_rgy_domain_org Returns the next organization item. -. - name A pointer to a sec_rgy_name_t character string containing the name of the returned PGO item. - status A pointer to the completion status. On successful completion, the routine returns error_status_ok. Otherwise, it returns an error. The sec_rgy_pgo_get_next() routine returns the data and name for the PGO in the registry database indicated by item_cursor. It also advances the cursor to point to the next PGO item in the database. Successive calls to this routine return all the PGO items in the database of the specified type (given by name_domain), in storage order. The PGO data consists of the following: - The Universal Unique Identifier (UUID) of the PGO item. - The UNIX number for the PGO item. - The quota for subaccounts. - The full name of the PGO item. - Flags indicating whether - A principal item is an alias. - The PGO item can be deleted. - A principal item can have a concurrent group set. - A group item can appear on a concurrent group set. Permissions RequiredThe sec_rgy_pgo_get data for the returned PGO item in pgo_item and the name in name. - _server_unavailable The DCE Registry Server is unavailable. Functions: sec_rgy_pgo_add(), sec_rgy_cursor_reset(), sec_rgy_pgo_get_by_id(), sec_rgy_pgo_get_by_name(), sec_rgy_pgo_get_by_unix_num(), sec_rgy_pgo_id_to_unix_num(), sec_rgy_pgo_unix_num_to_id().
http://pubs.opengroup.org/onlinepubs/9696989899/sec_rgy_pgo_get_next.htm
CC-MAIN-2017-17
refinedweb
234
52.36
Bugzilla – Bug 89 Crashes and wrong results due to GCC <=4.3 compiler bug with asserts inside of Eigen's code Last modified: 2011-02-16 16:05:54 UTC I built with g++ 4.3.4 on cygwin. I cannot reproduce the issue on VC10 (64bit, debug/release nor 32bit debug/release). The project was generated with the default cmake configuration, i.e. I just called cmake ../eigen I checked and I have the same problem with g++ 4.3.3 (32 bits Linux). householder_{1,2} segfaults when SSE is turned off: and gives errors (results are way off) when SSE is turned on: I haven't investigated it further yet. Can't reproduce on linux x86-64, gcc 4.4 Even with -DEIGEN_TEST_X87=ON, i.e. with -mfpmath=387, I can't reproduce. So this is: - either a 32-bit-specific bug in our code - or a gcc 4.3 bug Please attach a stack trace for when it's segfaulting. Created attachment 17 [details] Stack trace for householder_1 Created attachment 18 [details] householder_1 trace (relwithdebinfo) I patched eigen so all arrays are heap-allocated, and ran householder_1 in valgrind, no errors found. Created attachment 19 [details] householder_1 valgrind output (relwithdebinfo) I had a spare ten minutes to have a look at it. I get the same stack trace as Hauke. Debug build does not show segfault, but RelWithDebInfo does. I ran it through valgrind and attach the report. The first thing valgrind says is a 'Use of uninitialised value of size 4' at the line where the program segfaults. Happy bug hunting!. The error (a 'use of uninitialized value' according to valgrind) appears in line 62 in the function householder(). However, if I comment out lines 83 until the end of the function, the error disappears. This does not make any sense at all! So, we have a weird error that only appears with gcc 4.3 and only for small matrices. That reminds me of the error discussed in the thread half a year ago. Indeed, if I try compiling with the same flags as normal for RelWithDebInfo, but with -fno-strict-aliasing instead of -fstrict-aliasing, then the error disappears again. We never really found out what happens with the bug half a year ago (as far as I remember), Gael suspects a GCC bug, and it was way over my head, so I don't know how to proceed. If this were the only issue left, one possibility would be to release 3.0-beta3 with a health warning ("exposes a bug in some situations when compiled with gcc 4.3 only"). Thanks a lot for looking into this, I agree that we seem to know enough about this bug to drop 3.0-beta3 blocker status. Only a gcc 4.3 bug --> not a blocker. (In reply to comment #11) > Indeed, if I try compiling with the same flags as normal for > RelWithDebInfo, but with -fno-strict-aliasing instead of -fstrict-aliasing, > then the error disappears again. Ah ok, so could it be that we're infringing on strict aliasing rules, and that only gives a crash with a particular optimization that gcc 4.3 does. That would be our bug, but still not a blocker I guess. I cannot reproduce with householder_1, but now the same issue shows up with adjoint_1 lines 71 and 72. (1x1 matrix)... If it's only reproducible with 1x1 matrices on gcc 4.3, our users are not very likely to ever hit this bug. Maybe it should not block? yes and I have no clue on how to workaround it... Created attachment 96 [details] Patch for fuzzy compare Since 8 February, the following tests are failing on my computer with gcc 4.3: basicstuff_1, linearstructure_1, array_for_matrix_1, cholesky_1, jacobisvd_1, jacobisvd_3, eigen2support_1. I looked a bit into the first one, basicstuff_1. It seems very similar at first sight: the failure is resolved when building in debug mode or with -fno-strict-aliasing. The test failure is caused by a segfault in the last line of basicStuff(): VERIFY_IS_APPROX(sm2,-sm1.transpose()); Here, sm1 and sm2 are of type Matrix<float,1,1>. The segfault disappears if we replace the line by the equivalent VERIFY_IS_APPROX(-sm2,sm1.transpose()); When rebuilding with RelWithDebInfo, the stack trace is as follows: #0 Eigen::DenseBase<Eigen::Matrix<float, 1, 1, 1, 1, 1> >::isApprox<Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<float>, Eigen::Matrix<float, 1, 1, 1, 1, 1> const> > ( this=0xbfd38ee8, other=@0xbfd38e88, prec=0.00100000005) at /home/amsta/jitse/scratch/eigen-official/Eigen/src/Core/Functors.h:188 #1 0x0804f353 in basicStuff<Eigen::Matrix<float, 1, 1, 1, 1, 1> > (m=@0xbfd38f68) at /home/amsta/jitse/scratch/eigen-official/test/main.h:350 #2 0x0804c1ea in test_basicstuff () at /home/amsta/jitse/scratch/eigen-official/test/basicstuff.cpp:216 #3 0x0804c939 in main (argc=1, argv=0xbfd39064) at /home/amsta/jitse/scratch/eigen-official/test/main.h:533 Bisection says that the first bad revision is 5e6b790649c4 (fix fuzzy compares for integer types, using a selector). Interestingly, like last time this is a change to the fuzzy compares, though I cannot see why the change triggers a bug. Nevertheless, I tried to rewrite the fuzzy compare; see patch. The resulting code evaluates the matrices being compared twice instead of using the ::Nested type (so it's less efficient). However, the patch does get rid of the basicstuff_1 failure, and also of the failing tests linearstructure_1, array_for_matrix_1, jacobisvd_1, jacobisvd_3. On the other hand, the tests cholesky_1, eigen2support_1, householder_1, householder_2 still fail after applying the patch, and additionally the test array_1 now fails while it passed beforehand. So the patch is not a solution, but it might hint at where to look at. Thanks a lot Jitse for investigating this. I changed my mind, let's make this a 3.0 blocker. I am especially concerned that _we_ might be doing something evil wrt strict-aliasing rules. I can reproduce (gcc 4.3, linux 64bit). removing the x86-32bit and other-unix-like flags. Created attachment 98 [details] valgrind log Obtained with: valgrind --track-origins=yes ./test/basicstuff_1 Created attachment 100 [details] test case Here's a small test case. It runs fine by default, but segfaults if you compile with -DEIGEN_INTERNAL_DEBUGGING. $ g++-4.3 a.cpp -I eigen -o a -O2 -DEIGEN_INTERNAL_DEBUGGING && ./a Segmentation fault More specifically, the segfault disappears if I define eigen_internal_assert(x) as empty. So it is really eigen_internal_assert that is triggering the crash, and I now really believe that it is a plain GCC 4.3 bug, because I can't see how this legitimately be blamed on strict aliasing. Aaaargh! removing eigen_internal_assert only fixes a few of those unit tests. other like array_2 keep crashing. Back to the drawing board... Created attachment 101 [details] no boolean redux unrolling with gcc 4.3 : makes array tests pass This makes gcc4.3 pass array_2 and array_3 Created attachment 102 [details] no internal debugging with gcc 4.3: makes basicstuff_1 and linearstructure_1 pass I had a look at the other, older compiler that's installed at uni and I'm getting similar issues there. The compiler version is gcc (GCC) 4.1.2 20070925 (Red Hat 4.1.2-27) and five tests fail with segfaults; see . I looked into one of them, product_small_4. Valgrind says the following (the segfault occurs soon afterward in the same line of code) Use of uninitialised value of size 4 at 0x805AD1D: bool Eigen::DenseBase<Eigen::Transpose<Eigen::Matrix<double, 4, 1, 0, 4, 1> > >::isApprox<Eigen::CoeffBasedProduct<Eigen::Transpose<Eigen::Matrix<double, 4, 1, 0, 4, 1> >, Eigen::Matrix<double, 4, 4, 0, 4, 4> const&, 6> >(Eigen::DenseBase<Eigen::CoeffBasedProduct<Eigen::Transpose<Eigen::Matrix<double, 4, 1, 0, 4, 1> >, Eigen::Matrix<double, 4, 4, 0, 4, 4> const&, 6> > const&, double) const (MathFunctions.h:299) by 0x80646FC: void product<Eigen::Matrix<double, 4, 4, 0, 4, 4> >(Eigen::Matrix<double, 4, 4, 0, 4, 4> const&) (main.h:350) by 0x8053777: test_product_small() (product_small.cpp:34) by 0x8053B91: main (main.h:533) The test fails only if SSE2 is enabled and the build type is either Release or RelWithDebInfo. The failure is resolved when compiling with -fno-strict-aliasing. Disabling boolean redux unrolling per comment 24 does not make a difference, but disabling internal debugging per comment 25 does make the test pass. In both cases, I changed the patch so that it's also activated by gcc 4.1. (In reply to comment #10) >. Oh, I had missed that. I confirm that undoing this change makes at least the householder and basicstuff tests pass, but not the array tests (which already have a work-around above). ignore me, i was still at bisected revision... Created attachment 103 [details] work around assert bug, makes householder tests pass fwiw, here's the implementation of assert() in all gcc4 versions: #if defined __cplusplus && __GNUC_PREREQ (2,95) # define __ASSERT_VOID_CAST static_cast<void> #else # define __ASSERT_VOID_CAST (void) #endif # define assert(expr) \ ((expr) \ ? __ASSERT_VOID_CAST (0) \ : __assert_fail (__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION)) It's really not doing anything nasty. So we can't do anything more than working around it in our own tests. With this patch, I am down to only 3 failures: 239 - cholesky_1 (Failed) 345 - jacobisvd_3 (Failed) 367 - geo_quaternion_6 (Failed) the first two are segfaults, the latter is a wrong result. I ran the tests in various configurations in the hope I'd see a pattern. Nothing emerged, but perhaps it's of use to somebody else. In the following table, the top half is the configuration. All use GCC 4.3.3 and Release builds, the first row indicates whether SSE2 is enabled, the second row whether I used -fstrict-aliasing or -fno-strict-aliasing, the other rows which of the patches attached to this bag was been applied. In the bottom half, failing tests are indicated with a '-'. The main conclusion for me is that we still haven't nailed this bug. SSE2 y n n n y y y y y -fstrict-aliasing y y y y y y n y y work-around-assert-bug n n y y y y n n n no-booleanredux-unrolling n n n y y n n n n no-internal-debug n n n n n n n y n no-nested-in-fuzzy-compare n n n n n n n n y array_1 - - - - - array_2 - array_for_matrix_1 - - - - - - - array_for_matrix_2 - - basicstuff_1 - - cblat1 - - cholesky_1 - - - - - - cwiseop_1 - eigen2support_1 - - - eigensolver_selfadjoint_1 - - eigensolver_selfadjoint_6 - - - geo_homogeneous_2 - geo_transformations_3 - geo_quaternion_5 - - - geo_quaternion_6 - - - householder_1 - - - - householder_2 - - - - jacobisvd_1 - - - jacobisvd_3 - - - - linearstructure_1 - - - linearstructure_2 - - linearstructure_3 - lu_5 - - mixingtypes_3 - product_large_4 - - product_extra_3 - - - - - - product_symm_7 - - - - - - product_trmv_4 - - - product_trsolve_3 - - - - - - schur_complex_2 - stable_norm_1 - - - - - - - - upperbidiagonalization_3 - - - failures 16 10 8 8 14 15 4 16 10 Some notes: * the third and fourth columns are identical, so I might have done something wrong there. * when using -fno-strict-aliasing, the four remaining failures are not segfaults but wrong results. * obviously, tests can fail for multiple reasons. For instance, the array_for_matrix_1 test seems to have at least two failure points, one of which is fixed by turning of internal debugging. Created attachment 104 [details] makes 100% tests pass: use custom assert, and introduce copy_bool non-inline function This patch makes 100% tests pass. It does 2 things on GCC <= 4.3: * use custom assert() implementation * introduce this function: namespace { EIGEN_DONT_INLINE bool copy_bool(bool b) { return b; } } to evaluate the bool condition in assert, and in the debug helpers used in test/main.h. OK, now I have checked with EIGEN_NO_ASSERTION_CHECKING so that our test suite doesn't fiddle with eigen_assert() anymore, so we are in the real-world conditions of our users, and I have changed the VERIFY macro to just #define VERIFY(a) assert(a) in order to simulate a user using assert() on Eigen expressions. I didn't get any crash. --> So it really seems that the issue was purely with the asserts that we have inside of Eigen's code, and that the patch fixes it i.e. it's not just hiding it. Pushed. Jitse still gets failures on gcc 4.3.3 32bit+SSE2, while for me it's fixed on gcc 4.3.5 64bit :-(. I can't reproduce, even with -m32 -mfpmath=387 and no vectorization. So either it's specific to the 32bit version of gcc itself, or it's 4.3.3 vs 4.3.5. The common thing about the four product_xxx failures is that they test MatrixXcf. In one of the cases (product_extra), the problem is that a product evaluates to a matrix of NaN's where it shouldn't. Sorry, actually I can now reproduce with -m32 -msse2 on gcc 4.3.5 64bit. But this is a separate bug than what we were investigating originally here, which was crashes and valgrind errors. Here, we have what looks like floating point errors. Valgrind reports no error. So, filing a new bug. Filed bug 186
http://eigen.tuxfamily.org/bz/show_bug.cgi?id=89
CC-MAIN-2014-42
refinedweb
2,148
56.96
Various macros useful for development. More... #include <ecl/config/ecl.hpp> Go to the source code of this file. Various macros useful for development. Definition: Each package needs to create it's own macro to make use of the macro that cmake defines for library targets: #ifdef ROS_BUILD_SHARED_LIBS // ros is being built around shared libraries #ifdef ecl_common_EXPORTS // we are building a shared lib/dll #define ecl_common_PUBLIC ROS_HELPER_EXPORT #else // we are using shared lib/dll #define ecl_common_PUBLIC ROS_HELPER_IMPORT #endif #else // ros is being built around static libraries #define ecl_common_DECL #endif And use it alongside class or function definitions: extern "C" ecl_common_PUBLIC void function(int a); class ecl_common_PUBLIC SomeClass { int c; ecl_common_LOCAL void privateMethod(); // Only for use within this DSO public: Person(int _c) : c(_c) { } static void foo(int a); }; Definition at line 144 of file macros.hpp. Definition at line 143 of file macros.hpp. Definition at line 145 of file macros.hpp. Definition at line 151 of file macros.hpp. Definition at line 150 of file macros.hpp.
https://docs.ros.org/en/groovy/api/ecl_config/html/macros_8hpp.html
CC-MAIN-2021-21
refinedweb
169
51.89
April Reagan: The Future of MSDN Help - Posted: Jan 29, 2008 at 5:53 AM - 19,772 Views - 15 Comments Something went wrong getting user information from Channel 9 Something went wrong getting user information from MSDN Something went wrong getting the Visual Studio Achievements Right click “Save as…” April's taking feedback, I'll give my two cents party on the files themselves programatically (b) easily extend and add my own documentation for my own APIs/libraries or 3rd party libraries. I want.... 1. A great reading experience for documentation like the NYT Reader for docs. 2. The actual content to be in an open format, say some sort of XML file format so if I really want to, I can. First i m gonna watch video.., & then will reply for some interesting ways.... keep info for older bits around and findable. say for examplemI am working on a CE 4.1 device then I do not want to see how to do stuff in WM 5.xx or 6.xx I have to support and develop for a CE device and often find that the MSFT docs are jumping to the new version and forget the old one. also the times where the docs tell me the signature of a method but nothing about how to use it, or why to use it..... I think this has gotten better but.... just remember that with VS intelisense we have the signature already.... I am not looking in help to know that Foo(string Prompt) is the method signature.... got that already. sometimes things like: in linq if i call say: foo f = db.footable.Single(x=>x.id == 5); what happens if there is no item with an ID of 5? will this make "f" null ? will I get a Linq exception ? stuff like that ... I'm delighted that we can expect a totally new Help system based on the-thing-we-cannot-name. My crystal ball says the killer app for the-thing-we-cannot-name is actually Help/Education/Training systems. I hope to see a framework, not just MSDN Help-centric, but something that is open, cross and big picture oriented. Being able to right-click a C++ function with a window that's inlined (like intellisense, but readably-sized) with in-depth information about the function would be. 1. Relevence. There is a simple reason why I tend to Google for most of my searches, a lot of the documentation I am seeking has either been removed from MSDN or is out of date. 2. Delivery mechanism. Personally I don't care whether the content is delivered via web pages, PDF, chm, sliverlight etc so long as I can find what I want easily and quickly. However I'd probably prefer something not integrated with studio (other than support for F1) as I normally have multiple studios open and am happy only having one MSDN open. 3. Off-line availabililty. I work for a UK company who is owned by a Swedish parent - our net connection therefore goes through a proxy in Sweden and can be tempermental. (I also do the occasional burst of development on a laptop which is only on the web when I'm within range of my WiFi connection at home.) If I install the MSDN library I want to be able to find the information I want whether I am connected to the web or not. Perhaps the web can be used to provide for supplemental information or an effective errata list between MSDN releases. I'd like to see this information merged into the shipped MSDN library at every release which would keep the reliance on the web low. 4. Install size. The MSDN library is huge - it is possible to filter by topic, would it be possible to split the installer to allow selection of which topics to install. Perhaps if a topic was not locally installed then the help viewer could search the web. It would be nice to be able to select say language and or platform and install topics from those. 5. Quality. The quality of the library is variable - I suppose this is inevitable given the number of pages but particularly for some of the C++ API documentation the quality is very low - many topics almost read like stub pages which people have forgotten to expand. We also have a standing joke in the office about the code quality of the samples - I know a lot of the code is fairly crude in order to keep the sample size down but its not a good example to give novices reading the MSDN trying to learn to code. The library needs to be reviewed not just by technical authors but by area specialists who can write! (I'm a geek so I know how most programmers hate writing). 6. Searching/Library Organisation. Whilst the searching capability has improved in recent years its still not easy to find topics in the library. I've lost count of the number of times I've found something in the index only to find link to the page ends up with the equivalent of a http 404 error. The organisation of the library takes some getting used to as well - it is almost organised for an experienced developer trying to refresh knowledge rather than how a new developer would like to find stuff. A rule of thumb I have is that if you roughly know what you are looking for use MSDN otherwise use a search engine. 7. Legacy platforms. I get the impression that once a new flavour of the month comes along then the whole MSDN library is recompliled to reflect that. Currently it is .NET technology. Previously it was Windows Mobile and CE. The MSDN library team need to learn that there are still some of us splunking in old unfashionable tech who still need to look up documentation relevent to say programming C++ on windows 2000. If I do a search for C++ material I don't want have to be reliant on searching the mobile C++ APIs and guessing whether the function works the same on other window versions. 8. Learning Resource. IMO the MSDN library has never been a learning resource. This needs to change - it is criminal for someone spending a lot of money (in the UK about $1500) for Visual Studio 2008 and then having to buy books to learn the languages because there isn't enough introductory material in the help. When I started with Studio back in the days of version 3 or 4 we also had Borland C++ in the office. Both Borland and Studio were about the same cost, Borland came with buckets of documentation and introductory material, Studio came with a CD that wasn't any help. Fortunately it wasn't my money so I bought some books. If I had been a hobbist paying out of my own pocket I'd have stuck with Borland. Thanks for listening! Rant over Other than that, I'd like to have something like team annotations or MSDNwiki hosted on a local server, so my team could add comments and notes specific to our processes and projects. Also, if you're not aware of it, the inimitable Verity Stob discoursed at length on the shortcomings of MSDN help in an article here: It's humorous in tone, but the points are all valid. Especially "yes, thank you, I know the function signature, but what's it for?" I'd like to see more community interaction. If you look at the PHP's help system on php.net/manual/, there's a LOT of community comments that really help explain things that some users don't quite understand. Perhaps paying MVPs and authors to associate articles or comments or downloadable / working examples to various help entries would be also nice. I'd also like to be able to place bounties on getting help that would then be added back to the community. So, if I want to see an example for a class or method, I would like to place a "Help Wanted" sign on the class or method. If it's really critical, I like to be able to pay for support on-demand (perhaps at $25 increments) that might be answered by either Microsoft or someone in the community. I second the idea of better searchability and integration with existing content such as webcasts or other (possibly non-MS) online resources. This is one of the reasons I continue to program in PHP. There are tons of examples and gotchas posted by the community that would otherwise take you hours to figure out on your own. I'm still learning how to program in C#, but the only useful resource I have found has not been found on a single Microsoft run website. But other sites like codeproject.com. I take that back, there was one... Another item I dislike about MS help is that there are 5 languages that are documented and various .NET versions. An awesome addition to the current site would be to have an option to hide the languages I don't know yet and the .NET versions I will never write code for. There will probably besome sections in the TreeView on the right disappear, but that's fine, because thats all that should be relevant to me. If Microsoft is wanting to expand their market share and get more people to use their products, they've got to realize that leaving out this kind of information to sell Microsoft Press books or Certified Training classes is going to continue to hurt them. Those resources are still an option and are still viable avenues, but not every one learns the same way and finds them useful (or affordable). All: Yes - love all the comments about making Intellisense tooltips 'smarter'..we've got thoughts along those lines as well Agree that the content itself has room for improvement - I'm talking with the right folks about these issues Some specific responses: JChung2006 - I will look for and find a pointer to the Sidebar gadget that is running around out there to search MSDN - I'll post it to my blog when I find it; there had also been some internal efforts to get command line access to the library - I'll have to track that down and see where it landed. Again, watch my blog for more details. nektar - good question about Windows help, etc...currently help is a bit of a patchwork approach in even our biggest products. We will be talking to the windows client folks, and other product teams as we gain some traction. Our initial focus is on developers, and ITPro, which have some scenarios which aren't typical in a consumer environment. Certainly if we design with simplicity and flexibility, we will be able to serve the needs across the spectrum - the small and tidy 100 topic package up through the millions-of-topic-not-so-tidy assistance needs of, say, the MSDN library. Just not everyone all in one release BSalita - I think your crystal ball is probably right, but we must start out on a small focused goal and build on that...it would be great if we can end up serving the far broader need that you point out John E. Boy - have you got opposable thumbs for sale, then? My dog would love to purchase two but he can't work the mouse....besides that, great points Typesafe - thanks for the reference! These types of detailed customer verbatims do help to make a difference jlb0001 - cool ideas! we do have the community comments feature, but proportionately, we need much more involvement there! invenetix - You might look at the learning resources here: - not to say that we shouldn't also be doing a better job in helping people learn to use the product from the start, we should, but in the meantime perhaps these resources will help you out. AGAIN - thank you ALL for your comments - keep them coming and stay tuned to - AprilR I just want to be able to search for "struct" or "namespace" or"CPoint" with a C++ filter and get something useful - even if off line. Right now I can't (unless I use Google) Remove this comment Remove this threadclose
http://channel9.msdn.com/Blogs/Dan/April-Reagan-The-Future-of-MSDN-Help
CC-MAIN-2014-49
refinedweb
2,069
67.18
Skip to 0 minutes and 2 secondsOur simple function machines so far carry out single tasks in isolation. These functions are often called procedures or subroutines. Every time we call the function, it carries out its task. However, it currently doesn't accept any parameters, and doesn't give us any information back. Let's first look at parameters. Everyday machines give you some control over what they do. You could turn the temperature of an oven up or down. You could adjust the speed of a fan, or decrease the amount of water in your washing machine. Without these controls, we'd need a different machine for each type of job. Imagine needing to use a separate oven for each temperature you wanted to cook your food at. The same applies to programming functions. Skip to 0 minutes and 45 secondsWhile simple functions allow you to package and reuse your code, unless they have control over elements or parameters, you still have to use different functions for each individual task or situation. Rather than reinvent the wheel, programmers regularly try to combine functions together, making them flexible by using parameters. Let's have a look at how this works in practice. So here we have a function that somebody has written called isWeekday. And the purpose of this function is to take a date that has been given as a parameter and find out whether it's a weekday-- i.e. Monday to Friday. It uses the weekday function, which is part of the datetime library, to determine the number of the day of the week. Skip to 1 minute and 28 secondsAnd those numbers go from 0 for Monday all the way up to 6 for Sunday. So we want any value that is less than 5-- i.e. it's a 0 Monday, all the way up to a 4 for Friday. So what we're going to do is we're going to use an if statement to find out whether it is a weekday. So I'm going to say, if the day that I have got is less than 5, then I am going to use the return keyword, which is going to return some data back up to whichever bit of the program called this function. Skip to 2 minutes and 1 secondAnd I'm going to say that if it is less than 5, I'm going to return true, because it is a weekday. And otherwise-- or else-- I'm going to return false. So this function, when I run it, will find out what the day of the week is for the date that has been given, and tell me true for a weekday and false for a weekend. So now if I ask it to print my isWeekday, then what should happen when I run my code is today as a Thursday when I'm filming, so I should get a true statement. And I got that wrong, because I forgot to say in here that it is datetime.now. There we go. Let's run that again. Skip to 2 minutes and 47 secondsAnd we're going to run it on today's date. And I should get true, because today is a weekday. Now, because this function is also returning a true or false value-- a Boolean-- we can use it within if statements. So I could change the way this is written, and I could say that if isWeekday datetime.now, then print "It's a Weekday". OK, and then if it's not, then I could print-- so I'd say else-- if it's not a weekday, then I could print-- Skip to 3 minutes and 32 secondsoh, I put caps lock on there. "It's a Weekend". There we go. So now if I run my program, instead of saying true or false, it used the true or false value to determine what to print. And so it's saying "It's a Weekday", which it is. So then we've used a return value to determine the result of the function that we've just run. So let's have a look at another function that returns some data. Here we have a program which includes a getProfile function. This function asks the user for their first name, their last name, and also their age. But what we want to do is make this function return that data. So I'm going to add a return. Skip to 4 minutes and 20 secondsAnd I'm going to simply just for now return the Firstname value. And then what I want to do in my main program is when I run and getProfile, I want to store the results of that data-- i.e. the return value. I want to store the results in a variable. So I'm going to create a new variable, which I'm going to call fname. My names can be different. They can be the same. It's fine. And I'm going to say that fname equals getProfile. And then just to make sure it's worked, I'm going to print fname. Skip to 4 minutes and 54 secondsNow if I run my program, it's going to ask me what my first name is. It's going to ask me what my last name is. It's going to ask me what my age is. Let's say I'm 30, for argument's sake. Put that in, and it has printed out my fname-- my first name, which is James. So that's worked. But I can also do some really powerful things. I can say that actually, I want to return not just the first name, but last name and age as well. And all I need to do in Python is say that I've got not one variable where I'm storing the information, but I've got three variables. Skip to 5 minutes and 33 secondsSo I'm going to say name, and I'm going to call this one age. Now, the reason I can call this one age is because this variable here-- this age-- is inside the getProfile function, and is only visible to the getProfile function. This age is a different variable that is also called age. It exists outside the function. Let's just make sure his program works. If I say fname also you print lname and also print age, when I run that program again and I tell it who I am-- James, surname-- then it's printed those three bits of information out. So there we go. Skip to 6 minutes and 23 secondsWe've seen in these examples that we can return Boolean data, we can retain lists or strings, or anything else for that matter. And once we've returned that data, we can store that in a variable to use later as the program runs. Once you've gotten to grips with creating your own functions, you can begin to add more structure to your programs, taking each component of the program and creating a reusable function from it. Let's imagine we wanted to create a program that could convert a string message into a series of flashes on an LED to create a Morse code sequence. We might have a really high level abstract function called morseMessage. Skip to 6 minutes and 59 secondsIts job is to take a string message and create from it a sequence of flashes of our LED. It does this using four smaller functions. The first one, called char lookup, takes an individual character and converts it into a sequence of dots, dashes, and pauses. The morseMessage function uses that information to then either flash a dot, a dash, or a pause using the smaller component functions. So hopefully now you've got a good understanding of how our functions can be adapted using parameters and return values. Can you apply what you've learned? You'll find some small challenges at the end of this step to complete and share with your fellow learners. Functions including parameters and returns So far, you’ve used and created simple functions that carry out one task in isolation. This type of function is often refered to as a procedure or subroutine. These functions might accept parameters, but they do not return any information to the program that called them. In this step, you’ll learn more about these two aspects of functions - parameters and return values - and how they make functions incredibly useful. Let’s reuse the analogy from the previous step, and imagine our function as a machine carrying out a some computational task when switched on or called. A simple function or procedure is like a basic machine: it does one fixed task, like a kettle. We turn it on, it does the task, and we recieve no real feedback from the machine. Every time this function is called it carries out its task. Parameters = inputs Most everyday machines allow us some control over what the machine does: the temperature of an oven, the speed of a fan, or the amount of water a washing machine should use. Without these controllable elements we’d need a different machine with a different setting for every job, e.g. a different oven for each temperature we want to cook at. It’s a similar story with programming. Whilst simple functions allow a programmer to package up code and reuse it, without controllable elements they would need a different function for every scenario, even if they are very similar. Rather than re-invent the wheel every time, a programmer will create a function that can apply to multiple situations and be tailored to each one, using inputs or parameters. For example, here’s a pair of functions that each load some map data from a file. As you can see, they have very similar actions: they each open a text file in r (read) mode, and add the contents of the file to a list. map1 = [] #Creates an empty list #Here we define the function def load_level_1(): with open("map1.txt",mode="r") as file: for line in file: map1.append(line.strip().split(",")) map2 = [] #Creates an empty list #Here we define the function def load_level_2(): with open("map2.txt",mode="r") as file: for line in file: map2.append(line.strip().split(",")) Such duplication in programs can be avoided by writing a single function with parameters, which can then be used to load either map data file. Here the parameters have been given descriptive names ( file and map), but you can call them anything you like. The names don’t need to relate to anything in the rest of the program: they only exist within the scope of this function. map1 = [] map2 = [] def load_level(file,map): with open(file,mode="r") as file: for line in file: map.append(line.strip().split(",")) This function can then be called, and will use whichever map file and variable you ask for: load_level("map1.txt",map1) Return values = outputs A real life machine, like the functions we have seen, has consequences or side effects: it washes clothes, cooks food, or boils water, for example. However, unlike the functions we’ve seen so far, it may also provide some feedback or information as output. Machines might beep, display some text, or sound an alarm, for example. A function can also provide information, simply by returning some data to the program that called it. When programming, you will often need to get data back from a function, either simply to confirm that the function has done its job, or to get some richer data that the function has calculated. This is done via the return command, which “returns” data back to the process that called the function. In the simple example below, the function isWeekday checks whether the date provided is a weekday. from datetime import datetime def isWeekday(mydate): day = mydate.weekday() #Get the nunber of the day of the week - Monday = 0, Tuesday = 1 etc. if day < 5: return True else: return False # Calls the function providing a date workday = isWeekday(datetime.now()) #Call the isWeekday function with today's date, store the returned data in a variable "workday". Once defined, a function like isWeekday, which returns a True or False (Boolean) value, can be used in conditional statements: if isWeekday(datetime.now()): print("It is a week day") Of course, functions aren’t just limited to returning Boolean values. They can return any variable, list, or other object. For example, the following function asks the user to input some numbers, and then returns the same numbers as a list. def getNums(size): nums = [] for x in range(size): num = int(input("Enter a whole number: ")) nums.append(num) return nums mynums = getNums(10) You can even return several values from one function and then store these in separate variables: def get_profile(): firstname = input("What is your first name? ") lastname = input("What is your last name? ") age = int(input("What is your age? ")) return firstname, lastname, age fname,lname,user_age = get_profile() In this example, we have used different variable names when calling the function from the variable names inside the function. Whilst this is good practice as it helps the programmer distinguish between them, it is not actually necessary in Python. In other words, we could have called the function like this: firstname,lastname,age = get_profile() Variables defined inside a function, like firstname, exist in isolation from other variables and only whilst the function is run. This is their scope. Variables defined in the main program, rather than within functions, exist for the duration of the program and are said to be global in scope. If you want a function to have access to variables outside its own scope, best practice would be to add them as parameters to the function: am = "Good Morning" pm = "Good Evening" def get_profile(msg): print (msg) firstname = input("What is your first name? ") lastname = input("What is your last name? ") age = int(input("What is your age? ")) return firstname, lastname, age #Function called passing in variable from global scope fname,lname,user_age = get_profile(am) Combining functions Once you’ve got to grips with creating your own functions, you can begin to add more structure to your programs, taking each component of the program and creating a reusable function from it. For example, imagine you wanted to create a program that could send Morse code messages by blinking a single LED. This problem can be broken down into a hierarchy of functions. - The highest or most abstract function might be morseMessage(), whose job is to take a given string and turn it into a Morse sequence. To do this, it will call charLookup()for each character in turn, and then the relevant dot, dash, and pausefunctions. - The charLookup()function looks up a given character and determines the correct sequence of dots, dashes and pauses for that character. This sequence is returned as a string to the morseMessage()function. - The dot(), dash(), and pause()functions receive no input, and simply turn the LED on and off for the appropriate lengths of time to represent dots and dashes. We could represent this diagramatically like this: An example of the full code for a Morse code generator can be found here. Over to you Can you create your own functions that use parameters and return values? Pick one of these challenges to complete, and share your code in the comments for this step. - Create a function that accepts the dimensions of a triangle and returns its area. - Create a function that accepts a string and returns the same string reversed. - Create a function that simulates a pair of dice being rolled n times and returns the number of occurrences of each score.
https://www.futurelearn.com/courses/programming-102-think-like-a-computer-scientist/0/steps/53096
CC-MAIN-2020-16
refinedweb
2,658
71.24
16 April 2007 23:14 [Source: ICIS news] HOUSTON (ICIS news)--Dow Chemical said on Monday it removed former executive J. Pedro Reinhard from its list of nominees to the company’s board. Dow fired Reinhard as senior advisor earlier this month on allegations that he talked with other parties about acquiring the company. Dow fired another executive, Romeo Kreinberg, for the same reason. Reinhard and Kreinberg have denied participation in unauthorised talks concerning the company, according to news media reports. Dow said it removed Reinhard from the list of nominees on the recommendation of the board’s governance committee. Dow said it also reduced the board’s size by one seat. The remaining 11 board nominees are all current directors. Reinhard kept his seat on the board despite his firing, since only stockholders can remove members from the board. Stockholders will vote on the nominees during the company’s annual meeting on10 May at ?xml:namespace> By Al Greenwood + 1 713 525 26
http://www.icis.com/Articles/2007/04/16/9020874/dow-cuts-reinhard-from-board-nominee-list.html
CC-MAIN-2015-22
refinedweb
164
56.96
Once.) Once you learn this, it makes remembering the parameters for window messages a little easier. Conversely, if a message breaks this rule, then it sort of makes your brain say, "No, that's not right." Why not take this opportunity to fix this in Win64 then? Or is it fixed now? Does WinMain still take an hPrevInstance in Win64? Why is stuff like this never cleaned from the Windows API? So that you can have less #ifdef’s in the code? Thanks, Raymond, I enjoy your posts. They take me back to those halcyon days of message crackers, GPFs and UAEs. :) Curt, I think binary compatibility might be an issue as well. Native-code binaries tend to break if the number or size of function arguments etc. change, because the assumptions about the number of bytes on the stack or the offsets of structure members are baked into the binary. And it’s a pain to have to ship different binaries for different platforms. I think this is why as the Win32 API evolved they’ve moved towards using structures and versioning these using a size indicator as the first element (the cbSize member we see on so many API structs). This way the API can gain new "arguments" (struct members) but detect the caller’s expectations and structure layout in case it’s not been built against the latest and greatest header files. Great info. Do you know of an example of a message that breaks this rule? Jeff, unlike those two I know that your name is Jack, so while I have no useful information to offer you, Jack, gosh, aren’t you grateful at least I know your name? :P This is one of THE classic example of why Hungarian notation is a bad idea in any code that you think will survive long term. This is one of THE classic example of why Hungarian notation is a bad idea in any code that you think will survive long term. Here’s a mind-boggling question: why does every computer made (from 8086 up to the Intel/AMD processors of today) beep continuously when you hold down all six of the shift, alt and ctrl keys. :) I think the beep to which you’re referring is the heard only when muppets hold down keys (or sit on their keyboard). James: Yes, but that lack of #ifdefs pays a price. You have all of this built in crap that never works its way out of the API. You have ShellExecute and ShellExecuteEx, you have CreateFont and CreateFontIndirect. You have WinMain. You have pointers declared with NEAR in them still in the .h files. If they want to maintain compatibility, then give us a migration .lib (or .cpp’s and .h’s) rather than keeping all of this crap in the Windows DLLs. Clean things up. Namespace things so that functions begin with their subsystem (like the Reg* functions!). Make the UNICODE functions default and ANSI ones end in A so that we don’t have to have functions like GetComputerName #defined out in our code differently if we include windows.h or not. Ok, I’ll take some happy pills and chill out now. The Win32 API is broken beyond repair, that’s why we are getting WinFX instead of a new Win32 API. Things are not only getting "cleaned up," they are being written correctly from the ground up. The Win32 API is broken beyond repair, that’s why we are getting WinFX instead of a new Win32 API. Things are not only getting "cleaned up," they are being written correctly from the ground up. Matt, mine beeps on both control keys and any one shift. "So even though the "W" stands for "word", it isn’t a word any more." I think it is. As far as I remember, word relates to the standard size used for data on a machine, perhaps the register size. For example, DEC TOPS-20 machines used to (still?) have 36-bit words (I seem to remember some awkward transformations for downloading files from these machines – didn’t simtel used to run on TOPS-20 or something when it was at wsmr? Always used to think it was cool connecting up to a computer 1000’s of miles away on a missile range but I digress). On a 32-bit system, the word size is 32-bit so it WORD is a 32-bit value. c.f. Matt Mastracci: The beep is because the way the keyboard is scanned. It’s layed out in some kind of grid with the keys connecting the rows and the columns together. Power is applied to each column sequentially and then you look at which row has power coming out of it. From the intersection of the column and the row together you can figure out which key was pressed. However there is one flaw, if you press three keys in a "triangle" then the current can flow down the column, across where you pressed one of the keys, then down at the next key then across again. (Hmm, diagram here would be useful). When this happens the computer starts reading "ghost" keys. The computer can detect this condition and "beeps" at you slowly to let you know that it can’t reliably tell which keys are being pressed. This used to be an excellent way of telling if your computer hasn’t crashed, since if it had crashed (And taken out the keyboard handler) then it wouldn’t beep (since t wasn’t processing interrupts from the keyboard anymore) Perry: Actually that’s not true… at least not for modern PC keyboards. The beep is caused when the keyboard buffer in the BIOS is full. If you hold down too many keys at the same time, signals from the keyboard fill up the buffer faster than the OS handles them, causing the BIOS to make your computer beep. You can also see this happen when your computer crashes and locks up… if you keep typing on your computer while it is frozen, it will eventually beep at you when you have filled the keyboard buffer (since the OS is frozen and doesn’t handle it). At least under Dos, the beep you got from the bios keyboard buffer filling up was quite different, holding down all the shift keys gave you a beep with very long pauses between them. Under Windows 3.1 when the message buffer filled up the computer would beep at you too. Once a function is exported from a specific DLL you can’t move it. If you did, then you would break all the old programs that expected to see it in the old DLL. A migration DLL doesn’t help because it requires everybody with an old program recompiled it with the migration DLL — good luck trying to get Borland (for example) to recompile Sidekick 2.0 for Windows, or that ActiveX control you bought in 1998 from a company that is no longer in business. Moving functions into namespaces has the same problem – but worse: Not all languages support namespaces. (C for example doesn’t.) Ive been trying to understand how to increase the buffert in the BIOS for the keyboard so that more keys can be pressed at the same time. Is there any way to do this?
https://blogs.msdn.microsoft.com/oldnewthing/20031125-00/?p=41713/
CC-MAIN-2016-44
refinedweb
1,233
79.09
The first two are features that many developers have asked for in Java. They are included in a number of different Java variants. Generics A generic is a method, function, or class that does not completely specify all of the types of its variables, because the types can be specified later. The result is multiple versions of the method, function, or class that is specialized to a particular set of types. Generics fall under the rubric of parametric polymorphism (PP). PP exists in a number of forms, in numerous languages, and with many different names. For example, the C++ version of generics is templates. So in the case of Java, generics basically add templates to the languageand they are quite easy to use. As an example, you can create a simple pair class (a pair is a data structure containing a head and a tail). In regular Java, you could represent the head and tail as Objects. To get access to either, you would use the head() or tail() methods, each of which return an Object. Listing 1 shows OldPair.java, which implements a pair without using generics. head() tail() OldPair.java The problem is that many developers find casting from Object to Integer annoying. Creating a generic class can improve this process. You can declare a generic class by specifying one or more type parameters, like so: Object Integer public class MyPair<Head,Tail> { ... } The <head, tail> part of this declaration looks kind of like a function declaration, which is fine because it's supposed to. Just as a function takes some values and returns an answer, a generic class is a kind of meta-function that takes some types and returns a class. <head, tail> For example, you can declare a pair whose head and tail are both integers, like this: MyPair<int,int> p = new MyPair( 20, 30 ); This declares a pair called p, which is actually a pair of integers. MyPair<int,int> is a class, while MyPair is really a class template (not to be confused with C++ templates!). MyPair isn't really a type, so you use it directly. You must instantiate it by supplying types. In this case, you supplied int and int, resulting in MyPair<int,int>, which you can use directly (as shown above). MyPair<int,int> MyPair int The nice thing about such a parameterized type is that you don't have to use casts to access its members. For example, look at the declaration of the head() method from MyPair: public Head head() { return head; } Note the return type. It isn't Object or Integer, it's Headthat is, it's whatever type was declared for the head value of the pair. Accessing the head thus doesn't require a cast: Head head int head = p.head(); Listing 2 shows the complete source for MyPair. Function Pointers Pizza also adds a neat feature called a function pointer. A function pointer lets you refer to a function (method) as if it were a regular value. You can also create functions that aren't really methodsthey are just pure functions like you'd find in non-object-oriented languages. (If you are familiar with functional languages such as Scheme, you might have encountered these features under the name closure.) The following is an example of a function called isOdd, which tells you whether a number is odd: isOdd (int)->boolean isOdd = fun( int n ) -> boolean { return (n&1)==1; }; The syntax is a little tricky. First, note the fun keyword. Instead of writing isOdd( int n ) { ... }, you write fun( int n ) { ... }, for example: fun boolean isOdd( int n ) { ... } fun( int n ) -> boolean { ... } This function has no name. Instead of declaring the function as having the name isOdd, the code declares it anonymously. You then can assign it to a variable called isOdd: The first line declares a variable called isOdd. The type of this variable is (int)->Boolean, the type that takes an integer as a parameter and returns a boolean. Using such a function is easy. You just use the variable name as if it were the function name: isOdd( 23 ); So what do you gain from this? Well, for one thing, you easily can assign another function to the same variable, like this: isOdd = fun( int n ) -> boolean { ... }; This can be a completely different anonymous function. Also, you can assign such functions from variable to variable: isOdd = reallyFastIsOdd; One useful application of this is passing a function as a parameter to another function. For example, you can implement a filter that takes an array of integers and use it with an anonymous function that returns a boolean. This kind of function is often called a predicate. It answers a true-or-false question about an integer. Your filter method would run through a list of integers and ask the true-or-false question about each one. It would collect the ones that give a true answer and return an array containing them. So, for example, if you have an array of integers called integers, you can filter out the even ones as follows: integers int odds[] = filter( integers, isOdd ); The second argument to filter is the isOdd function, which returns true for odd numbers only. filter You can be even terser by just passing the predicate directly to filter without assigning it to isOdd first, like this: int odds[] = filter( integers, fun( int n ) -> boolean { return (n&1)==1; } ); Listing 3 includes the complete implementation of filter. Click here for complete instructions for running the Pizza variant. Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/Java/Article/10471/0/page/2
CC-MAIN-2016-50
refinedweb
958
64.3
1 /*2 * $Header: /home/projects/jaxen/scm/jaxen/src/java/main/org/jaxen/xom/XOMXPath.java,v 1.3 2005/01/30 03:12:35 elharo Exp $3 * $Revision: 1.3 $4 * $Date: 2005/01/30 03:12: XOMXPath.java,v 1.3 2005/01/30 03:12:35 elharo Exp $60 */61 62 63 package org.jaxen.xom;64 65 import org.jaxen.BaseXPath;66 import org.jaxen.JaxenException;67 68 /** An XPath implementation for the XOM model69 *70 * <p>This is the main entry point for matching an XPath against a DOM71 * tree. You create a compiled XPath object, then match it against72 * one or more context nodes using the {@link #selectNodes(Object)}73 * method, as in the following example:</p>74 *75 * <pre>76 * Object xomNode = ...; // Document, Element etc.77 * XPath path = new XOMXPath("a/b/c");78 * List results = path.selectNodes(xomNode);79 * </pre>80 *81 * @see BaseXPath82 * @see <a HREF="">The XOM website</a>83 *84 * @version $Revision: 1.3 $85 */86 public class XOMXPath extends BaseXPath87 {88 /** Construct given an XPath expression string.89 *90 * @param xpathExpr the XPath expression.91 *92 * @throws JaxenException if there is a syntax error while93 * parsing the expression94 */95 public XOMXPath(String xpathExpr) throws JaxenException96 {97 super( xpathExpr, new DocumentNavigator());98 }99 } 100 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/jaxen/xom/XOMXPath.java.htm
CC-MAIN-2018-26
refinedweb
230
51.55
part 1 find the most efficient way of making change for any amount of money up to $200.00. the most efficient way means the fewer pieces of currency. the following are the values of monies to use. $ 100.00 $1.00 $ 50.00 $.50 $20.00 $.25 $10.00 $.10 $5.00 $.05 $2.00 $.01 for example, if i were to give you change of $8.93, the most efficient would be 1-$5.00, 1-$2.00, 1-$1.00, 1-$.50, 1-$.25, 1-$.10, 1- $.05, 3- $.01. only tell me the change i will get, not what i will not get. part 2 if the amount of the change is $10.00 or less, i want you to tell me the number of different ways you could have made change for that amount. for example, if the my change was $.25, you give me a quarter, but tell me that there are 13 different ways you could have made change ( or if any change was $0.50, you would give me a hal-dollar and tell me there are 50 ways you could have made change). run the program to show the result for $10.00 = $5.00 - $4.00 - $3.00 - $2.00 - $1.00 - $.50 - $0.25 - $0.10. #include "stdafx.h" #include <iostream> using std:cout; using std:cin; int hundredD; int fiftyD; int twentyD; int tenD; int fiveD; int twoD; int oneD; int fiftyC; int quarter; int dime; int nickle; int penny; double change; // Whatever this is. hundredD = change / 100; change = change % hundred; fiftyD = change / 50; change = change % 50; twentyD = change / 20; change = change % 20; tenD = change / 10; change = change % 10; fiveD = change / 5; change = change % 5; twoD = change/ 2; change = change % 2; oneD = change / 1; change = change %1; fiftyC = change / 0.50; change = change % 0.50; quarter = change / 0.25; change = change %0.25; dime = change / 0.10; change = change % 0.10; nickle = change / 0.05; change = change % 0.05; penny = change / 0.01; change = change % 0.01 I am confuse, what do you do next. Can someone please please explain this to me?
https://www.daniweb.com/programming/software-development/threads/234722/help-help-help-with-my-homework
CC-MAIN-2017-13
refinedweb
355
92.63
Many Stackoverflow questions amount to nothing more than, “Which of these is faster?” or “Why is this so slow?” Very often, the person posting the question will include code that outputs some timing results. More often than not, the timing code is just wrong. Sometimes fatally so. By the way, most “Which is faster” questions are non-starters. You shouldn’t ask before you’ve done the benchmark yourself. Read on. If you want accurate timing information, you have to do it the right way. If you do it the wrong way, your results will be at best unreliable. Fortunately, doing things the right way is pretty easy. But before I go any further, I feel obligated to ask the most important question: Why do you care? Before you start adding code to profile small parts of your application, you need to ask yourself if it’s really that important. Or are you just wasting your time worrying about the performance of something that is already “fast enough?” I strongly suggest that you read Eric Lippert’s, Which is faster? Now, if you really need to time your code. . . The information below is for .NET, and the code samples are in C#. You should follow the same techniques if you’re writing in Visual Basic .NET or Managed C++, and probably any other .NET language. The general techniques are true of pretty much any other platform as well, although the specifics will be much different. When doing benchmarks, run them against a release build with no debugger attached. In Visual Studio, be sure to select the Release build, and either press Ctrl+F5 to run, or select Debug -> Start Without Debugging. Timings gathered from a debug build or from having the debugger attached (even in a Release build) will be inaccurate. You’ll often find that there is little difference between Debug and Release builds when the debugger is attached. Do not use DateTime.Now, DateTime.UtcNow, or anything else based on DateTime as your time source. There are two reasons for this. First, the resolution of DateTime is somewhat questionable, but probably not much better than 15 milliseconds. Secondly, the clock can change on you. I once had a bit of code take -54 minutes (yes, it completed 54 minutes before it started) to execute because it started four minutes before 2:00 AM on “Fall back” day (Daylight Saving Time autumn adjustment date) and finished six minutes later. So start time was 01:56:00 and end time was 01:02:00. You don’t control the system clock, so don’t depend on it. DateTime.Now DateTime.UtcNow DateTime Use the System.Diagnostics.Stopwatch class for all elapsed time measurements. That’s based on the Windows high performance timer, which is the most accurate interval timer you’re likely to get on a Windows box unless you have special hardware. Accept no substitutes. With Stopwatch, timings are easy. First, add this using statement to the top of your source file: Stopwatch using using System.Diagnostics; Then, surround the code you want to time with a Stopwatch: Stopwatch sw = Stopwatch.StartNew(); // creates and starts the stopwatch // // put the code you want to time here // sw.Stop(); // stop the watch. Console.WriteLine("Elapsed time = {0} milliseconds", sw.ElapsedMilliseconds); That’s all there is to it! I usually like to report times in milliseconds (1/1000 second), simply because the usable range is reasonable. If I’m timing something that takes less than a millisecond to run, I need to do it many times to get a good average. A million iterations of any non-trivial loop will likely take longer than a few milliseconds. On the same note, a full day is 86,400 seconds or 86,400,000 milliseconds: a number that is still reasonably easy to work with. If I’m timing something that takes longer than a full day to run, I might decide to use seconds as my comparison. One other nice thing about Stopwatch is that you can have many of them, each timing a discrete part of your program. For example: Stopwatch totalTime = Stopwatch.StartNew(); Stopwatch pass1Time = Stopwatch.StartNew(); DoPass1(); pass1Time.Stop(); Stopwatch pass2Time = Stopwatch.StartNew(); DoPass2(); pass2Time.Stop(); totalTime.Stop(); You then have separate values for the total time and the time to execute each pass. If you’ve done all of that and you still haven’t found an answer, then post a question. But include your timing code so that those of us who are willing to help you find an answer aren’t groping around in the dark. And be sure to mention that you ran in Release mode without the debugger attached. A few things that readers might want to keep in mind: If you’re timing .NET code, you should run an untimed pass of the function that contains the code you’re interested in benchmarking. Otherwise you may be including the time it takes to JIT some or all of the code under test, which probably isn’t what you want. This probably applies to Java as well. Another thing that can cause misleading results with simple benchmarks is that often the code being timed is simplified to the point where the compiler or jitter can optimize away many of the operations that you’re intending to time. I’ve seen confusion in several Stackoverflow questions/answers because of this. Oh, and if you’re benchmarking C/C++ code, please do it with an optimized build. There’s usually not much point benchmarking non-optimized.
http://blog.mischel.com/2013/04/24/how-to-time-code/
CC-MAIN-2017-22
refinedweb
929
75
Looking for a way to open a view before running the rest of the definition. This way i can view what is going on in that view. Call View to Open I’ve gotten around this in the past by using stuff on the active view only, or putting in a "is active view 3D (or whatever) and popping a message asking them to set the view to the correct type if not. I think I actually just figured this out… import clr clr.AddReference("RevitNodes") import Revit clr.ImportExtensions(Revit.GeometryConversion) from Revit.Elements import * clr.AddReference('System') from System.Collections.Generic import * clr.AddReference('RevitAPI') from Autodesk.Revit.DB #The inputs to this node will be stored as a list in the IN variables. dataEnteringNode = IN myView = UnwrapElement(IN[0]) uiapp.ActiveUIDocument.RequestViewChange(myView) #Assign your output to the OUT variable. OUT = "ActiveView set to: " + myView.Name Nick, Can you show an example of yours working? I cant get it to work on a newly created Drafting view that was just created by Dynamo. I can get it to work with the get current view node. If you’re creating the view in the same graph you’ll have to put a Transaction.End node between your newly created view and the python node. OK,Set Active View.dyn (15.1 KB) I had bake with a Passthrough instead of Transaction end. Still not working, here is my definition. Can you show a preview of your whole graph? I don’t have a few of those nodes so I’m not sure what they’re doing. Edit: I think you’re taking an extra step. DraftingView.ByName outputs the view you just created. There’s no need to create the view then get the view with its name. Just take the Transaction.End output directly to the Python node. Either way, the issue is because you’re sending a list to the Python node when it expects a singleton.
https://forum.dynamobim.com/t/call-view-to-open/17903
CC-MAIN-2018-39
refinedweb
331
69.89
> Wow! That's a long and a very wrong way of doing things. This is > Python! Do not evaluate strings - just manipulate objects. Thanks very much for the advice, I thought there must be a nicer way to do it. I ended up using apply() with the class name and the keyword dictionary. I've put the changed code at if you're interested. I tried _lazyUpdate = True and it does half of what I need (i.e. defers updates to the database until syncUpdate() is called). Is there a similar mechanism for deferring inserts? I hope so, then I can get rid of this ugly code for good! Cheers Peter I am using SQLObject with a pre-existing Postgresql database, so I enforce all validation constraints there instead of in the object mapper. I think that's really the most appropriate place to do data validation. Your situation may dictate otherwise, though. >Is it possible to defer the insert/update so that the object can be validated >before the changes are written to the database? Thanks for all the advice on this, I really appreciate it. I've managed to get this working by using the code below. You use it like this: class SomeDomainObject(SQLObject): ...etc # This will create a new object in the database form = FormValues(clazz = SomeDomainObject) form.attr1 = 'value1' form.attr2 = 'value2' form.save() #Insert deferred to here # This will update an existing object obj = SomeDomainObject.select(...) form = FormValues(object = obj) form.attr1 = 'newvalue' form.attr2 = 'newValue2' form.save() #Update deferred to here This code works but I'm not very keen on it because it seems like a hack to, in particular using "eval" to call the object constructor does not feel good. Any advice or comments on how to improve this are welcome. Cheers Peter class FormValues: def __init__(self, clazz = None, object = None): self.clazz = clazz self.object = object def __getattr__(self, attr): # If we just want the object (as in 'self.object') if attr == 'object' and self.__dict__.has_key('object'): return self.__dict__['object'] # Otherwise, if we have an object, pass the call to it elif self.__dict__.has_key('object') and self.__dict__['object'] is not None: return getattr(self.__dict__['object'], attr) # Otherwise return the attr we have (or None if not found) else: if self.__dict__.has_key(attr): return self.__dict__[attr] else: return None def __setattr__(self, attr, val): # Store the attribute to set it on the object later self.__dict__[attr] = val def save(self): # If we haven't been created with an object, create one if self.object is None: initStrings = [] removeAttrs = [] allAttrs = self.__dict__.keys() for col in self.clazz._SO_columns: if self.__dict__.has_key(col.name):) for attr in removeAttrs: del self.__dict__[attr] # Set the attributes that are not columns for key in allAttrs: if key != 'object' and key != 'clazz': setattr(self.object, key, self.__dict__[key]) del self.__dict__[key] else: # Otherwise set the values on the object we have for key in self.__dict__.keys(): if key != 'object' and key != 'clazz': setattr(self.object, key, self.__dict__[key]) del self.__dict__[key] > On Thu, 2004-12-09 at 05:51, Ian Bicking wrote: > > Peter Butler wrote: > > > I'm just getting to grips with SQLObject so please pardon me if this > > > is a question that has been asked before. > > > > > > Is it possible to defer the insert/update so that the object can be > > > validated before the changes are written to the database? > > > > > > I would like to be able to do the following: > > > > > > object = MyObject() > > > object.field1 = someValue > > > object.field2 = someValue > > > object.validate() object.save() > > > > > > With similar logic for objects that already exist in the database. > > > > > > From looking through the tutorial and source the philosophy seems > > > to be to write all object changes to the database as they occur. > > > This makes sense to me as it simplifies everything. > > > > You can also set several keys at once using .set(); you might require > > that the object be valid for each call to .set(). You can also delay > > saves to the database with _lazyUpdate = True, then you can override the > > .syncUpdate() method to do validation. Hmm... apparently I haven't > > included lazyUpdate in the docs, but it is noted in the News. On Mon, Dec 20, 2004 at 11:01:49AM +1300, Peter Butler wrote: >) Wow! That's a long and a very wrong way of doing things. This is Python! Do not evaluate strings - just manipulate objects. args = ["arg1", 2, 3.0] keywords = {"name1": "valu1", "name2": "value2"} self.object = self.clazz(*args, **kywords) Oleg. -- Oleg Broytmann phd@... Programmers don't die, they just GOSUB without RETURN. On Wed, Dec 22, 2004 at 03:27:53PM +1300, Peter Butler wrote: > Thanks very much for the advice, I thought there must be a nicer way to > do it. I ended up using apply() with the class name and the keyword > dictionary. You only need apply() for very old Python versions. In newer Python (and SQLObject requires such a new Python) you can just use the following simple syntax: args = [...] keywords = {...} function(*args, **keywords) > I tried _lazyUpdate = True and it does half of what I need (i.e. defers > updates to the database until syncUpdate() is called). Is there a > similar mechanism for deferring inserts? There is no, because when you create an object, it have to know its id, so SQLOBject does INSERT and asks for new id. Oleg. -- Oleg Broytmann phd@... Programmers don't die, they just GOSUB without RETURN. The topic of deferring object creation was brought up last December. Thanks for sharing your solution, Peter. I wanted to see what people thought about a different (unimplemented) approach. When dealing with unvalidated data, a temporary object is sufficient, and the overhead for persisting+removing the object is overkill. Typically I just create a normal python object for this purpose. However, this approach requires duplicating definitions of the eventual SQLObject object. (yuk!) It would be ideal to just use the actual SQLObject itself in this situation, but without persistence. I realize that during the initialization of a given SQLObject, the connection is used to create ids and such, which is why a valid connection is required. If there were an in-memory (non-persistent) connection type, maybe something like the following would be possible: in_memory_conn = SQLObject.InMemoryConnection() db_conn = SQLObject.MySQLConnection(....) temp = SomeSQLObject(connection=in_memory_conn) ... # do some validation actions here if validation_passed: persisted = SomeSQLObject(connection=db_conn) persisted = temp #or maybe some way to re-assign the connection of the temp object #and have the object recreated in new connection's database?? #ie temp.save(connection=db_conn) # or resave, or copy, etc No big deal either way... just wanted to throw the idea out there and see what people thought. Thanks for all of the cool tools and ideas everyone... -Charles.
http://sourceforge.net/p/sqlobject/mailman/message/9071120/
CC-MAIN-2014-42
refinedweb
1,133
60.72
Hi, I am trying to figure out how to make a program read 1 character at a time but have run into a snag. When I enter my data, my first character entered does not print. Is there a way to fix this in my loop? I know using normal strings and arrays would be much easier but I am trying to learn more about character manipulation here. An example of the input out put is this: [input]: Hello world [output]: ello world [input]: Hello world [output]: Hello world. <EOF> You can see that the first output 'H' is missing and it is because of the way my loop is incremented but I do not know how to fix this. The code I have is: Also, Is there a way to make sure that first (and only the first) letter is always converted to a Capital with all of the rest lower?Also, Is there a way to make sure that first (and only the first) letter is always converted to a Capital with all of the rest lower?Code:#include<iostream> #include<cctype> using namespace std; int main() { char text_main; int count; text_main = 0; count = 0; cin.get(text_main); while(text_main != '.') { count++; cin.get(text_main); cout << text_main; } cout << endl; return 0; } Any ideals?
http://cboard.cprogramming.com/cplusplus-programming/27391-loop-output-not-quite-what-i-want.html
CC-MAIN-2015-18
refinedweb
214
67.69
My aim is to roll out a big re-theming / re-skinning (including new URL routing) for a Laravel v5 project without touching the existing business logic (as much as possible that is). This is my current approach: I placed a APP_SKIN=v2 entry in my .env file APP_SKIN=v2 .env My app\Http\routes.php file has been changed as follows: app\Http\routes.php if (env('APP_SKIN') === "v2") { # Point to the v2 controllers Route::get('/', 'v2\GeneralController@home' ); ... all other v2 controllers here ... } else { # Point to the original controllers Route::get('/', 'GeneralController@home' ); ... all other controllers } All v2 controllers have been placed in app/Http/Controllers/v2 and namespaced accordingly app/Http/Controllers/v2 resources/views/v2 My question: Is there a "better" way to achieve the above?. Please note that the idea here is to affect as few files as possible when doing the migration, as well as ensure that the admin can simply change an environment variable and "roll back" to the previous skin if there are problems. Routes pass through Middleware. Thus you can achieve this by BeforeMiddleware as follows public function handle($request, Closure $next) { // Get path and append v2 if env is v2 $path = $request->path(); $page = $str = str_replace('', '', $path); // You can replace if neccesary // Before middleware if (env('APP_SKIN') === "v2") { return $next($request); } else { } } Within app/Providers/RouteServiceProvider.php you can define your routes and namespaces, etc. This is where I would put the logic you talked about (rather than in the routes file): protected function mapWebRoutes() { if (App::env('APP_SKIN') === 'v2') { Route::group([ 'middleware' => 'web', 'namespace' => $this->namespace, ], function ($router) { require base_path('routes/web_v2.php'); }); } else { // ... } } This way, you can create separate route files to make it a bit cleaner. Aside from that, I personally can't see a better solution for your situation than what you described as I'm guessing your templates want to vary in the data that they provide, which if that is the case then you will need new controllers - otherwise you could set a variable in a middleware which is then retrieved by your current controllers which could then determine which views, css and js are included. This would mean you would only need to update your existing controllers, but depending upon your current code - this could mean doing just as much work as your current solution.
http://jakzaprogramowac.pl/pytanie/59448,laravel-best-way-to-implement-dynamic-routing-in-routes-php-based-on-environment-variable
CC-MAIN-2017-26
refinedweb
392
58.92
Log message: py-configparser: needs setuptools Log message: py-configparser: updated to 4.0.2 v4.0.2 * Re-release after pulling 4.0.0 and 4.0.1 Log message: py-configparser: updated to 4.0.1 v4.0.1 Cleaned up broken badges and release notes publishing. v4.0.0 Switched to semver for versioning this backport. Project now uses setuptools_scm for tagging releases. Log message: py-configparser: updated to 3.8.1 3.8.1 Synced with Python 3.8.0b3. 3.7.5 Synced project with Python 3.7.4 (no meaningful changes). Log message: py-configparser: updated to 3.7.4 3.7.4 * Project is now officially supported through Tidelift Log. Log message: py-configparser: updated to 3.5.2 3.5.2 Issue 23: Use environment markers to indicate the ‘ordereddict’ dependency \ for Python 2.6. Issue 24: Limit DeprecationWarning when a filename is indicated as a bytestring \ on Python 2. Now the warning is only emitted when py3kwarning is indicated. Log message: py-configparser: updated to 3.5.1 3.5.1 jaraco adopts the package. Moved hosting to GitHub. Updated backports namespace package to conform with other packages sharing the \ namespace. Log message: py-configparser: add python to CATEGORIES; sort PLIST Log message: Follow some redirects.
https://pkgsrc.se/commits.php?path=devel/py-configparser
CC-MAIN-2020-24
refinedweb
215
55.2
14.6. Creating Table-Valued Functions Functions are going to continue to be a focus of this chapter for a bit. Why? Well, functions have a few more twists to them than some of the other assembly uses. In this section, we're going to focus in on table valued functions. They are among the more complex things we need to deal with in this chapter, but, as they are in the T-SQL version, they were also among the more powerful. The uses range far and wide. They can be as simple as special treatment of a column in something you could have otherwise done in a typical T-SQL function or can be as complex as a merge of data from several disparate and external datasources. Go ahead and start another Visual Studio project called ExampleTVF, using the SQL Server project template — also add a new user-defined function. We're going to be demonstrating accessing the file system this time, so add the following references: using System; using System.IO; using System.Collections; using Microsoft.SqlServer.Server; Before we get too much into the code, let's look ahead a bit at some of the things a table-valued function — or TVF — requires: The entry function must implement the IEnumerable interface. This is a special, widely used, interface in .NET that essentially allows for the iteration over some form of row (be it in an array, collection, table, or whatever). As part of this concept, we must also define the FillRowMethodName property. The function specified in this special property will be implicitly ... Get Professional SQL Server™ 2005 Programming now with O’Reilly online learning. O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
https://www.oreilly.com/library/view/professional-sql-servertm/9780764584343/9780764584343_creating_table-valued_functions.html
CC-MAIN-2020-10
refinedweb
293
54.83
Jayden Bell Total Post:110Points:774 Hi Everyone! I have a view with an Ajax form: <%= form_tag( {:action => 'some_action'}, {:remote => true}) do %> ... <%= submit_tag "Submit" %> <% end %> Now, in the target action, I want to display a partial def some_action # some logic render :partial => "some_partial" end The partial is just html. _some_partial.html.erb could be <br>Hi, this is the partial</br> When I submit the form, I see the html response packet is received in the browser (with firebug's net logs), but the html doesn't show up anywhere. Where should the html be? How to render a partial html view from an action? Please help ASAP. Thanks in advance Post:604Points:4228 Re: where does render :partial html end up Hi Jayden! you are not define place where partial view will be render Try this way create a file named some_action.js.erb and write the code in it: // update div with id some_div_id $("#some_div_id").html("<%= escape_javascript(render :partial => 'some_partial') %>"); in controller def some_action # some logic respond_to do |format| format.js end end
https://www.mindstick.com/forum/595/where-does-render-partial-html-end-up
CC-MAIN-2017-47
refinedweb
175
66.44
Kelp::Routes - Routing for a Kelp app use Kelp::Routes; my $r = Kelp::Routes->new( base => 'MyApp' ); $r->add( '/home', 'home' ); The router provides the connection between the HTTP requests and the web application code. It tells the application "If you see a request coming to *this* URI, send it to *that* subroutine for processing". For example, if a request comes to /home, then send it to sub home in the current namespace. The process of capturing URIs and sending them to their corresponding code is called routing. This router was specifically crafted as part of the Kelp web framework. It is, however, possible to use it on its own, if needed. It provides a simple, yet sophisticated routing utilizing Perl 5.10's regular expressions, which makes it fast, robust and reliable. The routing process can roughly be broken down into three steps: First you create a router object: my $r = Kelp::Routes->new(); Then you add your application's routes and their descriptions: $r->add( '/path' => 'Module::function' ); ... Once you have your routes added, you can match with the "match" subroutine. $r->match( $path, $method ); The Kelp framework already does matching for you, so you may never have to do your own matching. The above example is provided only for reference. You can name each of your routes, and use that name later to build a URL: $r->add( '/begin' => { to => 'function', name => 'home' } ); my $url = $r->url('home'); # /begin This can be used in views and other places where you need the full URL of a route. Often routes may get more complicated. They may contain variable parts. For example this one /user/1000 is expected to do something with user ID 1000. So, in this case we need to capture a route that begins with /user/ and then has something else after it. Naturally, when it comes to capturing routes, the first instinct of the Perl programmer is to use regular expressions, like this: qr{/user/(\d+)} -> "sub home" This module will let you do that, however regular expressions can get very complicated, and it won't be long before you lose track of what does what. This is why a good router (this one included) allows for named placeholders. These are words prefixed with special symbols, which denote a variable piece in the URI. To use the above example: "/user/:id" -> "sub home" It looks a little cleaner. Placeholders are variables you place in the route path. They are identified by a prefix character and their names must abide to the rules of a regular Perl variable. If necessary, curly braces can be used to separate placeholders from the rest of the path. There are three types of place holders: These placeholders begin with a column ( :) and must have a value in order for the route to match. All characters are matched, except for the forward slash. $r->add( '/user/:id' => 'module#sub' ); # /user/a -> match (id = 'a') # /user/123 -> match (id = 123) # /user/ -> no match # /user -> no match # /user/10/foo -> no match $r->add( '/page/:page/line/:line' => 'module#sub' ); # /page/1/line/2 -> match (page = 1, line = 2) # /page/bar/line/foo -> match (page = 'bar', line = 'foo') # /page/line/4 -> no match # /page/5 -> no match $r->add( '/{:a}ing/{:b}ing' => 'module#sub' ); # /walking/singing -> match (a = 'walk', b = 'sing') # /cooking/ing -> no match # /ing/ing -> no match Optional placeholders begin with a question mark ? and denote an optional value. You may also specify a default value for the optional placeholder via the "defaults" option. Again, like the explicit placeholders, the optional ones capture all characters, except the forward slash. $r->add( '/data/?id' => 'module#sub' ); # /bar/foo -> match ( id = 'foo' ) # /bar/ -> match ( id = undef ) # /bar -> match ( id = undef ) $r->add( '/:a/?b/:c' => 'module#sub' ); # /bar/foo/baz -> match ( a = 'bar', b = 'foo', c = 'baz' ) # /bar/foo -> match ( a = 'bar', b = undef, c = 'foo' ) # /bar -> no match # /bar/foo/baz/moo -> no match Optional default values may be specified via the defaults option. $r->add( '/user/?name' => { to => 'module#sub', defaults => { name => 'hank' } } ); # /user -> match ( name = 'hank' ) # /user/ -> match ( name = 'hank' ) # /user/jane -> match ( name = 'jane' ) # /user/jane/cho -> no match The wildcard placeholders expect a value and capture all characters, including the forward slash. $r->add( '/:a/*b/:c' => 'module#sub' ); # /bar/foo/baz/bat -> match ( a = 'bar', b = 'foo/baz', c = 'bat' ) # /bar/bat -> no match Curly braces may be used to separate the placeholders from the rest of the path: $r->add( '/{:a}ing/{:b}ing' => 'module#sub' ); # /looking/seeing -> match ( a = 'look', b = 'see' ) # /ing/ing -> no match $r->add( '/:a/{?b}ing' => 'module#sub' ); # /bar/hopping -> match ( a = 'bar', b = 'hopp' ) # /bar/ing -> match ( a = 'bar' ) # /bar -> no match $r->add( '/:a/{*b}ing/:c' => 'module#sub' ); # /bar/hop/ping/foo -> match ( a = 'bar', b = 'hop/p', c = 'foo' ) # /bar/ing/foo -> no match The "match" subroutine will stop and return the route that best matches the specified path. If that route is marked as a bridge, then "match" will continue looking for another match, and will eventually return an array of one or more routes. Bridges can be used for authentication or other route preprocessing. $r->add( '/users', { to => 'Users::auth', bridge => 1 } ); $r->add( '/users/:action' => 'Users::dispatch' ); The above example will require /users/profile to go through two subroutines: Users::auth and Users::dispatch: my $arr = $r->match('/users/view'); # $arr is an array of two routes now, the bridge and the last one matched A quick way to add bridges is to use the "tree" option. It allows you to define all routes under a bridge. Example: $r->add( '/users' => { to => 'users#auth', name => 'users', tree => [ '/profile' => { name => 'profile', to => 'users#profile' }, '/settings' => { name => 'settings', to => 'users#settings', tree => [ '/email' => { name => 'email', to => 'users#email' }, '/login' => { name => 'login', to => 'users#login' } ] } ] } ); The above call to add causes the following to occur under the hood: /users -> MyApp::Users::auth /users/profile -> MyApp::Users::profile /users/settings -> MyApp::Users::settings /users/settings/email -> MyApp::Users::email /users/settings/login -> MyApp::Users::login _with the name of their parent: /users -> 'users' /users/profile -> 'users_profile' /users/settings -> 'users_settings' /users/settings/email -> 'users_settings_email' /users/settings/login -> 'users_settings_login' /usersand /users/settingsroutes are automatically marked as bridges, because they contain a tree. Sets the base class for the routes destinations. my $r = Kelp::Routes->new( base => 'MyApp' ); This will prepend MyApp:: to all route destinations. $r->add( '/home' => 'home' ); # /home -> MyApp::home $r->add( '/user' => 'user#home' ); # /user -> MyApp::User::home $r->add( '/view' => 'User::view' ); # /view -> MyApp::User::view A Kelp application will automatically set this value to the name of the main class. If you need to use a route located in another package, you'll have to wrap it in a local sub: # Problem: $r->add( '/outside' => 'Outside::Module::route' ); # /outside -> MyApp::Outside::Module::route # (most likely not what you want) # Solution: $r->add( '/outside' => 'outside' ); ... sub outside { return Outside::Module::route; } Adds a new route definition to the routes array. $r->add( $path, $destination ); $path can be a path string, e.g. '/user/view' or an ARRAY containing a method and a path, e.g. [ PUT => '/item' ]. The route destination is very flexible. It can be one of these three things: "Users::item". Using a #sign to replace ::is also allowed, in which case the name will get converted. "users#item"becomes "Users::item". $r->add( '/home' => 'user#home' ); $r->add( '/system' => sub { return \%ENV } ); # GET /item/100 -> MyApp::Items::view $r->add( '/item/:id', { to => 'items#view', via => 'GET' } ); See "Destination Options" for details. There are a number of options you can add to modify the behavior of the route, if you specify a hashref for a destination: Sets the destination for the route. It should be a subroutine name or CODE reference. $r->add( '/user' => { to => 'users#home' } ); # /home -> MyApp::Users::home $r->add( '/sys' => { to => sub { ... } }); # /sys -> execute code $r->add( '/item' => { to => 'Items::handle' } ) ; # /item -> MyApp::Items::handle $r->add( '/item' => { to => 'Items::handle' } ); # Same as above Specifies an HTTP method to be considered by "match" when matching a route. # POST /item -> MyApp::Items::add $r->add( '/item' => { via => 'POST', to => 'items#add' } ); A shortcut for the above is this: $r->add( [ POST => '/item' ] => 'items#add' ); Give the route a name, and you can always use it to build a URL later via the "url" subroutine. $r->add( '/item/:id/:name' => { to => 'items#view', name => 'item' } ); # Later $r->url( 'item', id => 8, name => 'foo' ); # /item/8/foo A hashref of checks to perform on the captures. It should contain capture names and stringified regular expressions. Do not use ^ and $ to denote beginning and ending of the matched expression, because it will get embedded in a bigger Regexp. $r->add( '/item/:id/:name' => { to => 'items#view', check => { id => '\d+', # id must be a digit name => 'open|close' # name can be 'open' or 'close' } } ); Set default values for optional placeholders. $r->add( '/pages/?id' => { to => 'pages#view', defaults => { id => 2 } } ); # /pages -> match ( id = 2 ) # /pages/ -> match ( id = 2 ) # /pages/4 -> match ( id = 4 ) If set to one this route will be treated as a bridge. Please see "bridges" for more information. Creates a tree of sub-routes. See "trees" for more information and examples. Returns an array of Kelp::Routes::Pattern objects that match the path and HTTP method provided. Each object will contain a hash with the named placeholders in "named" in Kelp::Routes::Pattern, and an array with their values in the order they were specified in the pattern in "param" in Kelp::Routes::Pattern. $r->add( '/:id/:name', "route" ); for my $pattern ( @{ $r->match('/15/alex') } ) { $pattern->named; # { id => 15, name => 'alex' } $pattern->param; # [ 15, 'alex' ] } Routes that used regular expressions instead of patterns will only initialize the param array with the regex captures, unless those patterns are using named captures in which case the named hash will also be initialized. This module was inspired by Routes::Tiny.
http://search.cpan.org/~minimal/Kelp-0.4012/lib/Kelp/Routes.pm
CC-MAIN-2014-10
refinedweb
1,669
66.88
Provides a hint to the implementation to reschedule the execution of threads, allowing other threads to run. (none). (none). The exact behavior of this function depends on the implementation, in particular on the mechanics of the OS scheduler in use and the state of the system. For example, a first-in-first-out realtime scheduler ( SCHED_FIFO in Linux) would suspend the current thread and put it on the back of the queue of the same-priority threads that are ready to run (and if there are no other threads at the same priority, yield has no effect). The POSIX equivalent of this function is sched_yield. #include <stdio.h> #include <time.h> #include <threads.h> // utility function: difference between timespecs in microseconds double usdiff(struct timespec s, struct timespec e) { double sdiff = difftime(e.tv_sec, s.tv_sec); long nsdiff = e.tv_nsec - s.tv_nsec; if(nsdiff < 0) return 1000000*(sdiff-1) + (1000000000L+nsdiff)/1000.0; else return 1000000*(sdiff) + nsdiff/1000.0; } // busy wait while yielding void sleep_100us() { struct timespec start, end; timespec_get(&start, TIME_UTC); do { thrd_yield(); timespec_get(&end, TIME_UTC); } while(usdiff(start, end) < 100.0); } int main() { struct timespec start, end; timespec_get(&start, TIME_UTC); sleep_100us(); timespec_get(&end, TIME_UTC); printf("Waited for %.3f us\n", usdiff(start, end)); } Possible output: Waited for 100.344 us © cppreference.com Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://docs.w3cub.com/c/thread/thrd_yield/
CC-MAIN-2020-45
refinedweb
226
50.12
XAML 2009 Language Features XAML 2009 is the shorthand term for new XAML language features that extend the existing XAML language specification. XAML 2009 introduces several new directives and constructs. These include the x:Arguments Directive; the x:FactoryMethod Directive; the x:Reference Markup Extension; the x:TypeArguments Directive; and built-in types for common language primitives (for example x:Char). In WPF, you can use XAML 2009 features, but only for XAML that is not WPF markup-compiled. Markup-compiled XAML and the BAML form of XAML do not currently support the XAML 2009 language keywords and features. Note that existing techniques for loading loose XAML in WPF also have possible security and access restrictions to CLR types and the type system that are more restrictive than for markup-compiled XAML. For more information, see Security (WPF) or WPF Security Strategy - Platform Security. XAML 2009 also introduces additional features that either modify the previous XAML 2006 constructs or that modify the basic markup forms. XAML 2009 can support x:Key as an object (a property element that has object element value); however, XAML 2006 only supported x:Key as an attribute. See the "XAML 2009" section of x:Key Directive. XAML 2009 can support XAML namespace (xmlns) definitions on property elements; however, XAML 2006 only supports xmlns definitions on object elements. For attributes that are backed by events, XAML 2006 presumes that markup compilation is involved and submits the events to markup compilation. XAML 2009 supports a markup form that resembles a markup extension, which defers the event wiring until run-time parsing and loading of the XAML. However, WPF applications and XAML scenarios for WPF UI generally do not use this capability. WPF and its XAML 2006 implementation uses the combination of event handler wiring for routed events defined at the UIElement level and its markup compiler step for much of its event attribute processing. The markup compiler also preprocesses any event attributes found in XAML where the build actions declare that the markup compiler is used.
https://msdn.microsoft.com/en-us/library/ee792007
CC-MAIN-2016-50
refinedweb
339
50.77
View Complete Post, I want to fetch data from mysql database to asp.net dropdown control. How can I do this. I can fetch data from ms sql server to asp.net page. Please help me to fetch data from mysql database. i have a dropdownbox and a gridview what I want is to have a list item which populates all data in a gridview. I have tried using list item selected value=0 but to no avail. what is the easiest way to achieve, how would I join fields together? return (from c in storedb.Product_Categories where c.Category_Name.Contains(searchText) orderby c.Category_Name select new { c.Cat_GUID, c.Category_Key && " ;" && c.Category_Name // HOW CAN I DO THIS.....  
http://www.dotnetspark.com/links/21650-linq-problem-fetching-data.aspx
CC-MAIN-2017-13
refinedweb
118
71.61
Author:. Online documentation is all very well, but tabbing round your sixteen open browser windows to see the help topic quickly gets tedious. On the other hand, carrying around a book the dimensions and weight of several combined house bricks is no fun either. This is the market the ‘Phrasebook’ series of books aims to address. PHP and MySQL Phrasebook is out in an updated edition for PHP 5.4, and hits the mark so far as half the title goes. It’s has good general coverage of PHP, but this isn’t a book about using PHP with MySQL. There’s one short chapter of 14 pages on PHP and MySQL (and that’s not until you get to page 229), and another on using PHP with other databases. Other than that, this is a plain vanilla guide to PHP; not that there’s anything wrong with that, but just don’t buy this to learn in depth how to use PHP and MySQL together, nor to learn MySQL. So long as you’re wanting to know about PHP rather than MySQL, the book is well written and hits the mark. Introductory material is missed out, and the first chapter begins with a look at working with strings. This is followed by chapters on arrays and date and time, all the essentials you’d need to get straight to the heart of coding in PHP. By Chapter 4, Wenz has moved on to working with objects in PHP, and covers classes, inheritance, abstract classes, namespaces and traits. Like the rest of the book, you wouldn’t want to learn about object oriented programming using the material, but it’s ideal for finding out how PHP handles OOP. Chapter 5 covers web forms, and starts with the basics of form data, cookies and passwords. Multiline fields, radio buttons, checkboxes and selection lists are looked at next, along with mandatory fields. Having shown you how to get the data in, Wenz moves on to what you might do with it. He briefly discusses escaping output, but you’d need to understand the concept from elsewhere to understand what he means. The sections on validating input and sending the data to a file, email or other endpoint are dealt with more clearly. Cookies and sessions get a chapter to themselves and are dealt with clearly. At this point the book moves on to ways of storing data, starting with a chapter on working with file server files including PHP Streams and Bzip2 archives. MySQL gets a chapter showing how you connect to MySQL, send SQL commands, retrieve query results and use transactions. The material is clear and if you already know MySQL will be enough to show you how it works with PHP. The next chapter looks at working with other databases - SQLite, PostgreSQL, Oracle, Microsoft SQL Server, Firebird and PDO. There’s a chapter on using XML that introduces parsing XML from PHP using SAX and XMLReader, using DOM and XMLWriter, and using XPath with SimpleXML. In each case the description includes sample PHP showing the basic commands, along with a couple of paragraphs giving a brief overview of the process of using the tool under consideration. The final chapter covers communicating with other systems - HTTP servers, FTP Servers, generating and consuming Web Services using NuSOAP, and using the PHP 5 SOAP extension. My verdict on this book is twofold. Taken purely as a PHP phrasebook, it serves its purpose pretty well. The coverage of some material seemed a bit rushed, but a competent programmer would probably have enough info for them to work out what is going on. Taken as a PHP and MySQL Phrasebook, the implication is that you’re being shown how to use PHP and MySQL together throughout the book, and that’s just not what you get. {loadposition morebooksART
http://i-programmer.info/bookreviews/35-php/5732-php-and-mysql-phrasebook.html
CC-MAIN-2014-49
refinedweb
643
67.18
Warning! This page documents an earlier version of Kapacitor, which is no longer actively developed. Kapacitor v1.5 is the most recent stable version of Kapacitor. In addition to defining alert handler in TICKscript Kapacitor supports an alert system that follows a publish subscribe design pattern. Alerts are published to a topic and handlers subscribe to a topic. Topics An alert topic is simply a namespace where alerts are grouped. When an alert event fires it is assigned to a topic. Multiple handlers can be defined on a topic and all handlers process each alert event for the topic. Handlers A handler takes action on incoming alert events for a specific topic. Each handler operates on exactly one topic. A handler definition has a few properties: - ID - The unique ID of the handler. - Kind - The kind of handler, see handlers for a list of available kinds. - Match - A lambda expression to filter matching alerts. By default all alerts match, see matching for details on the match expression. - Options - A map of values, differs by kind. Example See the Using Alert Topics example for a walk through defining and using alert topics.
https://docs.influxdata.com/kapacitor/v1.3/alerts
CC-MAIN-2020-10
refinedweb
191
67.04
Release 5.4 i 4.4 Making use of context-sensitive comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 4.5 Defining your own explanation for failed assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 4.6 Assertion introspection details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 10 Warnings Capture 71 10.1 @pytest.mark.filterwarnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 10.2 Disabling warnings summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 10.3 Disabling warning capture entirely . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 10.4 DeprecationWarning and PendingDeprecationWarning . . . . . . . . . . . . . . . . . . . . . . . . . 73 10.5 Ensuring code triggers a deprecation warning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 10.6 Asserting warnings with the warns function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 10.7 Recording warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 ii 10.8 Custom failure messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 10.9 Internal pytest warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 iii 19.5 Assertion Rewriting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 19.6 Requiring/Loading plugins in a test module or conftest file . . . . . . . . . . . . . . . . . . . . . . . 118 19.7 Accessing another plugin by name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 19.8 Registering custom markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 19.9 Testing plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 21 Logging 129 21.1 caplog fixture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 21.2 Live Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 21.3 Release notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 21.4 Incompatible changes in pytest 3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 26 Configuration 203 26.1 Command line options and configuration file settings . . . . . . . . . . . . . . . . . . . . . . . . . . 203 26.2 Initialization: determining rootdir and inifile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 26.3 How to change command line options defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 iv 26.4 Builtin configuration file options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 31 History 277 31.1 Focus primary on smooth transition - stance (pre 6.0) . . . . . . . . . . . . . . . . . . . . . . . . . . 277 36 Sponsor 303 36.1 OpenCollective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 38 License 307 v40 Historical Notes 311 40.1 Marker revamp and iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 40.2 cache plugin integrated into the core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 40.3 funcargs and pytest_funcarg__ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 40.4 @pytest.yield_fixture decorator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 40.5 [pytest] header in setup.cfg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 40.6 Applying marks to @pytest.mark.parametrize parameters . . . . . . . . . . . . . . . . . . 313 40.7 @pytest.mark.parametrize argument names as a tuple . . . . . . . . . . . . . . . . . . . . 314 40.8 setup: is now an “autouse fixture” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 40.9 Conditions as strings instead of booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 40.10 pytest.set_trace() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 40.11 “compat” properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Index 323 vi pytest Documentation, Release 5.4 Contents 1pytest Documentation, Release 5.4 2 Contents CHAPTER 1 3pytest Documentation, Release 5.4 def test_answer(): assert func(3) == 5 $ pytest=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 1 item test_sample.py F [100%] def test_answer():> assert func(3) == 5E assert 4 == 5E + where 4 = func(3) test_sample.py:6: AssertionError========================= short test summary info ==========================FAILED test_sample.py::test_answer - assert 4 == 5============================ 1 failed in 0.12s ============================= This test returns a failure report because func(3) does not return 5. Note: You can use the assert statement to verify test expectations. pytest’s Advanced assertion introspection willintelligently report intermediate values of the assert expression so you can avoid the many names of JUnit legacymethods. pytest will run all files of the form test_*.py or *_test.py in the current directory and its subdirectories. Moregenerally, it follows standard test discovery rules. Use the raises helper to assert that some code raises an exception: # content of test_sysexit.pyimport pytest def f(): raise SystemExit(1) (continues on next page) def test_mytest(): with pytest.raises(SystemExit): f() $ pytest -q test_sysexit.py. [100%]1 passed in 0.12s Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a classcontaining more than one test: # content of test_class.pyclass TestClass: def test_one(self): x = "this" assert "h" in x def test_two(self): x = "hello" assert hasattr(x, "check") pytest discovers all tests following its Conventions for Python test discovery, so it finds both test_ prefixedfunctions. There is no need to subclass anything, but make sure to prefix your class with Test otherwise the classwill be skipped. We can simply run the module by passing its filename: $ pytest -q test_class.py.F [100%]================================= FAILURES =================================____________________________ TestClass.test_two ____________________________ def test_two(self): assert hasattr(x, "check")E AssertionError: assert FalseE + where False = hasattr('hello', 'check') test_class.py:8: AssertionError========================= short test summary info ==========================FAILED test_class.py::TestClass::test_two - AssertionError: assert False1 failed, 1 passed in 0.12s The first test passed and the second failed. You can easily see the intermediate values in the assertion to help youunderstand the reason for the failure. pytest provides Builtin fixtures/function arguments to request arbitrary resources, like a unique temporary directory: # content of test_tmpdir.pydef test_needsfiles(tmpdir): print(tmpdir) assert 0 List the name tmpdir in the test function signature and pytest will lookup and call a fixture factory to create theresource before performing the test function call. Before the test runs, pytest creates a unique-per-test-invocationtemporary directory: $ pytest -q test_tmpdir.pyF [100%]================================= FAILURES =================================_____________________________ test_needsfiles ______________________________ tmpdir = local('PYTEST_TMPDIR/test_needsfiles0') def test_needsfiles(tmpdir): print(tmpdir)> assert 0E assert 0 test_tmpdir.py:3: AssertionError--------------------------- Captured stdout call ---------------------------PYTEST_TMPDIR/test_needsfiles0========================= short test summary info ==========================FAILED test_tmpdir.py::test_needsfiles - assert 01 failed in 0.12s Note that this command omits fixtures with leading _ unless the -v option is added. Check out additional pytest resources to help you customize tests for your unique workflow: • “Calling pytest through python -m pytest” for command line invocation examples • “Using pytest with an existing test suite” for working with pre-existing tests • “Marking test functions with attributes” for information on the pytest.mark mechanism • “pytest fixtures: explicit, modular, scalable” for providing a functional baseline to your tests • “Writing plugins” for managing and writing plugins • “Good Integration Practices” for virtualenv and test layouts You can invoke testing through the Python interpreter from the command line: This is almost equivalent to invoking the command line script pytest [...] directly, except that calling viapython will also add the current directory to sys.path. Note: If you would like to customize the exit code in some scenarios, specially when no tests are collected, considerusing the pytest-custom_exit_code plugin. 7pytest Documentation, Release 5.4 Pytest supports several ways to run and select tests from the command-line.Run tests in a modulepytest test_mod.py This will run tests which contain names that match the given string expression (case-insensitive), which can in-clude Python operators that use filenames, class names and function names as variables. The example above willrun TestMyClass.test_something but not TestMyClass.test_method_simple.Run tests by node idsEach collected test is assigned a unique nodeid which consist of the module filename followed by specifiers likeclass names, function names and parameters from parametrization, separated by :: characters.To run a specific test within a module:pytest test_mod.py::test_func Will run all tests which are decorated with the @pytest.mark.slow decorator.For more information see marks.Run tests from packages This will import pkg.testing and use its filesystem location to find and run tests from. pytest --tb=auto # (default) 'long' tracebacks for the first and last # entry, but 'short' style for the other entriespytest --tb=long # exhaustive, informative traceback formattingpytest --tb=short # shorter traceback formatpytest --tb=line # only one line per failurepytest --tb=native # Python standard library formattingpytest --tb=no # no traceback at all The --full-trace causes very long traces to be printed on error (longer than --tb=long). It also ensures thata stack trace is printed on KeyboardInterrupt (Ctrl+C). This is very useful if the tests are taking too long and youinterrupt them with Ctrl+C to find out where the tests are hanging. By default no output will be shown (becauseKeyboardInterrupt is caught by pytest). By using this option you make sure a trace is shown. The -r flag can be used to display a “short test summary info” at the end of the test session, making it easy in largetest suites to get a clear picture of all failures, skips, xfails, etc.It defaults to fE to list failures and errors.Example: # content of test_example.pyimport pytest @pytest.fixturedef error_fixture(): assert 0 def test_ok(): print("ok") def test_fail(): assert 0 def test_error(error_fixture): pass def test_skip(): pytest.skip("skipping this test") def test_xfail(): pytest.xfail("xfailing this test") @pytest.mark.xfail(reason="always xfail")def test_xpass(): pass $ pytest -ra=========================== test_example.py:6: AssertionError================================= FAILURES =================================________________________________ test_fail _________________________________ def test_fail():> assert 0E assert 0 test_example.py:14: AssertionError========================= short test summary info ==========================SKIPPED [1] $REGENDOC_TMPDIR/test_example.py:22: skipping this testXFAIL test_example.py::test_xfail reason: xfailing this testXPASS test_example.py::test_xpass always xfailERROR test_example.py::test_error - assert 0FAILED test_example.py::test_fail - assert 0== 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s === The -r options accepts a number of characters after it, with a used above meaning “all except passes”.Here is the full list of available characters that can be used: • f - failed • E - error • s - skipped • x - xfailed • X - xpassed • p - passed • P - passed with outputSpecial characters for (de)selection of groups: • a - all except pP • A - all • N - none, this can be used to display nothing (since fE is the default)More than one character can be used, so for example to only see failed and skipped tests, you can execute: $ pytest -rfs=========================== def test_fail():> assert 0E assert 0 test_example.py:14: AssertionError========================= short test summary info ==========================FAILED test_example.py::test_fail - assert 0SKIPPED [1] $REGENDOC_TMPDIR/test_example.py:22: skipping this test== 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s === Using p lists the passing tests, whilst P adds an extra section “PASSES” with those tests that passed but had capturedoutput: $ pytest -rpP=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 6 items test_example.py:14: AssertionError================================== PASSES ==================================_________________________________ test_ok __________________________________--------------------------- Captured stdout call ---------------------------ok========================= short test summary info ==========================PASSED test_example.py::test_ok== 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s === Python comes with a builtin Python debugger called PDB. pytest allows one to drop into the PDB prompt via acommand line option: pytest --pdb This will invoke the Python debugger on every failure (or KeyboardInterrupt). Often you might only want to do thisfor the first failing test to understand a certain failure situation: pytest -x --pdb # drop to PDB on first failure, then end test sessionpycan also manually access the exception information, for example: pytest allows one to drop into the PDB prompt immediately at the start of each test via a command line option: pytest --trace This will invoke the Python debugger at the start of every test. To set a breakpoint in your code use the native Python import pdb;pdb.set_trace() call in your code andpytest automatically disables its output capture for that test: • Output capture in other tests is not affected. • Any prior test output that has already been captured and will be processed as such. • Output capture gets resumed when ending the debugger session (via the continue command). Python 3.7 introduces a builtin breakpoint() function. Pytest supports the use of breakpoint() with thefollowing behaviours: • When breakpoint() is called and PYTHONBREAKPOINT is set to the default value, pytest will use the custom internal PDB trace UI instead of the system default Pdb. • When tests are complete, the system will default back to the system Pdb trace UI. • With --pdb passed to pytest, the custom internal Pdb trace UI is used with both breakpoint() and failed tests/unhandled exceptions. • --pdbcls can be used to specify a custom debugger class. pytest --durations=10 By default, pytest will not show test durations that are too small (<0.01s) unless -vv is passed on the command-line. Note: This functionality has been integrated from the external pytest-faulthandler plugin, with two small differences: • To disable it, use -p no:faulthandler instead of --no-faulthandler: the former can be used with any plugin, so it saves one option. • The --faulthandler-timeout command-line option has become the faulthandler_timeout con- figuration option. It can still be configured from the command-line using -o faulthandler_timeout=X. To create result files which can be read by Jenkins or other Continuous integration servers, use this invocation: pytest --junitxml=path [pytest]junit_suite_name = my_suite [pytest]junit_duration_report = call 2.14.1 record_property If you want to log additional information for a test, you can use the record_property fixture: def test_function(record_property): record_property("example_key", 1) assert True This will add an extra property example_key="1" to the generated testcase tag: <properties> <property name="example_key" value="1" /> </properties></testcase> # content of conftest.py # content of test_function.pyimport pytest @pytest.mark.test_id(1501)def test_function(): assert True <properties> <property name="test_id" value="1501" /> </properties></testcase> Warning: Please note that using this feature will break schema verifications for the latest JUnitXML schema. This might be a problem when used with some CI servers. 2.14.2 record_xml_attribute To add an additional xml attribute to a testcase element, you can use record_xml_attribute fixture. This canalso be used to override existing values: def test_function(record_xml_attribute): record_xml_attribute("assertions", "REQ-1234") record_xml_attribute("classname", "custom_classname") print("hello world") assert True Unlike record_property, this will not add a new child element. Instead, this will add an attributeassertions="REQ-1234" inside the generated testcase tag and override the default classname with"classname=custom_classname": <system-out> hello world </system-out></testcase> Warning: record_xml_attribute is an experimental feature, and its interface might be replaced by some- thing more powerful and general in future versions. The functionality per-se will be kept, however. Using this over record_xml_property can help when using ci tools to parse the xml report. However, some parsers are quite strict about the elements and attributes that are allowed. Many tools use an xsd schema (like the example below) to validate incoming xml. Make sure you are using attribute names that are allowed by your parser. Below is the Scheme used by Jenkins to validate the XML report: <xs:element <xs:complexType> <xs:sequence> <xs:element <xs:element <xs:element <xs:element <xs:element </xs:sequence> <xs:attribute <xs:attribute <xs:attribute <xs:attribute <xs:attribute </xs:complexType> </xs:element> 2.14.3 record_testsuite_property @pytest.fixture(scope="session", autouse=True)def log_global_env_facts(record_testsuite_property): record_testsuite_property("ARCH", "PPC") record_testsuite_property("STORAGE_TYPE", "CEPH") class TestMe: def test_foo(self): assert True The fixture is a callable which receives name and value of a <property> tag added at the test-suite level of thegenerated xml:<testsuite errors="0" failures="0" name="pytest" skipped="0" tests="1" time="0.006"> <properties> <property name="ARCH" value="PPC"/> (continues on next page) </testsuite> name must be a string, value will be converted to a string and properly xml-escaped.The generated XML is compatible with the latest xunit standard, contrary to record_property andrecord_xml_attribute. pytest --resultlog=path and look at the content at the path location. Such files are used e.g. by the PyPy-test web page to show test resultsover several revisions. Warning: This option is rarely used and is scheduled for removal in pytest 6.0. If you use this option, consider using the new pytest-reportlog plugin instead. See the deprecation docs for more information. pytest --pastebin=failed This will submit test run information to a remote Paste service and provide a URL for each failure. You may selecttests as usual or add for example -x if you only want to send one particular failure.Creating a URL for a whole test session log: pytest --pastebin=all You can early-load plugins (internal and external) explicitly in the command-line with the -p option: pytest -p mypluginmodule pytest -p pytest_cov To disable loading specific plugins at invocation time, use the -p option together with the prefix no:.Example: to disable loading the plugin doctest, which is responsible for executing doctest tests from text files,invoke pytest like this: pytest -p no:doctest pytest.main() this acts as if you would call “pytest” from the command line. It will not raise SystemExit but return the exitcodeinstead. You can pass in options and arguments: pytest.main(["-x", "mytestdir"]) # content of myinvoke.pyimport pytest class MyPlugin: def pytest_sessionfinish(self): print("*** test run reporting finishing") pytest.main(["-qq"], plugins=[MyPlugin()]) Running it will show that MyPlugin was added and its hook was invoked: $ python myinvoke.py.FEsxX. [100%]*** test ˓→run reporting finishing @pytest.fixture def error_fixture(): (continues on next page) test_example.py:14: AssertionError========================= short test summary info ==========================FAILED test_example.py::test_fail - assert 0ERROR test_example.py::test_error - assert 0 Note: Calling pytest.main() will result in importing your tests and any modules that they import. Due to thecaching mechanism of python’s import system, making subsequent calls to pytest.main() from the same processwill not reflect changes to those files between the calls. For this reason, making multiple calls to pytest.main()from the same process (in order to re-run tests, for example) is not recommended. Pytest can be used with most existing test suites, but its behavior differs from other test runners such as nose orPython’s default unittest framework.Before using this section you will want to install pytest. Say you want to contribute to an existing repository somewhere. After pulling the code into your development spaceusingyour tests run against it as if it were installed.Setting up your project in development mode lets you avoid having to reinstall every time you want to run your tests,and is less brittle than mucking about with sys.path to point your tests at local code.Also consider using tox. 21pytest Documentation, Release 5.4 pytest allows you to use the standard python assert for verifying expectations and values in Python tests. Forexample, you can write the following:# content of test_assert1.pydef f(): return 3 def test_function(): assert f() == 4 to assert that your function returns a certain value. If this assertion fails you will see the return value of the functioncall:$ pytest test_assert1.py=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 1 item test_assert1.py F [100%] def test_function():> assert f() == 4E assert 3 == 4E + where 3 = f() 23pytest Documentation, Release 5.4 pytest has support for showing the values of the most common subexpressions including calls, attributes, compar-isons, and binary and unary operators. (See Demo of Python failure reports with pytest). This allows you to use theidiomatic python constructs without boilerplate code while not losing introspection information.However, if you specify a message with the assertion like this: then no assertion introspection takes places at all and the message will be simply shown in the traceback.See Assertion introspection details for more information on assertion introspection.of interest are .type, .value and .traceback.You can pass a match keyword parameter to the context-manager to test that a regular expression matches on the stringrepresentation of an exception (similar to the TestCase.assertRaisesRegexp method from unittest): def myfunc(): raise ValueError("Exception 123 raised") def test_match(): with pytest.raises(ValueError, match=r".* 123 .*"): myfunc() The regexp parameter of the match method is matched with the re.search function, so in the above examplematch='123' would have worked as well.There’s an alternate form of the pytest.raises function where you pass a function that will be executed with thegiven failing in a more specific way than just having any exception raised:@pytest.mark.xfail(raises=IndexError)def test_f(): f() Using pytest.raises is likely to be better for cases where you are testing exceptions your own code is deliber-ately raising, whereas using @pytest.mark.xfail with a check function is probably better for something likedocumenting unfixed bugs (where the test describes what “should” happen) or bugs in dependencies. You can check that code raises a particular warning using pytest.warns. pytest has rich support for providing context-sensitive information when it encounters comparisons. For example:# content of test_assert2.py def test_set_comparison(): set1 = set("1308") set2 = set("8035") assert set1 == set2 test_assert2.py F [100%] def test_set_comparison(): set1 = set("1308") set2 = set("8035") (continues on next page) test_assert2.py:6: AssertionError========================= short test summary info ==========================FAILED test_assert2.py::test_set_comparison - AssertionError: assert {'0'...============================ 1 failed in 0.12s ============================= It is possible to add your own detailed explanations by implementing the pytest_assertrepr_compare hookAs an example consider adding the following hook in a conftest.py file which provides an alternative explanation forFoo objects:# content of conftest.pyfrom test_foocompare import Foo def test_compare(): f1 = Foo(1) f2 = Foo(2) assert f1 == f2 you can run the test module and get the custom output defined in the conftest file: $ pytest -q test_foocompare.pyF [100%]================================= FAILURES =================================_______________________________ test_compare _______________________________ def test_compare(): f1 = Foo(1) f2 = Foo(2)> assert f1 == f2E assert Comparing Foo instances:E vals: 1 != 2 test_foocompare.py:12: AssertionError========================= short test summary info ==========================FAILED test_foocompare.py::test_compare - assert Comparing Foo instances:1 failed in 0.12s Reporting details about a failing assertion is achieved by rewriting assert statements before they are run. Rewrittenassert statements put introspection information into the assertion failure message. pytest only rewrites test modulesdirectly discovered by its test collection process, so asserts in supporting modules which are not themselves testmodules will not be rewritten.You can manually enable assertion rewriting for an imported module by calling register_assert_rewrite before youimport it (a good place to do that is in your root conftest.py).For further information, Benjamin Peterson wrote up Behind the scenes of pytest’s new assertion rewriting. pytest will write back the rewritten modules to disk for caching. You can disable this behavior (for example toavoid leaving stale .pyc files around in projects that move files around a lot) by adding this to the top of yourconftest.py file: import sys sys.dont_write_bytecode = True Note that you still get the benefits of assertion introspection, the only change is that the .pyc files won’t be cachedon disk. Additionally, rewriting will silently skip caching if it cannot write new .pyc files, i.e. in a read-only filesystem or azipfile. pytest rewrites test modules on import by using an import hook to write new pyc files. Most of the time this workstransparently. However, if you are working with the import machinery yourself, the import hook may interfere.If this is the case you have two options: • Disable rewriting for a specific module by adding the string PYTEST_DONT_REWRITE to its docstring. • Disable rewriting for all modules by using --assert=plain. Add assert rewriting as an alternate introspection technique. Introduce the --assert option. Deprecate --no-assert and --nomagic. Removes the --no-assert and --nomagic options. Removes the --assert=reinterp option. Software test fixtures initialize test functions. They provide a fixed baseline so that tests execute reliably and produceconsistent, repeatable, results. Initialization may setup services, state, or other operating environments. These areaccessed by test functions through arguments; for each fixture used by a test function there is typically a parameter(named after the fixture) in the test function’s definition.pytest fixtures offer dramatic improvements over the classic xUnit style of setup/teardown functions: • fixtures have explicit names and are activated by declaring their use from test functions, modules, classes or whole projects. • fixtures are implemented in a modular manner, as each fixture name triggers a fixture function which can itself use other fixtures. •classic to new style, as you prefer. You can also start out from existing unittest.TestCase style or nose based projects.Fixtures are defined using the @pytest.fixture decorator, described below. Pytest has useful built-in fixtures, listed herefor reference: capfd Capture, as text, output to file descriptors 1 and 2. capfdbinary Capture, as bytes, output to file descriptors 1 and 2. caplog Control logging and access log entries. capsys Capture, as text, output to sys.stdout and sys.stderr. capsysbinary Capture, as bytes, output to sys.stdout. 29pytest Documentation, Release 5.4 Test functions can receive fixture objects by naming them as an input argument. For each argument name, a fixturefunction with that name provides the fixture object. Fixture functions are registered by marking them with @pytest.fixture. Let’s look at a simple self-contained test module containing a fixture and a test function using it: # content of ./test_smtpsimple.pyimport pytest @pytest.fixturedef smtp_connection(): import smtpl-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 1 item test_smtpsimple.py F [100%] def test_ehlo(smtp_connection): response, msg = smtp_connection.ehlo() assert response == 250> assert 0 # for demo purposesEexact protocol used by pytest to call the test function this way: 1. pytest finds the test_ehlo because of the test_ prefix. The test function needs a function argument named smtp_connection. A matching fixture function is discovered by looking for a fixture-marked function named smtp_connection. 2. smtp_connection() is called to create an instance. 3. test_ehlo(<smtp_connection instance>) is called and fails in the last line of the test function.Note that if you misspell a function argument or want to use one that isn’t available, you’ll see an error with a list ofavailable function arguments. to see available fixtures (fixtures with leading _ are only shown if you add the -v option). Fixtures allow test functions to easily receive and work against specific pre-initialized application objects withouthaving to care about import/setup/cleanup details. It’s a prime example of dependency injection where fixture functionstake the role of the injector and test functions are the consumers of fixture objects. If during implementing your tests you realize that you want to use a fixture function from multiple test files you canmove it to a conftest.py file. You don’t need to import the fixture you want to use in a test, it automatically getsdiscovered by pytest. The discovery of fixture functions starts at test classes, then test modules, then conftest.pyfiles and finally builtin and third party plugins.You can also use the conftest.py file to implement local per-directory plugins. If you want to make test data from files available to your tests, a good way to do this is by loading these data in afixture for use by your tests. This makes use of the automatic caching mechanisms of pytest.Another good approach is by adding the data files in the tests folder. There are also community plugins availableto help managing this aspect of testing, e.g. pytest-datadir and pytest-datafiles. Fixtures requiring network access depend on connectivity and are usually time-expensive to create. Extending theprevious example, we can add a scope="module" parameter to the @pytest.fixture invocation to cause thedecorated smtp_connection fixture function to only be invoked once per test module (the default is to invoke onceper test function). Multiple test functions in a test module will thus each receive the same smtp_connection fixtureinstance, thus saving time. Possible values for scope are: function, class, module, package or session.The next example puts the fixture function into a separate conftest.py file so that tests from multiple test modulesin the directory can access the fixture function: # content of conftest.pyimport pytestimport smtplib @pytest.fixture(scope="module")def smtp_connection(): return smtplib.SMTP("smtp.gmail.com", 587, timeout=5) The name of the fixture again is smtp_connection and you can access its result by listing the namesmtp_connection as an input parameter in any test or fixture function (in or below the directory wherecon-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cache (continues on next page) test_module.py FF [100%] def test_ehlo(smtp_connection): response, msg = smtp_connection.ehlo() assert response == 250 assert b"smtp.gmail.com" in msg> assert 0 # for demo purposesE assert 0 test_module.py:7: AssertionError________________________________ test_noop _________________________________ def test_noop(smtp_connection): response, msg = smtp_connection.noop() assert response == 250> assert 0 # for demo purposesE assert 0 test_module.py:13: AssertionError========================= short test summary info ==========================FAILED test_module.py::test_ehlo - assert 0FAILEDvalues in the traceback. As a result, the two test functions using smtp_connection run as quick as a single onebecause. Note: Pytest will only cache one instance of a fixture at a time. This means that when using a parametrized fixture,pytest may invoke a fixture more than once in the given scope. 5.5. Scope: sharing a fixture instance across tests in a class, module or session 33pytest Documentation, Release 5.4 In pytest 3.7 the package scope has been introduced. Package-scoped fixtures are finalized when the last test of apackage. @pytest.fixture(scope=determine_scope)def docker_container(): yield spawn_container() Within a function request for fixtures, those of higher-scopes (such as session) are instantiated before lower-scopedfixtures (such as function or class). The relative order of fixtures of same scope follows the declared order in thetest function and honours dependencies between fixtures. Autouse fixtures will be instantiated before explicitly usedfixtures.Consider the code below:import pytest @pytest.fixture(scope="session")def s1(): order.append("s1") @pytest.fixturedef f1(f3): order.append("f1") @pytest.fixturedef f3(): order.append("f3") @pytest.fixture(autouse=True)def a1(): order.append("a1") @pytest.fixturedef f2(): order.append("f2") pytest supports execution of fixture specific finalization code when the fixture goes out of scope. By using a yieldstatement instead of return, all the code after the yield statement serves as the teardown code: import smtplibimport pytest @pytest.fixture(scope="module")def smtp_connection(): (continues on next page) The print and smtp.close() statements will execute when the last test in the module has finished execution,regardless of the exception status of the tests.Let’s execute it: $ pytest -s -q --tb=noFFteardown smtp We see that the smtp_connection instance is finalized after the two tests finished execution. Note that if wedecorated our fixture function with scope='function' then fixture setup and cleanup would occur around eachsingle test. In either case the test module itself does not need to change or know about these details of fixture setup.Note that we can also seamlessly use the yield syntax with with statements: # content of test_yield2.py smtp_connection object automatically closes when the with statement ends.Using the contextlib.ExitStack context manager finalizers will always be called regardless if the fixture setup coderaises an exception. This is handy to properly close all resources created by a fixture even if one of them fails to becreated/acquired: # content of test_yield3.py import contextlib @contextlib.contextmanagerdef connect(port): ... # create connection yield ... # close connection @pytest.fixture (continues on next page) In the example above, if "C28" fails with an exception, "C1" and "C3" will still be properly closed.Note that if an exception happens during the setup code (before the yield keyword), the teardown code (after theyield)import smtplibimport import contextlibimport functools @pytest.fixtured. Fixture functions can accept the request object to introspect the “requesting” test function, class or module context.Further extending the previous smtp_connection fixture example, let’s read an optional server URL from the testmodule which uses our fixture: just execute again, nothing much has changed: $ pytest -s -q --tb=noFFfinalizing <smtplib.SMTP object at 0xdeadbeef> (smtp.gmail.com) Let’s quickly create another test module that actually sets the server URL in its module namespace: # content of test_anothersmtp.py def test_showhelo(smtp_connection): assert 0, smtp_connection.helo() Running it: voila! The smtp_connection fixture function picked up our mail server name from the module namespace. The “factory as fixture” pattern can help in situations where the result of a fixture is needed multiple times in a singletest. Instead of returning data directly, the fixture instead returns a function which generates the data. This functioncan then be called multiple times in the test.Factories can have parameters as needed: @pytest.fixtured.fixturedef make_customer_record(): created_records = [] def _make_customer_record(name): record = models.Customer(name=name, orders=[]) created_records.append(record) return record yield _make_customer_record Fixture functions can be parametrized in which case they will be called multiple times, each time executing the setof dependent tests, i. e. the tests that depend on this fixture. Test functions usually do not need to be aware of theirre-running. Fixture parametrization helps to write exhaustive functional tests for components which themselves canbe configured in multiple ways. Extending the previous example, we can flag the fixture to create two smtp_connection fixture instances whichwill cause all tests using the fixture to run twice. The fixture function gets access to each parameter through the specialrequest object:# content of conftest.pyimport pytestimport smtplib The main change is the declaration of params with @pytest.fixture, a list of values for each of which thefixture function will execute and can access a value via request.param. No test function code needs to change.So let’s just do another run:$ pytest -q test_module.pyFFFF [100%]================================= FAILURES =================================________________________ test_ehlo[smtp.gmail.com] _________________________ test_module.py:7: AssertionError________________________ test_noop[smtp.gmail.com] _________________________ test_module.py:13: AssertionError________________________ test_ehlo[mail.python.org] ________________________ def test_ehlo(smtp_connection): response, msg = smtp_connection.ehlo() assert response == 250> assert b"smtp.gmail.com" in msgE AssertionError: assert b'smtp.gmail.com' in b'mail.python. ˓→org\nPIPELINING\nSIZE 51200000\nETRN\nSTARTTLS\nAUTH DIGEST-MD5 NTLM CRAM- ˓→MD5\nENHANCEDSTATUSCODES\n8BITMIME\nDSN\nSMTPUTF8\nCHUNKING' test_module.py:13: AssertionError------------------------- Captured stdout teardown -------------------------finalizing <smtplib.SMTP object at 0xdeadbeef>========================= short test summary info ==========================FAILED test_module.py::test_ehlo[smtp.gmail.com] - assert 0FAILED test_module.py::test_noop[smtp.gmail.com] - assert 0FAILED test_module.py::test_ehlo[mail.python.org] - AssertionError: asser...FAILED test_module.py::test_noop[mail.python.org] - assert 04 failed in 0.12s We see that our two test functions each ran twice, against the different smtp_connection instances. Note also,that with the mail.python.org connection the second test fails in test_ehlo because a different server stringto acertain fixture value by using the ids keyword argument:# content of test_ids.pyimport pytest def test_a(a): pass def idfn(fixture_value): if fixture_value == 0: return "eggs" else: return None def test_b(b): pass The above shows how ids can be either a list of strings to use or a function which will be called with the fixture valueand then has to return a string to use. In the latter case if the function return None then pytest’s auto-generated ID willbe used.Running the above tests results in the following test IDs being used: $ pytest --collect-only=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected]> pytest.param() can be used to apply marks in values sets of parametrized fixtures in the same way that they canbe used with @pytest.mark.parametrize.Example: # content of test_fixture_marks.pyimport pytest def test_data(data_set): pass Running this test will skip the invocation of data_set with value 2: $ pytest test_fixture_marks.py -v=========================== 3 items In addition to using fixtures in test functions, fixture functions can use other fixtures themselves. This contributesto a modular design of your fixtures and allows re-use of framework-specific fixtures across many projects. As asimple example, we can extend the previous example and instantiate an object app where we stick the already definedsmtp_connection resource into it: # content of test_appsetup.py class App:an App object with it. Let’s run it: $ pytest -v test_appsetup.py=========================== 2 items Due to the parametrization of smtp_connection, the test will run twice with two different App instances andrespective smtp servers. There is no need for the app fixture to be aware of the smtp_connection parametrizationbecause pytest will fully analyse the fixture dependency graph.Note that the app fixture has a scope of module and uses a module-scoped smtp_connection fixture. Theexample would still work if smtp_connection was cached on a session scope: it is fine for fixtures to use“broader” scoped fixtures but not the other way round: A session-scoped fixture could not use a module-scoped onein a meaningful way. pytest minimizes the number of active fixtures during test runs. If you have a parametrized fixture, then all the testsusingfunctions perform print calls to show the setup/teardown flow:# content of test_module.pyimport pytest def test_0(otherarg): print(" RUN test0 with otherarg", otherarg) def test_1(modarg): print(" RUN test1 with modarg", modarg) Let’s run the tests in verbose mode and with looking at the print-output:$ pytest -v -s test_module.py=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_ ˓→PREFIX/bin/python cachedir: $PYTHON_PREFIX/.pytest_cache (continues on next page) You can see that the parametrized module-scoped modarg resource caused an ordering of test execution that leadto the fewest possible “active” resources. The finalizer for the mod1 parametrized resource was executed before themod2 resource was setup.In particular notice that test_0 is completely independent and finishes first. Then test_1 is executed with mod1, thentest_2 with mod1, then test_1 with mod2 and finally test_2 with mod2.The otherarg parametrized resource (having function scope) was set up before and teared down after every test thatused it. Sometimes test functions do not directly need access to a fixture object. For example, tests may require to operatewith an empty directory as the current working directory but otherwise do not care for the concrete directory. Here ishow you can use the standard tempfile and pytest fixtures to achieve it. We separate the creation of the fixture into aconftest.py file: import osimport shutilimport tempfile @pytest.fixturedef cleandir(): old_cwd = os.getcwd() newpath = tempfile.mkdtemp() os.chdir(newpath) yield os.chdir(old_cwd) shutil.rmtree(newpath) # content of test_setenv.pyimport osimportas if you specified a “cleandir” function argument to each of them. Let’s run it to verify our fixture is activated and thetests pass: $ pytest -q.. [100%]2 passed in 0.12s . Occasionally, you may want to have fixtures get invoked automatically without declaring a function argument ex-plicitly or a usefixtures decorator. As a practical example, suppose we have a database fixture which has a be-gin/rollback/commit architecture and we want to automatically surround each test method by a transaction and arollback. Here is a dummy self-contained implementation of this idea: # content of test_db_transact.py class DB: def __init__(self): self.intransaction = [] def rollback(self): self.intransaction.pop() @pytest.fixture(scope="module")def db(): return DB() class TestClass: @pytest.fixture(autouse=True) def transact(self, request, db): db.begin(request.function.__name__) yield db.rollback() The class-level transact fixture is marked with autouse=true which implies that all test methods in the class willuse this fixture without a need to state it in the test function signature or with a class-level usefixtures decorator.If we run it, we get two passing tests: $ pytest -q.. [100%]2 passed in 0.12s # content of conftest.py@pytest.fixturedef transact(request, db): db.begin() yield db.rollback() @pytest.mark.usefixtures("transact")class TestClass: def test_method1(self): ... All test methods in this TestClass will use the transaction fixture while other test classes or functions in the modulewill not use it unless they also add a transact reference. In relatively large test suite, you most likely need to override a global or root fixture with a locally definedone, keeping the test code readable and maintainable.super fixture can be accessed from the overriding fixture easily - used in the example above. test_something.py # content of tests/test_something.py import pytest @pytest.fixture def username(username): (continues on next page). @pytest.fixture def other_username(username): return 'other-' + username be overridden this way even if the test doesn’t use it directly (doesn’t mention it in the function prototype). 5.16.4 Override a parametrized fixture with non-parametrized one and vice versa @pytest.fixture def non_parametrized_username(request): return 'username' @pytest.fixture def parametrized_username(): return 'overridden-username'fixture is overridden with a parametrized version for certain test module. The same applies for the test folder levelobviously. By using the pytest.mark helper you can easily set metadata on your test functions. There are some builtinmarkers, for example: • skip - always skip a test function • skipif - skip a test function if a certain condition is met • xfail - produce an “expected failure” outcome if a certain condition is met • parametrize to perform multiple calls to the same test function.It’s easy to create custom markers or to apply markers to whole test classes or modules. Those markers can be usedby plugins, and also are commonly used to select tests on the command-line with the -m option.See Working with custom markers for examples which also serve as documentation. You can register custom marks in your pytest.ini file like this: [pytest]markers = slow: marks tests as slow (deselect with '-m "not slow"') serial 53pytest Documentation, Release 5.4 def pytest_configure(config): config.addinivalue_line( "markers", "env(name): mark test to run only on named environment" ) Registered marks appear in pytest’s help text and do not emit warnings (see the next section). It is recommended thatthird-party plugins always register their markers. Unregistered marks applied with the @pytest.mark.name_of_the_mark decorator will always emit a warningin order to avoid silently doing something surprising due to mis-typed names. As described in the previous section,you can disable the warning for custom marks by registering them in your pytest.ini file or using a custompytest_configure hook.When the --strict-markers command-line flag is passed, any unknown marks applied with the @pytest.mark.name_of_the_mark decorator will trigger an error. You can enforce this validation in your project byadding --strict-markers to addopts: [pytest]addopts = --strict-markersmarkers = slow: marks tests as slow (deselect with '-m "not slow"') serial Sometimes tests need to invoke functionality which depends on global settings or which invokes code which cannot beeasily tested such as network access. The monkeypatch fixture helps you to safely set/delete an attribute, dictionaryitem or environment variable, or to modify sys.path for importing.The monkeypatch fixture provides these helper methods for safely patching and mocking functionality in tests: All modifications will be undone after the requesting test function or fixture has finished. The raising parameterdetermines if a KeyError or AttributeError will be raised if the target of the set/deletion operation does notexist.Consider the following scenarios:1. Modifying the behavior of a function or the property of a class for a test e.g. there is an API call or databaseconnectioncases. Use monkeypatch.setitem() to patch the dictionary for the test. monkeypatch.delitem() can beused to remove items.3. Modifying environment variables for a test e.g. to test program behavior if an environment variable is missing, or toset multiple values to a known variable. monkeypatch.setenv() and monkeypatch.delenv() can be usedfor these patches.4. Use monkeypatch.setenv("PATH", value, prepend=os.pathsep) to modify $PATH, andmonkeypatch.chdir() to change the context of the current working directory during a test. 55pytest Documentation, Release 5.4 Consider a scenario where you are working with user directories. In the context of testing, you do not want your testto depend on the running user. monkeypatch can be used to patch functions dependent on the user to always returna specific value.In this example, monkeypatch.setattr() is used to patch Path.home so that the known testing pathPath("/abc") is always used when the test is run. This removes any dependency on the running user for test-ing purposes. monkeypatch.setattr() must be called before the function which will use the patched functionis called. After the test function finishes the Path.home modification will be undone. def getssh(): """Simple function to return expanded homedir ssh path.""" return Path.home() / ".ssh" def test_getssh(monkeypatch): # mocked return function to replace Path.home # always return '/abc' def mockreturn(): return Path("/abc") monkeypatch.setattr() can be used in conjunction with classes to mock returned objects from functions in-stead of values. Imagine a simple function to take an API url and return the json response. def get_json(url): """Takes a URL, and returns the JSON.""" r = requests.get(url) return r.json() We need to mock r, the returned response object for testing purposes. The mock of r needs a .json() methodwhich returns a dictionary. This can be done in our test file by defining a class to represent r. def test_get_json(monkeypatch): # Any arguments may be passed and mock_get() will always return our # mocked object, which only has the .json() method. def mock_get(*args, **kwargs): return MockResponse() monkeypatch applies the mock for requests.get with our mock_get function. The mock_get functionreturns an instance of the MockResponse class, which has a json() method defined to return a known testingdictionary: # notice our test uses the custom fixture instead of monkeypatch directlydef test_get_json(mock_response): result = app.get_json("") assert result["mock_key"] == "mock_response" Furthermore, if the mock was designed to be applied to all tests, the fixture could be moved to a conftest.pyfile and use the with autouse=True option. If you want to prevent the “requests” library from performing http requests in all your tests, you can do: # contents of conftest.pyimportbreak pytest’s internals. If that’s unavoidable, passing --tb=native, --assert=plain and --capture=nomight help although there’s no guarantee. Note: Mind that patching stdlib functions and some third-party libraries used by pytest might break pytest itself,therefore in those cases it is recommended to use MonkeyPatch.context() to limit the patching to the blockyou want tested: import functools def test_partial(monkeypatch): with monkeypatch.context() as m: (continues on next page) If you are working with environment variables you often need to safely change the values or delete them from thesystem for testing purposes. monkeypatch provides a mechanism to do this using the setenv and delenvmethod. Our example code to test:# contents of our original code file e.g. code.pyimport environ-ment variable does not exist. Using monkeypatch both paths can be safely tested without impacting the runningenvironment:# contents of our test file e.g. test_code.pyimportimport pytest @pytest.fixture (continues on next page) @pytest.fixturedef mock_env_missing(monkeypatch): monkeypatch.delenv("USER", raising=False) def test_raise_exception(mock_env_missing): with pytest.raises(OSError): _ = get_os_user_lower() monkeypatch.setitem() can be used to safely set the values of dictionaries to specific values during tests. Takethis simplified connection string example:): # contents of test_app.pyimport pytest def test_missing_user(monkeypatch): The modularity of fixtures gives you the flexibility to define separate fixtures for each potential mock and referencethem in the needed tests.# contents of test_app.pyimport pytest @pytest.fixturedef mock_test_database(monkeypatch): """Set the DEFAULT_CONFIG database to test_db.""" monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db") @pytest.fixturedef mock_missing_default_user(monkeypatch): """Remove the user key from DEFAULT_CONFIG""" monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False) result = app.create_connection_string() assert result == expected def test_missing_user(mock_missing_default_user): with pytest.raises(KeyError): _ = app.create_connection_string() You can use the tmp_path fixture which will provide a temporary directory unique to the test invocation, created inthe base temporary directory.tmp_path is a pathlib/pathlib2.Path object. Here is an example test usage: # content of test_tmp_path.pyimport os-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 1 item test_tmp_path.py F [100%] 63pytest Documentation, Release 5.4E assert 0 test_tmp_path.py:13: AssertionError========================= short test summary info ==========================FAILED test_tmp_path.py::test_create_file - assert 0============================ 1 failed in 0.12s ============================= The tmp_path_factory is a session-scoped fixture which can be used to create arbitrary temporary directoriesfrom any other fixture or test.It is intended to replace tmpdir_factory, and returns pathlib.Path instances.See tmp_path_factory API for details. You can use the tmpdir fixture which will provide a temporary directory unique to the test invocation, created in thebase temporary directory.tmpdir is a py.path.local object which offers os.path methods and more. Here is an example test usage:# content of test_tmpdir.pyimport.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cache (continues on next page) test_tmpdir.py F [100%] tmpdir = local('PYTEST_TMPDIR/test_create_file0') def test_create_file(tmpdir): p = tmpdir.mkdir("sub").join("hello.txt") p.write("content") assert p.read() == "content" assert len(tmpdir.listdir()) == 1> assert 0E assert 0 test_tmpdir.py:9: AssertionError========================= short test summary info ==========================FAILED test_tmpdir.py::test_create_file - assert 0============================ 1 failed in 0.12s ============================= The tmpdir_factory is a session-scoped fixture which can be used to create arbitrary temporary directories fromany other fixture or test.For example, suppose your test suite needs a large image on disk, which is generated procedurally. Instead of com-puting the same image for each test that uses it into its own tmpdir, you can generate it once per-session to savetime: @pytest.fixture(scope="session")def image_file(tmpdir_factory): img = compute_expensive_image() fn = tmpdir_factory.mktemp("data").join("img.png") img.save(str(fn)) return fn # contents of test_image.pydef test_histogram(image_file): img = load_image(image_file) # compute and test histogram Temporary directories are by default created as sub-directories of the system temporary directory. The base namewill be pytest-NUM where NUM will be incremented with each test run. Moreover, entries older than 3 temporarydirectories will be removed.You can override the default temporary directory setting like this: pytest --basetemp=mydir When distributing tests on the local machine, pytest takes care to configure a basetemp directory for the sub pro-cesses such that all temporary data lands below a single per-test run basetemp directory. During test execution any output sent to stdout and stderr is captured. If a test or a setup method fails itsaccording captured output will usually be shown along with the failure traceback. (this behavior can be configured bythe --show-capture command-line option).In addition, stdin is set to a “null” object which will fail on attempts to read from it because it is rarely desired towait for interactive input when running automated tests.By default capturing is done by intercepting writes to low level file descriptors. This allows to capture output fromsimple print statements as well as output from a subprocess started by a test. 67pytest Documentation, Release 5.4 One primary benefit of the default capturing of stdout/stderr output is that you can use print statements for debugging:-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 2 items test_module.py .F [100%] def test_func2():> assert FalseE assert False test_module.py:12: AssertionError-------------------------- Captured stdout setup ---------------------------setting up <function test_func2 at 0xdeadbeef>========================= short test summary info ==========================FAILED test_module.py::test_func2 - assert False======================= 1 failed, 1 passed in 0.12s ======================== The capsys, capsysbinary, capfd, and capfdbinary fixtures allow access to stdout/stderr output createdduring test execution. Here is an example test function that performs some output related checks: The readouterr() call snapshots the output so far - and capturing will be continued. After the test function finishesthe original streams will be restored. Using capsys this way frees your test from having to care about setting/resettingoutput streams and also interacts well with pytest’s own per-test capturing.If you want to capture on filedescriptor level you can use the capfd fixture which offers the exact same interface butallowsreturns bytes from the readouterr method. The capfsysbinary fixture is currently only available in python3.If the code under test writes non-textual data, you can capture this using the capfdbinary fixture which insteadreturns bytes from the readouterr method. The capfdbinary fixture operates on the filedescriptor level.To temporarily disable capture within a test, both capsys and capfd have a disabled() method that can be usedas a context manager, disabling capture inside the with block: def test_disabling_capturing(capsys): print("this output is captured") with capsys.disabled(): print("output not captured, going directly to sys.stdout") print("this output is also captured") Warnings Capture Starting from version 3.1, pytest now automatically catches warnings during test execution and displays them at theend of the session: # content of test_show_warnings.pyimport warnings def api_v1(): warnings.warn(UserWarning("api v1, should use functions from v2")) return 1 def test_one(): assert api_v1() == 1 $ pytest test_show_warnings.py=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 1 item test_show_warnings.py . [100%] -- Docs: 1 passed, 1 warning in 0.12s ======================= 71pytest Documentation, Release 5.4 The -W flag can be passed to control which warnings will be displayed or even turn them into errors: file using the filterwarnings ini option. For example, theconfiguration below will ignore all user warnings, but will transform all other warnings into errors. [pytest]filterwarnings = error ignore::UserWarning When a warning matches more than one option in the list, the action for the last matching option is performed.Both -W command-line option and filterwarnings ini option are based on Python’s own -W option and warn-ings.simplefilter, so please refer to those sections in the Python documentation for other examples and advanced usage. 10.1 @pytest.mark.filterwarnings You can use the @pytest.mark.filterwarnings to add warning filters to specific test items, allowing you tohave finer control of which warnings should be captured at test, class or even module level: import warnings @pytest.mark.filterwarnings("ignore:api v1")def test_one(): assert api_v1() == 1 Filters applied using a mark take precedence over filters passed on the command line or configured by thefilterwarnings ini option.You may apply a filter to all tests of a class by using the filterwarnings mark as a class decorator or to all testsin a module by setting the pytestmark variable: Credits go to Florian Schulze for the reference implementation in the pytest-warnings plugin. Although not recommended, you can use the --disable-warnings command-line option to suppress the warningsummary entirely from the test run output. This plugin is enabled by default but can be disabled entirely in your pytest.ini file with: [pytest] addopts = -p no:warnings Or passing -p no:warnings in the command-line. This might be useful if your test suites handles warnings usingan external system. [pytest]filterwarnings = ignore:.*U.*mode is deprecated:DeprecationWarning This will ignore all warnings of type DeprecationWarning where the start of the message matches the regularexpression ".*U.*mode is deprecated". Note: If warnings are configured at the interpreter level, using the PYTHONWARNINGS environment variable orthe -W command-line option, pytest will not configure any filters by default.Also pytest doesn’t follow PEP-0506 suggestion of resetting all warning filters because it might break test suitesthat configure warning filters themselves by calling warnings.simplefilter (see issue #2430 for an exampleof that). You can also use pytest.deprecated_call() for checking that a certain function call triggers aDeprecationWarning or PendingDeprecationWarning:import pytest def test_myfunction_deprecated(): with pytest.deprecated_call(): myfunction(17) This test will fail if myfunction does not issue a deprecation warning when called with a 17 argument.By default, DeprecationWarning and PendingDeprecationWarning will not be caught when usingpytest.warns() or recwarn because the default Python warnings filters hide them. If you wish to record them inyour own code, use warnings.simplefilter('always'):import warningsimport pytest def test_deprecation(recwarn): warnings.simplefilter("always") myfunction(17) assert len(recwarn) == 1 assert recwarn.pop(DeprecationWarning) The recwarn fixture automatically ensures to reset the warnings filter at the end of the test, so no global state is leaked. You can check that code raises a particular warning using pytest.warns, which works in a similar manner toraises:import warningsimport pytest def test_warning(): with pytest.warns(UserWarning): warnings.warn("my warning", UserWarning) The test will fail if the warning in question is not raised. The keyword argument match to assert that the exceptionmatches a text or regex:>>> with warns(UserWarning, match='must be 0 or None'):... warnings.warn("value must be 0 or None", UserWarning) The function also returns a list of all raised warnings (as warnings.WarningMessage objects), which you canquery for additional information: Alternatively, you can examine raised warnings in detail using the recwarn fixture (see below). Note: DeprecationWarning and PendingDeprecationWarning are treated differently; see Ensuring codetriggers a deprecation warning. You can record raised warnings either using pytest.warns or with the recwarn fixture.To record with pytest.warns without asserting anything about the warnings, pass None as the expected warningtype: assert len(record) == 2assert str(record[0].message) == "user"assert str(record[1].message) == "runtime" The recwarn fixture will record warnings for the whole function:warnings, or index into it to get a particular recorded warning.Full API: WarningsRecorder. Recording warnings provides an opportunity to produce custom test failure messages for when no warnings are issuedclass Test: def __init__(self): pass def test_foo(self): assert 1 == 1 $ pytest test_pytest_warnings.py -q ˓→py) class Test: -- Docs: warning in 0.12s These warnings might be filtered using the same builtin mechanisms used to filter other types of warnings.Please read our Backwards Compatibility Policy to learn how we proceed about deprecating and eventually removingfeatures.The following warning types are used by pytest and are part of the public API: class PytestWarning Bases: UserWarning. Base class for all warnings emitted by pytest.class PytestAssertRewriteWarning Bases: PytestWarning. Warning emitted by the pytest assert rewrite module.class PytestCacheWarning Bases: PytestWarning. Warning emitted by the cache plugin in various situations.class PytestCollectionWarning Bases: PytestWarning. Warning emitted when pytest is not able to collect a file or symbol in a module.class PytestConfigWarning Bases: PytestWarning. Warning emitted for configuration issues.class PytestDeprecationWarning Bases: pytest.PytestWarning, DeprecationWarning. Warning class for features that will be removed in a future version.class PytestExperimentalApiWarning Bases: pytest.PytestWarning, FutureWarning. Warning category used to denote experiments in pytest. Use sparingly as the API might change or even be removed completely in future versionclass PytestUnhandledCoroutineWarning Bases: PytestWarning. Warning emitted when pytest encounters a test function which is a coroutine, but it was not handled by any async-aware plugin. Coroutine test functions are not natively supported.class PytestUnknownMarkWarning Bases: PytestWarning. Warning emitted on use of unknown markers. See for details. By default all files matching the test*.txt pattern will be run through the python standard doctest module. Youcan change the pattern by issuing: pytest --doctest-glob='*.rst' on the command line. --doctest-glob can be given multiple times in the command-line.If you then have a text file like this: # content of test_example.txt test_example.txt . [100%] By default, pytest will collect test*.txt files looking for doctest directives, but you can pass additional globs usingthe --doctest-glob option (multi-allowed).In addition to text files, you can also execute doctests directly from docstrings of your classes and functions, includingfrom test modules: 79pytest Documentation, Release 5.4 # content of mymodule.pydef something(): """ a doctest in a docstring >>> something() 42 """ return 42 $ pytest --doctest-modules=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 2 items mymodule.py . [ 50%]test_example.txt . [100%] You can make these changes permanent in your project by putting them into a pytest.ini file like this:# content of pytest.ini[pytest]addopts = --doctest-modules Note: The builtin pytest doctest supports only doctest blocks, but if you are looking for more advanced checkingover all your documentation, including doctests, .. codeblock:: python Sphinx directive support, and anyother examples your documentation may include, you may wish to consider Sybil. It provides pytest integration outof the box. 11.1 Encoding The default encoding is UTF-8, but you can specify the encoding that will be used for those doctest files using thedoctest_encoding ini option:# content of pytest.ini[pytest]doctest_encoding = latin1 Python’s standard doctest module provides some options to configure the strictness of doctest tests. In pytest, youcan: >>> math.pi 3.14 If you wrote 3.1416 then the actual output would need to match to 4 decimal places; and so on. This avoids false positives caused by limited floating-point precision, like this: Expected: 0.233 Got: 0.23300000000000001 NUMBER also supports lists of floating-point numbers – in fact, it matches floating-point numbers appearing anywhere in the output, even inside a string! This means that it may not be appropriate to enable globally in doctest_optionflags in your configuration file. New in version 5.1. By default, pytest would report only the first failure for a given doctest. If you want to continue the test even whenyou have failures, do: You can change the diff output format on failure for your doctests by using one of standard doctest modulesformat in options (see doctest.REPORT_UDIFF, doctest.REPORT_CDIFF, doctest.REPORT_NDIFF,doctest.REPORT_ONLY_FIRST_FAILURE): Some features are provided to make writing doctests easier or with better integration with your existing test suite. Keepin mind however that by using those features you will make your doctests incompatible with the standard doctestsmodule. # content of example.rst>>> tmp = getfixture('tmpdir')>>> ...>>> Also, Using fixtures from classes, modules or projects and Autouse fixtures (xUnit setup on steroids) fixtures aresupported when executing text doctest files. The doctest_namespace fixture can be used to inject items into the namespace in which your doctests run. It isintended to be used within your own fixtures to provide the tests that use them with context.doctest_namespace is a standard dict object into which you place the objects you want to appear in the doctestnamespace: # content of conftest.pyimport numpy @pytest.fixture(autouse=True)def add_np(doctest_namespace): doctest_namespace["np"] = numpy # content of numpy.pydef arange(): """ >>> a = np.arange(10) >>> len(a) 10 """ pass Note that like the normal conftest.py, the fixtures are discovered in the directory tree conftest is in. Meaning thatif you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree. Fixtureswill not be discovered in a sibling directory tree! You can mark test functions that cannot be run on certain platforms or that you expect to fail so pytest can deal withthem accordingly and present a summary of the test session, while keeping the test suite green.A skip means that you expect your test to pass only if some conditions are met, otherwise pytest should skip runningthe test altogether. Common examples are skipping windows-only tests on non-windows platforms, or skipping teststhat depend on an external resource which is not available at the moment (for example a database).A xfail means that you expect a test to fail for some reason. A common example is a test for a feature not yetimplemented,by default to avoid cluttering the output. You can use the -r option to see details corresponding to the “short” lettersshown in the test progress: pytest -rxXs # show extra info on xfailed, xpassed, and skipped tests The simplest way to skip a test function is to mark it with the skip decorator which may be passed an optionalreason: Alternatively, it is also possible to skip imperatively during test execution or setup by calling the pytest.skip(reason) function: 85pytest Documentation, Release 5.4import pytest if not sys.platform.startswith("win"): pytest.skip("skipping windows-only tests", allow_module_level=True) Reference: pytest.mark.skip 12.1.1 skipif If you wish to skip something conditionally then you can use skipif instead. Here is an example of marking a testfunction to be skipped when run on an interpreter earlier than Python3.6: If the condition evaluates to True during collection, the test function will be skipped, with the specified reasonappearing in the summary when using -rs.You can share skipif markers between modules. Consider this test module: # content of test_mymodule.pyimport mymodule minversion = pytest.mark.skipif( mymodule.__versioninfo__ < (1, 1), reason="at least mymodule-1.1 required") @minversiondef test_function(): ... You can import the marker and reuse it in another test module: # test_myothermodule.pyfrom test_mymodule import minversion @minversiondef test_anotherfunction(): ... 86 Chapter 12. Skip and xfail: dealing with tests that cannot succeed pytest Documentation, Release 5.4 For larger test suites it’s usually a good idea to have one file where you define the markers which you then consistentlyapply throughout your test suite.Alternatively, you can use condition strings instead of booleans, but they can’t be shared between modules easily sothey are supported mainly for backward compatibility reasons.Reference: pytest.mark.skipif You can use the skipif marker (as any other marker) on classes: If the condition is True, this marker will produce a skip result for each of the test methods of that class.If you want to skip all test functions of a module, you may use the pytestmark name on the global level: # test_module.pypytestmark = pytest.mark.skipif(...) If multiple skipif decorators are applied to a test function, it will be skipped if any of the skip conditions is true. Sometimes you may need to skip an entire file or directory, for example if the tests rely on Python version-specificfeatures or contain code that you do not wish pytest to run. In this case, you must exclude the files and directoriesfrom collection. Refer to Customizing test collection for more information.version number of a library: The version will be read from the specified module’s __version__ attribute. 12.1.5 Summary pexpect = pytest.importorskip("pexpect") You can use the xfail marker to indicate that you expect a test to fail: @pytest.mark.xfaildef test_function(): ... This test will run but no traceback will be reported when it fails. Instead, terminal reporting will list it in the “expectedtowhen Both XFAIL and XPASS don’t fail the test suite by default. You can change this by setting the strict keyword-onlyparameter 88 Chapter 12. Skip and xfail: dealing with tests that cannot succeed pytest Documentation, Release 5.4 As with skipif you can also mark your expectation of a failure on a particular platform:@pytest.mark.xfail(sys.version_info >= (3, 6), reason="python3.6 api changes")def test_function(): .... If a test should be marked as xfail and reported as such but should not be even executed, use the run parameter asFalse:@pytest.mark.xfail(run=False)def test_function(): ... This is specially useful for xfailing tests that are crashing the interpreter and should be investigated later. you can force the running and reporting of an xfail marked test as if it weren’t marked at all. This also causespytest.xfail to produce no effect. 12.2.6 Examples xfail = pytest.mark.xfail @xfaild 90 Chapter 12. Skip and xfail: dealing with tests that cannot succeed pytest Documentation, Release 5.4 It is possible to apply markers like skip and xfail to individual test instances when using parametrize: ˓→") ), ],)def test_increment(n, expected): assert n + 1 == expected 92 Chapter 12. Skip and xfail: dealing with tests that cannot succeed CHAPTER 13 The builtin pytest.mark.parametrize decorator enables parametrization of arguments for a test function. Here is atypical example of a test function that implements checking that a certain input leads to an expected output:# content of test_expectation.pyimport pytest Here, the @parametrize decorator defines three different (test_input,expected) tuples so that thetest_eval function will run three times using them in turn:$ pytest=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 3 items 93pytest Documentation, Release 5.4 test_expectation.py:6: AssertionError========================= short test summary info ==========================FAILED test_expectation.py::test_eval[6*9-42] - AssertionError: assert 54...======================= 1 failed, 2 passed in 0.12s ======================== Note: pytest by default escapes any non-ascii characters used in unicode strings for the parametrization because it hasseveral downsides. If however you would like to use unicode strings in parametrization and see them in the terminalas is (non-escaped), use this option in your pytest.ini: [pytest]disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True Keep in mind however that this might cause unwanted side effects and even bugs depending on the OS used andplugins currently installed, so use it at your own risk. As designed in this example, only one pair of input/output values fails the simple test function. And as usual with testfunctionimport pytest @pytest.mark.parametrize( "test_input,expected", [("3+5", 8), ("2+4", 6), pytest.param("6*9", 42, marks=pytest.mark.xfail)],)def test_eval(test_input, expected): assert eval(test_input) == expected $ pytest=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 3 items (continues on next page) The one parameter set which caused a failure previously now shows up as an “xfailed (expected to fail)” test.In case the values provided to parametrize result in an empty list - for example, if they’re dynamically generatedby some function - the behaviour of pytest is defined by the empty_parameter_set_mark option.To get all combinations of multiple parametrized arguments you can stack parametrize decorators:import pytest This will run the test with the arguments set to x=0/y=2, x=1/y=2, x=0/y=3, and x=1/y=3 exhausting parame-ters in the order of the decorators. Sometimes you may want to implement your own parametrization scheme or implement some dynamism for deter-mining the parameters or scope of a fixture. For this, you can use the pytest_generate_tests hook which iscalled when collecting a test function. Through the passed in metafunc object you can inspect the requesting testcontext and, most importantly, you can call metafunc.parametrize() to cause parametrization.For example, let’s say we want to run a test taking string inputs which we want to set via a new pytest commandlinetest function:# content of conftest.py def pytest_addoption(parser): parser.addoption( "--stringinput", action="append", default=[], help="list of stringinputs to pass to test functions", ) def pytest_generate_tests(metafunc): (continues on next page) If we now pass two stringinput values, our test will run twice: Let’s also run with a stringinput that will lead to a failing test: stringinput = '!' def test_valid_string(stringinput):> assert stringinput.isalpha()E AssertionError: assert FalseE + where False = <built-in method isalpha of str object at 0xdeadbeef>()E + where <built-in method isalpha of str object at 0xdeadbeef> = '!'.˓→isalpha test_strings.py:4: AssertionError========================= short test summary info ==========================FAILED test_strings.py::test_valid_string[!] - AssertionError: assert False1 failed in 0.12s 1 skipped in 0.12s Note that when calling metafunc.parametrize multiple times with different parameter sets, all parameter namesacross those sets cannot be duplicated, otherwise an error will be raised. For further examples, you might want to look at more parametrization examples. 14.1 Usage The plugin provides two command line options to rerun failures from the last pytest invocation: • --lf, --last-failed - to only re-run the failures. • --ff, --failed-first - to run the failures first and then the rest of the tests.For cleanup (usually not needed), a --cache-clear option allows to remove all cross-session cache contents aheadof a test run.Other plugins may access the config.cache object to set/get json encodable values between pytest invocations. Note: This plugin is enabled by default, but can be disabled if needed: see Deactivating / unregistering a plugin byname (the internal name for this plugin is cacheprovider). # content of test_50.pyimport pytest @pytest.mark.parametrize("i", range(50))def test_num(i): if i in (17, 25): pytest.fail("bad luck") If you run this for the first time you will see two failures: 97pytest Documentation, Release 5.4 $ pytest -q.................F.......F........................ [100%]================================= FAILURES =================================_______________________________ test_num[17] _______________________________ i = 17 @pytest.mark.parametrize("i", range(50)) def test_num(i): if i in (17, 25):> pytest.fail("bad luck")E Failed: bad luck test_50.py:7: Failed_______________________________ test_num[25] _______________________________ i = 25 test_50.py:7: Failed========================= short test summary info ==========================FAILED test_50.py::test_num[17] - Failed: bad luckFAILED test_50.py::test_num[25] - Failed: bad luck2 failed, 48 passed in 0.12s $ pytest --lf=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 2 itemsrun-last-failure: rerun previous 2 failures test_50.py FF [100%] i = 25 (continues on next page) test_50.py:7: Failed========================= short test summary info ==========================FAILED test_50.py::test_num[17] - Failed: bad luckFAILED test_50.py::test_num[25] - Failed: bad luck============================ 2 failed in 0.12s ============================= You have run only the two failing tests from the last run, while the 48 passing tests have not been run (“deselected”).Now, if you run with the --ff option, all tests will be run but the first previous failures will be executed first (as canbe seen from the series of FF and dots): $ pytest --ff=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 50 itemsrun-last-failure: rerun previous 2 failures first test_50.py:7: Failed========================= short test summary info ==========================FAILED test_50.py::test_num[17] - Failed: bad luckFAILED test_50.py::test_num[25] - Failed: bad luck======================= 2 failed, 48 passed in 0.12s ======================= New --nf, --new-first options: run new tests first followed by the rest of the tests, in both cases tests are also sorted by the file modified time, with more recent files coming first. When no tests failed in the last run, or when no cached lastfailed data was found, pytest can be configuredeither to run all of the tests or no tests, using the --last-failed-no-failures option, which takes one of thefollowing values:pytest --last-failed --last-failed-no-failures all # run all tests (default ˓→behavior) Plugins or conftest.py support code can get a cached value using the pytest config object. Here is a basic exampleplugin which implements a pytest fixtures: explicit, modular, scalable which re-uses previously created state acrosspytest invocations:# content of test_caching.pyimport pytestimport time def expensive_computation(): print("running expensive computation...") @pytest.fixturedef mydata(request): val = request.config.cache.get("example/value", None) if val is None: expensive_computation() val = 42 request.config.cache.set("example/value", val) return val def test_function(mydata): assert mydata == 23 If you run this command for the first time, you can see the print statement:$ pytest -qF [100%]================================= FAILURES =================================______________________________ test_function _______________________________ mydata = 42 def test_function(mydata):> assert mydata == 23E assert 42 == 23 If you run it a second time, the value will be retrieved from the cache and nothing will be printed: $ pytest -qF [100%]================================= FAILURES =================================______________________________ test_function _______________________________ def test_function(mydata):> assert mydata == 23E assert 42 == 23 test_caching.py:20: AssertionError========================= short test summary info ==========================FAILED test_caching.py::test_function - assert 42 == 231 failed in 0.12s You can always peek at the content of the cache using the --cache-show command line option: $ pytest --cache-show=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcachedir: $PYTHON_PREFIX/.pytest_cache--------------------------- cache values for '*' ---------------------------cache/lastfailed contains: {'test_50.py::test_num[17]': True, 'test_50.py::test_num[25]': True, 'test_assert1.py::test_function': True, 'test_assert2.py::test_set_comparison': True, 'test_caching.py::test_function': True, 'test_foocompare.py::test_compare': True}cache/nodeids contains: ['test_assert1.py::test_function', 'test_assert2.py::test_set_comparison', 'test_foocompare.py::test_compare', 'test_50.py::test_num[0]', 'test_50.py::test_num[1]', 'test_50.py::test_num[2]', 'test_50.py::test_num[3]', 'test_50.py::test_num[4]', (continues on next page) You can instruct pytest to clear all cache files and values by adding the --cache-clear option like this: pytest --cache-clear This is recommended for invocations from Continuous Integration servers where isolation and correctness is moreimportant than speed. 14.7 Stepwise As an alternative to --lf -x, especially for cases where you expect a large part of the test suite will fail, --sw,--stepwise allows you to fix them one at a time. The test suite will run until the first failure and then stop. At thenext invocation, tests will continue from the last failing test and then run until the next failing test. You may use the--stepwise-skip option to ignore one failing test and stop the test execution on the second failing test instead.This is useful if you get stuck on a failing test and just want to ignore it until later. unittest.TestCase Support pytest supports running Python unittest-based tests out of the box. It’s meant for leveraging existingunittest-based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite totake: • @unittest.skip style decorators; • setUp/tearDown; • setUpClass/tearDownClass; • setUpModule/tearDownModule;Up to this point pytest does not have support for the following features: • load_tests protocol; • subtests; By running your test suite with pytest you can make use of several features, in most cases without having to modifyexisting code: • Obtain more informative tracebacks; • stdout and stderr capturing; • Test selection options using -k and -m flags; 105pytest Documentation, Release 5.4 Running your unittest with pytest allows you to use its fixture mechanism with unittest.TestCase style tests.Assuming you have at least skimmed the pytest fixture features, let’s jump-start into an example that integrates a pytestdb_class fixture, setting up a class-cached database object, and then reference it from a unittest-style test: @pytest.fixture(scope="class")def db_class(request): class DummyDB: pass This defines a fixture function db_class which - if used - is called once for each test class and which sets the class-level db attribute to a DummyDB instance. The fixture function achieves this by receiving a special request objectwhich gives access to the requesting test context such as the cls attribute, denoting the class from which the fixture isused. This architecture de-couples fixture writing from actual test code and allows re-use of the fixture by a minimalreference, the fixture name. So let’s write an actual unittest.TestCase class using our fixture definition: # content of test_unittest_db.py import unittestimportdb_class is called once per class. Due to the deliberately failing assert statements, we can take a look at theself.db values in the traceback: $ pytest test_unittest_db.py=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 2 items test_unittest_db.py FF [100%] def test_method1(self): assert hasattr(self, "db")> assert 0, self.db # fail for demo purposesE AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef>E assert 0 test_unittest_db.py:10: AssertionError___________________________ MyTest.test_method2 ____________________________ def test_method2(self):> assert 0, self.db # fail for demo purposesEintention when writing the class-scoped fixture function above. 15.3. Mixing pytest fixtures into unittest.TestCase subclasses using marks 107pytest Documentation, Release 5.4 Although it’s usually better to explicitly declare use of fixtures you need for a given test, you may sometimes want tohave fixtures that are automatically used in a given context. After all, the traditional style of unittest-setup mandatesthe use of this implicit fixture writing and chances are, you are used to it or like it.You can flag fixture functions with @pytest.fixture(autouse=True) and define the fixture function in thecontext where you want it used. Let’s look at an initdir fixture which makes all test methods of a TestCaseclass execute in a temporary directory with a pre-initialized samplefile.ini. Our initdir fixture itself usesthe pytest builtin tmpdir fixture to delegate the creation of a per-test temporary directory: # content of test_unittest_cleandir.pyimport pytestimport de-fined. This is a shortcut for using a @pytest.mark.usefixtures("initdir") marker on the class like intinflict tobenefit from the full pytest feature set step by step. Note: Due to architectural differences between the two frameworks, setup and teardown for unittest-based testsis performed during the call phase of testing instead of in pytest’s standard setup and teardown stages.This can be important to understand in some situations, particularly when reasoning about errors. For example, if aunittest-based suite exhibits errors during setup, pytest will report no errors during its setup phase and willinstead raise the error during call. pytest has basic support for running tests written for nose. 16.1 Usage python setup.py develop # make sure tests can import our packagepytest # instead of 'nosetests' and you should be able to run your nose style tests and make use of pytest’s capabilities. 109pytest Documentation, Release 5.4 This section describes a classic and popular way how you can implement fixtures (setup and teardown test state) on aper-module/class/function basis. Note: While these setup/teardown methods are simple and familiar to those coming from a unittest or nosebackground, you may also consider using pytest’s more powerful fixture mechanism which leverages the conceptof dependency injection, allowing for a more modular and more scalable approach for managing test state, especiallyfor larger projects and for functional testing. You can mix both fixture mechanisms in the same file but test methodsof unittest.TestCase subclasses cannot receive fixture arguments. If you have multiple test functions and test classes in a single module you can optionally implement the followingfixture methods which will usually be called once for all the functions: def setup_module(module): """ setup any state specific to the execution of the given module.""" def teardown_module(module): """ teardown any state that was previously setup with a setup_module method. """ Similarly, the following methods are called at class level before and after all test methods of the class are called: 111pytest Documentation, Release 5.4 @classmethoddef setup_class(cls): """ setup any state specific to the execution of the given class (which usually contains tests). """ @classmethoddef teardown_class(cls): """ teardown any state that was previously setup with a call to setup_class. """ Similarly, the following methods are called around each method invocation: def setup_function(function): """ setup any state tied to the execution of the given function. Invoked for every test function in the module. """ def teardown_function(function): """ teardown any state that was previously setup with a setup_function call. """ This section talks about installing and using third party plugins. For writing your own plugins, please refer to Writingplugins.Installing a third party plugin can be easily done with pip: If a plugin is installed, pytest automatically finds and integrates it, there is no need to activate it.Here is a little annotated list for some popular plugins: • pytest-django: write tests for django apps, using pytest integration. • pytest-twisted: write tests for twisted apps, starting a reactor and processing deferreds from test functions. • pytest-cov: coverage reporting, compatible with distributed testing • pytest-xdist: to distribute tests to CPUs and remote hosts, to run in boxed mode which allows to survive seg- mentation faults, to run in looponfailing mode, automatically re-running failing tests on file changes. • pytest-instafail: to report failures while the test run is happening. • pytest-bdd: to write tests using behaviour-driven testing. • pytest-timeout: to timeout tests based on function marks or global definitions. • pytest-pep8: a --pep8 option to enable PEP8 compliance checking. • pytest-flakes: check source code with pyflakes. • oejskit: a plugin to run javascript unittests in live browsers.To see a complete list of all plugins with their latest testing status against different pytest and Python versions, pleasevisit plugincompat.You may also discover more plugins through a pytest- pypi.org search. 113pytest Documentation, Release 5.4 You can require plugins in a test module or a conftest file like this: pytest_plugins = ("myapp.testsupport.myplugin",) When the test module or conftest plugin is loaded the specified plugins will be loaded as well. Note: Requiring plugins using a pytest_plugins variable in non-root conftest.py files is deprecated. Seefull explanation in the Writing plugins section. Note: The name pytest_plugins is reserved and should not be used as a name for a custom plugin module. If you want to find out which plugins are active in your environment you can type: pytest --trace-config and will get an extended test header which shows activated plugins and their names. It will also print local plugins akaconftest.py files when they are loaded.environment variable to -p no:name.See Finding out which plugins are active for how to obtain the name of a plugin. Writing plugins It is easy to implement local conftest plugins for your own project or pip-installable plugins that can be used throughoutmany projects, including third party projects. Please refer to Installing and Using plugins if you only want to use butnot write plugins.A plugin contains one or multiple hook functions. Writing hooks explains the basics and details of how you can write ahook function yourself. pytest implements all aspects of configuration, collection, running and reporting by callingwell specified hooks of the following plugins: • builtin plugins: loaded from pytest’s internal _pytest directory. • external plugins: modules discovered through setuptools entry points • conftest.py plugins: modules auto-discovered in test directoriesIn principle, each hook call is a 1:N Python function call where N is the number of registered implementation functionsfor a given specification. All specifications and implementations follow the pytest_ prefix naming convention,making them easy to distinguish and find. 115pytest Documentation, Release 5.4 Note that pytest does not find conftest.py files in deeper nested sub directories at tool startup. It is usually a good idea to keep your conftest.py file in the top level test or project root directory. • by recursively loading all plugins specified by the pytest_plugins variable in conftest.py files Local conftest.py plugins contain directory-specific hook implementations. Hook Session and test running activi-ties will invoke all hooks defined in conftest.py files closer to the root of the filesystem. Example of implementingthe Note: If you have conftest.py files which do not reside in a python package directory (i.e. one containing an__init__.py) then “import conftest” can be ambiguous because there might be other conftest.py files as wellon your PYTHONPATH or sys.path. It is thus good practice for projects to either put conftest.py under apackage scope or to never import anything from a conftest.py file.See also: pytest import mechanisms and sys.path/PYTHONPATH. If you want to write a plugin, there are many real-life examples you can copy from: • a custom collection example plugin: A basic example for specifying tests in Yaml files • builtin plugins which provide pytest’s own functionality • many external plugins providing additional featuresAll of these plugins implement hooks and/or fixtures to extend and add functionality. Note: Make sure to check out the excellent cookiecutter-pytest-plugin project, which is a cookiecutter template forauthoring plugins. The template provides an excellent starting point with a working plugin, tests running with tox, a comprehensiveREADME file as well as a pre-configured entry-point. Also consider contributing your plugin to pytest-dev once it has some happy users other than yourself. If you want to make your plugin externally available, you may define a so-called entry point for your distribution sothat pytest finds your plugin module. Entry points are a feature that is provided by setuptools. pytest looks upthe pytest11 entrypoint to discover its plugins and you can thus make your plugin available by defining it in yoursetuptools-invocation:hooks. Note: Make sure to include Framework :: Pytest in your list of PyPI classifiers to make it easy for users tofind your plugin. One of the main features of pytest is the use of plain assert statements and the detailed introspection of expressionsupon assertion failures. This is provided by “assertion rewriting” which modifies the parsed AST before it gets com-piled to bytecode. This is done via a PEP 302 import hook which gets installed early on when pytest starts up andwill perform this rewriting when modules get imported. However, since we do not want to test different bytecode fromwhat you will run in production, this hook only rewrites test modules themselves (as defined by the python_filesconfiguration option), and any modules which are part of plugins. Any other imported module will not be rewrittenand normal assertion behaviour will happen.If you have assertion helpers in other modules where you would need assertion rewriting to be enabled you need toask pytest explicitly to rewrite this module before it gets imported.register_assert_rewrite(*names) → None. Raises TypeError – if the given module names are not strings. This is especially important when you write a pytest plugin which is created using a package. The import hook onlytreats conftest.py files and any modules which are listed in the pytest11 entrypoint as plugins. As an exampleconsider the following package: pytest_foo/__init__.pypytest_foo/plugin.pypytest_foo/helper.py In this case only pytest_foo/plugin.py will be rewritten. If the helper module also contains assert statementswhich need to be rewritten it needs to be marked as such, before it gets imported. This is easiest by marking itfor rewriting inside the __init__.py module, which will always be imported first when a module inside a pack-age is imported. This way plugin.py can still import helper.py normally. The contents of pytest_foo/__init__.py will then need to look like this: pytest.register_assert_rewrite("pytest_foo.helper") You can require plugins in a test module or a conftest.py file like this: When the test module or conftest plugin is loaded the specified plugins will be loaded as well. Any module can beblessedplugins, and so on. Note: Requiring plugins using a pytest_plugins variable in non-root conftest.py files is deprecated.This is important because conftest.py files implement per-directory hook implementations, but once a plugin isimported, it will affect the entire directory tree. In order to avoid confusion, defining pytest_plugins in anyconftest.py file which is not located in the tests root directory is deprecated, and will raise a warning. This mechanism makes it easy to share fixtures within applications or even external applications without the need tocreate external plugins using the setuptools’s entry point technique.Plugins imported by pytest_plugins will also automatically be marked for assertion rewriting (see pytest.register_assert_rewrite()). However for this to have any effect the module must not be imported already; ifit was already imported at the time the pytest_plugins statement is processed, a warning will result and assertionsinside the plugin will not be rewritten. To fix this you can either call pytest.register_assert_rewrite()yourself before the module is imported, or you can arrange the code to delay the importing until after the plugin isregistered. If a plugin wants to collaborate with code from another plugin it can obtain a reference through the plugin managerlike this:plugin = config.pluginmanager.get_plugin("name_of_plugin") If you want to look at the names of existing plugins, use the --trace-config option. If your plugin uses any markers, you should register them so that they appear in pytest’s help text and do not causespurious." ) pytest comes with a plugin named pytester that helps you write tests for your plugin code. The plugin is disabledby afixture hello which yields a function and we can invoke this function with one optional parameter. It will return astring().', ) def _hello(name=None): if not name: name = request.config.getoption("name") return "Hello {name}!".format(name=name) return _hello Now the testdir fixture provides a convenient API for creating temporary conftest.py files and test files. Italso allows us to run the tests and return a result object, with which we can assert the tests’ outcomes. def test_hello(testdir): """Make sure that our plugin works.""" @pytest.fixture(params=[ "Brianna", "Andreas", "Floris", ]) def name(request): return request.param """ ) additionally it is possible to copy examples for an example folder before running pytest on it # content of pytest.ini[pytest]pytester_example_dir = . # content of test_example.py (continues on next page) def test_plugin(testdir): testdir.copy_example("test_example.py") testdir.runpytest("-k", "test_example") def test_example(): pass $ pytest=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIR, inifile: pytest.inicollected 2 items test_example.py .. [100%] testdir.copy_example("test_example.py") test_example.py::test_plugin $PYTHON_PREFIX/lib/python3.8/site-packages/_pytest/terminal.py:287: ˓→PytestDeprecationWarning: TerminalReporter.writer attribute is deprecated, use warnings.warn( -- Docs: 2 passed, 2 warnings in 0.12s ======================= For more information about the result object that runpytest() returns, and the methods that it provides pleasecheck out the RunResult documentation. pytest calls hook functions from registered plugins for any given hook specification. Let’s look at a typical hook func-tion for the pytest_collection_modifyitems(session, config, items) hook which pytest callsafter collection of all test items is completed.When we implement a pytest_collection_modifyitems function in our plugin pytest will during registra-tion verify that you use argument names which match the specification and bail out if not.Let’s look at a possible implementation: Here, pytest will pass in config (the pytest config object) and items (the list of collected test items) but willnot pass in the session argument because we didn’t list it in the function signature. This dynamic “pruning” ofarguments allows pytest to be “future-compatible”: we can introduce new hook named parameters without breakingthe signatures of existing hook implementations. It is one of the reasons for the general long-lived compatibility ofpytest plugins.Note that hook functions other than pytest_runtest_* are not allowed to raise exceptions. Doing so will breakthe pytest run. Most calls to pytest hooks result in a list of results which contains all non-None results of the called hook functions.Some hook specifications use the firstresult=True option so that the hook call only executes until the first ofN registered functions returns a non-None result which is then taken as result of the overall hook call. The remaininghook functions will not be called in this case. 123pytest Documentation, Release 5.4 pytest plugins can implement hook wrappers which wrap the execution of other hook implementations. A hookwrapper is a generator function which yields exactly once. When pytest invokes hooks it first executes hook wrappersand passes the same arguments as to the regular hooks.At the yield point of the hook wrapper pytest will execute the next hook implementations and return their result to theyield point in the form of a Result instance which encapsulates a result or exception info. The yield point itself willthus typically not raise exceptions (unless there are bugs).Here is an example definition of a hook wrapper: @pytest.hookimpl(hookwrapper=True)def pytest_pyfunc_call(pyfuncitem): do_something_before_next_hook_executes() outcome = yield # outcome.excinfo may be None or a (cls, val, tb) tuple post_process_result(res) Note that hook wrappers don’t return results themselves, they merely perform tracing or other side effects around theactual hook implementations. If the result of the underlying hook is a mutable object, they may modify that result butit’s probably better to avoid it.For more information, consult the pluggy documentation. For any given hook specification there may be more than one implementation and we thus generally view hookexecution as a 1:N function call where N is the number of registered functions. There are ways to influence if a hookimplementation (continues on next page) Plugins and conftest.py files may declare new hooks that can then be implemented by other plugins in order toalter behaviour or interact with the new plugin:pytest_addhooks(pluginmanager) called at plugin registration time to allow adding new hooks via a call to pluginmanager. add_hookspecs(module_or_class, prefix). Parameters pluginmanager (_pytest.config.PytestPluginManager) – pytest plu- gin manager Hooks are usually declared as do-nothing functions that contain only documentation describing when the hook willbe called and what return values are expected. The names of the functions must start with pytest_ otherwise pytestwon’t recognize them.Here’s an example. Let’s assume this code is in the hooks.py module. def pytest_my_hook(config): """ Receives the pytest config and does things with it """ To register the hooks with pytest they need to be structured in their own module or class. This class or module canthen be passed to the pluginmanager using the pytest_addhooks function (which itself is a hook exposed bypytest). def pytest_addhooks(pluginmanager): """ This example assumes the hooks are grouped in the 'hooks' module. """ from my_app.tests import hooks (continues on next page) pluginmanager.add_hookspecs(hooks) @pytest.fixture()def my_fixture(pytestconfig): # call the hook called "pytest_my_hook" # 'result' will be a list of return values from all registered functions. result = pytestconfig.hook.pytest_my_hook(config=pytestconfig) Now your hook is ready to be used. To register a function at the hook, other plugins or users must now simply definethe function pytest_my_hook with the correct signature in their conftest.py.Example: def pytest_my_hook(config): """ Print all active hooks to the screen. """ print(config.hook) Occasionally, it is necessary to change the way in which command line options are defined by one plugin based onhooks in another plugin. For example, a plugin may expose a command line option for which another plugin needsto define the default value. The pluginmanager can be used to install and use hooks to accomplish this. The pluginwould define and add the hooks and use pytest_addoption as follows: # contents of hooks.py # contents of myplugin.py def pytest_addhooks(pluginmanager): """ This example assumes the hooks are grouped in the 'hooks' module. """ from . import hook pluginmanager.add_hookspecs(hook) (continues on next page) The conftest.py that is using myplugin would simply define the hook as follows: def pytest_config_file_default_value(): return "config.yaml" Using new hooks from plugins as explained above might be a little tricky because of the standard validation mecha-nism: if you depend on a plugin that is not installed, validation will fail and the error message will not make muchsense to your users.One approach is to defer the hook implementation to a new plugin instead of declaring the hook functions directly inyour plugin module, for example: class DeferPlugin: """Simple plugin to defer pytest-xdist hook functions.""" def pytest_configure(config): if config.pluginmanager.hasplugin("xdist"): config.pluginmanager.register(DeferPlugin()) This has the added benefit of allowing you to conditionally install hooks depending on which plugins are installed. Logging pytest captures log messages of level WARNING or above automatically and displays them in their own section foreach failed test in the same manner as captured stdout and stderr.Running without options: pytest By default each captured log message shows the module, line number, log level and message.If desired the log and date format can be specified to anything that the logging module supports by passing specificformatting options: 129pytest Documentation, Release 5.4 [pytest]log_format = %(asctime)s %(levelname)s %(message)slog_date_format = %Y-%m-%d %H:%M:%S Further it is possible to disable reporting of captured content (stdout, stderr and logs) on failed tests completely with: pytest --show-capture=no Inside tests it is possible to change the log level for the captured log messages. This is supported by the caplogfixture: def test_foo(caplog): caplog.set_level(logging.INFO) pass By default the level is set on the root logger, however as a convenience it is also possible to set the log level of anylogger:logging.LogRecord instances and the final log text. This is useful for when you want to assert on the contents ofaunder a given logger name with a given severity and message: def test_foo(caplog): logging.getLogger().info("boo %s", only setup logs, same with the call and teardown phases.To access logs from other stages, use the caplog.get_records(when) method. As an example, if you want tomake sure that tests which use a certain fixture never log any warnings, you can inspect the records for the setup andcall stages during teardown like so: @pytest.fixturedef window(caplog): window = create_window() yield window for when in ("setup", "call"): messages = [ x.message for x in caplog.get_records(when) if x.levelno == logging. ˓→WARNING ] if messages: pytest.fail( "warning messages encountered during testing: {}".format(messages) ) By setting the log_cli configuration option to true, pytest will output logging records as they are emitted directlyinto the console.You can specify the logging level for which log records with equal or higher level are printed to the console by passing--log-cli-level. This setting accepts the logging level names as seen in python’s documentation or an integeras the logging level num.Additionally, you can also specify --log-cli-format and --log-cli-date-format which mirror and de-fault to --log-format and --log-date-format if not provided, but are applied only to the console logginghandler.All of the CLI log options can also be set in the configuration INI file. The option names are: • log_cli_level • log_cli_format • log_cli_date_format If you need to record the whole test suite logging calls to a file, you can pass --log-file=/path/to/log/file.This log file is opened in write mode which means that it will be overwritten at each run tests session.You can also specify the logging level for the log file by passing --log-file-level. This setting accepts thelogging level names as seen in python’s documentation(ie, uppercased level names) or an integer as the logging levelnum: • log_file • log_file_level • log_file_format • log_file_date_formatYou can call set_log_path() to customize the log_file path dynamically. This functionality is considered exper-imental. This feature was introduced as a drop-in replacement for the pytest-catchlog plugin and they conflict with each other.The backward compatibility API with pytest-capturelog has been dropped when this feature was introduced, soif for that reason you still need pytest-catchlog you can disable the internal feature by adding to your pytest.ini: [pytest] addopts=-p no:logging This feature was introduced in 3.3 and some incompatible changes have been made in 3.4 after community feed-back: • Log levels are no longer changed unless explicitly requested by the log_level configuration or --log-level command-line options. This allows users to configure logger objects themselves. • Live Logs is now disabled by default and can be enabled setting the log_cli configuration option to true. When enabled, the verbosity is increased so logging for each test is visible. • Live Logs are now sent to sys.stdout and no longer require the -s command-line option to work.If you want to partially restore the logging behavior of version 3.3, you can add this options to your ini file: [pytest]log_cli=truelog_level=NOTSET More details about the discussion that lead to this changes can be read in issue #3013. API Reference • Functions – pytest.approx – pytest.fail – pytest.skip – pytest.importorskip – pytest.xfail – pytest.exit – pytest.main – pytest.param – pytest.raises – pytest.deprecated_call – pytest.register_assert_rewrite – pytest.warns – pytest.freeze_includes • Marks – pytest.mark.filterwarnings – pytest.mark.parametrize – pytest.mark.skip – pytest.mark.skipif 133pytest Documentation, Release 5.4 – pytest.mark.usefixtures – pytest.mark.xfail – custom marks • Fixtures – @pytest.fixture – config.cache – capsys – capsysbinary – capfd – capfdbinary – doctest_namespace – request – pytestconfig – record_property – record_testsuite_property – caplog – monkeypatch – testdir – recwarn – tmp_path – tmp_path_factory – tmpdir – tmpdir_factory • Hooks – Bootstrapping hooks – Initialization hooks – Test running hooks – Collection hooks – Reporting hooks – Debugging/Interaction hooks • Objects – CallInfo – Class – Collector – Config – ExceptionInfo – pytest.ExitCode – FixtureDef – FSCollector – Function – Item – MarkDecorator – MarkGenerator – Mark – Metafunc – Module – Node – Parser – PluginManager – PytestPluginManager – Session – TestReport – _Result• Special Variables – collect_ignore – collect_ignore_glob – pytest_plugins – pytestmark – PYTEST_DONT_REWRITE (module docstring)• Environment Variables – PYTEST_ADDOPTS – PYTEST_DEBUG – PYTEST_PLUGINS – PYTEST_DISABLE_PLUGIN_AUTOLOAD – PYTEST_CURRENT_TEST• Exceptions – UsageError• Configuration Options 135pytest Documentation, Release 5.4 22.1 Functions 22.1.1 pytest.approx This problem is commonly encountered when writing tests, e.g. when making sure that floating-point values are what you expect them to be. One way to deal with this problem is to assert that two floating-point numbers are equal to within some appropriate tolerance: However, comparisons like this are tedious to write and difficult to understand. Furthermore, absolute compar- isons like the one above are usually discouraged because there’s no tolerance that works well for all situations. 1e-6 class performs floating-point comparisons using a syntax that’s as intuitive as possible: Dictionary values: >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6}) True numpy arrays:: • math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0): True if the relative tolerance is met w.r.t. either. Only available in python>=3.5. More information. . . •. . . • unittest.TestCase.assertAlmostEqual(a, b): True if a and b are within an absolute tol- erance. . . •. In the second example one expects approx(0.1).__le__(0.1 + 1e-10) to be called. But instead, approx(0.1).__lt__(0.1 + 1e-10) is used to comparison. This is because the call hierarchy of rich comparisons follows a fixed behavior. More information. . . 22.1.2 pytest.fail Tutorial: Skip and xfail: dealing with tests that cannot succeedfail(msg: str = ”, pytrace: bool = True) → NoReturn Explicitly fail an executing test with the given message. Parameters • msg (str) – the message to show the user as reason for the failure. • pytrace (bool) – if false the msg represents the full failure information and no python traceback will be reported. 22.1.3 pytest.skip skip(msg[, allow_module_level=False ]) Skip an executing test with the given message. This function should be called only during testing (setup, call or teardown) or during collection by using the allow_module_level flag. This function can be called in doctests as well. Parameters allow_module_level (bool) – allows this function to be called at module level, skipping the rest of the module. Default to False. Note: It is better to use the pytest.mark.skipif marker when possible to declare a test to be skipped under certain conditions like mismatching platforms or dependencies. Similarly, use the # doctest: +SKIP directive (see doctest.SKIP) to skip a doctest statically. 22.1.4 pytest.importorskip docutils = pytest.importorskip("docutils") 22.1.5 pytest.xfail Note: It is better to use the pytest.mark.xfail marker when possible to declare a test to be xfailed under certain conditions like known bugs or missing features. 22.1.6 pytest.exit 22.1.7 pytest.main 22.1.8 pytest.param @pytest.mark.parametrize("test_input,expected", [ ("3+5", 8), pytest.param("6*9", 42, marks=pytest.mark.xfail), ]) def test_eval(test_input, expected): assert eval(test_input) == expected Parameters • values – variable args of the values of the parameter set, in order. • marks – a single mark or a list of marks to be applied to this parameter set. • id (str) – the id to attribute to this parameter set. 22.1.9 pytest.raises If the code block does not raise the expected exception (ZeroDivisionError in the example above), or no exception at all, the check will fail instead. You can also use the keyword argument match to assert that the exception matches a text or regex: The context manager produces an ExceptionInfo object which can be used to inspect the details of the captured exception: Note: When using pytest.raises): The form above is fully supported but discouraged for new code because the context manager form is regarded as more readable and less error-prone. Note: Similar to caught exception objects in Python, explicitly clearing local references to returned ExceptionInfo objects. 22.1.10 pytest.deprecated_call deprecated_call can also be used by passing a function and *args and *kwargs, in which case it will ensure calling func(*args, **kwargs) produces one of the warnings types above. 22.1.11 pytest.register_assert_rewrite 22.1.12 pytest.warns In the context manager form you may use the keyword argument match to assert that the exception matches a text or regex: >>> with warns(UserWarning, match='must be 0 or None'): ... warnings.warn("value must be 0 or None", UserWarning) 22.1.13 pytest.freeze_includes 22.2 Marks Marks can be used apply meta data to test functions (but not fixtures), which can then be accessed by fixtures orplugins. 22.2.1 pytest.mark.filterwarnings Tutorial: @pytest.mark.filterwarnings.Add warning filters to marked test items.pytest.mark.filterwarnings(filter) Parameters filter (str) – A warning specification string, which is composed of contents of the tuple (action, message, category, module, lineno) as specified in The Warnings filter section of the Python documentation, separated by ":". Optional fields can be omitted. Module names passed for filtering are not regex-escaped. For example: def test_foo(): ... 22.2.2 pytest.mark.parametrize.2.3 pytest.mark.skip 22.2.4 pytest.mark.skipif 22.2.5 pytest.mark.usefixtures pytest.mark.usefixtures(*names) Parameters args – the names of the fixture to use, as strings 22.2.6 pytest.mark.xfail • condition (bool or str) – Condition for marking the test function as xfail (True/ False or a condition string). • reason (str) – Reason why the test function is marked as xfail. • raises (Exception) – Exception subclass expected to be raised by the test function; other exceptions will fail the test. • run (bool) – If the test function should actually be executed. If False, the function will always xfail and will not be executed (useful if a function is segfaulting). • strict (bool) – – If False (the default) the function will be shown in the terminal output as xfailed if it fails and as xpass if it passes. In both cases this will not cause the test suite to fail as a whole. This is particularly useful to mark flaky tests (tests that fail at random) to be tackled later. – If True, the function will be shown in the terminal output as xfailed if it fails, but if it unexpectedly passes then it will fail the test suite. This is particularly useful to mark func- tions that are always failing and there should be a clear indication if they unexpectedly start to pass (for example a new release of a library fixes a known bug). Marks are created dynamically using the factory object pytest.mark and applied as a decorator.For example: Will create and attach a Mark object to the collected Item, which can then be accessed by fixtures or hooks withNode.iter_markers. The mark object will have the following attributes: 22.3 Fixtures def test_output(capsys): print("hello") out, err = capsys.readouterr() assert out == "hello\n" @pytest.fixturedef db_session(tmpdir): fn = tmpdir / "db.file" return connect(str(fn)) 22.3.1 @pytest.fixture 22.3.2 config.cache Under the hood, the cache plugin uses the simple dumps/loads API of the json stdlib module.Cache.get(key, default) return cached value for the given key. If no value was yet cached or the value cannot be read, the specified default is returned. Parameters • key – must be a / separated value. Usually the first name is the name of your plugin or your application. • default – must be provided in case of a cache-miss or invalid cache values.Cache.set(key, value) save value for the given key. Parameters • key – must be a / separated value. Usually the first name is the name of your plugin or your application. • value – must be of any combination of basic python types, including nested types like e. g. lists of dictionaries.Cache.makedir(name) return a directory path object with the given name. If the directory does not yet exist, it will be created. You can use it to manage files likes e. g. store/retrieve database dumps across test sessions. Parameters name – must be a string not containing a / separator. Make sure the name contains your plugin or application identifiers to prevent clashes with other cache users. 22.3.3 capsys def test_output(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n" class CaptureFixture Object returned by capsys(), capsysbinary(), capfd() and capfdbinary() fixtures. readouterr() Read and return the captured output so far, resetting the internal buffer. Returns captured content as a namedtuple with out and err string attributes with disabled() Temporarily disables capture while inside the ‘with’ block. 22.3.4 capsysbinary def test_output(capsysbinary): print("hello") captured = capsysbinary.readouterr() assert captured.out == b"hello\n" 22.3.5 capfd def test_system_echo(capfd): os.system('echo "hello"') captured = capfd.readouterr() assert captured.out == "hello\n" 22.3.6 capfdbinary def test_system_echo(capfdbinary): os.system('echo "hello"') captured = capfdbinary.readouterr() assert captured.out == b"hello\n" 22.3.7 doctest_namespace @pytest.fixture(autouse=True) def add_np(doctest_namespace): doctest_namespace["np"] = numpy 22.3.8 request Tutorial: Pass different values to a test function, depending on command line options.The request fixture is a special fixture providing information of the requesting test function.class FixtureRequest A request for a fixture from a test or fixture function. A request object gives access to the requesting test context and has an optional param attribute in case the fixture is parametrized indirectly. fixturename = None fixture for which this request is being performed scope = None Scope string, one of “function”, “class”, “module”, “session” fixturenames names of all active fixtures in this request funcargnames alias attribute for fixturenames for pre-2.3 compatibility node underlying collection node (depends on current request scope) config the pytest config object associated with this request. function test function object if the request has a per-function scope. cls class (can be None) where the test function was collected. instance instance (can be None) on which test function was collected. module python module object where the test function was collected. fspath the file system path of the test module which collected this test. keywords keywords/markers dictionary for the underlying node. session pytest session object. addfinalizer(finalizer) add finalizer/teardown function to be called after the last test within the requesting test context finished execution. applymarker(marker) Apply a marker to a single test function invocation. This method is useful if you don’t want to have a keyword/marker on all function invocations. Parameters marker – a _pytest.mark.MarkDecorator object created by a call to pytest.mark.NAME(...). raiseerror(msg) raise a FixtureLookupError with the given message. getfixturevalue(argname) Dynamically run a named fixture function. Declaring fixtures via function argument is recommended where possible. But if you can only decide whether to use another fixture at test setup time, you may use this function to retrieve it inside a fixture or test function body. 22.3.9 pytestconfig pytestconfig() Session-scoped fixture that returns the _pytest.config.Config object. Example: def test_foo(pytestconfig): if pytestconfig.getoption("verbose") > 0: ... 22.3.10 record_property Tutorial: record_property) 22.3.11 record_testsuite_property Tutorial: record_testsuite_property.record_testsuite_property() Records a new <property> tag as child of the root <testsuite>. This is suitable to writing global infor- mation regarding the entire test suite, and is compatible with xunit2 JUnit family. def test_foo(record_testsuite_property): record_testsuite_property("ARCH", "PPC") record_testsuite_property("STORAGE_TYPE", "CEPH") name must be a string, value will be converted to a string and properly xml-escaped. 22.3.12 caplog Tutorial: Logging.caplog() Access and control log capturing. Captured logs are available through the following properties/methods: Note that traceback or stack info (from logging.exception() or the exc_info or stack_info arguments to the logging functions) is not included, as this is added by the formatter in the handler. New in version 3.7. clear() Reset the list of log records and the captured log text. set_level(level, logger=None) Sets the level for capturing of logs. The level will be restored to its previous value at the end of the test. Parameters • level (int) – the logger to level. • logger (str) – the logger to update the level. If not given, the root logger level is updated. Changed in version 3.4: The levels of the loggers changed by this function will be restored to their initial values at the end of the test. with at_level(level, logger=None) Context manager that sets the level for capturing of logs. After the end of the ‘with’ statement the level is restored to its original value. Parameters • level (int) – the logger to level. • logger (str) – the logger to update the level. If not given, the root logger level is updated. 22.3.13 monkeypatch All modifications will be undone after the requesting test function or fixture has finished. The raising pa- rameter determines if a KeyError or AttributeError will be raised if the set/deletion operation has no target. This returns a MonkeyPatch instance.class MonkeyPatch Object returned by the monkeypatch fixture keeping a record of setattr/item/env/syspath changes. with context() → Generator[MonkeyPatch, None, None] Context manager that returns a new MonkeyPatch object which undoes any patching done inside the with block upon exit: import functools def test_partial(monkeypatch): with monkeypatch.context() as m: m.setattr(functools, "partial", 3) Useful in situations where it is desired to undo some patches before the test ends, such as mocking stdlib functions that might break pytest itself if mocked (for examples of this see #3290. setattr(target, name, value=<notset>, raising=True) Set attribute value on target, memorizing the old value. By default raise AttributeError if the attribute did not exist. For convenience you can specify a string as target which will be interpreted as a dotted import path, with the last part being the attribute name. Example: monkeypatch.setattr("os.getcwd", lambda: "/") would set the getcwd function of the os module. The raising value determines if the setattr should fail if the attribute is not already present (defaults to True which means it will raise). delattr(target, name=<notset>, raising=True) Delete attribute name from target, by default raise AttributeError it the attribute did not previously exist. If no name is specified and target is a string it will be interpreted as a dotted import path with the last part being the attribute name. If raising is set to False, no exception will be raised if the attribute is missing. setitem(dic, name, value) Set dictionary entry name to value. delitem(dic, name, raising=True) Delete name from dict. Raise KeyError if it doesn’t exist. If raising is set to False, no exception will be raised if the key is missing. setenv(name, value, prepend=None) Set environment variable name to value. If prepend is a character, read the current environment variable value and prepend the value adjoined with the prepend character. delenv(name, raising=True) Delete name from the environment. Raise KeyError if it does not exist. If raising is set to False, no exception will be raised if the environment variable is missing. syspath_prepend(path) Prepend path to sys.path list of import locations. chdir(path) Change the current working directory to the specified path. Path can be a string or a py.path.local object. undo(). 22.3.14 testdir This fixture provides a Testdir instance useful for black-box testing of test files, making it ideal to test plugins.To use it, include in your top-most conftest.py file: pytest_plugins = "pytester" class Testdir Temporary test directory with tools to test/run pytest itself. This is based on the tmpdir fixture but provides a number of methods which aid with testing pytest itself. Unless chdir() is used all methods will use tmpdir as their current working directory. Attributes: Variables • tmpdir – The py.path.local instance of the temporary directory. • plugins – A list of plugins to use with parseconfig() and runpytest(). Initially this is an empty list but plugins can be added to the list. The type of items to add to the list depends on the method using them so refer to them for details. CLOSE_STDIN alias of builtins.object exception TimeoutExpired finalize() Clean up global state artifacts. Some methods modify the global interpreter state and this tries to clean this up. It does not remove the temporary directory however so it can be looked at after the test run has finished. make_hook_recorder(pluginmanager) Create a new HookRecorder for a PluginManager. chdir() Cd into the temporary directory. This is done automatically upon instantiation. makefile(ext, *args, **kwargs) Create new file(s) in the testdir. Parameters • ext (str) – The extension the file(s) should use, including the dot, e.g. .py. • args (list[str]) – All args will be treated as strings and joined using newlines. The result will be written as contents to the file. The name of the file will be based on the test function requesting this fixture. • kwargs – Each keyword is the name of a file, while the value of it will be written as contents of the file. Examples: testdir.makefile(".ini", pytest="[pytest]\naddopts=-rs\n") makeconftest(source) Write a contest.py file with ‘source’ as contents. makeini(source) Write a tox.ini file with ‘source’ as contents. getinicfg(source) Return the pytest section from the tox.ini config file. makepyfile(*args, **kwargs) Shortcut for .makefile() with a .py extension. maketxtfile(*args, **kwargs) Shortcut for .makefile() with a .txt extension. syspathinsert(path=None) Prepend a directory to sys.path, defaults to tmpdir. This is undone automatically when this object dies at the end of each test. mkdir(name) Create a new (sub)directory. mkpydir(name) Create a new python package. This creates a (sub)directory with an empty __init__.py file so it gets recognised as a python package. copy_example(name=None) Copy file from project’s directory into the testdir. Parameters name (str) – The name of the file to copy. Returns path to the copied directory (inside self.tmpdir). class Session(config: _pytest.config.Config) exception Failed signals a stop as failed test run. exception Interrupted signals an interrupted test run. for ... in collect() returns a list of children (items and collectors) for this collection node. getnode(config, arg) Return the collection node of a file. Parameters • config – _pytest.config.Config instance, see parseconfig() and parseconfigure() to create the configuration • arg – a py.path.local instance of the file getpathnode(path) Return the collection node of a file. This is like getnode() but uses parseconfigure() to create the (configured) pytest Config in- stance. Parameters path – a py.path.local instance of the file genitems(colitems) Generate all test items from a collection node. This recurses into the collection node and returns a list of all the test items contained within. runitem(source) Run the “test_func” Item. The calling test instance (class containing the test method) must provide a .getrunner() method which should return a runner which can run the test protocol for a single item, e.g. _pytest.runner. runtestprotocol(). inline_runsource(source, *cmdlineargs) Run a test module in process using pytest.main(). This run writes “source” into a temporary file and runs pytest.main() on it, returning a HookRecorder instance for the result. Parameters • source – the source code of the test module • cmdlineargs – any extra command line arguments to use Returns HookRecorder instance of the result inline_genitems(*args) Run pytest.main(['--collectonly']) in-process. Runs the pytest.main() function to run all of pytest inside the test process itself like inline_run(), but returns a tuple of the collected items and a HookRecorder instance. inline_run(*args, plugins=(), no_reraise_ctrlc: bool = False) Run pytest.main() in-process, returning a HookRecorder. Runs the pytest.main() function to run all of pytest inside the test process itself. This means it can return a HookRecorder instance which gives more detailed results from that run than can be done by matching stdout/stderr from runpytest(). Parameters • args – command line arguments to pass to pytest.main() • plugins – extra plugin instances the pytest.main() instance should use. • no_reraise_ctrlc – typically we reraise keyboard interrupts from the child run. If True, the KeyboardInterrupt exception is captured. Returns a HookRecorder instance runpytest_inprocess(*args, **kwargs) → _pytest.pytester.RunResult Return result of running pytest in-process, providing a similar interface to what self.runpytest() provides. runpytest(*args, **kwargs) → _pytest.pytester.RunResult Run pytest inline or in a subprocess, depending on the command line option “–runpytest” and return a RunResult. parseconfig(*args) Return a new pytest Config instance from given commandline args. This invokes the pytest bootstrapping code in _pytest.config to create a new _pytest.core. PluginManager and call the pytest_cmdline_parse hook to create a new _pytest.config. Config instance. If plugins has been populated they should be plugin modules to be registered with the PluginManager. parseconfigure(*args) Return a new pytest configured Config instance. This returns a new _pytest.config.Config instance like parseconfig(), but also calls the pytest_configure hook. getitem(source, funcname=’test_func’) Return the test item for a test function. This writes the source to a python file and runs pytest’s collection on the resulting module, returning the test item for the requested function name. Parameters • source – the module source • funcname – the name of the test function for which to return a test item getitems(source) Return all test items collected from the module. This writes the source to a python file and runs pytest’s collection on the resulting module, returning all test items contained within. getmodulecol(source, configargs=(), withinit=False) Return the module collection node for source. This writes source to a file using makepyfile() and then runs the pytest collection on it, returning the collection node for the test module. Parameters • source – the source code of the module to collect • configargs – any extra arguments to pass to parseconfigure() • withinit – whether to also write an __init__.py file to the same directory to ensure it is a package collect_by_name(modcol: _pytest.python.Module, name: str) → Union[_pytest.nodes.Item, _pytest.nodes.Collector, None] Return the collection node for name from the module collection. This will search a module collection node for a collection node matching the given name. Parameters • modcol – a module collection node; see getmodulecol() • name – the name of the node to return popen(cmdargs, stdout=-1, stderr=-1, stdin=<class ’object’>, **kw) Invoke subprocess.Popen. This calls subprocess.Popen making sure the current working directory is in the PYTHONPATH. You probably want to use run() instead. run(*cmdargs, timeout=None, stdin=<class ’object’>) → _pytest.pytester.RunResult Run a command with arguments. Run a process using subprocess.Popen saving the stdout and stderr. Parameters • args – the sequence of arguments to pass to subprocess.Popen() • timeout – the period in seconds after which to timeout and raise Testdir. TimeoutExpired • stdin – optional standard input. Bytes are being send, closing the pipe, otherwise it is passed through to popen. Defaults to CLOSE_STDIN, which translates to using a pipe (subprocess.PIPE) that gets closed. Returns a RunResult. runpython(script) → _pytest.pytester.RunResult Run a python script using sys.executable as interpreter. Returns a RunResult. runpython_c(command) Run python -c “command”, return a RunResult. runpytest_subprocess(*args, timeout=None) → _pytest.pytester.RunResult Run pytest as a subprocess with given arguments. Any plugins added to the plugins list will be added using the -p command line option. Additionally --basetemp is used to put any temporary files and directories in a numbered directory prefixed with “runpytest-” to not conflict with the normal numbered pytest location for temporary files and directories. Parameters • args – the sequence of arguments to pass to the pytest subprocess • timeout – the period in seconds after which to timeout and raise Testdir. TimeoutExpired Returns a RunResult. spawn_pytest(string: str, expect_timeout: float = 10.0) → pexpect.spawn Run pytest using pexpect. This makes sure to use the right pytest and sets up the temporary directory locations. The pexpect child is returned. spawn(cmd: str, expect_timeout: float = 10.0) → pexpect.spawn Run a command using pexpect. The pexpect child is returned.class RunResult The result of running a command. Attributes: Variables • ret – the return value • outlines – list of lines captured from stdout • errlines – list of lines captured from stderr • stdout – LineMatcher of stdout, use stdout.str() to reconstruct stdout or the commonly used stdout.fnmatch_lines() method • stderr – LineMatcher of stderr • duration – duration in seconds parseoutcomes() → Dict[str, int] Return a dictionary of outcomestring->num from parsing the terminal output that the test process produced. assert_outcomes(passed: int = 0, skipped: int = 0, failed: int = 0, error: int = 0, xpassed: int = 0, xfailed: int = 0) → None Assert that the specified outcomes appear with the respective numbers (0 means it didn’t occur) in the text output from a test run.class LineMatcher Flexible matching of text. This is a convenience class to test large texts like the output of commands. The constructor takes a list of lines without their trailing newlines, i.e. text.splitlines(). fnmatch_lines_random(lines2: Sequence[str]) → None Check lines exist in the output in any order (using fnmatch.fnmatch()). re_match_lines_random(lines2: Sequence[str]) → None Check lines exist in the output in any order (using re.match()). get_lines_after(fnline: str) → Sequence[str] Return all lines following the given line in the text. The given line can contain glob wildcards. fnmatch_lines(lines2: Sequence[str], *, consecutive: bool = False) → None • lines2 – string patterns to match. • consecutive – match lines consecutive? re_match_lines(lines2: Sequence[str], *, consecutive: bool = False) → None Check lines exist in the output (using re.match()). The argument is a list of lines which have to match using re.match. If they do not match a pytest.fail() is called. The matches and non-matches are also shown as part of the error message. Parameters • lines2 – string patterns to match. • consecutive – match lines consecutively? no_fnmatch_line(pat: str) → None Ensure captured lines do not match the given pattern, using fnmatch.fnmatch. Parameters pat (str) – the pattern to match lines. no_re_match_line(pat: str) → None Ensure captured lines do not match the given pattern, using re.match. Parameters pat (str) – the regular expression to match lines. str() → str Return the entire original text. 22.3.15 recwarn Note: RecordedWarning was changed from a plain class to a namedtuple in pytest 3.1 22.3.16 tmp_path 22.3.17 tmp_path_factory • numbered – If True, ensure the directory is unique by adding a number prefix greater than any existing one: basename="foo" and numbered=True means that this function will create directories named "foo-0", "foo-1", "foo-2" and so on. Returns The path to the new directory.TempPathFactory.getbasetemp() → pathlib.Path return base temporary directory. 22.3.18 tmpdir 22.3.19 tmpdir_factory 22.4 Hooks Bootstrapping hooks called for plugins registered early enough (internal and setuptools plugins).pytest_load_initial_conftests(early_config, parser, args) implements the loading of initial conftest files ahead of command line option parsing. Note: This hook will not be called for conftest.py files, only for setuptools plugins. Parameters • early_config (_pytest.config.Config) – pytest config object • args (list[str]) – list of arguments passed on the command line • parser (_pytest.config.argparsing.Parser) – to add command line options pytest_cmdline_preparse(config, args) (Deprecated) modify command line arguments before option parsing. This hook is considered deprecated and will be removed in a future pytest version. Consider using pytest_load_initial_conftests() instead. Parameters • config (_pytest.config.Config) – pytest config object • args (list[str]) – list of arguments passed on the command line pytest_cmdline_parse(pluginmanager, args) return initialized config object, parsing the specified args. Stops at first non-None result, see firstresult: stop at first non-None result Note: This hook will only be called for plugin classes passed to the plugins arg when using pytest.main to perform an in-process test run. Parameters • pluginmanager (_pytest.config.PytestPluginManager) – pytest plugin manager • args (list[str]) – list of arguments passed on the command line pytest_cmdline_main(config) called for performing the main command line action. The default implementation will invoke the configure hooks and runtest_mainloop. Stops at first non-None result, see firstresult: stop at first non-None result Parameters config (_pytest.config.Config) – pytest config object Note: This function should be implemented only in plugins or conftest.py files situated at the tests root directory due to how pytest discovers plugins during startup. Parameters pytest_addhooks(pluginmanager) called at plugin registration time to allow adding new hooks via a call to pluginmanager. add_hookspecs(module_or_class, prefix). Parameters pluginmanager (_pytest.config.PytestPluginManager) – pytest plu- gin manager pytest_configure(config) Allows plugins and conftest files to perform initial configuration. This hook is called for every plugin and initial conftest file after command line options have been parsed. After that, the hook is called for other conftest files as they are imported. pytest_unconfigure(config) called before test process is exited. Parameters config (_pytest.config.Config) – pytest config objectpytest_sessionstart(session) called after the Session object has been created and before performing collection and entering the run test loop. Parameters session (_pytest.main.Session) – the pytest session objectpytest_sessionfinish(session, exitstatus) called after whole test run finished, right before returning the exit status to the system. Parameters • session (_pytest.main.Session) – the pytest session object • exitstatus (int) – the status which pytest will return to the system pytest_plugin_registered(plugin, manager) a new pytest plugin got registered. Parameters • plugin – the plugin module or instance • manager (_pytest.config.PytestPluginManager) – pytest plugin manager pytest_runtest_call(item) called to execute the test item.pytest_runtest_teardown(item, nextitem) called after pytest_runtest_call. Parameters nextitem – the scheduled-to-be-next test item (None if no further test item is sched- uled). This argument can be used to perform exact teardowns, i.e. calling just enough finalizers so that nextitem only needs to call setup-functions.pytest_runtest_makereport(item, call) return a _pytest.runner.TestReport object for the given pytest.Item and _pytest.runner. CallInfo. Stops at first non-None result, see firstresult: stop at first non-None resultFor deeper understanding you may look at the default implementation of these hooks in _pytest.runner andmaybe also in _pytest.pdb which interacts with _pytest.capture and its input/output capturing in order toimmediately drop into interactive debugging when a test failure occurs.The _pytest.terminal reported specifically uses the reporting hook to print information about a test run.pytest_pyfunc_call(pyfuncitem) call underlying test function. Stops at first non-None result, see firstresult: stop at first non-None result pytest calls the following hooks for collecting files and directories:pytest_collection(session: Session) → Optional[Any] Perform the collection protocol for the given session. Stops at first non-None result, see firstresult: stop at first non-None result. Parameters session (_pytest.main.Session) – the pytest session objectpytest_ignore_collect(path, config) return True to prevent considering this path for collection. This hook is consulted for all files and directories prior to calling more specific hooks. Stops at first non-None result, see firstresult: stop at first non-None result Parameters • path – a py.path.local - the path to analyze • config (_pytest.config.Config) – pytest config objectpytest_collect_directory(path, parent) called before traversing a directory for collection files. Stops at first non-None result, see firstresult: stop at first non-None result Parameters path – a py.path.local - the path to analyzepytest_collect_file(path, parent) return collection Node or None for the given path. Any new node needs to have the specified parent as a parent. Parameters path – a py.path.local - the path to collect pytest_pycollect_makemodule(path, parent) – a py.path.local - the path of module to collectFor influencing the collection of objects in Python modules you can use the following hook:pytest_pycollect_makeitem(collector, name, obj) return custom item/collector for a python object in a module, or None. Stops at first non-None result, see firstresult: stop at first non-None resultpytest_generate_tests(metafunc) generate (multiple) parametrized calls to a test function.pytest_make_parametrize_id(config, val, argname) Return a user-friendly string representation of the given val that will be used by @pytest.mark.parametrize calls. Return None if the hook doesn’t know about val. The parameter name is available as argname, if required. Stops at first non-None result, see firstresult: stop at first non-None result Parameters • config (_pytest.config.Config) – pytest config object • val – the parametrized value • argname (str) – the automatic parameter name produced by pytestAfter collection is complete, you can modify the order of items, delete or otherwise amend the test items:pytest_collection_modifyitems(session, config, items) called after collection has been performed, may filter or re-order the items in-place. Parameters • session (_pytest.main.Session) – the pytest session object • config (_pytest.config.Config) – pytest config object • items (List[_pytest.nodes.Item]) – list of item objectspytest_collection_finish(session) called after collection has been performed and modified. Parameters session (_pytest.main.Session) – the pytest session object pytest_itemcollected(item) we just collected a test item.pytest_collectreport(report) collector finished collecting.pytest_deselected(items) called for test items deselected, e.g. by keyword.pytest_report_header(config, startdir) return a string or list of strings to be displayed as header info for terminal reporting. Parameters • config (_pytest.config.Config) – pytest config object • startdir – py.path object with the starting dir Note: If the fixture function returns None, other implementations of this hook function will continue to be called, according to the behavior of the firstresult: stop at first non-None result option. pytest_fixture_post_finalizer(fixturedef, request) Called after fixture teardown, but before the cache is cleared, so the fixture result fixturedef. cached_result is still available (not None).pytest_warning_captured(warning_message, when, item, location) Process a warning captured by the internal pytest warnings plugin. Parameters • warning_message (warnings.WarningMessage) – The captured warning. This is the same object produced by warnings.catch_warnings(), and contains the same attributes as the parameters of warnings.showwarning(). • when (str) – Indicates when the warning was captured. Possible values: – "config": during pytest configuration/initialization stage. – "collect": during test collection. – "runtest": during test execution. • item (pytest.Item|None) – DEPRECATED: This parameter is incompatible with pytest-xdist, and will always receive None in a future release. The item being executed if when is "runtest", otherwise None. • location (tuple) – Holds information about the execution context of the captured warn- ing (filename, linenumber, function). function evaluates to <module> when the execu- tion context is at the module level.Central hook for reporting about test execution:pytest_runtest_logreport(report) process a test setup/call/teardown report relating to the respective phase of executing a test.Assertion related hookspytest_assertion_pass(item, lineno, orig, expl) (Experimental) New in version 5.0. Hook called whenever an assertion passes. Use this hook to do some processing after a passing assertion. The original assertion information is available in the orig string and the pytest introspected assertion information is available in the expl string. This hook must be explicitly enabled by the enable_assertion_pass_hook ini-file option: [pytest] enable_assertion_pass_hook=true You need to clean the .pyc files in your project directory and interpreter libraries when enabling this option, as assertions will require to be re-written. Parameters • item (_pytest.nodes.Item) – pytest item object of current test • lineno (int) – line number of the assert statement • orig (string) – string with original assertion • expl (string) – string with assert explanation Note: This hook is experimental, so its parameters or even the hook itself might be changed/removed without warning in any future pytest release. If you find this hook useful, please share your feedback opening an issue. There are few hooks which can be used for special reporting or interaction with exceptions:pytest_internalerror(excrepr, excinfo) called for internal errors.pytest_keyboard_interrupt(excinfo) called for keyboard interrupt.pytest_exception_interact(node, call, report) called when an exception was raised which can potentially be interactively handled. This hook is only called if an exception was raised that is not an internal exception like skip.Exception.pytest_enter_pdb(config, pdb) called upon pdb.set_trace(), can be used by plugins to take special action just before the python debugger enters in interactive mode. Parameters • config (_pytest.config.Config) – pytest config object • pdb (pdb.Pdb) – Pdb instance 22.5 Objects 22.5.1 CallInfo class CallInfo Result/Exception info a function invocation. 22.5.2 Class class Class Bases: _pytest.python.PyCollector Collector for test methods. classmethod from_parent(parent, *, name, obj=None) The public constructor collect() returns a list of children (items and collectors) for this collection node. 22.5.3 Collector class Collector Bases: _pytest.nodes.Node Collector instances create children through collect() and thus iteratively build a tree. exception CollectError Bases: Exception an error during collection, contains a custom message. collect() returns a list of children (items and collectors) for this collection node. repr_failure(excinfo) represent a collection failure. 22.5.4 Config class Config Access to configuration values, pluginmanager and plugin hooks. Variables • pluginmanager (PytestPluginManager) – the plugin manager handles plugin reg- istration and hook invocation. • option (argparse.Namespace) – access to command line option as attributes. • invocation_params (InvocationParams) – Object containing the parameters re- garding the pytest.main invocation. Contains the following read-only attributes: – args: tuple of command-line arguments as passed to pytest.main(). – plugins: list of extra plugins, might be None. – dir: directory where pytest.main() was invoked from. class InvocationParams(args, plugins, dir: pathlib.Path) Holds parameters passed during pytest.main() New in version 5.1. Note: Note that the environment variable PYTEST_ADDOPTS and the addopts ini option are handled by pytest, not being included in the args attribute. invocation_dir Backward compatibility add_cleanup(func) Add a function to be called when the config object gets out of use (usually coninciding with pytest_unconfigure). classmethod fromdictargs(option_dict, args) constructor usable for subprocesses. addinivalue_line(name, line) add a line to an ini-file option. The option must have been declared but might not yet be set in which case the line becomes the the first line in its value. getini(name: str) return configuration value from an ini file. If the specified name hasn’t been registered through a prior parser.addini call (usually from a plugin), a ValueError is raised. getoption(name: str, default=<NOTSET>, skip: bool = False) return command line option value. Parameters • name – name of the option. You may also specify the literal --OPT option instead of the “dest” option name. • default – default value if no option of that name exists. • skip – if True raise pytest.skip if option does not exists or has a None value. getvalue(name, path=None) (deprecated, use getoption()) getvalueorskip(name, path=None) (deprecated, use getoption(skip=True)) 22.5.5 ExceptionInfo 22.5.6 pytest.ExitCode class ExitCode New in version 5.0. Encodes the valid exit codes by pytest. Currently users and plugins may supply other exit codes as well. OK = 0 tests passed TESTS_FAILED = 1 tests failed INTERRUPTED = 2 pytest was interrupted INTERNAL_ERROR = 3 an internal error got in the way USAGE_ERROR = 4 pytest was misused NO_TESTS_COLLECTED = 5 pytest couldn’t find tests 22.5.7 FixtureDef class FixtureDef Bases: object A container for a factory definition. 22.5.8 FSCollector class FSCollector Bases: _pytest.nodes.Collector classmethod from_parent(parent, *, fspath) The public constructor 22.5.9 Function class Function Bases: _pytest.python.PyobjMixin, _pytest.nodes.Item a Function Item is responsible for setting up and executing a Python test function. originalname = None original function name, without any decorations (for example parametrization adds a "[...]" suffix to function names). 22.5.10 Item class Item Bases: _pytest.nodes.Node a basic test invocation item. Note that for a single function there might be multiple test invocation items. user_properties = None user properties is a list of tuples (name, value) that holds user defined properties for this test. add_report_section(when: str, key: str, content: str) → None Adds a new report section, similar to what’s done internally to add stdout and stderr captured output: Parameters • when (str) – One of the possible capture states, "setup", "call", "teardown". • key (str) – Name of the section, can be customized at will. Pytest uses "stdout" and "stderr" internally. • content (str) – The full contents as a string. 22.5.11 MarkDecorator class MarkDecorator(mark) A decorator for test functions and test classes. When applied it will create Mark objects which are often created like this: @mark2 def test_function(): pass 2. If called with a single function as its only positional argument and no additional keyword arguments, it attaches a MarkInfo object to the function, containing all the arguments already stored internally in the MarkDecorator. 3. When called in any other case, it performs a ‘fake construction’ call, i.e. it returns a new MarkDecorator instance with the original MarkDecorator’s content updated with the arguments passed to this call. Note: The rules above prevent MarkDecorator objects from storing only a single function or class reference as their positional argument with no additional keyword or positional arguments. name alias for mark.name args alias for mark.args kwargs alias for mark.kwargs with_args(*args, **kwargs) return a MarkDecorator with extra arguments added unlike call this can be used even if the sole argument is a callable/class Returns MarkDecorator 22.5.12 MarkGenerator class MarkGenerator Factory for MarkDecorator objects - exposed as a pytest.mark singleton instance. Example: import pytest @pytest.mark.slowtest def test_function(): pass 22.5.13 Mark name = None name of the mark args = None positional arguments of the mark decorator kwargs = None keyword arguments of the mark decorator combined_with(other: _pytest.mark.structures.Mark) → _pytest.mark.structures.Mark Parameters other (Mark) – the mark to combine with Return type Mark combines by appending args and merging the mappings 22.5.14 Metafunc.5.15 Module class Module Bases: _pytest.nodes.File, _pytest.python.PyCollector Collector for test classes and functions. collect() returns a list of children (items and collectors) for this collection node. 22.5.16 Node class Node base class for Collector and Item the test collection tree. Collector subclasses have children, Items are terminal nodes. name = None a unique name within the scope of the parent node parent = None the parent collector node. fspath = None filesystem path where this node was collected from (can be None) keywords = None keywords/markers collected from all scopes own_markers = None the marker objects belonging to this node extra_keyword_matches = None allow adding of extra keywords to use for matching classmethod from_parent(parent: _pytest.nodes.Node, **kw) Public Constructor for Nodes This indirection got introduced in order to enable removing the fragile logic from the node constructors. Subclasses can use super().from_parent(...) when overriding the construction Parameters parent – the parent node of this test Node ihook fspath sensitive hook proxy used to call pytest hooks warn(warning) Issue a warning for this item. Warnings will be displayed after the test session, unless explicitly suppressed node.warn(PytestWarning("some message")) nodeid a ::-separated string denoting its collection tree address. listchain() return list of all parent collectors up to self, starting from root of collection tree. add_marker(marker: Union[str, _pytest.mark.structures.MarkDecorator], append: bool = True) → None dynamically add a marker object to the node. Parameters marker (str or pytest.mark.* object) – append=True whether to append the marker, if False insert at position 0. iter_markers(name=None) Parameters name – if given, filter the results by the name attribute iterate over all markers of the node for ... in iter_markers_with_node(name=None) Parameters name – if given, filter the results by the name attribute iterate over all markers of the node returns sequence of tuples (node, mark) get_closest_marker(name, default=None) return the first marker matching the name, from closest (for example function) to farther level (for example module level). Parameters • default – fallback return value of no marker was found • name – name to filter by listextrakeywords() Return a set of all extra keywords in self and any parents. addfinalizer(fin) register a function to be called when this node is finalized. This method can only be called when this node is active in a setup chain, for example during self.setup(). getparent(cls) get the next parent node (including ourself) which is an instance of the given class 22.5.17 Parser class Parser Parser for command line arguments and ini-file values. Variables extra_info – dict of generic param -> value to display in case there’s an error pro- cessing the command line arguments. 22.5.18 PluginManager class PluginManager Core PluginManager class which manages registration of plugin objects and 1:N hook calling. You can register new hooks by calling add_hookspecs(module_or_class). You can register plugin objects (which contain hooks) by calling register(plugin). The PluginManager is initialized with a prefix that is searched for in the names of the dict of registered plugin objects. For debugging purposes you can call PluginManager.enable_tracing() which will subsequently send debug information to the trace helper. register(plugin, name=None) Register a plugin and return its canonical name or None if the name is blocked from registering. Raise a ValueError if the plugin is already registered. unregister(plugin=None, name=None) unregister a plugin object and all its contained hook implementations from internal data structures. set_blocked(name) block registrations of the given name, unregister if already registered. is_blocked(name) return True if the given plugin name is blocked. add_hookspecs(module_or_class) add new hook specifications defined in the given module_or_class. Functions are recognized if they have been decorated accordingly. get_plugins() return the set of registered plugins. is_registered(plugin) Return True if the plugin is already registered. get_canonical_name(plugin) Return canonical name for a plugin object. Note that a plugin may be registered under a different name which was specified by the caller of register(plugin, name). To obtain the name of an registered plugin use get_name(plugin) instead. get_plugin(name) Return a plugin or None for the given name. has_plugin(name) Return True if a plugin with the given name is registered. get_name(plugin) Return name for registered plugin or None if not registered. check_pending() Verify that all hooks which have not been verified against a hook specification are optional, otherwise raise PluginValidationError. load_setuptools_entrypoints(group, name=None) Load modules from querying the specified setuptools group. Parameters • group (str) – entry point group to load plugins • name (str) – if given, loads only plugins with the given name. Return type int Returns return the number of loaded plugins by this call. list_plugin_distinfo() return list of distinfo/plugin tuples for all setuptools registered plugins. list_name_plugin() return list of name/plugin pairs. get_hookcallers(plugin) get all hook callers for the specified plugin. add_hookcall_monitoring(before, after) but also a pluggy.callers._Result object which represents the result of the overall hook call. enable_tracing() enable tracing of hook calls and return an undo function. subset_hook_caller(name, remove_plugins) Return a new hooks._HookCaller instance for the named method which manages calls to all regis- tered plugins except the ones from remove_plugins. 22.5.19 PytestPluginManager class PytestPluginManager Bases: pluggy.manager.PluginManager Overwrites pluggy.PluginManager to add pytest-specific functionality: • loading plugins from the command line, PYTEST_PLUGINS env variable and pytest_plugins global variables found in plugins being loaded; • conftest.py loading during start-up; parse_hookimpl_opts(plugin, name) parse_hookspec_opts(module_or_class, name) register(plugin, name=None) Register a plugin and return its canonical name or None if the name is blocked from registering. Raise a ValueError if the plugin is already registered. getplugin(name) hasplugin(name) Return True if the plugin with the given name is registered. pytest_configure(config) consider_preparse(args, *, exclude_only=False) consider_pluginarg(arg) consider_conftest(conftestmodule) consider_env() consider_module(mod) import_plugin(modname, consider_entry_points=False) Imports a plugin with modname. If consider_entry_points is True, entry point names are also considered to find a plugin. 22.5.20 Session class Session Bases: _pytest.nodes.FSCollector exception Interrupted Bases: KeyboardInterrupt signals an interrupted test run. exception Failed Bases: Exception signals a stop as failed test run. for ... in collect() returns a list of children (items and collectors) for this collection node. 22.5.21 TestReport class TestReport Basic test report object (also used for setup and teardown calls if they fail). nodeid = None normalized collection node id location = None a (filesystempath, lineno, domaininfo) tuple indicating the actual location of a test item - it might be different from the collected one e.g. if a method is inherited from a different module. keywords = None a name -> value dictionary containing all keywords and markers associated with a test invocation. outcome = None test outcome, always one of “passed”, “failed”, “skipped”. longrepr = None None or a failure representation. when = None one of ‘setup’, ‘call’, ‘teardown’ to indicate runtest phase. user_properties = None user properties is a list of tuples (name, value) that holds user defined properties of the test sections = [] list of pairs (str, str) of extra information which needs to marshallable. Used by pytest to add captured text from stdout and stderr, but may be used by other plugins to add arbitrary information to reports. duration = None time it took to run just the test classmethod from_item_and_call(item, call) → _pytest.reports.TestReport Factory method to create and fill a TestReport with standard item and call info. caplog Return captured log lines, if log capturing is enabled New in version 3.5. capstderr Return captured text from stderr, if capturing is enabled New in version 3.0. capstdout Return captured text from stdout, if capturing is enabled New in version 3.0. count_towards_summary Experimental Returns True if this report should be counted towards the totals shown at the end of the test session: “1 passed, 1 failure, etc”. Note: This function is considered experimental, so beware that it is subject to changes even in patch releases. head_line Experimental Returns the head line shown with longrepr output for this report, more commonly during traceback repre- sentation during failures: longreprtext Read-only property that returns the full string representation of longrepr. New in version 3.0. 22.5.22 _Result result Get the result(s) for this hook call (DEPRECATED in favor of get_result()). force_result(result) Force the result(s) to result. If the hook was marked as a firstresult a single value should be set otherwise set a (modified) list of results. Any exceptions found during invocation will be deleted. get_result() Get the result(s) for this hook call. If the hook was marked as a firstresult only a single value will be returned otherwise a list of results. pytest treats some global variables in a special manner when defined in a test module. 22.6.1 collect_ignore collect_ignore = ["setup.py"] 22.6.2 collect_ignore_glob collect_ignore_glob = ["*_ignore.py"] 22.6.3 pytest_plugins 22.6.4 pytestmark pytestmark = pytest.mark.webtest The text PYTEST_DONT_REWRITE can be add to any module docstring to disable assertion rewriting for thatmodule. 22.7.1 PYTEST_ADDOPTS This contains a command-line (parsed by the py:mod:shlex module) that will be prepended to the command linegiven by the user, see How to change command line options defaults for more information. 22.7.2 PYTEST_DEBUG 22.7.3 PYTEST_PLUGINS export PYTEST_PLUGINS=mymodule.plugin,xdist 22.7.4 PYTEST_DISABLE_PLUGIN_AUTOLOAD When set, disables plugin auto-loading through setuptools entrypoints. Only explicitly specified plugins will be loaded. 22.7.5 PYTEST_CURRENT_TEST This is not meant to be set by users, but is set by pytest internally with the name of the current test so other processescan inspect it, see PYTEST_CURRENT_TEST environment variable for more information. 22.8 Exceptions 22.8.1 UsageError class UsageError error in pytest usage or invocation Here is a list of builtin configuration options that may be written in a pytest.ini, tox.ini or setup.cfg file,usually located at the root of your repository. All options must be under a [pytest] section ([tool:pytest] forsetup.cfg files). Warning: Usage of setup.cfg is not recommended unless for very simple use cases. .cfg files use a different parser than pytest.ini and tox.ini which might cause hard to track down problems. When possible, it is recommended to use the latter files to hold your pytest configuration. Configuration file options may be overwritten in the command-line by using -o/--override, which can also bepassed multiple times. The expected format is name=value. For example: addopts Add the specified OPTS to the set of command line arguments as if they had been specified by the user. Example: if you have this ini file content: # content of pytest.ini [pytest] addopts = --maxfail=2 -rf # exit after 2 failures, report fail info # content of pytest.ini [pytest] console_output_style = classic doctest_encoding Default encoding to use to decode text files with docstrings. See how pytest handles doctests.doctest_optionflags One or more doctest flag names from the standard doctest module. See how pytest handles doctests.empty_parameter_set_mark Allows to pick the action for empty parametersets in parameterization • skip skips tests with an empty parameterset (default) • xfail marks tests with an empty parameterset as xfail(run=False) • fail_at_collect raises an exception if parametrize collects an empty parameter set # content of pytest.ini [pytest] empty_parameter_set_mark = xfail Note: The default value of this option is planned to change to xfail in future releases as this is considered less error prone, see #3155 for more details. faulthandler_timeout Dumps the tracebacks of all threads if a test takes longer than X seconds to run (including fixture setup and teardown). Implemented using the faulthandler.dump_traceback_later function, so all caveats there apply. # content of pytest.ini [pytest] faulthandler_timeout=5 # content of pytest.ini [pytest] filterwarnings = error ignore::DeprecationWarning This tells pytest to ignore deprecation warnings and turn all other warnings into errors. For more information please refer to Warnings Capture.junit_duration_report New in version 4.1. Configures how durations are recorded into the JUnit XML report: • total (the default): duration times reported include setup, call, and teardown times. • call: duration times reported include only call times, excluding setup and teardown. [pytest] junit_duration_report = call junit_family New in version 4.2. Configures the format of the generated JUnit XML file. The possible options are: • xunit1 (or legacy): produces old style output, compatible with the xunit 1.0 format. This is the default. • xunit2: produces xunit 2.0 style output, which should be more compatible with latest Jenkins ver- sions. [pytest] junit_family = xunit2 junit_logging New in version 3.5. [pytest] junit_logging = system-out junit_log_passing_tests New in version 4.6. If junit_logging != "no", configures if the captured output should be written to the JUnit XML file for passing tests. Default is True. [pytest] junit_log_passing_tests = False junit_suite_name To set the name of the root test suite xml item, you can configure the junit_suite_name option in your config file: [pytest] junit_suite_name = my_suite log_auto_indent Allow selective auto-indentation of multiline log messages. Supports command line option --log-auto-indent [value] and config option log_auto_indent = [value] to set the auto-indentation behavior for all logging. [value] can be: • True or “On” - Dynamically auto-indent multiline log messages • False or “Off” or 0 - Do not auto-indent multiline log messages (the default behavior) • [positive integer] - auto-indent multiline log messages by [value] spaces [pytest] log_auto_indent = False [pytest] log_cli = True log_cli_date_format Sets a time.strftime()-compatible string that will be used when formatting dates for live logging. [pytest] log_cli_date_format = %Y-%m-%d %H:%M:%S [pytest] log_cli_format = %(asctime)s %(levelname)s %(message)s [pytest] log_cli_level = INFO [pytest] log_date_format = %Y-%m-%d %H:%M:%S [pytest] log_file = logs/pytest-logs.txt [pytest] log_file_date_format = %Y-%m-%d %H:%M:%S [pytest] log_file_format = %(asctime)s %(levelname)s %(message)s log_file_level Sets the minimum log message level that should be captured for the logging file. The integer value or the names of the levels can be used. [pytest] log_file_level = INFO [pytest] log_format = %(asctime)s %(levelname)s %(message)s [pytest] log_level = INFO [pytest] log_print = False [pytest] addopts = --strict-markers markers = slow serial minversion Specifies a minimal pytest version required for running tests. # content of pytest.ini [pytest] minversion = 3.0 # will fail if we run with pytest-2.8 norecursedirs replaces the default. Here is an example of how to avoid certain di- rectories: [pytest] norecursedirs = .svn _build tmp* This would tell pytest to not look into typical subversion or sphinx-build directories or into any tmp prefixed directory. Additionally, pytest will attempt to intelligently identify and ignore a virtualenv by the presence of an activa- tion script. Any directory deemed to be the root of a virtual environment will not be considered during test col- lection unless --collect-in-virtualenv is given. Note also that norecursedirs takes precedence over --collect-in-virtualenv; e.g. if you intend to run tests in a virtualenv with a base directory that matches '.*' you must override norecursedirs in addition to using the --collect-in-virtualenv flag.python_classes One or more name prefixes or glob-style patterns determining which classes are considered for test collection. Search for multiple glob patterns by adding a space between patterns. By default, pytest will consider any class prefixed with Test as a test collection. Here is an example of how to collect tests from classes that end in Suite: [pytest] python_classes = *Suite Note that unittest.TestCase derived classes are always collected regardless of this option, as unittest’s own collection framework is used to collect those tests.python_files One or more Glob-style file patterns determining which python files are considered as test modules. Search for multiple glob patterns by adding a space between patterns: [pytest] python_files = test_*.py check_*.py example_*.py [pytest] python_files = test_*.py check_*.py example_*.py By default, files matching test_*.py and *_test.py will be considered test modules.python_functions One or more name prefixes or glob-patterns determining which test functions and methods are considered tests. Search for multiple glob patterns by adding a space between patterns. By default, pytest will consider any function prefixed with test as a test. Here is an example of how to collect test functions and methods that end in _test: [pytest] python_functions = *_test Note that this has no effect on methods that live on a unittest .TestCase derived class, as unittest’s own collection framework is used to collect those tests. See Changing naming conventions for more detailed examples.testpaths and doc directories when executing from the root directory.usefixtures List of fixtures that will be applied to all test functions; this is semantically the same to apply the @pytest. mark.usefixtures marker to all test functions. [pytest] usefixtures = clean_db xfail_strict If set to True, tests marked with @pytest.mark.xfail that actually succeed will by default fail the test suite. For more information, see strict parameter. [pytest] xfail_strict = True For development, we recommend you use venv for virtual environments and pip for installing your application andany dependencies, as well as the pytest package itself. This ensures your code and dependencies are isolated fromyour system Python installation.Next, place a setup.py file in the root of your package with the following minimum content: setup(name="PACKAGENAME", packages=find_packages()) Where PACKAGENAME is the name of your package. You can then install your package in “editable” mode by runningfrom the same directory: pip install -e . which lets you change your source code (both tests and application) and rerun tests at will. This is similar to run-ning python setup.py develop or conda develop in that it installs your package using a symlink to yourdevelopment code. 193pytest Documentation, Release 5.4 Putting tests into an extra directory outside your actual application code might be useful if you have many functionaltests or for other reasons want to keep tests separate from actual application code (often a good idea):setup.pymypkg/ __init__.py app.py view.pytests/ test_app.py test_view.py ... Note: See Invoking pytest versus python -m pytest for more information about the difference between calling pytestand python -m pytest. Note that using this scheme your test files must have unique names, because pytest will import them as top-levelmodules since there are no packages to derive a full package name from. In other words, the test files in the exampleabove will be imported as test_app and test_view top-level modules by adding tests/ to sys.path.If you need to have test modules with the same name, you might add __init__.py files to your tests folder andsubfolders, changing them to packages:setup.pymypkg/ ...tests/ __init__.py foo/ (continues on next page) Now pytest will load the modules as tests.foo.test_view and tests.bar.test_view, allowing you tohave modules with the same name. But now this introduces a subtle problem: in order to load the test modules from thetests directory, pytest prepends the root of the repository to sys.path, which adds the side-effect that now mypkgof your root: setup.pysrc/ mypkg/ __init__.py app.py view.pytests/ __init__.py foo/ __init__.py test_view.py bar/ __init__.py test_view.py This layout prevents a lot of common pitfalls and has many benefits, which are better explained in this excellent blogpost by Ionel Cristian Măries, . Inlining test directories into your application package is useful if you have direct relation between tests and applicationmodules and want to distribute them along with your application: setup.pymypkg/ __init__.py app.py view.py test/ __init__.py test_app.py test_view.py ... In this scheme, it is easy to run your tests using the --pyargs option:package name discovery based on the presence of __init__.py files. If you use one of the two recommended filesystem layouts above but leave away the __init__.py files from your directories it should just work on Python3.3and above. From “inlined tests”, however, you will need to use absolute imports for getting at your application code. Note: If pytest finds an “a/b/test_module.py” test file while recursing into the filesystem it determines the importname as follows: • determine basedir: this is the first “upward” (towards the root) directory not containing an __init__.py. If e.g. both a and b contain an __init__.py file then the parent directory of a will become the basedir. • perform sys.path.insert(0, basedir) to make the test module importable under the fully qualified import name. • import a.b.test_module where the path is determined by converting path separators / into “.” charac- ters. This means you must follow the convention of having directory and file names map directly to the import names.The reason for this somewhat evolved importing technique is that in larger projects multiple test modules might importfrom each other and thus deriving a canonical import name helps to avoid surprises such as a test module gettingimported twice. 23.4 tox Once you are done with your work and want to make sure that your actual package passes all tests you may want tolook into tox, the virtualenv test automation tool and its pytest support. tox helps you to setup virtualenv environmentswith pre-defined dependencies and then executing a pre-configured test command with options. It will run tests againstthe installed package and not against your source code checkout, helping to detect packaging glitches. Flaky tests A “flaky” test is one that exhibits intermittent or sporadic failure, that seems to have non-deterministic behaviour.Sometimes it passes, sometimes it fails, and it’s not clear why. This page discusses pytest features that can help andother general strategies for identifying, fixing or mitigating them. Flaky tests are particularly troublesome when a continuous integration (CI) server is being used, so that all tests mustpass before a new code change can be merged. If the test result is not a reliable signal – that a test failure meansthe code change broke the test – developers can become mistrustful of the test results, which can lead to overlookinggenuine failures. It is also a source of wasted time as developers must re-run test suites and investigate spuriousfailures. Broadly speaking, a flaky test indicates that the test relies on some system state that is not being appropriately con-trolled - the test environment is not sufficiently isolated. Higher level tests are more likely to be flaky as they rely onmore state.Flaky tests sometimes appear when a test suite is run in parallel (such as use of pytest-xdist). This can indicate a testis reliant on test ordering. • Perhaps a different test is failing to clean up after itself and leaving behind data which causes the flaky test to fail. • The flaky test is reliant on data from a previous test that doesn’t clean up after itself, and in parallel runs that previous test is not always present • Tests that modify global state typically cannot be run in parallel. 197pytest Documentation, Release 5.4 Overly strict assertions can cause problems with floating point comparison as well as timing issues. pytest.approx isuseful here. pytest.mark.xfail with strict=False can be used to mark a test so that its failure does not cause the whole build tobreak. This could be considered like a manual quarantine, and is rather dangerous to use permanently. 24.3.2 PYTEST_CURRENT_TEST PYTEST_CURRENT_TEST environment variable may be useful for figuring out “which test got stuck”. 24.3.3 Plugins Rerunning any failed tests can mitigate the negative effects of flaky tests by giving them additional chances to pass, sothat the overall build does not fail. Several pytest plugins support this: • flaky • pytest-flakefinder - blog post • pytest-rerunfailures • pytest-replay: This plugin helps to reproduce locally crashes or flaky tests observed during CI runs.Plugins to deliberately randomize tests can help expose tests with state problems: • pytest-random-order • pytest-randomly It can be common to split a single test suite into two, such as unit vs integration, and only use the unit test suite as aCI gate. This also helps keep build times manageable as high level tests tend to be slower. However, it means it doesbecome possible for code that breaks the build to be merged, so extra vigilance is needed for monitoring the integrationtest results. For UI tests these are important for understanding what the state of the UI was when the test failed. pytest-splinter canbe used with plugins like pytest-bdd and can save a screenshot on test failure, which can help to isolate the cause. If the functionality is covered by other tests, perhaps the test can be removed. If not, perhaps it can be rewritten at alower level which will remove the flakiness or make its source more apparent. 24.4.4 Quarantine Mark Lapierre discusses the Pros and Cons of Quarantined Tests in a post from 2018. Azure Pipelines (the Azure cloud CI/CD tool, formerly Visual Studio Team Services or VSTS) has a feature to identifyflaky tests and rerun failed tests. 24.5 Research This is a limited list, please submit an issue or pull request to expand it! • • Palomba, Fabio, and Andy Zaidman. “Does refactoring of test smells induce fixing flaky tests?.” In Software Maintenance and Evolution (ICSME), 2017 IEEE International Conference on, pp. 1-12. IEEE, 2017. PDF in Google Drive • Bell, Jonathan, Owolabi Legunsen, Michael Hilton, Lamyaa Eloussi, Tifany Yung, and Darko Marinov. “De- Flaker: Automatically detecting flaky tests.” In Proceedings of the 2018 International Conference on Software Engineering. 2018. PDF 24.6 Resources Here’s a list of scenarios where pytest may need to change sys.path in order to import test modules or conftest.py files. modulesto have duplicated names. This is also discussed in details in Conventions for Python test discovery. 201pytest Documentation, Release 5.4 root/|- foo/ |- conftest.py |- bar/ |- tests/ |- test_foo.py pytest will find foo/bar/tests/test_foo.py and realize it is NOT part of a package given that there’s no__init__.py file in the same folder. It will then add root/foo/bar/tests to sys.path in order to importtest_foo.py as the module test_foo. The same is done with the conftest.py file by adding root/foo tosys.path to import it as conftest.For this reason this layout cannot have test modules with the same name, as they all will be imported in the globalimport namespace.This is also discussed in details in Conventions for Python test discovery. Running pytest with pytest [...] instead of python -m pytest [...] yields nearly equivalent behaviour,except that the latter will add the current directory to sys.path, which is standard python behavior.See also Calling pytest through python -m pytest. Configuration You can get help on command line options and values in INI-style configurations files by using the general help option: This will display command line and configuration file settings which were registered by installed plugins. pytest determines a rootdir for each test run which depends on the command line arguments (specified test files,paths) and on the existence of ini-files. The determined rootdir and ini-file are printed as part of the pytest headerduring startup.Here’s a summary what pytest uses rootdir for: • Construct nodeids during collection; each test is assigned a unique nodeid which is rooted at the rootdir and takes into account the full path, class name, function name and parametrization (if any). • Is used by plugins as a stable location to store project/test run specific information; for example, the internal cache plugin creates a .pytest_cache subdirectory in rootdir to store its cross-test run state.rootdir is NOT used to modify sys.path/PYTHONPATH or influence how modules are imported. See pytestimport mechanisms and sys.path/PYTHONPATH for more details.The --rootdir=path command-line option can be used to force a specific directory. The directory passed maycontain environment variables when it is used in conjunction with addopts in a pytest.ini file. 203pytest Documentation, Release 5.4 • determine the common ancestor directory for the specified args that are recognised as paths that exist in the file system. If no such paths are found, the common ancestor directory is set to the current working directory. • look for pytest.ini, tox.ini and setup.cfg files in the ancestor directory and upwards. If one is matched, it becomes the ini-file and its directory becomes the rootdir. • if no ini-file was found, look for setup.py upwards from the common ancestor directory to determine the rootdir. • if no setup.py was found, look for pytest.ini, tox.ini and setup.cfg in each of the specified args and upwards. If one is matched, it becomes the ini-file and its directory becomes the rootdir. •from there..Note that an existing pytest.ini file will always be considered a match, whereas tox.ini and setup.cfg willonly match if they contain a [pytest] or [tool:pytest] section, respectively. Options from multiple ini-filescandidates are never merged - the first one wins (pytest.ini always wins, even if it does not contain a [pytest]section).The config object will subsequently carry these attributes: • config.rootdir: the determined root directory, guaranteed to exist. • config.inifile: the determined ini-file, may be None.The rootdir is used as a reference directory for constructing test addresses (“nodeids”) and can be used also by pluginsfor storing per-testrun information.Example: will determine the common ancestor as path and then check for ini-files as follows: It can be tedious to type the same series of command line options every time you use pytest. For example, if youalways want to see detailed info on skipped and xfailed tests, as well as have terser “dot” progress output, you can # content of setup.cfg[tool:pytest]addopts = -ra -q Alternatively, you can set a PYTEST_ADDOPTS environment variable to add command line options while the envi-ronment is in use: export PYTEST_ADDOPTS="-v" Here’s how the command-line is built in the presence of addopts or the environment variable: pytest -m slow Note that as usual for other command-line applications, in case of conflicting options the last one wins, so the exampleabove will show verbose output because -v overwrites -q. Here is a (growing) list of examples. Contact us if you need more examples or have questions. Also take a look atthe comprehensive documentation which contains many example snippets as well. Also, pytest on stackoverflow.comoften comes with example answers.For basic examples, see • Installation and Getting Started for basic introductory examples • Asserting with the assert statement for basic assertion examples • pytest fixtures: explicit, modular, scalable for basic fixture/setup examples • Parametrizing fixtures and test functions for basic test function parametrization • unittest.TestCase Support for basic unittest integration • Running tests written for nose for basic nosetests integrationThe following examples aim at various use cases you might encounter. Here is a nice run of several failures and how pytest presents things:assertion $ pytest failure_demo.py=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIR/assertioncollected 44 items 207pytest Documentation, Release 5.4 param1 = 3, param2 = 6 failure_demo.py:20: AssertionError_________________________ TestFailing.test_simple __________________________ def test_simple(self): def f(): return 42 def g(): return 43 failure_demo.py:31: AssertionError____________________ TestFailing.test_simple_multiline _____________________ def test_simple_multiline(self):> otherfunc_multi(42, 6 * 9) failure_demo.py:34:_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ a = 42, b = 54 failure_demo.py:15: AssertionError___________________________ TestFailing.test_not ___________________________ def test_not(self): def f(): return 42 failure_demo.py:40: AssertionError_________________ TestSpecialisedExplanations.test_eq_text _________________ (continues on next page) def test_eq_text(self):> assert "spam" == "eggs"E AssertionError: assert 'spam' == 'eggs'E - eggsE + spam failure_demo.py:45: AssertionError_____________ TestSpecialisedExplanations.test_eq_similar_text _____________ def test_eq_similar_text(self):> assert "foo 1 bar" == "foo 2 bar"E AssertionError: assert 'foo 1 bar' == 'foo 2 bar'E - foo 2 barE ? ^E + foo 1 barE ? ^ failure_demo.py:48: AssertionError____________ TestSpecialisedExplanations.test_eq_multiline_text ____________ def test_eq_multiline_text(self):> assert "foo\nspam\nbar" == "foo\neggs\nbar"E AssertionError: assert 'foo\nspam\nbar' == 'foo\neggs\nbar'E fooE - eggsE + spamE bar failure_demo.py:51: AssertionError______________ TestSpecialisedExplanations.test_eq_long_text _______________ def test_eq_long_text(self): a = "1" * 100 + "a" + "2" * 100 b = "1" * 100 + "b" + "2" * 100> assert a == bE AssertionError: assert '111111111111...2222222222222' == '111111111111... ˓→2222222222222' failure_demo.py:56: AssertionError_________ TestSpecialisedExplanations.test_eq_long_text_multiline __________ def test_eq_long_text_multiline(self): a = "1\n" * 100 + "a" + "2\n" * 100 b = "1\n" * 100 + "b" + "2\n" * 100> assert a == bE AssertionError: assert '1\n1\n1\n1\n...n2\n2\n2\n2\n' == '1\n1\n1\n1\n... ˓→n2\n2\n2\n2\n' failure_demo.py:61: AssertionError_________________ TestSpecialisedExplanations.test_eq_list _________________ def test_eq_list(self):> assert [0, 1, 2] == [0, 1, 3]E assert [0, 1, 2] == [0, 1, 3]E At index 2 diff: 2 != 3E Use -v to get the full diff failure_demo.py:64: AssertionError______________ TestSpecialisedExplanations.test_eq_list_long _______________ def test_eq_list_long(self): a = [0] * 100 + [1] + [3] * 100 b = [0] * 100 + [2] + [3] * 100> assert a == bE assert [0, 0, 0, 0, 0, 0, ...] == [0, 0, 0, 0, 0, 0, ...]E At index 100 diff: 1 != 2E Use -v to get the full diff failure_demo.py:69: AssertionError_________________ TestSpecialisedExplanations.test_eq_dict _________________ def test_eq_dict(self):> assert {"a": 0, "b": 1, "c": 0} == {"a": 0, "b": 2, "d": 0}E AssertionError: assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}E Omitting 1 identical items, use -vv to showE Differing items:E {'b': 1} != {'b': 2}E Left contains 1 more item:E {'c': 0}E Right contains 1 more item:E {'d': 0}...E (continues on next page) failure_demo.py:72: AssertionError_________________ TestSpecialisedExplanations.test_eq_set __________________ def test_eq_set(self):> assert {0, 10, 11, 12} == {0, 20, 21}E AssertionError: assert {0, 10, 11, 12} == {0, 20, 21}E Extra items in the left set:E 10E 11E 12E Extra items in the right set:E 20E 21...EE ...Full output truncated (2 lines hidden), use '-vv' to show failure_demo.py:75: AssertionError_____________ TestSpecialisedExplanations.test_eq_longer_list ______________ def test_eq_longer_list(self):> assert [1, 2] == [1, 2, 3]E assert [1, 2] == [1, 2, 3]E Right contains one more item: 3E Use -v to get the full diff failure_demo.py:78: AssertionError_________________ TestSpecialisedExplanations.test_in_list _________________ def test_in_list(self):> assert 1 in [0, 2, 3, 4, 5]E assert 1 in [0, 2, 3, 4, 5] failure_demo.py:81: AssertionError__________ TestSpecialisedExplanations.test_not_in_text_multiline __________ def test_not_in_text_multiline(self): assert "foo" not in textE AssertionError: assert 'foo' not in 'some multil...nand a\ntail'E 'foo' is contained here:E some multilineE textE whichE includes fooE ? +++E and a...E (continues on next page) failure_demo.py:85: AssertionError___________ TestSpecialisedExplanations.test_not_in_text_single ____________ def test_not_in_text_single(self): assert "foo" not in textE AssertionError: assert 'foo' not in 'single foo line'E 'foo' is contained here:E single foo lineE ? +++ failure_demo.py:89: AssertionError_________ TestSpecialisedExplanations.test_not_in_text_single_long _________ def test_not_in_text_single_long(self): text = "head " * 50 + "foo " + "tail " * 20> assert "foo" not in textE AssertionError: assert 'foo' not in 'head head h...l tail tail 'E 'foo' is contained here:E head head foo tail tail tail tail tail tail tail tail tail tail tail tail ˓→tail tail tail tail tail tail tail tail E ? +++ failure_demo.py:93: AssertionError______ TestSpecialisedExplanations.test_not_in_text_single_long_term _______ def test_not_in_text_single_long_term(self): text = "head " * 50 + "f" * 70 + "tail " * 20> assert "f" * 70 not in textE AssertionError: assert 'fffffffffff...ffffffffffff' not in 'head head h...l ˓→tail tail ' ˓→tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail ˓→tail tail E ? ˓→++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ failure_demo.py:97: AssertionError______________ TestSpecialisedExplanations.test_eq_dataclass _______________ def test_eq_dataclass(self): from dataclasses import dataclass @dataclass class Foo: (continues on next page) failure_demo.py:109: AssertionError________________ TestSpecialisedExplanations.test_eq_attrs _________________ def test_eq_attrs(self): import attr @attr.s class Foo: a = attr.ib() b = attr.ib() failure_demo.py:121: AssertionError______________________________ test_attribute ______________________________ def test_attribute(): class Foo: b = 1 i = Foo()> assert i.b == 2E assert 1 == 2E + where 1 = <failure_demo.test_attribute.<locals>.Foo object at 0xdeadbeef>.˓→ b failure_demo.py:129: AssertionError_________________________ test_attribute_instance __________________________ def test_attribute_instance(): class Foo: b = 1 failure_demo.py:136: AssertionError__________________________ test_attribute_failure __________________________ def test_attribute_failure(): class Foo: def _get_b(self): raise Exception("Failed to get attrib") b = property(_get_b) i = Foo()> assert i.b == 2 failure_demo.py:147:_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def _get_b(self):> raise Exception("Failed to get attrib")E Exception: Failed to get attrib failure_demo.py:142: Exception_________________________ test_attribute_multiple __________________________ def test_attribute_multiple(): class Foo: b = 1 class Bar: b = 2 failure_demo.py:157: AssertionError__________________________ TestRaises.test_raises __________________________ def test_raises(self): raises(TypeError, int, s)E ValueError: invalid literal for int() with base 10: 'qwe' failure_demo.py:167: ValueError (continues on next page) def test_raises_doesnt(self):> raises(IOError, int, "3")E Failed: DID NOT RAISE <class 'OSError'> failure_demo.py:170: Failed__________________________ TestRaises.test_raise ___________________________ def test_raise(self):> raise ValueError("demo error")E ValueError: demo error failure_demo.py:173: ValueError________________________ TestRaises.test_tupleerror ________________________ def test_tupleerror(self):> a, b = [1] # NOQAE ValueError: not enough values to unpack (expected 2, got 1) failure_demo.py:176: ValueError______ TestRaises.test_reinterpret_fails_with_print_for_the_fun_of_it ______ def test_reinterpret_fails_with_print_for_the_fun_of_it(self): items = [1, 2, 3] print("items is {!r}".format(items))> a, b = items.pop()E TypeError: cannot unpack non-iterable int object failure_demo.py:181: TypeError--------------------------- Captured stdout call ---------------------------items is [1, 2, 3]________________________ TestRaises.test_some_error ________________________ def test_some_error(self):> if namenotexi: # NOQAE NameError: name 'namenotexi' is not defined failure_demo.py:184: NameError____________________ test_dynamic_compile_shows_nicely _____________________ def test_dynamic_compile_shows_nicely(): import importlib.util import sys failure_demo.py:203:_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def foo():> assert 1 == 0E AssertionError def test_complex_error(self): def f(): return 44 failure_demo.py:214:_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _failure_demo.py:11: in somefunc otherfunc(x, y)_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ a = 44, b = 43 failure_demo.py:7: AssertionError___________________ TestMoreErrors.test_z1_unpack_error ____________________ def test_z1_unpack_error(self): items = []> a, b = itemsE ValueError: not enough values to unpack (expected 2, got 0) failure_demo.py:218: ValueError____________________ TestMoreErrors.test_z2_type_error _____________________ def test_z2_type_error(self): items = 3 (continues on next page) failure_demo.py:222: TypeError______________________ TestMoreErrors.test_startswith ______________________ def test_startswith(self): assert s.startswith(g)E AssertionError: assert FalseE + where False = <built-in method startswith of str object at 0xdeadbeef>( ˓→'456') failure_demo.py:227: AssertionError__________________ TestMoreErrors.test_startswith_nested ___________________ def test_startswith_nested(self): def f(): return "123" def g(): return "456" failure_demo.py:236: AssertionError_____________________ TestMoreErrors.test_global_func ______________________ def test_global_func(self):> assert isinstance(globf(42), float)E assert FalseE + where False = isinstance(43, float)E + where 43 = globf(42) failure_demo.py:239: AssertionError_______________________ TestMoreErrors.test_instance _______________________ failure_demo.py:243: AssertionError_______________________ TestMoreErrors.test_compare ________________________ def test_compare(self):> assert globf(10) < 5E assert 11 < 5E + where 11 = globf(10) failure_demo.py:246: AssertionError_____________________ TestMoreErrors.test_try_finally ______________________ def test_try_finally(self): x = 1 try:> assert x == 0E assert 1 == 0 failure_demo.py:251: AssertionError___________________ TestCustomAssertMsg.test_single_line ___________________ def test_single_line(self): class A: a = 1 b = 2> assert A.a == b, "A.a appears not to be b"E AssertionError: A.a appears not to be bE assert 1 == 2E + where 1 = <class 'failure_demo.TestCustomAssertMsg.test_single_line.˓→<locals>.A'>.a failure_demo.py:262: AssertionError____________________ TestCustomAssertMsg.test_multiline ____________________ def test_multiline(self): class A: a = 1 b = 2> assert ( A.a == b ), "A.a appears not to be b\nor does not appear to be b\none of those"E AssertionError: A.a appears not to be b (continues on next page) failure_demo.py:269: AssertionError___________________ TestCustomAssertMsg.test_custom_repr ___________________ def test_custom_repr(self): class JSON: a = 1 def __repr__(self): return "This is JSON\n{\n 'foo': 'bar'\n}" a = JSON() b = 2> assert a.a == b, aE AssertionError: This is JSONE {E 'foo': 'bar'E }E assert 1 == 2E + where 1 = This is JSON\n{\n 'foo': 'bar'\n}.a failure_demo.py:282: AssertionError========================= short test summary info ==========================FAILED failure_demo.py::test_generative[3-6] - assert (3 * 2) < 6FAILED failure_demo.py::TestFailing::test_simple - assert 42 == 43FAILED failure_demo.py::TestFailing::test_simple_multiline - assert 42 == 54FAILED failure_demo.py::TestFailing::test_not - assert not 42FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_text - Asser...FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_similar_textFAILED failure_demo.py::TestSpecialisedExplanations::test_eq_multiline_textFAILED failure_demo.py::TestSpecialisedExplanations::test_eq_long_text - ...FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_long_text_multilineFAILED failure_demo.py::TestSpecialisedExplanations::test_eq_list - asser...FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_list_long - ...FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_dict - Asser...FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_set - Assert...FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_longer_listFAILED failure_demo.py::TestSpecialisedExplanations::test_in_list - asser...FAILED failure_demo.py::TestSpecialisedExplanations::test_not_in_text_multilineFAILED failure_demo.py::TestSpecialisedExplanations::test_not_in_text_singleFAILED failure_demo.py::TestSpecialisedExplanations::test_not_in_text_single_longFAILED failure_demo.py::TestSpecialisedExplanations::test_not_in_text_single_long_termFAILED failure_demo.py::TestSpecialisedExplanations::test_eq_dataclass - ...FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_attrs - Asse...FAILED failure_demo.py::test_attribute - assert 1 == 2FAILED failure_demo.py::test_attribute_instance - AssertionError: assert ...FAILED failure_demo.py::test_attribute_failure - Exception: Failed to get...FAILED failure_demo.py::test_attribute_multiple - AssertionError: assert ...FAILED failure_demo.py::TestRaises::test_raises - ValueError: invalid lit...FAILED failure_demo.py::TestRaises::test_raises_doesnt - Failed: DID NOT ... (continues on next page) 27.2.1 Pass different values to a test function, depending on command line options Suppose we want to write a test that depends on a command line option. Here is a basic pattern to achieve this: # content of test_sample.pydefimport pytest def pytest_addoption(parser): parser.addoption( "--cmdopt", action="store", default="type1", help="my option: type1 or type2" ) @pytest.fixturedef cmdopt(request): return request.config.getoption("--cmdopt") $ pytest -q test_sample.pyF [100%]================================= FAILURES =================================_______________________________ test_answer ________________________________ cmdopt = 'type1' def test_answer(cmdopt): if cmdopt == "type1": print("first") elif cmdopt == "type2": print("second")> assert 0 # to see what was printedE assert 0 test_sample.py:6: AssertionError--------------------------- Captured stdout call ---------------------------first========================= short test summary info ==========================FAILED test_sample.py::test_answer - assert 01 failed in 0.12s cmdopt = 'type2' test_sample.py:6: AssertionError--------------------------- Captured stdout call ---------------------------second========================= short test summary info ==========================FAILED test_sample.py::test_answer - assert 01 failed in 0.12s You can see that the command line option arrived in our test. This completes the basic pattern. However, one oftenrather wants to process command line options outside of the test and rather pass in different or more complex objects. Through addopts you can statically add command line options for your project. You can also dynamically modifythe command line arguments before they get processed:# setuptools pluginimport sys (continues on next page) def pytest_load_initial_conftests toyour CPU. Running in an empty directory with the above conftest.py:$ pytest=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 0 items Here is a conftest.py file adding a --runslow command line option to control skipping of pytest.mark.slow marked tests:# content of conftest.py def pytest_addoption(parser): parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" ) def pytest_configure(config): config.addinivalue_line("markers", "slow: mark test as slow to run") def test_func_fast(): pass @pytest.mark.slowdef test_func_slow(): pass test_module.py .s [100%] $ pytest --runslow=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 2 items test_module.py .. [100%] If you have a test helper function called from a test you can use the pytest.fail marker to fail a test with a certainmessage. The test support function will not show up in the traceback if you set the __tracebackhide__ optionsomewhere in the helper function. Example: # content of test_checkconfig.pyimport pytest def checkconfig(x): __tracebackhide__ = True if not hasattr(x, "config"): pytest.fail("not configured: {}".format(x)) def test_something(): checkconfig(42) The __tracebackhide__ setting influences pytest showing of tracebacks: the checkconfig function willnot be shown unless the --full-trace command line option is specified. Let’s run our little function: $ pytest -q test_checkconfig.pyF [100%]================================= FAILURES =================================______________________________ test_something ______________________________ def test_something():> checkconfig(42)E Failed: not configured: 42 test_checkconfig.py:11: Failed========================= short test summary info ==========================FAILED test_checkconfig.py::test_something - Failed: not configured: 421 failed in 0.12s If you only want to hide certain exceptions, you can set __tracebackhide__ to a callable which gets theExceptionInfo object. You can for example use this to make sure unexpected exception types aren’t hidden: import operatorimport pytest class ConfigException(Exception): pass def checkconfig(x): __tracebackhide__ = operator.methodcaller("errisinstance", ConfigException) if not hasattr(x, "config"): raise ConfigException("not configured: {}".format(x)) This will avoid hiding the exception traceback on unrelated exceptions (i.e. bugs in assertion helpers). Usually it is a bad idea to make application code behave differently if called from a test. But if you absolutely mustfind out if your application code is running from a test you can do something like this: # content of your_module.py _called_from_test = False def pytest_configure(config): your_module._called_from_test = True if your_module._called_from_test: # called from within a test run ...else: # called "normally" ... def pytest_report_header(config): return "project deps: mylib-1.1" $ pytest=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacheproject deps: mylib-1.1rootdir: $REGENDOC_TMPDIRcollected 0 items It is also possible to return a list of strings which will be considered as several lines of information. You may considerconfig.getoption('verbose') in order to display more information if applicable: def pytest_report_header(config): if config.getoption("verbose") > 0: return ["info1: did you know that ...", "did you?"] $ pytest -v=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_ ˓→PREFIX/bin/python cachedir: $PYTHON_PREFIX/.pytest_cacheinfo1: did you know that ...did you?rootdir: $REGENDOC_TMPDIRcollecting ... collected 0 items $ pytest=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 0 items If you have a slow running large test suite you might want to find out which tests are the slowest. Let’s make anartificial test suite:# content of test_some_are_slow.pyimport time def test_funcfast(): time.sleep(0.1) def test_funcslow1(): time.sleep(0.2) def test_funcslow2(): time.sleep(0.3) Sometimes you may have a testing situation which consists of a series of test steps. If one step fails it makes no senseto execute further steps as they are all expected to fail anyway and their tracebacks add no insight. Here is a simpleconftest.py file which introduces an incremental marker which is to be used on classes:# content of conftest.py # store history of failures per test class name and per index in parametrize (if ˓→parametrize used) parametrize_index = ( tuple(item.callspec.indices.values()) if hasattr(item, "callspec") else () ) # retrieve the name of the test function test_name = item.originalname or item.name # store in _test_failed_incremental the original name of the failed test _test_failed_incremental.setdefault(cls_name, {}).setdefault( parametrize_index, test_name ) def pytest_runtest_setup(item): if "incremental" in item.keywords: # retrieve the class name of the test cls_name = str(item.cls) # check if a previous test has failed for this class if cls_name in _test_failed_incremental: # retrieve the index of the test (if parametrize is used in combination ˓→with incremental) parametrize_index = ( tuple(item.callspec.indices.values()) if hasattr(item, "callspec") else () ) # retrieve the name of the first test function to fail for this class ˓→name and index test_name = _test_failed_incremental[cls_name].get(parametrize_index, ˓→None) # if name found, test has failed for the combination of class name & test ˓→name These two hook implementations work together to abort incremental-marked tests in a class. Here is a test moduleexample: # content of test_step.py (continues on next page) @pytest.mark.incrementalclass TestUserHandling: def test_login(self): pass def test_modification(self): assert 0 def test_deletion(self): pass def test_normal(): pass If we run this: $ pytest -rx=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 4 items def test_modification(self):> assert 0E assert 0 test_step.py:11: AssertionError========================= short test summary info ==========================XFAIL test_step.py::TestUserHandling::test_deletion reason: previous test failed (test_modification)================== 1 failed, 2 passed, 1 xfailed in 0.12s ================== We’ll see that test_deletion was not executed because test_modification failed. It is reported as an“expected failure”. If you have nested test directories, you can have per-directory fixture scopes by placing fixture functions in aconftest.py file in that directory You can use all types of fixtures including autouse fixtures which are the equiv-alent of xUnit’s setup/teardown concept. It’s however recommended to have explicit fixture references in your tests ortest classes rather than relying on implicitly executing setup/teardown functions, especially if they are far away fromthe actual tests. class DB: pass @pytest.fixture(scope="session")def db(): return DB() and then a module in a sister directory which will not see the db fixture:# content of b/test_error.pydef test_root(db): # no db here, will error out pass ˓→factory $REGENDOC_TMPDIR/b/test_error.py:1 (continues on next page) test_step.py:11: AssertionError_________________________________ test_a1 __________________________________ def test_a1(db):> assert 0, db # to show valueE AssertionError: <conftest.DB object at 0xdeadbeef>E assert 0 a/test_db.py:2: AssertionError_________________________________ test_a2 __________________________________ def test_a2(db):> assert 0, db # to show valueE AssertionError: <conftest.DB object at 0xdeadbeef>E assert 0 a/test_db2.py:2: AssertionError========================= short test summary info ==========================FAILED test_step.py::TestUserHandling::test_modification - assert 0FAILED a/test_db.py::test_a1 - AssertionError: <conftest.DB object at 0x7...FAILED a/test_db2.py::test_a2 - AssertionError: <conftest.DB object at 0x...ERROR b/test_error.py::test_root============= 3 failed, 2 passed, 1 xfailed, 1 error in 0.12s ============== The two test modules in the a directory see the same db fixture instance while the one test in the sister-directory bdoesn’t see it. We could of course also define a db fixture in that sister directory’s conftest.py file. Note thateach fixture is only instantiated if there is a test actually needing it (unless you use “autouse” fixture which are alwaysexecuted ahead of the first test executing). If you want to postprocess test reports and need access to the executing environment you can implement a hook thatgets called when the test “report” object is about to be created. Here we write out all failing test calls and also accessa fixture (if it was used by the test) in case you want to query/look at it during your post processing. In our case wejust write some information out to a failures file:# content of conftest.py import pytestimport os.path def test_fail2(): assert 0 test_module.py FF [100%] tmpdir = local('PYTEST_TMPDIR/test_fail10') def test_fail1(tmpdir):> assert 0E assert 0 test_module.py:2: AssertionError________________________________ test_fail2 ________________________________ def test_fail2():> assert 0E assert 0 test_module.py:6: AssertionError========================= short test summary info ========================== (continues on next page) you will have a “failures” file which contains the failing test ids:$ cat failurestest_module.py::test_fail1 (PYTEST_TMPDIR/test_fail10)test_module.py::test_fail2 If you want to make test result reports available in fixture finalizers here is a little example implemented via a localplugin:# content of conftest.py @pytest.hookimpl(tryfirst=True, hookwrapper=True)def pytest_runtest_makereport(item, call): # execute all other hooks to obtain the report object outcome = yield rep = outcome.get_result() @pytest.fixtured) @pytest.fixturedef other(): assert 0 def test_call_fails(something): assert 0 $ pytest -s test_module.py=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 3 items @pytest.fixture def other():> assert 0E assert 0 test_module.py:7: AssertionError================================= FAILURES =================================_____________________________ test_call_fails ______________________________ something = None def test_call_fails(something):> assert 0E assert 0 test_module.py:15: AssertionError________________________________ test_fail2 ________________________________ test_module.py:19: AssertionError========================= short test summary info ==========================FAILED test_module.py::test_call_fails - assert 0FAILED test_module.py::test_fail2 - assert 0ERROR test_module.py::test_setup_fails - assert 0======================== 2 failed, 1 error in 0.12s ======================== You’ll see that the fixture finalizers could use the precise reporting information. Sometimes a test session might get stuck and there might be no easy way to figure out which test got stuck, for exampleif pytest was run in quiet mode (-q) or you don’t have access to the console output. This is particularly a problem ifthe problem helps only sporadically, the famous “flaky” kind of tests.pytest sets a PYTEST_CURRENT_TEST environment variable when running tests, which can be inspected byprocess monitoring utilities or libraries like psutil to discover which test got stuck if necessary: import psutil During the test session pytest will set PYTEST_CURRENT_TEST to the current test nodeid and the current stage,which can be setup, call and teardown.For example, when running a single test function named test_foo from foo_module.py,PYTEST_CURRENT_TEST will be set to: 1. foo_module.py::test_foo (setup) 2. foo_module.py::test_foo (call) 3. foo_module.py::test_foo (teardown)In that order. Note: The contents of PYTEST_CURRENT_TEST is meant to be human readable and the actual format can bechanged between releases (even bug fixes) so it shouldn’t be relied on for scripting or automation. If you freeze your application using a tool like PyInstaller in order to distribute it to your end-users, it is a good ideato also package your test runner and run your tests using the frozen application. This way packaging errors such asdependencies not being included into the executable can be detected early while also allowing you to send test files tousers so they can run them in their machines, which can be useful to obtain more information about a hard to reproducebug.Fortunately recent PyInstaller releases already have a custom hook for pytest, but if you are using another toolto freeze executables such as cx_freeze or py2exe, you can use pytest.freeze_includes() to obtain thefull list of internal pytest modules. How to configure the tools to find the internal modules varies from tool to tool,however.Instead of freezing the pytest runner as a separate executable, you can make your frozen program work as the pytestrunner by some clever argument handling during program startup. This allows you to have a single executable, whichis usually more convenient. Please note that the mechanism for plugin discovery used by pytest (setupttools entrypoints) doesn’t work with frozen executables so pytest can’t find any third party plugins automatically. To includethird party plugins like pytest-timeout they must be imported explicitly and passed on to pytest.main. # contents of app_main.pyimport sysimport pytest_timeout # Third party plugin sys.exit(pytest.main(sys.argv[2:], plugins=[pytest_timeout])/ pytest allows to easily parametrize test functions. For basic docs, see Parametrizing fixtures and test functions.In the following we provide some examples using the builtin mechanisms. Let’s say we want to execute a test with different computation parameters and the parameter range shall be determinedby a command line argument. Let’s first write a simple (do-nothing) computation test:# content of test_compute.py def test_compute(param1): assert param1 < 4 def pytest_addoption(parser): parser.addoption("--all", action="store_true", help="run all combinations") def pytest_generate_tests(metafunc): if "param1" in metafunc.fixturenames: if metafunc.config.getoption("all"): end = 5 else: end = 2 metafunc.parametrize("param1", range(end)) We run only two computations, so we see two dots. let’s run the full monty: $ pytest -q --all....F [100%]================================= FAILURES =================================_____________________________ test_compute[4] ______________________________ param1 = 4 def test_compute(param1):> assert param1 < 4E assert 4 < 4 test_compute.py:4: AssertionError========================= short test summary info ==========================FAILED test_compute.py::test_compute[4] - assert 4 < 41 failed, 4 passed in 0.12s As expected when running the full range of param1 values we’ll get an error on the last one. def idfn(val): if isinstance(val, (datetime,)): # note this wouldn't show any hours/minutes/seconds return val.strftime("%Y%m%d") @pytest.mark.parametrize( "a,b,expected", [ pytest.param( datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1), id="forward" ), pytest.param( datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1), id= ˓→"backward" ), ],)def test_timedistance_v3(a, b, expected): diff = a - b assert diff == expected In test_timedistance_v3, we used pytest.param to specify the test IDs together with the actual data,instead of listing them separately. Here is a quick port to run tests configured with test scenarios, an add-on from Robert Collins for the standardun") class TestSampleWithScenarios: scenarios = [scenario1, scenario2] If you just collect tests you’ll also nicely see ‘advanced’ and ‘basic’ as variants for the test function:$ pytest --collect-only test_scenarios.py=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 4 items<Module test_scenarios.py> <Class TestSampleWithScenarios> <Function test_demo1[basic]> <Function test_demo2[basic]> (continues on next page) Note that we told metafunc.parametrize() that your scenario values should be considered class-scoped. Withpytest-2.3 this leads to a resource-based ordering. The parametrization of test functions happens at collection time. It is a good idea to setup expensive resources like DBconnections or subprocess only when the actual test is run. Here is a simple example how you can achieve that. Thistest requires a db object fixture: # content of test_backends.py def test_db_initialized(db): # a dummy test if db.__class__.__name__ == "DB2": pytest.fail("deliberately failing for demo purposes") We can now add a test configuration that generates two invocations of the test_db_initialized function andalso implements a factory that creates a database object for the actual test invocations: def pytest_generate_tests(metafunc): if "db" in metafunc.fixturenames: metafunc.parametrize("db", ["d1", "d2"], indirect=True) class DB1: "one database object" class DB2: "alternative database object" @pytest.fixturedef db(request): if request.param == "d1": return DB1() elif request.param == "d2": return DB2() else: raise ValueError("invalid internal test config") $ pytest -q test_backends.py.F [100%]================================= FAILURES =================================_________________________ test_db_initialized[d2] __________________________ def test_db_initialized(db): # a dummy test if db.__class__.__name__ == "DB2":> pytest.fail("deliberately failing for demo purposes")E Failed: deliberately failing for demo purposes test_backends.py:8: Failed========================= short test summary info ==========================FAILED test_backends.py::test_db_initialized[d2] - Failed: deliberately f...1 failed, 1 passed in 0.12s The first invocation with db == "DB1" passed while the second with db == "DB2" failed. Our db fixture func-tion has instantiated each of the DB values during the setup phase while the pytest_generate_tests generatedtwo according calls to the test_db_initialized during the collection phase. Very often parametrization uses more than one argument name. There is opportunity to apply indirect parameteron particular arguments. It can be done by passing list or tuple of arguments’ names to indirect. In the examplebelow there is a function test_indirect which uses two fixtures: x and y. Here we give to indirect the list, whichcontains the name of the fixture x. The indirect parameter will be applied to this argument only, and the value a willbe passed to respective fixture function: # content of test_indirect_list.py @pytest.fixture(scope="function")def x(request): return request.param * 3 @pytest.fixture(scope="function") (continues on next page) Note, that each argument in parametrize list should be explicitly declared in corresponding python test functionor via indirect. # content of ./test_parametrize.pyimport)], } Our test generator looks up a class-level definition which specifies which argument sets to use for each test function.Let’s run it:$ pytest -qF.. [100%]================================= FAILURES =================================________________________ TestClass.test_equals[1-2] ________________________ test_parametrize.py:21: AssertionError========================= short test summary info ==========================FAILED test_parametrize.py::TestClass::test_equals[1-2] - assert 1 == 21 failed, 2 passed in 0.12s Here is a stripped down real-life example of using parametrized testing for testing serialization of objects betweendifferent python interpreters. We define a test_basic_objects function which is to be run with different sets ofarguments for its three arguments: • python1: first python interpreter, run to pickle-dump an object to a file • python2: second interpreter, run to pickle-load an object from a file • obj: object to be dumped/loaded"""module containing a parametrized tests testing cross-pythonserialization via the pickle module."""import shutilimport subprocessimport textwrap @pytest.fixture(params=pythonlist)def python1(request, tmpdir): picklefile = tmpdir.join("data.pickle") return Python(request.param, picklefile) @pytest.fixture(params=pythonlist)def python2(request, python1): return Python(request.param, python1.picklefile) (continues on next page) class Python: def __init__(self, version, picklefile): self.pythonpath = shutil.which(version) if not self.pythonpath: pytest.skip("{!r} not found".format(version)) self.picklefile = picklefile Running it results in some skips if we don’t have all the python interpreters installed and otherwise runs all combina-tions (3 interpreters times 3 interpreters times 3 objects to serialize/deserialize): If you want to compare the outcomes of several implementations of a given API, you can write test functions thatreceive the already imported implementations and get skipped in case the implementation is not importable/available.Let’s say we have a “base” implementation and the other (possibly optimized ones) need to provide similar results:# content of conftest.py @pytest.fixture(scope="session")def basemod(request): return pytest.importorskip("base") test_module.py .s [100%] (continues on next page) You’ll see that we don’t have an opt2 module and thus the second test run of our test_func1 was skipped. A fewnotes: • the fixture functions in the conftest.py file are “session-scoped” because we don’t need to import more than once • if you have multiple test functions and a skipped import, you will see the [1] count increasing in the report • you can put @pytest.mark.parametrize style parametrization on the test functions to parametrize input/output values as well. Use pytest.param to apply marks or set test ID to individual parametrized test. For example: # content of test_pytest_param_example.pyimport pytest @pytest.mark.parametrize( "test_input,expected", [ ("3+5", 8), pytest.param("1+7", 8, marks=pytest.mark.basic), pytest.param("2+4", 6, marks=pytest.mark.basic, id="basic_2+4"), pytest.param( "6*9", 42, marks=[pytest.mark.basic, pytest.mark.xfail], id="basic_6*9" ), ],)def test_eval(test_input, expected): assert eval(test_input) == expected In this example, we have 4 parametrized tests. Except for the first test, we mark the rest three parametrized tests withthe custom marker basic, and for the fourth test we also use the built-in mark xfail to indicate this test is expectedto fail. For explicitness, we set test ids for some tests.Then run pytest with verbose mode and with only the basic marker: $ pytest -v -m basic=========================== 14 items / 11 deselected / 3 selected As the result: • Four tests were collected • One test was deselected because it doesn’t have the basic mark. • Three tests with the basic mark was selected. • The test test_eval[1+7-8] passed, but the name is autogenerated and confusing. • The test test_eval[basic_2+4] passed. • The test test_eval[basic_6*9] was expected to fail and did fail. Use pytest.raises() with the pytest.mark.parametrize decorator to write parametrized tests in which some testsraise exceptions and others do not.It is helpful to define a no-op context manager does_not_raise to serve as a complement to raises. Forexample: @contextmanagerdef does_not_raise(): yield In the example above, the first three test cases should run unexceptionally, while the fourth should raiseZeroDivisionError.If you’re only supporting Python 3.7+, you can simply use nullcontext to define does_not_raise: Here are some examples using the Marking test functions with attributes mechanism. You can “mark” a test function with custom metadata like this: # content of test_server.py @pytest.mark.webtestdef test_send_http(): pass # perform some webtest test for your app def test_something_quick(): pass def test_another(): pass class TestClass: def test_method(self): pass You can then restrict a test run to only run tests marked with webtest: $ pytest -v -m webtest=========================== 4 items / 3 deselected / 1 selected cachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollecting ... collected 4 items / 1 deselected / 3 selected You can provide one or more node IDs as positional arguments to select only specified tests. This makes it easy toselect tests based on their module, class, method, or function name: $ pytest -v test_server.py::TestClass::test_method=========================== 1 item $ pytest -v test_server.py::TestClass=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_ ˓→PREFIX/bin/python Note: Node IDs are of the form module.py::class::method or module.py::function. Node IDscontrol which tests are collected, so module.py::class will select all test methods on the class. Nodes are alsocreated for each parameter of a parametrized fixture or test, so selecting a parametrized test must include the parametervalue, e.g. module.py::function[param].Node IDs for failing tests are displayed in the test summary info when running pytest with the -rf option. You canalso construct Node IDs from the output of pytest --collectonly. You can use the -k command line option to specify an expression which implements a substring match on the testnames instead of the exact match on markers that -m provides. This makes it easy to select tests based on their names:The expression matching is now case-insensitive.$ pytest -v -k http # running with the above defined example module=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_ ˓→PREFIX/bin/python And you can also run all tests except the ones that match the keyword:$ pytest -k "not send_http" -v=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_ ˓→PREFIX/bin/python Note: If you are using expressions such as "X and Y" then both X and Y need to be simple non-keyword names.For example, "pass" or "from" will result in SyntaxErrors because "-k" evaluates the expression using Python’seval function. However, if the "-k" argument is a simple string, no such restrictions apply. Also "-k 'not STRING'" has no restrictions. You can also specify numbers like "-k 1.3" to match tests which are parametrized with the float "1.3". You can ask which markers exist for your test suite - the list includes our just defined webtest markers:$ pytest --markers@pytest.mark.webtest: mark a test as a webtest. ˓→Optionally specify a reason for better reporting and run=False if you don't even ˓→want to execute the test function. If only specific exception(s) are expected, you ˓→can list them in raises, and if the test fails in other ways, it will be reported ˓→to two calls of the decorated test function, one with arg1=1 and another with (continues on next page) ˓→arg1=2.see for more info and ˓→examples. ˓→#usefixtures For an example on how to add and work with markers from a plugin, see Custom marker and command line option tocontrol test runs. You may use pytest.mark decorators with classes to apply markers to all of its test methods: # content of test_mark_classlevel.pyimport pytest @pytest.mark.webtestclass TestClass: def test_startup(self): pass def test_startup_and_more(self): pass This is equivalent to directly applying the decorator to the two test functions.Due to legacy reasons, it is possible to set the pytestmark attribute on a TestClass like this: class TestClass: pytestmark = pytest.mark.webtest class TestClass: pytestmark = [pytest.mark.webtest, pytest.mark.slowtest] or multiple markers:pytestmark = [pytest.mark.webtest, pytest.mark.slowtest] in which case markers will be applied (in left-to-right order) to all functions and methods defined in the module. When using parametrize, applying a mark will make it apply to each individual test. However it is also possible toapply a marker to an individual test instance:import pytest @pytest.mark.foo@pytest.mark.parametrize( ("n", "expected"), [(1, 2), pytest.param(1, 3, marks=pytest.mark.bar), (2, 3)])def test_increment(n, expected): assert n + 1 == expected In this example the mark “foo” will apply to each of the three tests, whereas the “bar” mark is only applied to thesecond test. Skip and xfail marks can also be applied in this way, see Skip/xfail with parametrize. 27.4.7 Custom marker and command line option to control test runs Plugins can provide custom markers and implement specific behaviour based on it. This is a self-contained examplewhich adds a command line option and a parametrized test function marker to run tests specifies via named environ-ments:# content of conftest.pynames = [mark.args[0] for mark in item.iter_markers(name="env")] if envnames: if item.config.getoption("-E") not in envnames: pytest.skip("test requires env in {!r}".format(envnames)) @pytest.mark.env("stage1")def test_basic_db_operation(): pass and an example invocations specifying a different environment than what the test needs:$ pytest -E stage2=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 1 item test_someenv.py s [100%] test_someenv.py . [100%] ˓→to two calls of the decorated test function, one with arg1=1 and another with Below is the config file that will be used in the next examples:# content of conftest.pyimport sys def pytest_runtest_setup(item): for marker in item.iter_markers(name="my_marker"): print(marker) sys.stdout.flush() A custom marker can have its argument set, i.e. args and kwargs properties, defined by either invoking it as acallable or using pytest.mark.MARKER_NAME.with_args. These two methods achieve the same effect mostof the time.However, if there is a callable as the single positional argument with no keyword arguments, using the pytest.mark.MARKER_NAME(c) will not pass c as a positional argument but decorate c with the custom marker (seeMarkDecorator). Fortunately, pytest.mark.MARKER_NAME.with_args comes to the rescue:# content of test_custom_marker.pyimport pytest $ pytest -q -sMark(name='my_marker', args=(<function hello_world at 0xdeadbeef>,), kwargs={}).1 passed in 0.12s We can see that the custom marker has its argument set extended with the function hello_world. This is the keydifference between creating a custom marker as a callable, which invokes __call__ behind the scenes, and usingwith_args. If you are heavily using markers in your test suite you may encounter the case where a marker is applied several timesto a test function. From plugin code you can read over all such settings. Example: # content of test_mark_three_times.pyimport pytest @pytest.mark.glob("class", x=2)class TestClass: @pytest.mark.glob("function", x=3) def test_something(self): pass Here we have the marker “glob” applied three times to the same test function. From a conftest file we can read it likethis: # content of conftest.pyimport sys def pytest_runtest_setup(item): for mark in item.iter_markers(name="glob"): print("glob args={} kwargs={}".format(mark.args, mark.kwargs)) sys.stdout.flush() Let’s run this without capturing output and see what we get: $ pytest -q -sglob args=('function',) kwargs={'x': 3}glob args=('class',) kwargs={'x': 2}glob args=('module',) kwargs={'x': 1}.1 passed in 0.12s Consider you have a test suite which marks tests for particular platforms, namely pytest.mark.darwin,pytest.mark.win32 etc. and you also have tests that run on all platforms and have no specific marker. If younow want to have a way to only run the tests for your particular platform, you could use the following plugin: # content of conftest.py#import sysimport pytest def pytest_runtest_setup(item): supported_platforms = ALL.intersection(mark.name for mark in item.iter_markers()) plat = sys.platform if supported_platforms and plat not in supported_platforms: pytest.skip("cannot run on platform {}".format(plat)) then tests will be skipped if they were specified for a different platform. Let’s do a little test file to show how this lookslike: # content of test_plat.py @pytest.mark.darwindef test_if_apple_is_evil(): pass @pytest.mark.linuxdef test_if_linux_works(): pass @pytest.mark.win32def test_if_win32_crashes(): pass def test_runs_everywhere(): pass then you will see two tests skipped and two executed tests as expected: Note that if you specify a platform via the marker-command line option like this: $ pytest -m linux=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 4 items / 3 deselected / 1 selected test_plat.py . [100%] then the unmarked-tests will not be run. It is thus a way to restrict the run to the specific tests. If you a test suite where test function names indicate a certain type of test, you can implement a hook that automaticallydefines markers so that you can use the -m option with it. Let’s look at this test module: def test_interface_simple(): assert 0 def test_interface_complex(): assert 0 def test_event_simple(): assert 0 def test_something_else(): assert 0 def pytest_collection_modifyitems(items): for item in items: if "interface" in item.nodeid: item.add_marker(pytest.mark.interface) elif "event" in item.nodeid: item.add_marker(pytest.mark.event) test_module.py FF [100%] A session-scoped fixture effectively has access to all collected test items. Here is an example of a fixture functionwhich walks all collected tests and looks if their test class defines a callme method and calls it: @pytest.fixture(scope="session", autouse=True)def callattr_ahead_of_alltests(request): print("callattr_ahead_of_alltests called") seen = ") class SomeTest(unittest.TestCase): @classmethod def callme(self): print("SomeTest callme called") You can easily ignore certain test directories and modules during collection by passing the --ignore=path option tests/example/test_example_01.py . [ 20%]tests/example/test_example_02.py . [ 40%]tests/example/test_example_03.py . [ 60%]tests/foobar/test_foobar_01.py . [ 80%]tests/foobar/test_foobar_02.py . [100%] The --ignore-glob option allows to ignore test file paths based on Unix shell-style wildcards. If you want toexclude test-modules that end with _01.py, execute pytest with --ignore-glob='*_01.py'. Tests can individually be deselected during collection by passing the --deselect=item option. For exam-ple, say tests/foobar/test_foobar_01.py contains test_a and test_b. You can run all of thetests within tests/ except for tests/foobar/test_foobar_01.py::test_a by invoking pytest with--deselect tests/foobar/test_foobar_01.py::test_a. pytest allows multiple --deselectoptions. Default behavior of pytest is to ignore duplicate paths specified from the command line. Example: ...collected 1 item... ...collected 2 items... As the collector just works on directories, if you specify twice a single test file, pytest will still collect it twice, nomatter if the --keep-duplicates is not specified. Example:directory. You can configure different naming conventions by setting the python_files, python_classes andpython_functions configuration options. Here is an example:# content of pytest.ini# Example 1: have pytest look for "check" instead of "test"# can also be defined in tox.ini or setup.cfg file, although the section# name in setup.cfg files should be "tool:pytest"[pytest]python_files = check_*.pypython_classes = Checkpython_functions = *_check This would make pytest look for tests in files that match the check_* .py glob-pattern, Check prefixes inclasses, and functions and methods that match *_check. For example, if we have:# content of check_myapp.pyclass CheckMyApp: def simple_check(self): pass def complex_check(self): pass You can check for multiple glob patterns by adding a space between the patterns:# Example 2: have pytest look for files with "test" and "example"# content of pytest.ini, tox.ini, or setup.cfg file (replace "pytest"# with "tool:pytest" for setup.cfg)[pytest]python_files = test_*.py example_*.py Note: the python_functions and python_classes options has no effect for unittest.TestCase testdiscovery because pytest delegates discovery of test case methods to unittest code. You can use the --pyargs option to make pytest try interpreting arguments as python package names, derivingtheir file system path and then running the test. For example if you have unittest2 installed you can type: which would run the respective test module. Like with other options, through an ini-file and the addopts option youcan make this change more permanently:# content of pytest.ini[pytest]addopts = --pyargs Now a simple invocation of pytest NAME will check if NAME exists as an importable package/module and other-wise treat it as a filesystem path. You can always peek at the collection tree without running tests like this:. $ pytest --collect-only pythoncollection.py=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIR, inifile: pytest.inicollected 3 items<Module CWD/pythoncollection.py> <Function test_function> <Class TestClass> <Function test_method> <Function test_anothermethod> You can easily instruct pytest to discover tests from every Python file:# content of pytest.ini[pytest]python_files = *.py However, many projects will have a setup.py which they don’t want to be imported. Moreover, there may files onlyimportable by a specific python version. For such cases you can dynamically define files to be ignored by listing themin a conftest.py file:# content of conftest.pyimport sys collect_ignore = ["setup.py"]if sys.version_info[0] > 2: collect_ignore.append("pkg/module_py2.py") # content of setup.py0 / 0 # will raise exception if imported If you run with a Python 2 interpreter then you will find the one test and will leave out the setup.py file: #$ pytest --collect-only====== test session starts ======platform linux2 -- Python 2.7.10, pytest-2.9.1, py-1.4.31, pluggy-0.3.1rootdir: $REGENDOC_TMPDIR, inifile: pytest.inicollected 1 items<Module 'pkg/module_py2.py'> <Function 'test_only_on_python2'> If you run with a Python 3 interpreter both the one test and the setup.py file will be left out: $ pytest --collect-only=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIR, inifile: pytest.inicollected 0 items It’s also possible to ignore files based on Unix shell-style wildcards by adding patterns to collect_ignore_glob.The following example conftest.py ignores the file setup.py and in addition all files that end with *_py2.pywhen executed with a Python 3 interpreter: collect_ignore = ["setup.py"]if sys.version_info[0] > 2: collect_ignore_glob = ["*_py2.py"] Here is an example conftest.py (extracted from Ali Afshnars special purpose pytest-yamlwsgi plugin). Thisconftest.py will collect test*.yaml files and will execute the yaml-formatted content as custom tests: # content of conftest.pyimport pytest (continues on next page) class YamlFile(pytest.File): def collect(self): import yaml # we need a yaml parser, e.g. PyYAML raw = yaml.safe_load(self.fspath.open()) for name, spec in sorted(raw.items()): yield YamlItem.from_parent(self, name=name, spec=spec) class YamlItem(pytest.Item): def __init__(self, name, parent, spec): super().__init__(name, parent) self.spec = spec def runtest(self): for name, value in sorted(self.spec.items()): # some custom test execution (dumb example follows) if name != value: raise YamlException(self, name, value) def reportinfo(self): return self.fspath, 0, "usecase: {}".format(self.name) class YamlException(Exception): """ custom exception for error reporting. """ # test_simple.yamlok: sub1: sub1 hello: world: world some: other and if you installed PyYAML or a compatible YAML-parser you can now execute the test specification: test_simple.yaml F. [100%] You get one dot for the passing sub1: sub1 check and one failure. Obviously in the above conftest.py you’llwant to implement a more interesting interpretation of the yaml-values. You can easily write your own domain specifictesting language this way. Note: repr_failure(excinfo) is called for representing test failures. If you create custom collection nodesyou can return an error representation string of your choice. It will be reported as a (red) string. reportinfo() is used for representing the test location and is also consulted when reporting in verbose mode:nonpython $ pytest -v=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_ ˓→PREFIX/bin/python cachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIR/nonpythoncollecting ... collected 2 items While developing your custom test collection and execution it’s also interesting to just look at the collection tree:nonpython $ pytest --collect-only=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIR/nonpythoncollected 2 items<Package $REGENDOC_TMPDIR/nonpython> (continues on next page) When using bash as your shell, pytest can use argcomplete () for auto-completion. For this argcomplete needs to be installed and enabled.Install argcomplete using: sudo activate-global-python-argcomplete 269pytest Documentation, Release 5.4 Note: This FAQ is here only mostly for historic reasons. Checkout pytest Q&A at Stackoverflow for many questionsand answers related to pytest and/or use Contact channels to get help. pytest and nose share basic philosophy when it comes to running and writing Python tests. In fact, you can runmany tests written for nose with pytest. nose was originally created as a clone of pytest when pytest was inthe 0.8 release cycle. Note that starting with pytest-2.0 support for running unittest test suites is majorly improved. Since some time pytest has builtin support for supporting tests written using trial. It does not itself start a reactor,however, and does not handle Deferreds returned from a test in pytest style. If you are using trial’s unittest.TestCasechances. In 2012, some work is going into the pytest-django plugin. It substitutes the usage of Django’s manage.py testand allows the use of all pytest features most of which are not available from Django directly. 271pytest Documentation, Release 5.4 Around 2007 (version 0.8) some people thought that pytest was using too much “magic”. It had been part ofthe pylib which contains a lot of unrelated python library code. Around 2010 there was a major cleanup refactoring,which removed unused or deprecated code and resulted in the new pytest PyPI package which strictly contains onlytest-related code. This release also brought a complete pluginification such that the core is around 300 lines of codeand everything else is implemented in plugins. Thus pytest today is a small, universally runnable and customizabletesting framework for Python. Note, however, that pytest uses metaprogramming techniques and reading its sourceis thus likely not something for Python beginners.A second “magic” issue was the assert statement debugging feature. Nowadays, pytest explicitly rewrites assertstatements in test modules in order to provide more useful assert feedback. This completely avoids previous issues ofconfusing assertion-reporting. It also means, that you can use Python’s -O optimization without losing assertions intest modules.You can also turn off all assertion interaction using the --assert=plain option. pytest used to be part of the py package, which provided several developer utilities, all starting with py.<TAB>, thusproviding nice TAB-completion. If you install pip install pycmd you get these tools from a separate package.Once pytest became a separate package, the py.test name was retained due to avoid a naming conflict withanother tool. This conflict was eventually resolved, and the pytest command was therefore introduced. In futureversions of pytest, we may deprecate and later remove the py.test command to avoid perpetuating the confusion. For simple applications and for people experienced with nose or unittest-style test setup using xUnit style setup proba-bly feels natural. For larger test suites, parametrized testing or setup of complex test resources using fixtures may feelmore natural. Moreover, fixtures are ideal for writing advanced test support code (like e.g. the monkeypatch, the tmpdiror capture fixtures) because the support code can register setup/teardown functions in a managed class/module/functionscope. There are two conceptual reasons why yielding from a factory function is not possible: • If multiple factories yielded values there would be no natural place to determine the combination policy - in real-world examples some combinations often should not run. •tests depending on the factory-created resource will run multiple times with different parameters.You can also use the pytest_generate_tests hook to implement the parametrization scheme of your choice.See also Parametrizing tests for more examples. On Windows the multiprocess package will instantiate sub processes by pickling and thus implicitly re-import a lotof local modules. Unfortunately, setuptools-0.6.11 does not if __name__=='__main__' protect its generatedcommand line script. This leads to infinite recursion when running a test that instantiates Processes.As of mid-2013, there shouldn’t be a problem anymore when you use the standard setuptools (note that distribute hasbeen merged back into setuptools which is now shipped directly with virtualenv). pytest is actively evolving and is a project that has been decades in the making, we keep learning about new and betterstructures to express different details about testing.While we implement those modifications we try to ensure an easy transition and don’t want to impose unnecessarychurn on our users and community/plugin authors.As of now, pytest considers multipe types of backward compatibility transitions: a) trivial: APIs which trivially translate to the new mechanism, and do not cause problematic changes. We try to support those indefinitely while encouraging users to switch to newer/better mechanisms through documentation. b) transitional: the old and new API don’t conflict and we can help users transition by using warnings, while supporting both for a prolonged time. We will only start the removal of deprecated functionality in major releases (e.g. if we deprecate something in 3.0 we will start to remove it in 4.0), and keep it around for at least two minor releases (e.g. if we deprecate something in 3.9 and 4.0 is the next release, we start to remove it in 5.0, not in 4.0). When the deprecation expires (e.g. 4.0 is released), we won’t remove the deprecated functionality immediately, but will use the standard warning filters to turn them into errors by default. This approach makes it explicit that removal is imminent, and still gives you time to turn the deprecated feature into a warning instead of an error so it can be dealt with in your own time. In the next minor release (e.g. 4.1), the feature will be effectively removed. c) true breakage: should only to be considered when normal transition is unreasonably unsustainable and would offset important development/features by years. In addition, they should be limited to APIs where the number of actual users is very small (for example only impacting some plugins), and can be coordinated with the community in advance. Examples for such upcoming changes: • removal of pytest_runtest_protocol/nextitem - #895 • rearranging of the node tree to include FunctionDefinition • rearranging of SetupState #895 275pytest Documentation, Release 5.4 History Keeping backwards compatibility has a very high priority in the pytest project. Although we have deprecated func-tionality over the years, most of it is still supported. All deprecations in pytest were done because simpler or moreefficient ways of accomplishing the same tasks have emerged, making the old way of doing things unnecessary.With the pytest 3.0 release we introduced a clear communication scheme for when we will actually remove the oldbusted joint and politely ask you to use the new hotness instead, while giving you enough time to adjust your tests orraise concerns if there are valid reasons to keep deprecated functionality around.To communicate changes we issue deprecation warnings using a custom warning hierarchy (see Internal pytest warn-ings). These warnings may be suppressed using the standard means: -W command-line flag or filterwarningsini options (see Warnings Capture), but we suggest to use these sparingly and temporarily, and heed the warningswhen possible.We will only start the removal of deprecated functionality in major releases (e.g. if we deprecate something in 3.0 wewill start to remove it in 4.0), and keep it around for at least two minor releases (e.g. if we deprecate something in 3.9and 4.0 is the next release, we start to remove it in 5.0, not in 4.0).When the deprecation expires (e.g. 4.0 is released), we won’t remove the deprecated functionality immediately, butwill use the standard warning filters to turn them into errors by default. This approach makes it explicit that removalis imminent, and still gives you time to turn the deprecated feature into a warning instead of an error so it can be dealtwith in your own time. In the next minor release (e.g. 4.1), the feature will be effectively removed. Features currently deprecated and removed in previous releases can be found in Deprecations and Removals.We track future deprecation and removal of features using milestones and the deprecation and removal labels onGitHub. 277pytest Documentation, Release 5.4 This page lists all pytest features that are currently deprecated or have been removed in past major releases. Theobjective is to give users a clear rationale why a certain feature has been removed, and what alternatives should beused instead. • Deprecated Features – --no-print-logs command-line option – Node Construction changed to Node.from_parent – junit_family default value change to “xunit2” – funcargnames alias for fixturenames – Result log (--result-log) – TerminalReporter.writer • Removed Features – pytest.config global – "message" parameter of pytest.raises – raises / warns with a string as the second argument – Using Class in custom Collectors – marks in pytest.mark.parametrize – pytest_funcarg__ prefix – [pytest] section in setup.cfg files – Metafunc.addcall – cached_setup – pytest_plugins in non-top-level conftest files 279pytest Documentation, Release 5.4 Below is a complete list of all pytest features which are considered deprecated. Using those features will issue_pytest.warning_types.PytestWarning or subclasses, which can be filtered using standard warning fil-ters. Add 'junit_family=legacy' to your pytest.ini file to silence this warning and make ˓→your suite compatible. In order to silence this warning, users just need to configure the junit_family option explicitly: [pytest]junit_family=legacy 32.1.6 TerminalReporter.writer As stated in our Backwards Compatibility Policy policy, deprecated features are removed only in major releases afteran appropriate period of deprecation has passed. Becomes: with pytest.raises(TimeoutError): wait_for(websocket.recv(), 0.5) pytest.fail("Client got unexpected message") If you still have concerns about this deprecation and future removal, please comment on issue #3974. pytest.warns(DeprecationWarning, "my_function()")pytest.warns(SyntaxWarning, "assert(1, 2)") with pytest.raises(ZeroDivisionError): 1 / 0with pytest.raises(SyntaxError): exec("a $ b") # exec is required for invalid syntax with pytest.warns(DeprecationWarning): my_function()with pytest.warns(SyntaxWarning): exec("assert(1, 2)") # exec is used to avoid a top-level warning parametrization call.This was considered hard to read and understand, and also its implementation presented problems to the code prevent-ing): ... In very early pytest versions fixtures could be defined using the pytest_funcarg__ prefix: def pytest_funcarg__data(): return SomeData() @pytest.fixturedef data(): return SomeData() 32.2.8 Metafunc.addcall def pytest_generate_tests(metafunc): metafunc.addcall({"i": 1}, id="1") metafunc.addcall({"i": 2}, id="2") def pytest_generate_tests(metafunc): metafunc.parametrize("i", [1, 2], ids=["1", "2"]) 32.2.9 cached_setup @pytest.fixturedef db_session(): return request.cached_setup( setup=Session.create, teardown=lambda session: session.close(), scope="module" ) @pytest.fixture(scope="module")def db_session(): session = Session.create() yield session session.close() You can consult funcarg comparison section in the docs for more information. warnings.warn(pytest.PytestWarning("some warning")) 32.2.12 record_xml_property def test_foo(record_xml_property): ... Change to: def test_foo(record_property): ... pytest.main("-v -s") pytest.main(["-v", "-s"]) By passing a string, users expect that pytest will interpret that command-line using the shell rules they are working on(for example bash or Powershell), but this is very hard/impossible to do in a portable way. @pytest.fixturedef cell(): return ... @pytest.fixturedef full_cell(): cell = cell() cell.make_full() return cell This is a great source of confusion to new users, which will often call the fixture functions and request them from testfunctions interchangeably, which breaks the fixture resolution model.In those cases just request the function directly in the dependent fixture: @pytest.fixturedtogether with the name parameter: def cell(): return ... def test_squared(): yield check, 2, 4 yield check, 3, 9 This would result into two actual test functions being generated.This form of test function doesn’t support fixtures properly, and users should switch to pytest.mark.parametrize: Users should just import pytest and access those objects using the pytest module.This has been documented as deprecated for years, but only now we are actually emitting deprecation warnings. 32.2.17 Node.get_marker 32.2.18 somefunction.markname As part of a large Marker revamp and iteration we already deprecated using MarkInfo the only correct way to getmarkers of an element is via node.iter_markers(name). 32.2.19 pytest_namespace class MySymbol: ... def pytest_namespace(): return {"my_symbol": MySymbol()} Plugin authors relying on this hook should instead require that users now import the plugin modules directly (with anappropriate public API).As a stopgap measure, plugin authors may still inject their names into pytest’s namespace, usually duringpytest_configure: def pytest_configure(): pytest.my_symbol = MySymbol() It is demanding on the maintainers of an open source project to support many Python versions, as there’s extra cost ofkeeping code compatible between all versions, while holding back on features only made possible on newer Pythonversions.In case of Python 2 and 3, the difference between the languages makes it even more prominent, because many newPython 3 features cannot be used in a Python 2/3 compatible code base.Python 2.7 EOL has been reached in 2020, with the last release planned for mid-April, 2020.Python 3.4 EOL has been reached in 2019, with the last release made in March, 2019.For those reasons, in Jun 2019 it was decided that pytest 4.6 series will be the last to support Python 2.7 and 3.4. Thanks to the python_requires setuptools option, Python 2.7 and Python 3.4 users using a modern pip version willinstall the last pytest 4.6.X version automatically even if 5.0 or later versions are available on PyPI.Users should ensure they are using the latest pip and setuptools versions for this to work. Until January 2020, the pytest core team ported many bug-fixes from the main release into the 4.6.x branch, withseveral 4.6.X releases being made along the year.From now on, the core team will no longer actively backport patches, but the 4.6.x branch will continue to existso the community itself can contribute patches.The core team will be happy to accept those patches, and make new 4.6.X releases until mid-2020 (but consider thatdate as a ballpark, after that date the team might still decide to make new releases for critical bugs). 291pytest Documentation, Release 5.4 New 4.6.X releases will happen after we have a few bugs in place to release, or if a few weeks have passed (say asingle bug has been fixed a month after the latest 4.6.X release).No hard rules here, just ballpark. We core maintainers expect that people still using Python 2.7/3.4 and being affected by bugs to step up and providepatches and/or port bug fixes from the active branches.We will be happy to guide users interested in doing so, so please don’t hesitate to ask.Backporting changes into 4.6Please follow these instructions: 1. git fetch --all --prune 2. git checkout origin/4.6.x -b backport-XXXX # use the PR number here 3. Locate the merge commit on the PR, in the merged message, for example: nicoddemus merged commit 0f8b462 into pytest-dev:features 4. git cherry-pick -m1 REVISION # use the revision you found above (0f8b462). 5. Open a PR targeting 4.6.x: • Prefix the message with [4.6] so it is an obvious backport • Delete the PR body, it usually contains a duplicate commit message.Providing new PRs to 4.6Fresh pull requests to 4.6.x will be accepted provided that the equivalent code in the active branches does not containthat bug (for example, a bug is specific to Python 2 only).Bug fixes that also happen in the mainstream version should be first fixed there, and then backported as per instructionsabove. Contributions are highly welcomed and appreciated. Every little bit of help counts, so do not hesitate! Contents Do you like pytest? Share some love on Twitter or in your blog posts!We’d also like to hear about your propositions and suggestions. Feel free to submit them as issues and: • Explain in detail how they should work. • Keep the scope as narrow as possible. This will make it easier to implement. 293pytest Documentation, Release 5.4 $ tox -e docs The built documentation should be available in doc/en/_build/html, where ‘en’ refers to the documentationlanguage. Pytest development of the core, some plugins and support code happens in repositories living under the pytest-devorganisations: • pytest-dev on GitHub • pytest-dev on BitbucketAll pytest-dev Contributors team members have write access to all contained repositories. Pytest core and plugins aregenerally developed using pull requests to respective repositories.The objectives of the pytest-dev organisation are: • Having a central location for popular pytest plugins • Sharing some of the maintenance responsibility (in case a maintainer no longer wishes to maintain a plugin)You can submit your plugin by subscribing to the pytest-dev mail list and writing a mail pointing to your existingpytest plugin repository which must have the following: • PyPI presence with a setup.py that contains a license, pytest- prefixed name, version number, authors, short and long description. • a tox.ini for running tests using tox. • a README.txt describing how to use the plugin and on which platforms it runs. • a LICENSE.txt file or equivalent containing the licensing information, with matching info in setup.py. • an issue tracker for bug reports and enhancement requests. • a changelog.If no contributor strongly objects and two agree, the repository can then be transferred to the pytest-dev organisa-tion.Here’s a rundown of how a repository transfer usually proceeds (using a repository named joedoe/pytest-xyzas example): • joedoe transfers repository ownership to pytest-dev administrator calvin. • calvin creates pytest-xyz-admin and pytest-xyz-developers teams, inviting joedoe to both as maintainer. • calvin transfers repository to pytest-dev and configures team access: – pytest-xyz-admin admin access; – pytest-xyz-developers writeor take ownership in any way, except in rare cases where someone becomes unresponsive after months of contactattempts. As stated, the objective is to share maintenance and avoid “plugin-abandon”. tox -e linting,py37 The test environments above are usually enough to cover most cases locally. 5. Write a changelog entry: changelog/2574.bugfix.rst, use issue id number and one of bugfix, removal, feature, vendor, doc or trivial for the issue type. 6. Unless your change is a trivial or a documentation fix (e.g., a typo or reword of a small section) please add yourself to the AUTHORS file, in alphabetical order. What is a “pull request”? It informs the project’s core developers about the changes you want to review and merge.Pull requests are stored on GitHub servers. Once you send a pull request, we can discuss its potential modificationsand even add more commits to it later on. There’s an excellent tutorial on how Pull Requests work in the GitHub HelpCenter.Here is a simple overview, with pytest-specific bits: 1. Fork the pytest GitHub repository. It’s fine to use pytest as your fork repository name because it will live under your user. 2. Clone your fork locally using git and create a branch: Given we have “major.minor.micro” version numbers, bug fixes will usually be released in micro releases whereas features will be released in minor releases and incompatible changes in major releases. If you need some help with Git, follow this quick start guide: 3. Install pre-commit and its hook on the pytest repo: Note: pre-commit must be installed as admin, as it will not function otherwise: 4. Install tox Tox is used to run all the tests and will automatically setup virtualenvs to run the tests in. (will implicitly use): $ tox -e linting,py37 This command will run tests via the “tox” tool against Python 3.7 and also perform “lint” coding-style checks. 6.: Afterwards, you can edit the files and run pytest normally: $ pytest testing/test_config.py 8. Commit and push once your tests pass and you are happy with your change(s): 9. Create a new changelog entry in changelog. The file should be named <issueid>.<type>.rst, where issueid is the number of the issue related to the change and type is one of bugfix, removal, feature, vendor, doc or trivial. You may not create a changelog entry if the change doesn’t affect the documented behaviour of Pytest. 10. Add yourself to AUTHORS file if not there yet, in alphabetical order. 11. Finally, submit a pull request through the GitHub website using this data: head-fork: YOUR_GITHUB_USERNAME/pytest compare: your-branch-name base-fork: pytest-dev/pytest base: master Writing tests for plugins or for pytest itself is often done using the testdir fixture, as a “black-box” test.For example, to ensure a simple test passes you can write: def test_true_assertion(testdir): testdir.makepyfile( """ def test_foo(): assert True """ ) result = testdir.runpytest() result.assert_outcomes(failed=0, passed=1) Alternatively, it is possible to make checks based on the actual output of the termal using glob-like expressions: def test_true_assertion(testdir): testdir.makepyfile( """ def test_foo(): assert False """ ) result = testdir.runpytest() result.stdout.fnmatch_lines(["*assert False*", "*1 failed*"]) When choosing a file where to write a new test, take a look at the existing files and see if there’s one file which looks likea good fit. For example, a regression test about a bug in the --lf option should go into test_cacheprovider.py, given that this option is implemented in cacheprovider.py. If in doubt, go ahead and open a PR with yourbest guess and we can discuss this over the code. Anyone who has successfully seen through a pull request which did not require any extra work from the developmentteam to merge will themselves gain commit access if they so wish (if we forget to ask please send a friendly reminder).This does not mean there is any change in your contribution workflow: everyone goes through the same pull-request-and-review process and no-one merges their own pull requests unless already approved. It does however mean you canparticipate in the de
https://ru.scribd.com/document/453546490/Pytest-Documentation-pdf
CC-MAIN-2021-04
refinedweb
40,783
50.02
On Fri, Dec 12, 2008 at 04:29:43PM +0100, Jim Meyering wrote: > Dave Allan <dallan redhat com> wrote: > > Since we're using NUMA_VERSION1_COMPATIBILITY mode (anyone know why?) > > #if HAVE_NUMACTL > #define NUMA_VERSION1_COMPATIBILITY 1 > #include <numa.h> > #endif In Fedora 10, they introduced libnuma 2.x, whereas all previous Fedora had 1.x. libnuma 2.x changed API decl for various functions. libvirt is written against 1.x API, so we need to declare NUMA_VERSION1_COMPATIBILITY to make sure our header import on 2.x systems, uses the 1.x APIs. The black magic in the header, actually compiles our 1.x usage into calls to the 2.x APIs. The 1.x ABIs still existed as versioned symbols so if you compiled against 1.x, you can still run against 2.x. Fun isn't :|
https://www.redhat.com/archives/libvir-list/2008-December/msg00338.html
CC-MAIN-2015-18
refinedweb
134
61.53
hey. Im not sure how to adapt cin.get(); to stop my prog exiting here it is. If sum1 could point me in the correct direction that would be cool thankz ;)thankz ;)Code: #include <iostream> #include <string> using namespace std; int main() { string firstName; string lastName; int ID; int age; float salary; string occupation; cout << "Enter your first name "; cin >> firstName; cout << "Enter your last name "; cin >> lastName; cout << "Enter your ID number "; cin >> ID; cout << "Enter your age "; cin >> age; cout << "Enter your salary (Per Year) "; cin >> salary; cout << "Enter your occupation "; cin >> occupation; cout << "Hello " << firstName << " " << lastName << " " << age << " " << salary << " "<< occupation; cout << " or should I say " << ID << end1; return 0; }
https://cboard.cprogramming.com/cplusplus-programming/56596-prog-prob-printable-thread.html
CC-MAIN-2017-30
refinedweb
111
59.6
Equinox Table of contents - I. Introduction - II. Start Equinox Runtime from Eclipse - III. Run Equinox standalone - IV. Commands - V. Equinox Bundles - VI. p2 - VII. Further Reading I. Introduction Equinox is considered to be a reference implementation of the OSGi Core 4.x specification and one of the most widely used. It is an open source project, part of the Eclipse project. It provides a set of bundles, that implement various optional OSGi services. The openHAB bundles are deployed on Equinox runtime. Knowledge about how to start the runtime and execute basic commands will help you to speedup the development process. Some of the bundles that you are going to use from Eclipse SmartHomeTM and openHAB depend on Equinox bundles and this article will list some of the Equinox core bundles and the services that they provide. II. Start Equinox Runtime from Eclipse First make sure that you have installed openHAB Eclipse IDE. Then follow these steps: - Start Eclipse and go to “Run” -> “Run Configurations”. - From the list in the left panel choose “OSGi Framework”. Right click on it and choose “New”. - After you’ve been created a new configuration, select the bundles that you need from the workspace. Then make sure that the following bundles from the target platform are selected, otherwise the OSGi console will not be available: org.apache.felix.gogo.runtime org.apache.felix.gogo.shell org.apache.felix.gogo.command org.eclipse.equinox.console - Click on “Add Required Bundles”. Eclipse will resolve all dependencies of the bundles listed above and include new bundles to the configuration. - Click on “Validate Bundles” and make sure that “No problems were detected” is displayed. - You can start Equinox with the “Run” button. If you use Eclipse for an IDE, this will be the easiest way to run your bundles in an Equinox runtime. If you do not have experience with writing OSGi bundles, go to our coding tasks page. III. Run Equinox standalone The org.eclipse.osgi bundle is the framework implementation of the Core Framework R4 specification in a standalone package. You can get it from your Eclipse IDE installation for openHAB (If you’re using Windows, it should be located at C:\Users\your.name\.p2\pool\plugins\org.eclipse.osgi_3.x.x_xxxx.jar). - Equinox versions before 3.8.0.M4. In some older version of Equinox, using the following command line: java -jar org.eclipse.osgi_3.x.x_xxxx.jar -console was enough to run it standalone. - Equinox versions after 3.8.0.M4. Starting from Equinox 3.8.0.M4, it has a new console. So the command line above will probably not work. You need some additional bundles in order to run Equinox properly. There are different ways to add those bundles and one of them is given below: After you have downloaded and installed Eclipse IDE for openHAB, find your .p2 repository and go to the pluginsfolder. (if you’re using Windows, it should be located at C:\Users\your.name\.p2\pool\plugins). Make sure that there is a org.eclipse.osgi_3.x.x_xxxx.jarin that folder. Create configurationfolder in the pluginsfolder. Inside the configurationfolder create a file config.ini. Save the following content in the config.inifile: osgi.bundles=\ org.eclipse.core.runtime,\ org.eclipse.equinox.common,\ org.eclipse.core.jobs,\ org.eclipse.equinox.registry,\ org.eclipse.equinox.preferences,\ org.eclipse.core.contenttype,\ org.eclipse.equinox.app,\ org.eclipse.equinox.console,\ org.apache.felix.gogo.runtime,\ org.apache.felix.gogo.shell,\ org.apache.felix.gogo.command eclipse.ignoreApp=true eclipse.consoleLog=true - Use the following command line to run Equinox: java -jar org.eclipse.osgi_3.x.x_xxxx.jar -console -configuration configuration IV. Commands Once you have Equinox running, you will see a prompt. Some of the basic osgi commands are: Table 1. Equinox commands (Source:) V. Equinox Bundles Another part of the Equinox project is the Equinox Bundles component. It consists of bundles that implement all add-on services from the OSGi specification and additional services defined in various OSGi expert groups. Some of the core bundles are listed in the table below. Some or all of these bundles must be included in your runtime configuration, if you want to use the services that they provide. Table 2. OSGi Bundles (Full list can be found at:) VI. p2 The p2 project is a sub-project of Equinox that focuses on provisioning technology for OSGi-based applications. Provisioning is the act of finding and installing new functionality and updating or removing existing functionality; it is distinct from building. Although p2 has a specific support for Equinox and Eclipse, can be used as a general purpose provisioning infrastructure. 1. Core Concepts p2 manages artifacts, such as plug-ins(bundles), features and products. You can think of these as bags of bytes. p2 not only stores these artifacts, it also stores metadata about these artifacts, such as version information, cryptographic signatures, dependencies, platform specifics and special installation requirements. 2. Installable Unit Every p2 artifact Installable Unit or IU is uniquely identified by an identifier and version number. For example, in the Equinox OSGi container from the Indigo release there is a bundle whose identifier is org.eclipse.osgi and version 3.7.0.v20110110. p2 assumes that two artifacts with the same identifier and same version number are the same artifact. An IU representing the SWT bundle: id=org.eclipse.swt, version=3.5.0, singleton=true Capabilities: {namespace=org.eclipse.equinox.p2.iu, name=org.eclipse.swt, version=3.5.0} {namespace=org.eclipse.equinox.p2.eclipse.type name=bundle version=1.0.0} {namespace=java.package, name=org.eclipse.swt.graphics, version=1.0.0} {namespace=java.package, name=org.eclipse.swt.layout, version=1.2.0} Requirements: {namespace=java.package, name=org.eclipse.swt.accessibility2, range=[1.0.0,2.0.0), optional=true, filter=(&(os=linux))} {namespace=java.package, name=org.mozilla.xpcom, range=[1.0.0, 1.1.0), optional=true, greed=false} Updates: {namespace=org.eclipse.equinox.p2.iu, name=org.eclipse.swt, range=[0.0.0, 3.5.0)} As you can see the installable unit defines capabilities - what the IU expose to the rest of the world, requirements - what the IU needs (the requirements are satisfied by capabilities). This metadata is used in the resolvement process. 3. Update sites Installable units can be grouped into a p2 repository (also called update site). A repository is defined via its URI and can point to a local file system or to a web server. A p2 repository is also frequently called update site. The most important characteristic of p2 repositories (and difference compared to the Maven repositories) is that IU do not depend directly on each other, they depend on packages identified by namespace + name + version(unless Require-Bundle is specified). A sample p2 repository(update site) has the following layout features plugins artifacts.jar content.jar site.xml Some of the most popular p2 repositories are orbit p2 Repo and Eclipse p2 Repo. You can find information about the Eclipse SmartHomeTM update sites at this link. VII. Further Reading - - - - - - OSGiEquinoxExplained - - - - - - - Products and features - Dependency Management for the Eclipse Ecosystem, Eclipse p2, metadata and resolution, Daniel Le Berre, Pascal Rapicault,2009 - RT meets p2
https://docs.openhab.org/v2.2/developers/prerequisites/equinox.html
CC-MAIN-2018-39
refinedweb
1,204
50.23
18 Paths & Custom Shapes become adept at creating custom shapes with which you’ll crop the photos. You’ll tap a photo on the card, which enables the Frames button. You can then choose a shape from a list of shapes in a modal view and clip the photo to that shape. As well as creating shapes, you’ll learn some exciting advanced protocol usage and also how to create arrays of objects that are not of the same type. The starter project The starter project moves on from hedgehogs to giraffes. A new published property in ViewState, called selectedElement, holds the currently selected element. In CardDetailView, tapping an element updates selectedElement and CardElementView shows a border around the selected element. In CardBottomToolbar, the Frames button is disabled when selectedElement is nil, but enabled when you tap an element. Tapping the background color deselects the element and disables Frames again. Currently when you tap Frames, a modal pops up with an EmptyView. You’ll replace this modal view with a FramePicker view where you’ll be able to select a shape. ➤ Build and run the project to see the changes. Shapes Skills you’ll learn in this section: predefined shapes var body: some View { VStack { Rectangle() RoundedRectangle(cornerRadius: 25.0) Circle() Capsule() Ellipse() } .padding() } Paths Skills you’ll learn in this section: paths; lines; arcs; quadratic curves struct Triangle: Shape { func path(in rect: CGRect) -> Path { var path = Path() return path } } Lines ➤ Create a triangle with the same coordinates as in the diagram above. Add this to path(in:) before return path: //1 path.move(to: CGPoint(x: 20, y: 30)) // 2 path.addLine(to: CGPoint(x: 130, y: 70)) path.addLine(to: CGPoint(x: 60, y: 140)) // 3 path.closeSubpath() struct Shapes: View { let currentShape = Triangle() var body: some View { currentShape .background(Color.yellow) } } func path(in rect: CGRect) -> Path { let width = rect.width let height = rect.height var path = Path() path.addLines([ CGPoint(x: width * 0.13, y: height * 0.2), CGPoint(x: width * 0.87, y: height * 0.47), CGPoint(x: width * 0.4, y: height * 0.93) ]) path.closeSubpath() return path } currentShape .aspectRatio(1, contentMode: .fit) .background(Color.yellow) .previewLayout(.sizeThatFits) Arcs Another useful path component is an arc. struct Cone: Shape { func path(in rect: CGRect) -> Path { var path = Path() // path code goes here return path } } let radius = min(rect.midX, rect.midY) path.addArc( center: CGPoint(x: rect.midX, y: rect.midY), radius: radius, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 180), clockwise: true) let currentShape = Cone() path.addLine(to: CGPoint(x: rect.midX, y: rect.height)) path.addLine(to: CGPoint(x: rect.midX + radius, y: rect.midY)) path.closeSubpath() Curves As well as lines and arcs, you can add various other standard elements to a path, such as rectangles and ellipses. With curves, you can create any custom shape you want. struct Lens: Shape { func path(in rect: CGRect) -> Path { var path = Path() // path code goes here return path } } path.move(to: CGPoint(x: 0, y: rect.midY)) path.addQuadCurve( to: CGPoint(x: rect.width, y: rect.midY), control: CGPoint(x: rect.midX, y: 0)) path.addQuadCurve( to: CGPoint(x: 0, y: rect.midY), control: CGPoint(x: rect.midX, y: rect.height)) path.closeSubpath() let currentShape = Lens() Strokes and fills Skills you’ll learn in this section: stroke; stroke style; fill .stroke(lineWidth: 5) Stroke style When you define a stroke, instead of giving it a lineWidth, you can give it a StrokeStyle instance. currentShape .stroke(style: StrokeStyle(dash: [30, 10])) .stroke( Color.primary, style: StrokeStyle(lineWidth: 10, lineJoin: .round)) .padding() Clip shapes modal You’ve now created a few shapes and feel free to experiment with more. The challenge for this chapter will suggest a few shapes for you to try. static let shapes: [Shape] = [Circle(), Rectangle()] Protocol 'Shape' can only be used as a generic constraint because it has Self or associated type requirements. Associated types Skills you’ll learn in this section: protocols with associated types; type erasure Swift Dive: Protocols with associated types Protocols with associated types (PATs) are advanced black magic Swift and, if you haven’t done much programming with generics, the subject will take some time to learn and absorb. Apple APIs use them everywhere, so it’s useful to have an overview. public protocol View { associatedtype Body : View @ViewBuilder var body: Self.Body { get } } struct ContentView: View { var body: some View { EmptyView() } } protocol CardElement { var id: UUID { get } var transform: Transform { get set } } protocol CardElement { associatedtype ID var id: ID { get } var transform: Transform { get set } } struct NewElement: CardElement { let id = Int.random(in: 0...1000) var transform = Transform() } static let shapes: [Shape] = [Circle(), Rectangle()] Type erasure You are able to place different Views in an array by converting the View type to AnyView: // does not compile let views: [View] = [Text("Hi"), Image("giraffe")] // does compile let views: [AnyView] = [ AnyView(Text("Hi")), AnyView(Image("giraffe")) ] import SwiftUI struct AnyShape: Shape { func path(in rect: CGRect) -> Path { } } private let path: (CGRect) -> Path // 1 init<CustomShape: Shape>(_ shape: CustomShape) { // 2 self.path = { rect in // 3 shape.path(in: rect) } } path(rect) A type erased array ➤ In Shapes.swift, add a new extension to Shapes: extension Shapes { static let shapes: [AnyShape] = [ AnyShape(Circle()), AnyShape(Rectangle()), AnyShape(Cone()), AnyShape(Lens()) ] } Shape selection modal Now that you have all your shapes in an array, you can create a selection modal, just as you did for your stickers. struct FramePicker: View { @Environment(\.presentationMode) var presentationMode // 1 @Binding var frame: AnyShape? private let columns = [ GridItem(.adaptive(minimum: 120), spacing: 10) ] private let style = StrokeStyle( lineWidth: 5, lineJoin: .round) var body: some View { ScrollView { LazyVGrid(columns: columns) { // 2 ForEach(0..<Shapes.shapes.count, id: \.self) { index in Shapes.shapes[index] // 3 .stroke(Color.primary, style: style) // 4 .background( Shapes.shapes[index].fill(Color.secondary)) .frame(width: 100, height: 120) .padding() // 5 .onTapGesture { frame = Shapes.shapes[index] presentationMode.wrappedValue.dismiss() } } } } .padding(5) } } struct FramePicker_Previews: PreviewProvider { static var previews: some View { FramePicker(frame: .constant(nil)) } } Add the frame picker modal to the card ➤ Open CardDetailView.swift and add a new property: @State private var frame: AnyShape? case .framePicker: FramePicker(frame: $frame) .onDisappear { if let frame = frame { card.update( viewState.selectedElement, frame: frame) } frame = nil } Add the frame to the card element ➤ Open CardElement.swift and add a new property to ImageElement: var frame: AnyShape? mutating func update(_ element: CardElement?, frame: AnyShape) { if let element = element as? ImageElement, let index = element.index(in: elements) { var newElement = element newElement.frame = frame elements[index] = newElement } } Add a modifier conditionally ➤ In ImageElementView, rename body to bodyMain. var body: some View { if let frame = element.frame { bodyMain .clipShape(frame) } else { bodyMain } } Challenges Challenge 1: Create new shapes Practice creating new shapes and place them in the frame picker modal. Here are some suggestions: Challenge 2: Clip the selection border Currently, when you tap an image, it gets a rectangular border around it. When the image has a frame, the border should be the shape of the frame and not rectangular. To achieve this, you’ll replace the border with the stroked frame in an overlay. Key points - The Shapeprotocol provides an easy way to draw a 2D shape. There are some built-in shapes, such as Rectangleand Circle, but you can create custom shapes by providing a Path. Paths are the outline of the 2D shape, made up of lines and curves. - A Shapefills by default with the primary color. You can override this with the fill(_:style:)modifier to fill with a color or gradient. Instead of filling the shape, you can stroke it with the stroke(_:lineWidth:)modifier to outline the shape with a color or gradient. - With the clipShape(_:style:)modifier, you can clip any view to a given shape. - Associated types in a protocol make a protocol generic, making the code reusable. Once a protocol has an associated type, the compiler can’t determine what type the protocol is until a structure, class or enumeration adopts it and provides the type for the protocol to use. - Using type erasure, you can hide the type of an object. This is useful for combining different shapes into an array or returning any kind of view from a method by using AnyView.
https://koenig-assets.raywenderlich.com/books/swiftui-apprentice/v1.0/chapters/18-paths-custom-shapes
CC-MAIN-2021-49
refinedweb
1,378
67.86
PEP 100 -- Python Unicode Integration Contents - Historical Note - Introduction - Conventions - General Remarks - Unicode Default Encoding - Unicode Constructors - Unicode Type Object - Unicode Output - Unicode Ordinals - Comparison & Hash Value - Coercion - Exceptions - Codecs (Coder/Decoders) Lookup - Standard Codecs - Codecs Interface Definition - Whitespace - Case Conversion - Line Breaks - Unicode Character Properties - Private Code Point Areas - Internal Format - Buffer Interface - Pickle/Marshalling - Regular Expressions - Formatting Markers - Internal Argument Parsing - File/Stream Output - File/Stream Input - Unicode Methods & Attributes - Code Base - Test Cases - References - History of this Proposal Historical Note This document was first written by Marc-Andre in the pre-PEP days, and was originally distributed as Misc/unicode.txt in Python distributions up to and included Python 2.1. The last revision of the proposal in that location was labeled version 1.7 (CVS revision 3.10). Because the document clearly serves the purpose of an informational PEP in the post-PEP era, it has been moved here and reformatted to comply with PEP guidelines. Future revisions will be made to this document, while Misc/unicode.txt will contain a pointer to this PEP. -Barry Warsaw, PEP editor Introduction The idea of this proposal is to add native Unicode 3.0 support to Python in a way that makes use of Unicode strings as simple as possible without introducing too many pitfalls along the way. Since this goal is not easy to achieve -- strings being one of the most fundamental objects in Python -- we expect this proposal to undergo some significant refinements. Note that the current version of this proposal is still a bit unsorted due to the many different aspects of the Unicode-Python integration. The latest version of this document is always available at: Older versions are available as: [ed. note: new revisions should be made to this PEP document, while the historical record previous to version 1.7 should be retrieved from MAL's url, or Misc/unicode.txt] Conventions - In examples we use u = Unicode object and s = Python string - 'XXX' markings indicate points of discussion (PODs) General Remarks - Unicode encoding names should be lower case on output and case-insensitive on input (they will be converted to lower case by all APIs taking an encoding name as input). - Encoding names should follow the name conventions as used by the Unicode Consortium: spaces are converted to hyphens, e.g. 'utf 16' is written as 'utf-16'. - Codec modules should use the same names, but with hyphens converted to underscores, e.g. utf_8, utf_16, iso_8859_1. Unicode Default Encoding The Unicode implementation has to make some assumption about the encoding of 8-bit strings passed to it for coercion and about the encoding to as default for conversion of Unicode to strings when no specific encoding is given. This encoding is called <default encoding> throughout this text. For this, the implementation maintains a global which can be set in the site.py Python startup script. Subsequent changes are not possible. The <default encoding> can be set and queried using the two sys module APIs: - sys.setdefaultencoding(encoding) Sets the <default encoding> used by the Unicode implementation. encoding has to be an encoding which is supported by the Python installation, otherwise, a LookupError is raised. Note: This API is only available in site.py! It is removed from the sys module by site.py after usage. - sys.getdefaultencoding() - Returns the current <default encoding>. If not otherwise defined or set, the <default encoding> defaults to 'ascii'. This encoding is also the startup default of Python (and in effect before site.py is executed). Note that the default site.py startup module contains disabled optional code which can set the <default encoding> according to the encoding defined by the current locale. The locale module is used to extract the encoding from the locale default settings defined by the OS environment (see locale.py). If the encoding cannot be determined, is unknown or unsupported, the code defaults to setting the <default encoding> to 'ascii'. To enable this code, edit the site.py file or place the appropriate code into the sitecustomize.py module of your Python installation. Unicode Constructors Python should provide a built-in constructor for Unicode strings which is available through __builtins__: u = unicode(encoded_string[,encoding=<default encoding>][,errors="strict"]) u = u'<unicode-escape encoded Python string>' u = ur'<raw-unicode-escape encoded Python string>' With the 'unicode-escape' encoding being defined as: - all non-escape characters represent themselves as Unicode ordinal (e.g. 'a' -> U+0061). - all existing defined Python escape sequences are interpreted as Unicode ordinals; note that \xXXXX can represent all Unicode ordinals, and \OOO (octal) can represent Unicode ordinals up to U+01FF. - a new escape sequence, \uXXXX, represents U+XXXX; it is a syntax error to have fewer than 4 digits after \u. For an explanation of possible values for errors see the Codec section below. Examples: u'abc' -> U+0061 U+0062 U+0063 u'\u1234' -> U+1234 u'abc\u1234\n' -> U+0061 U+0062 U+0063 U+1234 U+005c The 'raw-unicode-escape' encoding is defined as follows: - \uXXXX sequence represent the U+XXXX Unicode character if and only if the number of leading backslashes is odd - all other characters represent themselves as Unicode ordinal (e.g. 'b' -> U+0062) Note that you should provide some hint to the encoding you used to write your programs as pragma line in one the first few comment lines of the source file (e.g. '# source file encoding: latin-1'). If you only use 7-bit ASCII then everything is fine and no such notice is needed, but if you include Latin-1 characters not defined in ASCII, it may well be worthwhile including a hint since people in other countries will want to be able to read your source strings too. Unicode Type Object Unicode objects should have the type UnicodeType with type name 'unicode', made available through the standard types module. Unicode Output Unicode objects have a method .encode([encoding=<default encoding>]) which returns a Python string encoding the Unicode string using the given scheme (see Codecs). print u := print u.encode() # using the <default encoding> str(u) := u.encode() # using the <default encoding> repr(u) := "u%s" % repr(u.encode('unicode-escape')) Also see Internal Argument Parsing and Buffer Interface for details on how other APIs written in C will treat Unicode objects. Unicode Ordinals Since Unicode 3.0 has a 32-bit ordinal character set, the implementation should provide 32-bit aware ordinal conversion APIs: ord(u[:1]) (this is the standard ord() extended to work with Unicode objects) --> Unicode ordinal number (32-bit) unichr(i) --> Unicode object for character i (provided it is 32-bit); ValueError otherwise Both APIs should go into __builtins__ just like their string counterparts ord() and chr(). Note that Unicode provides space for private encodings. Usage of these can cause different output representations on different machines. This problem is not a Python or Unicode problem, but a machine setup and maintenance one. Comparison & Hash Value Unicode objects should compare equal to other objects after these other objects have been coerced to Unicode. For strings this means that they are interpreted as Unicode string using the <default encoding>. Unicode objects should return the same hash value as their ASCII equivalent strings. Unicode strings holding non-ASCII values are not guaranteed to return the same hash values as the default encoded equivalent string representation. When compared using cmp() (or PyObject_Compare()) the implementation should mask TypeErrors raised during the conversion to remain in synch with the string behavior. All other errors such as ValueErrors raised during coercion of strings to Unicode should not be masked and passed through to the user. In containment tests ('a' in u'abc' and u'a' in 'abc') both sides should be coerced to Unicode before applying the test. Errors occurring during coercion (e.g. None in u'abc') should not be masked. Coercion Using Python strings and Unicode objects to form new objects should always coerce to the more precise format, i.e. Unicode objects. u + s := u + unicode(s) s + u := unicode(s) + u All string methods should delegate the call to an equivalent Unicode object method call by converting all involved strings to Unicode and then applying the arguments to the Unicode method of the same name, e.g. string.join((s,u),sep) := (s + sep) + u sep.join((s,u)) := (s + sep) + u For a discussion of %-formatting w/r to Unicode objects, see Formatting Markers. Exceptions UnicodeError is defined in the exceptions module as a subclass of ValueError. It is available at the C level via PyExc_UnicodeError. All exceptions related to Unicode encoding/decoding should be subclasses of UnicodeError. Codecs (Coder/Decoders) Lookup A Codec (see Codec Interface Definition) search registry should be implemented by a module "codecs": codecs.register(search_function) Search functions are expected to take one argument, the encoding name in all lower case letters and with hyphens and spaces converted to underscores, and return a tuple of need to be factory functions with the following interface: factory(stream,errors='strict') The factory functions must return objects providing the interfaces defined by StreamWriter/StreamReader resp. (see Codec Interface). Stream codecs can maintain state. Possible values for errors are defined in the Codec section below. In case a search function cannot find a given encoding, it should return None. Aliasing support for encodings is left to the search functions to implement. The codecs module will maintain an encoding cache for performance reasons. Encodings are first looked up in the cache. If not found, the list of registered search functions is scanned. If no codecs tuple is found, a LookupError is raised. Otherwise, the codecs tuple is stored in the cache and returned to the caller. To query the Codec instance the following API should be used: codecs.lookup(encoding) This will either return the found codecs tuple or raise a LookupError. Standard Codecs Standard codecs should live inside an encodings/ package directory in the Standard Python Code Library. The __init__.py file of that directory should include a Codec Lookup compatible search function implementing a lazy module based codec lookup. Python should provide a few standard codecs for the most relevant encodings, e.g. 'utf-8': 8-bit variable length encoding 'utf-16': 16-bit variable length encoding (little/big endian) 'utf-16-le': utf-16 but explicitly little endian 'utf-16-be': utf-16 but explicitly big endian 'ascii': 7-bit ASCII codepage 'iso-8859-1': ISO 8859-1 (Latin 1) codepage 'unicode-escape': See Unicode Constructors for a definition 'raw-unicode-escape': See Unicode Constructors for a definition 'native': Dump of the Internal Format used by Python Common aliases should also be provided per default, e.g. 'latin-1' for 'iso-8859-1'. Note: 'utf-16' should be implemented by using and requiring byte order marks (BOM) for file input/output. All other encodings such as the CJK ones to support Asian scripts should be implemented in separate packages which do not get included in the core Python distribution and are not a part of this proposal. Codecs Interface Definition The following base class should be defined in the module "codecs". They provide not only templates for use by encoding module implementors, but also define the interface which is expected by the Unicode implementation. Note that the Codec Interface defined here is well suitable for a larger range of applications. The Unicode implementation expects Unicode objects on input for .encode() and .write() and character buffer compatible objects on input for .decode(). Output of .encode() and .read() should be a Python string and .decode() must return an Unicode object. First, we have the stateless encoders/decoders. These do not work in chunks as the stream codecs (see below) do, because all components are expected to be available in memory. class Codec: """Defines the interface for stateless encoders/decoders. The .encode()/.decode() methods may implement different error handling schemes by providing the errors argument. These string values are defined: 'strict' - raise an error (or a subclass) 'ignore' - ignore the character and continue with the next 'replace' - replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the builtin Unicode codecs. """ def encode(self,input,errors='strict'): """Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling. The method may not store state in the Codec instance. Use StreamCodec for codecs which have to keep state in order to make encoding/decoding efficient. """ def decode(self,input,errors='strict'): """Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling. The method may not store state in the Codec instance. Use StreamCodec for codecs which have to keep state in order to make encoding/decoding efficient. """ StreamWriter and StreamReader define the interface for stateful encoders/decoders which work on streams. These allow processing of the data in chunks to efficiently use memory. If you have large strings in memory, you may want to wrap them with cStringIO objects and then use these codecs on them to be able to do chunk processing as well, e.g. to provide progress information to the user. class StreamWriter(Codec): def __init__(self,stream,errors='strict'): """Creates a StreamWriter instance. stream must be a file-like object open for writing (binary) data. The StreamWriter may implement different error handling schemes by providing the errors keyword argument. These parameters are defined: 'strict' - raise a ValueError (or a subclass) 'ignore' - ignore the character and continue with the next 'replace'- replace with a suitable replacement character """ self.stream = stream self.errors = errors def write(self,object): """Writes the object's contents encoded to self.stream. """ data, consumed = self.encode(object,self.errors) self.stream.write(data) def writelines(self, list): """Writes the concatenated list of strings to the stream using .write(). """ self.write(''.join(list)) def reset(self): """Flushes and resets the codec buffers used for keeping state. Calling this method should ensure that the data on the output is put into a clean state, that allows appending of new fresh data without having to rescan the whole stream to recover state. """ pass def __getattr__(self,name, getattr=getattr): """Inherit all other methods from the underlying stream. """ return getattr(self.stream,name) class StreamReader(Codec): def __init__(self,stream,errors='strict'): """Creates a StreamReader instance. stream must be a file-like object open for reading (binary) data. The StreamReader may implement different error handling schemes by providing the errors keyword argument. These parameters are defined: 'strict' - raise a ValueError (or a subclass) 'ignore' - ignore the character and continue with the next 'replace'- replace with a suitable replacement character; """ self.stream = stream self.errors = errors def read(self,size=-1): """Decodes data from the stream self.stream and returns the resulting. """ # Unsliced reading: if size < 0: return self.decode(self.stream.read())[0] # Sliced reading: read = self.stream.read decode = self.decode data = read(size) i = 0 while 1: try: object, decodedbytes = decode(data) except ValueError,why: # This method is slow but should work under pretty # much all conditions; at most 10 tries are made i = i + 1 newdata = read(1) if not newdata or i > 10: raise data = data + newdata else: return object def readline(self, size=None): """Read one line from the input stream and return the decoded data. Note: Unlike the .readlines() method, this method inherits the line breaking knowledge from the underlying stream's .readline() method -- there is currently no support for line breaking using the codec decoder due to lack of line buffering. Subclasses should however, if possible, try to implement this method using their own knowledge of line breaking. size, if given, is passed as size argument to the stream's .readline() method. """ if size is None: line = self.stream.readline() else: line = self.stream.readline(size) return self.decode(line)[0] def readlines(self, sizehint=0): """Read all lines available on the input stream and return them as list of lines. Line breaks are implemented using the codec's decoder method and are included in the list entries. sizehint, if given, is passed as size argument to the stream's .read() method. """ if sizehint is None: data = self.stream.read() else: data = self.stream.read(sizehint) return self.decode(data)[0].splitlines(1) def reset(self): """Resets the codec buffers used for keeping state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors. """ pass def __getattr__(self,name, getattr=getattr): """ Inherit all other methods from the underlying stream. """ return getattr(self.stream,name) Stream codec implementors are free to combine the StreamWriter and StreamReader interfaces into one class. Even combining all these with the Codec class should be possible. Implementors are free to add additional methods to enhance the codec functionality or provide extra state information needed for them to work. The internal codec implementation will only use the above interfaces, though. It is not required by the Unicode implementation to use these base classes, only the interfaces must match; this allows writing Codecs as extension types. As guideline, large mapping tables should be implemented using static C data in separate (shared) extension modules. That way multiple processes can share the same data. A tool to auto-convert Unicode mapping files to mapping modules should be provided to simplify support for additional mappings (see References). Whitespace The .split() method will have to know about what is considered whitespace in Unicode. Case Conversion Case conversion is rather complicated with Unicode data, since there are many different conditions to respect. See for some guidelines on implementing case conversion. For Python, we should only implement the 1-1 conversions included in Unicode. Locale dependent and other special case conversions (see the Unicode standard file SpecialCasing.txt) should be left to user land routines and not go into the core interpreter. The methods .capitalize() and .iscapitalized() should follow the case mapping algorithm defined in the above technical report as closely as possible. Line Breaks Line breaking should be done for all Unicode characters having the B property as well as the combinations CRLF, CR, LF (interpreted in that order) and other special line separators defined by the standard. The Unicode type should provide a .splitlines() method which returns a list of lines according to the above specification. See Unicode Methods. Unicode Character Properties A separate module "unicodedata" should provide a compact interface to all Unicode character properties defined in the standard's UnicodeData.txt file. Among other things, these properties provide ways to recognize numbers, digits, spaces, whitespace, etc. Since this module will have to provide access to all Unicode characters, it will eventually have to contain the data from UnicodeData.txt which takes up around 600kB. For this reason, the data should be stored in static C data. This enables compilation as shared module which the underlying OS can shared between processes (unlike normal Python code modules). There should be a standard Python interface for accessing this information so that other implementors can plug in their own possibly enhanced versions, e.g. ones that do decompressing of the data on-the-fly. Private Code Point Areas Support for these is left to user land Codecs and not explicitly integrated into the core. Note that due to the Internal Format being implemented, only the area between \uE000 and \uF8FF is usable for private encodings. Internal Format The internal format for Unicode objects should use a Python specific fixed format <PythonUnicode> implemented as 'unsigned short' (or another unsigned numeric type having 16 bits). Byte order is platform dependent. This. UTF-16 without surrogates provides access to about 64k characters and covers all characters in the Basic Multilingual Plane (BMP) of Unicode. It is the Codec's responsibility to ensure that the data they pass to the Unicode object constructor respects this assumption. The constructor does not check the data for Unicode compliance or use of surrogates. Future implementations can extend the 32 bit restriction to the full set of all UTF-16 addressable characters (around 1M characters). The Unicode API should provide interface routines from <PythonUnicode> to the compiler's wchar_t which can be 16 or 32 bit depending on the compiler/libc/platform being used. Unicode objects should have a pointer to a cached Python string object <defenc> holding the object's value using the <default encoding>. This is needed for performance and internal parsing (see Internal Argument Parsing) reasons. The buffer is filled when the first conversion request to the <default encoding> is issued on the object. Interning is not needed (for now), since Python identifiers are defined as being ASCII only. codecs.BOM should return the byte order mark (BOM) for the format used internally. The codecs module should provide the following additional constants for convenience and reference (codecs.BOM will either be BOM_BE or BOM_LE depending on the platform): BOM_BE: '\376\377' (corresponds to Unicode U+0000FEFF in UTF-16 on big endian platforms == ZERO WIDTH NO-BREAK SPACE) BOM_LE: '\377\376' (corresponds to Unicode U+0000FFFE in UTF-16 on little endian platforms == defined as being an illegal Unicode character) BOM4_BE: '\000\000\376\377' (corresponds to Unicode U+0000FEFF in UCS-4) BOM4_LE: '\377\376\000\000' (corresponds to Unicode U+0000FFFE in UCS-4) Note that Unicode sees big endian byte order as being "correct". The swapped order is taken to be an indicator for a "wrong" format, hence the illegal character definition. The configure script should provide aid in deciding whether Python can use the native wchar_t type or not (it has to be a 16-bit unsigned type). Buffer Interface Implement the buffer interface using the <defenc> Python string object as basis for bf_getcharbuf and the internal buffer for bf_getreadbuf. If bf_getcharbuf is requested and the <defenc> object does not yet exist, it is created first. Note that as special case, the parser marker "s#" will not return raw Unicode UTF-16 data (which the bf_getreadbuf returns), but instead tries to encode the Unicode object using the default encoding and then returns a pointer to the resulting string object (or raises an exception in case the conversion fails). This was done in order to prevent accidentely writing binary data to an output stream which the other end might not recognize. This has the advantage of being able to write to output streams (which typically use this interface) without additional specification of the encoding to use. If you need to access the read buffer interface of Unicode objects, use the PyObject_AsReadBuffer() interface. The internal format can also be accessed using the 'unicode-internal' codec, e.g. via u.encode('unicode-internal'). Pickle/Marshalling Should have native Unicode object support. The objects should be encoded using platform independent encodings. Marshal should use UTF-8 and Pickle should either choose Raw-Unicode-Escape (in text mode) or UTF-8 (in binary mode) as encoding. Using UTF-8 instead of UTF-16 has the advantage of eliminating the need to store a BOM mark. Regular Expressions Secret Labs AB is working on a Unicode-aware regular expression machinery. It works on plain 8-bit, UCS-2, and (optionally) UCS-4 internal character buffers. Also see for some remarks on how to treat Unicode REs. Formatting Markers Format markers are used in Python format strings. If Python strings are used as format strings, the following interpretations should be in effect: '%s': For Unicode objects this will cause coercion of the whole format string to Unicode. Note that you should use a Unicode format string to start with for performance reasons. In case the format string is an Unicode object, all parameters are coerced to Unicode first and then put together and formatted according to the format string. Numbers are first converted to strings and then to Unicode. '%s': Python strings are interpreted as Unicode string using the <default encoding>. Unicode objects are taken as is. All other string formatters should work accordingly. Example: u"%s %s" % (u"abc", "abc") == u"abc abc" Internal Argument Parsing These markers are used by the PyArg_ParseTuple() APIs: - "U" - Check for Unicode object and return a pointer to it - "s" - For Unicode objects: return a pointer to the object's <defenc> buffer (which uses the <default encoding>). - "s#" - Access to the default encoded version of the Unicode object (see Buffer Interface); note that the length relates to the length of the default encoded string rather than the Unicode object length. - "t#" - Same as "s#". - "es" Takes two parameters: encoding (const char *) and buffer (char **). The input object is first coerced to Unicode in the usual way and then encoded into a string using the given encoding. On output, a buffer of the needed size is allocated and returned through *buffer as NULL-terminated string. The encoded may not contain embedded NULL characters. The caller is responsible for calling PyMem_Free() to free the allocated *buffer after usage. - "es#" Takes three parameters: encoding (const char *), buffer (char **) and buffer_len (int *). The input object is first coerced to Unicode in the usual way and then encoded into a string using the given encoding. If *buffer is non-NULL, *buffer_len must be set to sizeof(buffer) on input. Output is then copied to *buffer. If *buffer is NULL, a buffer of the needed size is allocated and output copied into it. *buffer is then updated to point to the allocated memory area. The caller is responsible for calling PyMem_Free() to free the allocated *buffer after usage. In both cases *buffer_len is updated to the number of characters written (excluding the trailing NULL-byte). The output buffer is assured to be NULL-terminated. Examples: Using "es#" with auto-allocation: static PyObject * test_parser(PyObject *self, PyObject *args) { PyObject *str; const char *encoding = "latin-1"; char *buffer = NULL; int buffer_len = 0; if (!PyArg_ParseTuple(args, "es#:test_parser", encoding, &buffer, &buffer_len)) return NULL; if (!buffer) { PyErr_SetString(PyExc_SystemError, "buffer is NULL"); return NULL; } str = PyString_FromStringAndSize(buffer, buffer_len); PyMem_Free(buffer); return str; } Using "es" with auto-allocation returning a NULL-terminated string: static PyObject * test_parser(PyObject *self, PyObject *args) { PyObject *str; const char *encoding = "latin-1"; char *buffer = NULL; if (!PyArg_ParseTuple(args, "es:test_parser", encoding, &buffer)) return NULL; if (!buffer) { PyErr_SetString(PyExc_SystemError, "buffer is NULL"); return NULL; } str = PyString_FromString(buffer); PyMem_Free(buffer); return str; } Using "es#" with a pre-allocated buffer: static PyObject * test_parser(PyObject *self, PyObject *args) { PyObject *str; const char *encoding = "latin-1"; char _buffer[10]; char *buffer = _buffer; int buffer_len = sizeof(_buffer); if (!PyArg_ParseTuple(args, "es#:test_parser", encoding, &buffer, &buffer_len)) return NULL; if (!buffer) { PyErr_SetString(PyExc_SystemError, "buffer is NULL"); return NULL; } str = PyString_FromStringAndSize(buffer, buffer_len); return str; } File/Stream Output Since file.write(object) and most other stream writers use the "s#" or "t#" argument parsing marker for querying the data to write, the default encoded string version of the Unicode object will be written to the streams (see Buffer Interface). For explicit handling of files using Unicode, the standard stream codecs as available through the codecs module should be used. The codecs module should provide a short-cut open(filename,mode,encoding) available which also assures that mode contains the 'b' character when needed. File/Stream Input Only the user knows what encoding the input data uses, so no special magic is applied. The user will have to explicitly convert the string data to Unicode objects as needed or use the file wrappers defined in the codecs module (see File/Stream Output). Unicode Methods & Attributes All Python string methods, plus: .encode([encoding=<default encoding>][,errors="strict"]) --> see Unicode Output .splitlines([include_breaks=0]) --> breaks the Unicode string into a list of (Unicode) lines; returns the lines with line breaks included, if include_breaks is true. See Line Breaks for a specification of how line breaking is done. Code Base We should use Fredrik Lundh's Unicode object implementation as basis. It already implements most of the string methods needed and provides a well written code base which we can build upon. The object sharing implemented in Fredrik's implementation should be dropped. Test Cases Test cases should follow those in Lib/test/test_string.py and include additional checks for the Codec Registry and the Standard Codecs. References - Unicode Consortium: - Unicode FAQ: - Unicode 3.0: - Unicode-TechReports: - Unicode-Mappings: - Introduction to Unicode (a little outdated by still nice to read): - For comparison: Introducing Unicode to ECMAScript (aka JavaScript) -- - IANA Character Set Names: - Discussion of UTF-8 and Unicode support for POSIX and Linux: - Encodings: - Overview: - UCS-2: - UTF-7: Defined in RFC2152, e.g. - UTF-8: Defined in RFC2279, e.g. - UTF-16: History of this Proposal [ed. note: revisions prior to 1.7 are available in the CVS history of Misc/unicode.txt from the standard Python distribution. All subsequent history is available via the CVS revisions on this file.] 1.6 - Changed <defencstr> to <defenc> since this is the name used in the implementation. - Added notes about the usage of <defenc> in the buffer protocol implementation. 1.5 - Added notes about setting the <default encoding>. - Fixed some typos (thanks to Andrew Kuchling). - Changed <defencstr> to <utf8str>. 1.4 - Added note about mixed type comparisons and contains tests. - Changed treating of Unicode objects in format strings (if used with '%s' % u they will now cause the format string to be coerced to Unicode, thus producing a Unicode object on return). - Added link to IANA charset names (thanks to Lars Marius Garshol). - Added new codec methods .readline(), .readlines() and .writelines(). 1.1 - Added note about comparisons and hash values. - Added note about case mapping algorithms. - Changed stream codecs .read() and .write() method to match the standard file-like object methods (bytes consumed information is no longer returned by the methods) 1.0 - changed encode Codec method to be symmetric to the decode method (they both return (object, data consumed) now and thus become interchangeable); - removed __init__ method of Codec class (the methods are stateless) and moved the errors argument down to the methods; - made the Codec design more generic w/r to type of input and output objects; - changed StreamWriter.flush to StreamWriter.reset in order to avoid overriding the stream's .flush() method; - renamed .breaklines() to .splitlines(); - renamed the module unicodec to codecs; - modified the File I/O section to refer to the stream codecs. 0.9 - changed errors keyword argument definition; - added 'replace' error handling; - changed the codec APIs to accept buffer like objects on input; - some minor typo fixes; - added Whitespace section and included references for Unicode characters that have the whitespace and the line break characteristic; - added note that search functions can expect lower-case encoding names; - dropped slicing and offsets in the codec APIs 0.8 - added encodings package and raw unicode escape encoding; - untabified the proposal; - added notes on Unicode format strings; - added .breaklines() method 0.6 - changed "s#" to "t#"; - changed <defencbuf> to <defencstr> holding a real Python string object; - changed Buffer Interface to delegate requests to <defencstr>'s buffer interface; - removed the explicit reference to the unicodec.codecs dictionary (the module can implement this in way fit for the purpose); - removed the settable default encoding; - move UnicodeError from unicodec to exceptions; - "s#" not returns the internal data; - passed the UCS-2/UTF-16 checking from the Unicode constructor to the Codecs 0.5 - moved sys.bom to unicodec.BOM; - added sections on case mapping, - private use encodings and Unicode character properties 0.4 - added Codec interface, notes on %-formatting, - changed some encoding details, - added comments on stream wrappers, - fixed some discussion points (most important: Internal Format), - clarified the 'unicode-escape' encoding, added encoding references 0.3 - added references, comments on codec modules, the internal format, bf_getcharbuffer and the RE engine; - added 'unicode-escape' encoding proposed by Tim Peters and fixed repr(u) accordingly
https://www.python.org/dev/peps/pep-0100/
CC-MAIN-2017-51
refinedweb
5,332
55.13
I'm currently working on an ERB View class for a gem. With this class I would like to have some helper methods for ERB templates. It's okay about basic helpers like h(string) erbh content_for Proc call content_for After reading this blog article I finally found why it wasn't working. I don't know if I did it in the best way and cleaner way but it works. So the bug was mainly from the ERB initilization. By using a property instead a local variable as eoutvar it now works. erb = ERB.new(str, nil, "<>", "@_erbout") I also change a bit the capture method who is used by content_for helper. It looks like this now (gist) def content_for(key, content = nil, &block) block ||= proc { |*| content } content_blocks[key.to_sym] << capture_later(&block) end def content_for?(key) content_blocks[key.to_sym].any? end def yield_content(key, default = nil) return default if content_blocks[key.to_sym].empty? content_blocks[key.to_sym].map { |b| capture(&b) }.join end def capture(&block) @capture = nil @_erbout, _buf_was = '', @_erbout result = yield @_erbout = _buf_was result.strip.empty? && @capture ? @capture : result end def capture_later(&block) proc { |*| @capture = capture(&block) } end
https://codedump.io/share/TiLWVSgSE4Op/1/ruby-erb---create-a-contentfor-method
CC-MAIN-2017-39
refinedweb
190
67.25
React Native Component Lifecycle As an introduction, I would like to show you what exactly I will cover in this article, how lifecycles are divided into categories, and what each category is responsible for. What are the React lifecycle methods?All React class components have their own phases. When an instance of a component is being created and inserted into the DOM, it gets properties, orprops, and from now on they can be accessed using this.props. Then the whole lifecycle ‘thing’ begins. Note: A React component may NOT go through all of the phases. The component could get mounted and unmounted the next minute — without any updates or error handling. A component’s lifecycle can be divided into 4 parts: - Mounting — an instance of a component is being created and inserted into the DOM. - Updating — when the React component is born in the browser and grows by receiving new updates. - Unmounting — the component is not needed and gets unmounted. - Error handling — called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component. Lifecycle Phases As I have introduced the basic idea of each phase, let’s take a closer look at their methods. Mounting These methods are called in the following order when an instance of a component is being created and inserted into the DOM: Updating An update can be caused by changes to props or state. These methods are called in the following order when a component is re-rendered: - static getDerivedStateFromProps() - shouldComponentUpdate() - render() - getSnapshotBeforeUpdate() - componentDidUpdate() Unmounting This method is called when a component is removed from the DOM: Error Handling These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component. Now that we know what are the lifecycle phases and their methods, we can get down to the next part — a detailed description of each method. Detailed Lifecycle Mounting constructor() First of all, the constructor method is called before mounting to the DOM and rendering. Usually, you’d initialize state and bind event handler methods within the constructor method. This is the first part of the lifecycle and is only called when it is explicitly declared, so there is no need to declare it in every component you create. If you need to make any side-effects or subscriptions in this method, you should use componentDidMount(). I will introduce it later on as we are going through each method the in order they are invoked. constructor(props){ super(props); this.state = { message: 'hello world', } // this is our initial data } static getDerivedStateFromProps() Instead of calling setState, getDerivedStateFromProps simply. You can either return an object to update the state of the component or return null to make no updates: // ... static getDerivedStateFromProps(props, state) { return { message: 'updated msg', } } // or you can return null to make no update static getDerivedStateFromProps(props, state) { return null } // ... You are probably wondering why exactly is this lifecycle method important. It’s true that it is one of the rarely used lifecycle methods, but it comes in handy in certain scenarios. Just because you can update state doesn’t mean you should go ahead and do this. There are specific use cases for the static getDerivedStateFromProps method, or you’ll be solving your. The component state reached in this manner is referred to as a derived state.As a rule, the derived state should be used with an understanding of what you are doing, as you can introduce subtle bugs into your application if you’re driving blind. render() Next, after the static getDerivedStateFromProps method is called, the next lifecycle method in line is the render method. The render method must return a React Native component (JSX element) to render (or null, to render nothing). In this step, the UI component is rendered. An important thing to note about the render method is that the render function should be pure, so do not attempt to use setState or interact with the external APIs. render(){ return ( <View> <Text>{this.state.message}</Text> </View> ) } componentDidMount() Just after render() is finished, the component is mounted to the DOM and another method is called — componentDidMount(). When this method is called, we know for sure that we have a UI element which is rendered. This is a good place to do a fetch request to the server or set up subscriptions (such as timers). Remember, updating the state will invoke the render() method again, without noticing the previous state. Until this method is called we are operating on the virtual DOM. // good place to call setState here componentDidMount(){ this.setState({ message: 'i got changed', }); } --- // or to make request to the server componentDidMount() { fetch('') .then(response => response.json()) .then(data => this.setState({ message: data.message })); } Second use case: componentDidMount() is a great place to make a fetch() to a server and to call our setState() method to change the state of our application and render() the updated data. For example, if we are going to fetch any data from an API, then the API call should be placed in this lifecycle method, and then we get the response and we can call the setState() method to render the element with updated data. import React, {Component} from 'react'; import { View, Text } from 'react-native'; class App extends Component { constructor(props){ super(props); this.state = { message: 'hello world', } } componentDidMount() { fetch('') .then(response => response.json()) .then(data => this.setState({ message: data.message })); // data.message = 'updated message' } render(){ return( <View> {/* 'updated message' will be rendered as soon as fetch return data */} <Text>{this.state.message}</Text> </View> ) } } export default App; In the above example, I have a fake API call to fetch the data. So, after the component is rendered correctly, the componentDidMount() function is called and we request data from the server. As soon as data is received, we re-render component with new data. With this, we come to the end of the Mounting phase. When our component gets new props, changes its state, or its parent component is updated, the updating part of the life-cycle begins. Let’s have a look at the next phase the component goes through — the updating phase. Updating Each time something changes inside our component or parent component, in other words, when the state or props are changed, the component may need to be re-rendered. In simple terms, the component is updated. So what lifecycle methods are invoked when a component is to be updated? static getDerivedStateFromProps() Firstly, the static getDerivedStateFromProps method is invoked. That’s the first method to be invoked. I already explained this method in the mounting phase, so I’ll skip it. What’s important to note is that this method is invoked in both the mounting and updating phases. shouldComponentUpdate() By default, or in most cases, you’ll want a component to re-render when the state or props change. However, you do have control over this behaviour. Here is the moment React decides whether we should update a component or not. Within this lifecycle method, you can return a boolean and control whether the component gets re-rendered or not, i.e upon a change in the state or props.This lifecycle method is mostly used for performance optimisation measures. Example usage of shouldComponentUpdate: If the only way your component ever changes is when the this.props.color or the this.state.count variable changes, you could have ( <View> <Button color={this.props.color} onPress={() => this.setState(state => ({count: state.count + 1}))} /> <Text>Count: {this.state.count}</Text> </View> ); } } In this code, shouldComponentUpdate is just checking if there is any change in this.props.color or this.state.count. If those values don’t change, the component doesn’t update. If your component is more complex, you could use a similar pattern of doing a “shallow comparison” between all the fields of ( <View> <Button title="Press me" color={this.props.color} onPress={() => this.setState(state => ({count: state.count + 1}))} /> <Text> Count: {this.state.count} </Text> </View> ); } } Most of the time, you can use React.PureComponent instead of writing your own shouldComponentUpdate, but it only does a shallow comparison, so you can’t use it if the props or state may have been mutated in a way that a shallow comparison would miss. This can be a problem with more complex data structures. render() After the shouldComponentUpdate method is called, a render is called immediately afterwards depending on the returned value from shouldComponentUpdate, which defaults to true. getSnapshotBeforeUpdate(prevProps, prevState) Right after the render method is called and before the most recently rendered output is committed, for example to the DOM, getSnapshotBeforeUpdate() is invoked . There is a common use case in React when you can use it, but it is useless in React Native. To cut a long story short, if you are building a chat application using React, you can use this method to calculate the scroll size and scroll to the bottom as new messages appear In React Native you can simply use the onContentSizeChange prop for ScrollView. A component with an auto-scroll feature can look like this: <ScrollView onContentSizeChange={()=>{this.scrollViewRef.scrollToEnd();}} ref={(ref) => this.scrollViewRef = ref} > <Chats chatList={this.state.chatList} /> </ScrollView> When chatList is updated with new data, ScrollView is automatically scrolled to the very bottom, so you are up to date with new messages. componentDidUpdate() componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed). componentDidUpdate(preProps) { if(prevProps.selectedState !== this.props.selectedState){ fetch('') .then(resp => resp.json()) .then(respJson => { // do what ever you want with your `response` this.setState({ isLoading: false, data: respJson, }); }) .catch(err => { console.log(err) }) } } Unmounting componentWillUnmount() componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount(). // e.g add event listener componentDidMount() { el.addEventListener() } // e.g remove event listener componentWillUnmount() { el.removeEventListener() } Typical uses of componentDidMount with componentWillUnmountYou should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again. Error handling Sometimes it pays to stay in bed on Monday, rather than spending the rest of the week debugging Monday’s code. CHRISTOPHER THOMPSON All of us would be more than happy to write code without any errors, but this is more of a dream. In real life, errors appear everywhere, sometimes we are aware of them, sometimes we are not. This part will introduce you to some basic ways of handling errors. Let’s implement a simple component to catch errors in the demo app. For this, we’ll create a new component called ErrorBoundary. Here’s the most basic implementation: import React, { Component } from 'react'; class ErrorBoundary extends Component { state = { hasError: false, }; render() { return this.props.children; } } export default ErrorBoundary; static getDerivedStateFromError() Whenever an error is thrown in a descendant component, this method is called first, and the error thrown is passed as an argument. Whatever value is returned from this method is used to update the state of the component. }; } render() { if(this.state.hasError) { return <Text> Something went wrong :( </Text> } return this.props.children; } } export default ErrorBoundary; Right now, whenever an error is thrown in a descendant component, the error will be logged to the console, console.log(error), and an object will be returned from the getDerivedStateFromError method. This will be used to update the state of the ErrorBoundary component with hasError: true. Note getDerivedStateFromError() is called during the “render” phase, so side-effects are not permitted. For those use cases, use componentDidCatch() instead. componentDidCatch(error, info) The componentDidCatch method is also called after an error in a descendant component is thrown. Apart from the error thrown, it passes one more argument which represents more information about the error. In this method, you can send the error or info received to an external logging service. Unlike getDerivedStateFromError, componentDidCatch allows for side-effects: componentDidCatch(error, info) { logComponentStackToMyService(info.componentStack); // logToExternalService may make an API call. } Let’s update the ErrorBoundary component to use the componentDidCatch method: <Text>Something went wrong.</Text>; } return this.props.children; } } Also, since ErrorBoundary can only catch errors from descendant components, we’ll have the component render whatever is passed as children or render a default error UI if something went wrong. Conclusion That’s it. I tried to write this article for both React Native newcomers and developers who are familiar with React Native or React. In case of any questions, feel free to ask me in the comment section below. Below is a short cheat sheet summarising the article and pointing out the principles of each life-cycle method: constructor DO - Assign the initial state to this.state directly - If not using class properties syntax — prepare all class fields and bind functions that will be passed as callbacks DON’T - Cause any side effects (AJAX calls, subscriptions, etc.) - Call setState() - Copy props into state (only use this pattern if you intentionally want to ignore prop updates) render DO - Return a valid Javascript value - The render() function should be pure DON’T - Call setState() componentDidMount DO - Set up subscriptions - Network requests - You may setState() immediately (use this pattern with caution, because it often causes performance issues) DON’T - Call this.setState as it will result in a re-render componentDidUpdate DO - Network requests (e.g. a network request may not be necessary if the props have not changed) - You may call setState() immediately in componentDidUpdate(), but note that it must be wrapped in a condition DON’T - Call this.setState, as it will result in a re-render shouldComponentUpdate DO - Use to increase performance of components DON’T - Cause any side effects (AJAX calls etc.) - Call this.setState componentWillUnmount DO - Remove any timers or listeners created in the lifespan of the component DON’T - Call this.setState, start new listeners or timers static getDerivedStateFromError() DO - Catch errors and return them as state objects DON’T - Cause any side effects componentDidCatch DO - Side effects are permitted - Log errors DON’T - Render a fallback UI with componentDidCatch() by calling setState (use static getDerivedStateFromError() to handle fallback rendering). Related topics More posts by this author
https://www.netguru.com/codestories/react-native-lifecycle
CC-MAIN-2021-21
refinedweb
2,417
54.93
plone.jsonapi.routes 0.2 Plone JSON API -- Routes plone.jsonapi.routes Table of Contents Introduction This is an add-on package for plone.jsonapi.core which provides some basic URLs for Plone standard contents (and more). Motivation The routes package is built on top of the plone.jsonapi.core package to allow Plone developers to build modern (JavaScript) web UIs which communicate through a RESTful API with their Plone site. Compatibility The plone.jsonapi.routes is compatible with Plone 4. Installation The official release is on pypi, so you have to simply include plone.jsonapi.routes to your buildout config. Example: [buildout] ... [instance] ... eggs = ... plone.jsonapi.core plone.jsonapi.routes The routes for the standard Plone content types get registered on startup. API URL After installation, the Plone API routes are available below the plone.jsonapi.core root URL (@@API) with the base /plone/api/1.0, for example. Note Please see the documentation of plone.jsonapi.core for the API root URL. There is also an overview of the registered routes which can be accessed here: API Routes This is an overview of the provided API Routes. The basic content routes provide all an interface for CRUD operations. Important the optional UID of the create, update and delete URLs is to specify the target container where to create the content. If this is omitted, the API expects a parameter parent_uid in the request body JSON. If this is also not found, an API Error will be returned. Request Parameters All GET resources acceppt request parameters. Examples Search all content created by admin Search for all documents created by admin which contain the text Open-Source Response Format The response format is for all resources the same. Example: { url: "", count: 0, _runtime: 0.0021538734436035156, items: [ ] } - url - The resource root url - count - Count of found results - _runtime - The processing time in milliseconds after the request was received until the respone was prepared. - items - An array of result items Content URLs All content informations are dynamically gathered by the contents schema definition through the IInfo adapter. It is possible to define a more specific adapter for your content type to control the data returned by the API. Special URLs Beside the content URLs described above, there are some other resources available in this extension. Write your own API This package is designed to provide an easy way for you to write your own JSON API for your custom Dexterity content types. The plone.jsonapi.example package shows how to do so. Example Lets say you want to provide a simple CRUD JSON API for your custom Dexterity content type. You want to access the API directly from the plone.jsonapi.core root URL (). First of all, you need to import the CRUD functions of plone.jsonapi.routes: from plone.jsonapi.routes.api import get_items from plone.jsonapi.routes.api import create_items from plone.jsonapi.routes.api import update_items from plone.jsonapi.routes.api import delete_items To register your custom routes, you need to import the router module of plone.jsonapi.core. The add_route decorator of this module will register your function with the api framework: from plone.jsonapi.core import router The next step is to provide the a function which get called by the plone.jsonapi.core framework: @router.add_route("/example", "example", methods=["GET"]) def get(context, request): return {} Lets go through this step by step… The @router.add_route(…) registers the decorated function with the framework. So the function will be invoked when someone sends a request to @@API/example. The framework registers the decorated function with the key example. We also provide the HTTP Method GET which tells the framework that we only want to get invoked on a HTTP GET request. When the function gets invoked, the framework provides a context and a request. The context is usually the Plone site root, because this is where the base view (@@API) is registered. The request contains all needed parameters and headers from the original request. At the moment we return an empty dictionary. Lets provide something more useful here: @router.add_route("/example", "example", methods=["GET"]) def get(context, request=None): items = get_items("my.custom.type", request, uid=None, endpoint="example") return { "count": len(items), "items": items, } The get_items function of the plone.jsonapi.routes.api module does all the heavy lifting here. It searches the catalog for my.custom.type contents, parses the request for any additional parameters or returns all informations of the “waked up” object if the uid is given. The return value is a list of dictionaries, where each dictionary represents the information of one result, be it a catalog result or the full information set of an object. Note without the uid given, only catalog brains are returned Now we need a way to handle the uid with this function. Therefore we can simple add another add_route decorator around this function: @router.add_route("/example", "example", methods=["GET"]) @router.add_route("/example/<string:uid>", "example", methods=["GET"]) def get(context, request=None, uid=None): items = get_items("my.custom.type", request, uid=uid, endpoint="example") return { "count": len(items), "items": items, } This function handles now URLs like @@API/example/4b7a1f… as well and invokes the function directly with the provided UID as the parameter. The get_items tries to find the object with the given UID to provide all informations of the waked up object. Note API URLs which contain the UID are automatically generated with the provided endpoint The CREATE, UPDATE and DELETE functionality is basically identical with the basic VIEW function above, so here in short: # CREATE @router.add_route("/example/create", "example_create", methods=["POST"]) @router.add_route("/example/create/<string:uid>", "example_create", methods=["POST"]) def create(context, request, uid=None): items = create_items("plone.example.todo", request, uid=uid, endpoint="example") return { "count": len(items), "items": items, } # UPDATE @router.add_route("/example/update", "example_update", methods=["POST"]) @router.add_route("/example/update/<string:uid>", "example_update", methods=["POST"]) def update(context, request, uid=None): items = update_items("plone.example.todo", request, uid=uid, endpoint="example") return { "count": len(items), "items": items, } # DELETE @router.add_route("/example/delete", "example_delete", methods=["POST"]) @router.add_route("/example/delete/<string:uid>", "example_delete", methods=["POST"]) def delete(context, request, uid=None): items = delete_items("plone.example.todo", request, uid=uid, endpoint="example") return { "count": len(items), "items": items, } See it in action A small tec demo is available on youtube: Changelog 0.2 - 2014-03-05 FIXED ISSUES -: Dexterity support -: Update on UID Urls not working -: Started with some basic browsertests API CHANGES API root url provided. Image and file fields are now rendered as a nested structure, e.g: { data: b64, size: 42, content_type: "image/png" } Workflow info is provided where possible, e.g: { status: "Private", review_state: "private", transitions: [ { url: ".../content_status_modify?workflow_action=submit", display: "Puts your item in a review queue, so it can be published on the site.", value: "submit" }, ], workflow: "simple_publication_workflow" } 0.1 - 2014-01-23 - first public release - Author: Ramon Bartl - License: MIT - Categories - Package Index Owner: ramonski, jdinuncio - DOAP record: plone.jsonapi.routes-0.2.xml
https://pypi.python.org/pypi/plone.jsonapi.routes/0.2
CC-MAIN-2016-30
refinedweb
1,169
50.23
TDDA’s API for Rexpy¶ tdda.rexpy¶ Python API¶ The tdda.rexpy.rexpy module, size=None, seed=None, dialect='portable', of strings, a integer-valued, string-keyed dictionary or a function. - If it’s a list, each string in the list is an example string - It it’s a dictionary (or counter), each string is to be used, and the values are taken as frequencies (should be non-negative) - If it’s a function, it should be as specified below (see the definition of example_check_function) - size can be provided as: - a Size() instance, to control various sizes within rexpy - None (the default), in which case rexpy’s defaults are used - False or 0, which means don’t use sampling_fragments(vrle, v_id)¶ Analyse the contents of each fragment in vrle across the examples it matches. Return zip of - the characters in each fragment - the strings in each fragment - the run-length encoded fine classes in each fragment - the run-length encoded characters in each fragment - the fragment itself all indexed on the (zero-based) group number. build_tree_inner(vrles, fulls=None)¶ Turn the VRLEs into a tree based on the different initial fragments. check_for_failures(rexes, maxExamples)¶ This method is the default check_fn (See the definition of example_check_function below.)_bad_patterns(freqs)¶ Given freqs, a list of frequencies (for the corresponding indexed RE) identify indexes to patterns that: - have too few strings - cause too many patterns to be returned NOTE: min_diff_strings_per_pattern is currently ignored. Returns set of indices for deletion find_frag_sep_frag_repeated(tree, existing=None, results=None)¶ This specifically looks for patterns in the tree constructed by self.build_tree of the general formA ABA ABABA etc., where A and B are both fragments. A common example is that A is recognizably a pattern and B is recognizably a separator. So, for example: HM MH-RT QY-TR-BF QK-YT-IU-QP all fit [A-Z]{2}(-[A-Z])* which, as fragments, would be A = (C, 2, 2) and B = (‘.’, 1, 1). The tree is currently not recording or taking account of frequency in the fragments. We might want to do that. Or we might leave that as a job for whatever is going to consolidate the different branches of the tree that match the repeating patterns returned. find_non_matches(rexes)¶ Returns all example strings that do not match any of the regular expressions in results, together with their frequencies. fragment2re(fragment, tagged=False, as_re=True, output=False)¶ Convert fragment to RE. If output is set, this is for final output, and should be in the specified dialect (if any). in the sort order._fragments(vrle, v_id)¶ Refine the categories for variable-run-length-encoded pattern (vrle) provided by narrowing the characters in each fragment.). specialize(patterns)¶ Check all the catpure groups in each patterns and simplify any that are sufficiently low frequency. vrle2re(vrles, tagged=False, as_re=True, output=False)¶ Convert variable run-length-encoded code string to regular expression If output is set, this is for final output, and should be in the specified dialect (if any). - class tdda.rexpy.rexpy. Fragment¶ Container for a fragment. Attributes: re: the regular expression for the fragment group: True if it forms a capture group (i.e. is not constant) - class tdda.rexpy.rexpy. IDCounter¶ Rather Like a counter, but also assigns a numeric ID (from 1) to each key and actually builds the counter on that. Use .add to increment an existing key’s count, or to initialize it to (by default) 1. Get the key’s ID with .ids[key] or .keys.get(key). - class tdda.rexpy.rexpy. PRNGState(n)¶ Seeds the Python PRNG and after captures its state. restore() cam be used to set them back to the captured state. tdda.rexpy.rexpy. capture_group(s)¶ Places parentheses around s to form a capure group (a tagged piece of a regular expression), unless it is already a capture group. tdda.rexpy.rexpy. escaped_bracket(chars, dialect=None, inner=False)¶ Construct a regular expression Bracket (character class), obeying the special regex rules for escaping these: - Characters do not, in general need to be escaped - If there is a close bracket (“]”) it mst be the first character - If there is a hyphen (“-”) it must be the last character - If there is a carat (“^”), it must not be the first character - If there is a backslash, it’s probably best to escape it. Some implementations don’t require this, but it will rarely do any harm, and most implementation understand at least some escape sequences (“w”, “W”, “d”, “s” etc.), so escaping seems prudent. However, javascript and ruby do not follow the unescaped “]” as the first character rule, so if either of these dialects is specified, the “]” will be escaped (but still placed in the first position. If inner is set to True, the result is returned without brackets. tdda.rexpy.rexpy. example_check_function(rexes, maxN=None)¶ CHECK FUNCTIONS This is an example check function A check function takes a list of regular expressions (as strings) and optionally, a maximum number of (different) strings to return. It should return two things: - An Examples object (importing that class from rexpy.py) containing strings that don’t match any of the regular expressions in the list provided. (If the list is empty, all strings are candidates to be returned.) - a list of how many strings matched each regular expression provided (in the same order). If maxN is None, it should return all strings that fail to match; if it is a number, that is the maximum number of (distinct) failures to return. The function is expected to return all failures, however, if there are fewer than maxN failures (i.e., it’s not OK if maxN is 20 to return just 1 failiing string if actually 5 different strings fail.) Examples: The examples object is initialized with a list of (distinct) failing strings, and optionally a corresponding list of their frequencies. If no frequencies are provided, all frequencies will be set to 1 when the Examples object is initialized. The regular expression match frequencies are used to eliminate low-frequency or low-ranked regular expressions. It is not essential that the values cover all candidate strings; it is enough to give frequencies for those strings tested before maxN failures are generated. (Normally, the regular expressions provided will be exclusive, i.e. at most one will match, so it’s also fine only to test a string against regular expressions until a match is found…you don’t need to test against other patterns in case the string also matches more than one.), size=None, seed=None, dialect='portable',, examples, sort_on_deduped=False)¶ Find patterns, in (descending) order of # of matches, and pull out freqs. Then set overlapping matches to zero and repeat. Returns ordered dict, sorted by incremental match rate, with number of (previously unaccounted for) strings matched. tdda.rexpy.rexpy. pdextract(cols, seed=None)¶ Extract regular expression(s) from the Pandas column ( Series) object or list of Pandas columns given. All columns provided should be string columns (i.e. of type np.dtype(‘O’), possibly including null values, which will be ignored. Example use: import numpy as np import pandas as pd from tdda.rexpy import pdextract df = pd.DataFrame({'a3': ["one", "two",, examples,, examples, sort_on_deduped, examples, sort_on_deduped.
https://tdda.readthedocs.io/en/v2.0.02/rexpy-api.html
CC-MAIN-2022-40
refinedweb
1,206
53.21
a side-by-side reference sheet sheet one: grammar and invocation | variables and expressions | arithmetic and logic | strings | regexes dates and time | arrays | dictionaries | functions | execution control sheet two: file handles | files | directories | processes and environment | libraries and namespaces | objects | reflection net and web | unit tests | debugging and profiling | java interop | contact sheet two: file handles | files | directories | processes and environment | libraries and namespaces | objects | reflection net and web | unit tests | debugging and profiling | deployment General versions used The versions used for testing code in the reference sheet. show version How to get the version. php: The function phpversion() will return the version number as a string. perl: Also available in the predefined variable $], or in a different format in $^V and $PERL_VERSION. python: The following function will return the version number as a string: import platform platform.python_version() ruby: Also available in the global constant VERSION (Ruby 1.8) or RUBY_VERSION (Ruby 1.9). implicit prologue Code which examples in the sheet assume to have already been executed. perl: We adopt the convention that if an example uses a variable without declaring it, it should be taken to have been previously declared with my. python: We assume that os, re, and sys are always imported. Grammar and Invocation REPL does not save or display the result of an expression. php -a offers a different style of interactive mode. It collects input until EOF is encountered and then it executes it. Text inside <? code ?> and <?= code ?> is executed as PHP code. Text outside of PHP markup tags is echoed. perl: The Perl REPL perl -de 0 does not save or display the result of an expression. perl -d is the Perl debugger and perl -e runs code provided on the command line. perl -de 0 does not by default have readline, but it can be added: $ cpan -i Term::Readline::Perl <cpan output omitted> $ perl -de 0 DB<1> use Term::Readline::Perl; DB<2> print 1 + 1; 2. perl: Curly brackets {} delimit blocks. They are also used for: - hash literal syntax which returns a reference to the hash: $rh = { 'true' => 1, 'false' => 0 } - hash value lookup: $h{'true'}, $rh->{'true'} - variable name delimiter: $s = "hello"; print "${s}goodbye"; ?> perl: In a script statements are separated by semicolons and never by newlines. However, when using perl -de 0 a newline terminates the statement.. perl: Variables don't need to be declared unless use strict is in effect. If not initialized, scalars are set to undef, arrays are set to an empty array, and hashes are set to an empty hash. Perl can also declare variables with local. These replace the value of a global variable with the same name, if any, for the duration of the enclosing scope, after which the old value is restored.. perl: A local variable can be defined outside of any function definition or anonymous block, in which case the scope of the variable is the file containing the source code. In this way Perl resembles Ruby and contrasts with PHP and Python. In PHP and Python, any variable defined outside a function definition is global. In Perl, when a region which defines a scope is nested inside another, then the inner region has read and write access to local variables defined in the outer region. Note that the blocks associated with the keywords if, unless, while, until, for, and foreach are anonymous blocks, and thus any my declarations in them create variables local to the block.: Note that though the keywords if, unless, case, while, and until each define a block which is terminated by an end keyword, In Ruby 1.8, the scope of the parameter of an anonymous block or function or block is local to the block or function body if the name is not already bound to a variable in the containing scope. However, if it is, then the variable in the containing scope will be used. This behavior was changed in Ruby 1.9 so that parameters are always local to function body or block. Here is an example of code which behaves differently under Ruby 1.8 and Ruby 1.9: x = 3 id = lambda { |x| x } id.call(7) puts x # 1.8 prints 7; 1.9 prints 3 Ruby 1.9 also adds the ability mark variables as local, even when they are already defined in the containing scope. All such variables are listed inside the parameter pipes, separated from the parameters by a semicolon: x = 3 noop = lambda { |; x| x = 15 } # bad syntax under 1.8. perl: Undeclared variables, which are permitted unless use strict is in effect, are global. If use strict is in effect, a global can be declared at the top level of a package (i.e. outside any blocks or functions) with the our keyword. A variable declared with my inside a function will hide a global with the same name, if there is one.. perl: Assignment operators have right precedence and evaluate to the right argument, so assignments can be chained: $a = $b = 3; any--; perl:"; } perl: $v == undef does not imply that $v is undef. Any comparison between undef and a falsehood will return true. The following comparisons are true: $v = undef; if ($v == undef) { print "true"; } $v = 0; if ($v == undef) { print "sadly true"; } $v = ''; if ($v == undef) { print "sadly true"; } undefined variable access The result of attempting to access an undefined variable. php: PHP does not provide the programmer with a mechanism to distinguish an undefined variable from a variable which has been set to NULL. A test showing that isset is the logical negation of is_null. perl: Perl does not distinguish between unset variables and variables that have been set to undef. In Perl, calling defined($a) does not result in a error if $a is undefined, even with the strict pragma., perl,. perl: The operators: == != > < >= <= convert strings to numbers before performing a comparison. Many string evaluate as zero in a numeric context and are equal according to the == operator. To perform a lexicographic string comparison, use: eq, ne, gt, lt, ge, le. compare strings How to compare strings.. perl: The integer pragma makes all arithmetic operations integer operations. Floating point numbers are truncated before they are used. Hence integer division could be performed with: use integer; my $a = 7 / 3; no integer;. perl: The CPAN module Number::Format provides a round function. The 2nd argument specifies the number of digits to keep to the right of the radix. The default is 2. use Number::Format 'round'; round(3.14, 0); 1.9 base conversion How to convert integers to strings of digits of a given base. How to convert such strings into integers. perl Perl has the functions oct and hex which convert strings encoded in octal and hex and return the corresponding integer. The oct function will handle binary or hex encoded strings if they have "0b" or "0x" prefixes. oct("60") oct("060") oct("0b101010") oct("0x2a") hex("2a") hex("0x2a"). perl: Perl has supported multibyte characters since version 5.6. python: In Python 2.7 the str type assumes single byte characters. A separate unicode type is available for working with Unicode strings. In Python 3 the str type supports multibtye characters and the unicode type has been removed. ruby: In Ruby 1.8 the String type assumes single byte characters. In Ruby 1.9 the String type supports multibtye characters. Furthermore, all strings have an explicit Encoding. string literal The syntax for string literals. perl: When use strict is not in effect bareword strings are permitted. Barewords are strings without quote delimiters. They are a feature of shells. Barewords cannot contain whitespace or any other character used by the tokenizer to distinguish words. Before Perl 5 subroutines were invoked with an ampersand prefix & or the older do keyword. With Perl 5 neither is required, but this made it impossible to distinguish a bareword string from a subroutine without knowing all the subroutines which are in scope. The following code illustrates the bareword ambiguity: no strict; print rich . "\n"; # prints "rich"; rich is a bareword string sub rich { return "poor" } print rich . "\n"; # prints "poor"; rich is now a subroutine. perl: In addition to the character escapes, Perl has the following translation escapes: When use charnames is in effect the \N escape sequence is available: binmode(STDOUT, ':utf8'); use charnames ':full'; print "lambda: \N{GREEK SMALL LETTER LAMDA}\n"; use charnames ':short'; print "lambda: \N{greek:lamda}\n"; use charnames qw(greek); print "lambda: \N{lamda}\n";' custom delimiters How to specify custom delimiters for single and double quoted strings. These can be used to avoid backslash escaping. If the left delimiter is (, [, or { the right delimiter must be ), ], or }, respectively. here document Here documents are strings terminated by a custom identifier. They perform variable substitution and honor the same backslash escapes as double quoted strings. perl: Put the custom identifer in single quotes to prevent variable interpolation and backslash escape interpretation: s = <<'EOF'; Perl code uses variables with dollar signs, e.g. $var EOF())) format. perl: An example of how to trim a string without installing a library: $s = " lorem "; $s =~ s/^\s*(.*)\s*$/\1/; The return value of the =~ operator is boolean, indicating whether a match occurred. Also the left hand side of the =~ operator must be a scalar variable that can be modified. Using the =~ operator is necessarily imperative, unlike the Text::Trim functions which can be used in expressions.. perl: Perl. extract character How to extract a character from a string by its - perlre and perlreref - hypen and Perl use the m modifer. Python uses the re.M flag. Ruby usse the s modifer. Perl and a hex digit in Ruby. Similarly \H refers to something that isn't horizontal whitespace in PHP and Perl. perl: The =~ operator performs the substitution in place on the string and returns the number of substitutions performed. The g modifiers specifies that all occurrences should be replaced. If omitted, only the first occurrence. perl: The special variables $&, $`, and $' also contain the match, prematch, and postmatch.. perl: Perl 5.10 added support for both Python-stye and Perl-style named groups. probably more useful than one which contains just date information or just time information; it is unfortunate that ISO 8601 doesn't provide a name for this entity. The word timestamp often gets used to denote a combined date and time. PHP and Python use the compound noun datetime for combined date and time values. An useful property of ISO 8601 dates, times, and date/time combinations is that they are correctly ordered by a lexical sort on their string representations. This is because they are big-endian (the year is the leftmost element) and they used fixed-length fields for each term in the string representation. The C standard library provides two methods for representing dates. The first is the UNIX epoch, which is the seconds since January 1, 1970 in UTC. If such a time were stored in a 32-bit signed integer, the rollover would happen on January 18, 2038. The other method of representing dates */ }; Perl and Python both use and expose the tm struct of the standard library. In the case of Perl, the first nine values of the struct (up to the member tm_isdst) are put into an array. Python, meanwhile, has a module called time which is a thin wrapper to the standard library functions which operate on this struct. Here is how get a tm struct in Python: import time utc = time.gmtime(time.time()) t = time.localtime(time.time()) The tm struct is a low level entity, and interacting with it directly should be avoided. In the case of Python it is usually sufficient to use the datetime module instead. For Perl, one can use the Time::Piece module to wrap the tm struct in an object. date/time type The data type used to hold a combined date and time. perl Built in Perl functions work with either (1) scalars containing the Unix epoch as an integer or (2) arrays containing the first nine values of the standard C library tm struct. When use Time::Piece is in effect functions which work with tm arrays are replaced with variant that work with the Time::Piece wrapper. The modules Time::Local and Date::Parse can create scalars containing the Unix epoch. CPAN provides the DateTime module which provides objects with functionality comparable to the DateTime objects of PHP and Python. current date/time How to get the combined date and time for the present moment in both local time and UTC. to unix epoch, from unix epoch How to convert the native date/timezone. current unix epoch How to get the current time as a Unix epoch timestamp. strftime How to format a date/time as a string using the format notation of the strftime function from the standard C library. This same format notation is used by the Unix date command. php: PHP supports strftime but it also has its own time formatting system used by date, DateTime::format, and DateTime::createFromFormat. The letters used in the PHP time formatting system are described here. default format example Examples of how a date/time object appears when treated as a string such as when it is printed to standard out. The formats are in all likelihood locale dependent. The provided examples come from a machine running Mac OS X in the Pacific time zone of the USA. php: It is a fatal error to treat a DateTime object as a string. strptime How to parse a date/time using the format notation of the strptime function from the standard C library. parse date w/o format How to parse a date without providing a format string. result date subtraction The data type that results when subtraction is performed on two combined date and time values. add time duration How to add a time duration to a date/time. A time duration can easily be added to a date/time value when the value is a Unix epoch value. ISO 8601 distinguishes between a time interval, which is defined by two date/timezone Do date/time values include timezone information. When a date/time value for the local time is created, how the local timezone is determined. A date/time value can represent a local time but not have any timezone information associated with it. On Unix systems processes determine the local timezone by inspecting the file /etc/localtime. php: The default timezone can also be set in the php.ini file. date.timezone = "America/Los_Angeles" Here is the list of timezones supported by PHP. arbitrary timezone How to convert a timestamp to the equivalent timestamp in an arbitrary timezone. timezone name, offset from UTC, is daylight savings? How to get time zone information: the name of the timezone, the offset in hours from UTC, and whether the timezone is currently in daylight savings. Timezones are often identified by three or four letter abbreviations. As can be seen from the list, many of the abbreviations do not uniquely identify a timezone. Furthermore many of the timezones have been altered in the past. The Olson database (aka Tz database) decomposes the world into zones in which the local clocks have all been set to the same time since 1970 and it gives these zones unique names. perl: It is not necessary to create a DateTime object to get the local timezone offset: use Time::Piece; $t = localtime(time); $offset_hrs = $t->tzoffset / 3600; ruby: The Time class has a zone method which returns the time zone abbreviation for the object. There is a tzinfo gem which can be used to create timezone objects using the Olson database name. This can in turn be used to convert between UTC times and local times which are daylight saving aware.); perl: The Perl standard library includes a version of sleep which supports fractional seconds: use Time::HiRes qw(sleep); sleep 0.5; timeout How to cause a process to timeout if it takes too long. Techniques relying on SIGALRM only work on Unix systems. Arrays What the languages call their basic container types: php: PHP uses the same data structure for arrays and dictionaries. perl: array refers to a data type. list refers to a context.. perl: Square brackets create an array and return a reference to it: $a = [1,2. perl: A negative index refers to the length - index element. refererenced. index of array element perl: Some techniques for getting the index of an array element. slice How to slice a subarray from an array by specifying a start index and an end index; how to slice a subarray from an array by specifying an offset index and a length index. perl: Perl arrays can take an array of indices as the index value. The range of values selected can be discontinuous and the order of the values can be manipulated: @nums = (1,2,3,4,5,6); @nums[(1,3,2,4)];. perl: Taking a reference is customary way to make an address copy in Perl, but the Perl example is not equivalent to the other languages in that different syntax has to be used to access the original array and the address copy: @a and @$a1. To make @a1 and @a refer to the same array, use typeglobs: *a1 = *a;. arrays as function arguments How arrays are passed as arguments. iteration How to iterate through the elements of an array. perl: for and foreach are synonyms. Some use for exclusively for C-style for loops and foreach for array iteration. indexed iteration How to iterate through the elements of an array while keeping track of the index of each element. iterate over range Iterate over a range without instantiating it as a list. perl: With Perl 5.005 the for and foreach operators were optimized to not instantiate a range argument = array("b", "A", "a", "B"); usort($a, "cmp"); = array(1, 2, 3, 4); $sample = array(); foreach (array_rand($a, 2) as $i) { array_push($sample, $a[$i]); } zip How to interleave arrays. In the case of two arrays the result is an array of pairs or an associative list. perl: zip expects arrays as arguments, which makes it difficult to define the arrays to be zipped on the same line as the invocation. It can be done like this: @a = zip @{[1,2,3]}, @{['a','b','c']}; Dictionaries literal perl: Curly brackets create a hash and return a reference to it: $h = { 'hello' => 5, 'goodbye' => 7 } size How to get the number of dictionary keys in a dictionary. lookup How to lookup a dictionary value using a dictionary key. perl: Use the ampersand prefix @ to slice a Perl hash. The index is a list of keys. %nums = ('b'=>1, 't'=>2, 'a'=>3); @nums{('b','t')} out-of-bounds entry sort the data in a dictionary by its(); perl: How to use a tied hash. If the CPAN module Tie::ExtraHash is installed there is a shorter way. Functions Python has both functions and methods. Ruby only has methods: functions defined at the top level are in fact methods on a special main object. Perl subroutines can be invoked with a function syntax or a method syntax. define function How to define a function. perl: One can also use shift to put the arguments into local variables: sub add { my $a = shift; my $b = shift; $a + $b; } invoke function. As of Ruby 1.9, How incorrect number of arguments upon invocation are handled. perl: Perl collects all arguments into the @_ array, and subroutines normally don't declare the number of arguments they expect. However, this can be done with prototypes. Prototypes also provide a method for taking an array from the caller and giving a reference to the array to the callee. default value How to declare a default value for an argument. variable number of arguments pass number or string by reference How to pass numbers or strings by reference. The three common methods of parameter passing are pass by value, pass by reference, and pass by address. Pass by value is the default in most languages. When a parameter is passed by reference, the callee can changed the value in the variable that was provided as a parameter, and the caller will see the new value when the callee returns. When the parameter is passed by value the callee cannot do this. When a language has mutable data types it can be unclear whether the language is using pass by value or pass by reference. perl: Here is a potential for confusion: if a reference is used in Perl to pass data, that is pass by address, not pass by reference. A Perl reference is comparable to a pointer in C, albeit one that knows the data type of what it points to at runtime. C++ has both pointers and references and thus can pass data by address or by reference, though pass by value is the default. pass array or dictionary by reference How to pass an array or dictionary without making a copy of it. perl: Arrays and hashes are not passed by reference by default. If an array is provided as a argument, each element of the array will be assigned to a parameter. A change to the parameter will change the corresponding value in the original array, but the number of elements in the array cannot be increased. To write a function which changes the size of the array the array must be passed by reference using the backslash notation. When a hash is provided as a argument each key of the has will be assigned to a parameter and each value of the hash will be assigned to a parameter. In other words the number of parameters seen by the body of the function will be twice the size of the hash. Each value parameter will immediately follow its key parameter. return value How the return value of a function is determined. multiple return values How to return multiple values from a function. lambda declaration and invocation How to define and invoke 1.9 introduces new syntax for defining lambdas and invoking them: sqr = ->(x) {x*x} sqr.(2). perl: CPAN provides a module called Coro which implements coroutines. Some notes on the distinction between coroutines and generators. python: Python generators can be used in for/in statements and list comprehensions.. operator as function How to call an operator using the function invocation syntax. This can if statement. php: PHP has the following alternate syntax for if statements: if ($n == 0): echo "no hits\n"; elseif ($n == 1): echo "one hit\n"; else: echo "$n hits\n"; endif; perl: When an if block is the last statement executed in a subroutine, the return value is the value of the branch that executed. ruby: If an if statement is the last statement executed in a function, the return value is the value of the branch that executed. Ruby if statements are expressions. They can be used on the right hand side of assignments: m = if n 1 else 0 end switch The switch statement. while php: PHP provides a do-while loop. The body of such a loop is guaranteed to execute at least once. $i = 0; do { echo $i; } while ($i > 0); perl: Perl provides until, do-while, and do-until loops. An until or a do-until loop can be replaced by a while or a do-while loop by negating the condition. ruby: Ruby provides a loop with no exit condition: def yes(expletive="y") loop do puts expletive end end Ruby also provides the until loop. Ruby loops can be used in expression contexts but they always evaluate to nil. c-style for How to write a C-style for loop. break, continue, redo break exits a for or while loop immediately. continue goes to the next iteration of the loop. redo goes back to the beginning of the current iteration. control structure keywords A list of control structure keywords. The loop control keywords from the previous line are excluded. The list summarizes the available control structures. It excludes the keywords for exception handling, loading libraries, and returning from functions. what do does How the do keyword is used. perl: The do keyword can convert an if statement to a conditional expression: my $m = do { if ($n) { 1 } else { 0 } }; statement modifiers Clauses added to the end of a statement to control execution. Perl and Ruby have conditional statement modifers. Ruby also has looping statement modifers. ruby: Ruby has the looping statement modifiers while and until: i = 0 i += 1 while i < 10 j = 10 j -= 1 until j < 0 raise exception How to raise exceptions. ruby: Ruby has a throw keyword in addition to raise. throw can have a symbol as an argument, and will not convert a string to a RuntimeError exception.. catch exception global variable for last exception The global variable name for the last exception raised. define exception How to define a new variable class. catch exception by type How to catch exceptions of a specific type and assign the exception a name. php: PHP exceptions when caught must always be assigned a variable name. finally/ensure Clauses that are guaranteed to be executed even if an exception is thrown or caught. start thread ruby: Ruby 1.8 threads are green threads, and the interpreter is limited to a single operating system thread. wait on thread How to make a thread wait for another thread to finish. Perl The first character of a Perl variable $ @ % determines the type of value that can be stored in the variable: scalar, array, hash. Using an array variable @foo in a scalar context yields the size of the array, and assigning a scalar to an array will modify the array to contain a single element. $foo[0] accesses the first element of the array @foo, and $bar{'hello'} accesses the value stored under 'hello' in the hash %bar. $#foo is the index of the last element in the array @foo. Scalars can store a string, integer, or float. If an operator is invoked on a scalar which contains an incorrect data type, perl will perform an implicit conversion to the correct data type: non-numeric strings evaluate to zero. Scalars can also contain a reference to a variable, which can be created with a backslash: $baz = \@foo; The original value can be dereferenced with the correct prefix: @$baz. References are how perl creates complex data structures, such as arrays of hashes and arrays of arrays. If $baz contains a reference to an array, then $baz->[0] is the first element of the array. if $baz contains a reference to a hash, $baz->{'hello'} is the value indexed by 'hello'. The literals for arrays and hashes are parens with comma separated elements. Hash literals must contain an even number of elements, and the => operator can be used in placed of a comma between a key and its value. Square brackets, e.g. [1, 2, 3], create an array and return a reference to it, and curly brackets, e.g. {'hello' => 5, 'bye' => 3} , create a hash and return a reference to it. By default Perl variables are global. They can be made local to the containing block with the my keyword or the local keyword. my gives lexical scope, and local gives dynamic scope. Also by default, the perl interpreter creates a variable whenever it encounters a new variable name in the code. The use strict; pragma requires that all variables be declared with my, local, or our. The last is used to declare global variables. Perl functions do not declare their arguments. Any arguments passed to the function are available in the @_ array, and the shift command will operate on this array if no argument is specified. An array passed as an argument is expanded: if the array contains 10 elements, the callee will have 10 arguments in its @_ array. A reference (passing \@foo instead of @foo) can be used to prevent this. Some of Perl’s special variables: - $$: pid of the perl process - $0: name of the file containing the perl script (may be a full pathname) - $@: error message from last eval or require command - $& $` $’: what last regex matched, part of the string before and after the match - $1 … $9: what subpatterns in last regex matched Why Python3 Summary of Backwardly Non-compatible Changes in Python 3 3.2: Language, Standard Library Python uses leading whitespace to indicate block structure. It is not recommended to mix tabs and spaces in leading whitespace, but when this is done, a tab is equal to 8 spaces. The command line options '-t' and '-tt' will warn and raise an error respectively when tabs are used inconsistently for indentation. Regular expressions and functions for interacting with the operating system are not available by default and must be imported to be used, i.e. import re, sys, os Identifiers in imported modules must be fully qualified unless imported with from/import: from sys import path from re import * There are two basic sequence types: the mutable list and the immutable tuple. The literal syntax for lists uses square brackets and commas [1,2,3] and the literal syntax for tuples uses parens and commas (1,2,3). The dictionary data type literal syntax uses curly brackets, colons, and commas { “hello”:5, “goodbye”:7 }. Python 3 adds a literal syntax for sets which uses curly brackets and commas: {1,2,3}. This notation is also available in Python 2.7. Dictionaries and sets are implemented using hash tables and as a result 1.8.7 core, stdlib 1.9.3 core, stdlib Ruby has a special. In Ruby 1.8 the arguments of the block are local to the block unless the variables were already in use in the enclosing scope. In Ruby 1.9 this was changed so that block arguments are always local to the block. In addition Ruby 1.9 add semicolon syntax.
http://hyperpolyglot.org/scripting/
CC-MAIN-2013-20
refinedweb
5,026
64.2
JSF 2.0 New Feature Preview Series (Part 4) Resource Re-location Thursday Jun 26, 2008 This is the sixth entry in the JSF 2.0 New Feature Preview Series. The last entry covered the new event system. For this entry, we'll cover resource re-location. The driving force behind this feature is to simplify development of pages. A page author shouldn't need to know what resources a particular component needs. The Tomahawk component set does this by having the user install a Filter that post-processes the response produced by JSF. This solution doesn't scale all that well as the entire response needs to be buffered, parsed, manipulated and then rendered out. Building off the new resource and event systems, we can avoid doing this and allow resources to be placed where they should be (e.g. stylesheet and script references within the head element).: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns: <h:head <title>resourcereslocation</title> </h:head> <h:body <h:form <h:outputScript <h:outputText <h:outputStylesheet </h:form> </h:body> </html>: <html xmlns=""> <head> <title>resourcereslocation</title> <link type="text/css" rel="stylesheet" href="/ctx/faces/javax.faces.resource/simple.css" /> </head> <body> <form id="form" name="form" method="post" action="..." enctype="..."> <script type="text/javascript" src="/ctx/faces/javax.faces.resource/simple.js"></script> hello </form> </body> </html> Issue the same request, this time with a request parameter location=head: <html xmlns=""> <head> <title>resourcereslocation</title> <link type="text/css" rel="stylesheet" href="/ctx/faces/javax.faces.resource/simple.css" /> <script type="text/javascript" src="/ctx/faces/javax.faces.resource/simple.js"></script> </head> <body> <form id="form" name="form" method="post" action="..." enctype="..."> hello </form> </body> </html> Then issue the request again this time with the request parameter value equal to body: <html xmlns=""> <head> <title>resourcereslocation</title> <link type="text/css" rel="stylesheet" href="/ctx/faces/javax.faces.resource/simple.css" /> </head> <body> <form id="form" name="form" method="post" action="..." enctype="..."> hello </form> <script type="text/javascript" src="/ctx/faces/javax.faces.resource/simple.js"></script> </body> </html> Notice that the style sheet render ignores the target attribute and always renderes the link within the head - as it should! Recall how I said that page authors shouldn't have to know what resources a component needs? Well, the above examples only get you so far. It would be tedious if using a third party component set would require you to use different h:outputScript or h:outputStylesheet references depending on which component was being used. So the 2.0 specification has added:.@ListenerFor(systemEventClass=AfterAddToParentEvent.class, sourceClass=UIOutput.class) public class Script); } } . . . } Well, I think that about covers it. I had initially thought this blog was going to be quick and easy, but it kinda snowballed it seems. I hope this all made sense. If not, please leave comments with questions and I'll do my best to clarify. It is a great entry. I hope we are also planning... This is excellent. You mentioned: &... @Rahul: Skinning is on the list of things to ... If I create a web app for desktop and mobile users... I believe this type of situation is why there shou... Oh, like using layout managers instead of HTML mar...
http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature4
crawl-002
refinedweb
551
51.24
Intro to Rails Engines I have recently been hearing quite a bit about people using Rails engines. I was intrigued about how they are used and how they integrate into a Rails application, and I soon got a chance to satisfy my curiosity by working on a couple projects that used these engines. Here I will talk a little about what Rails engines are used for and how they are integrated into a Rails application. What’s a Rails Engine? So the first question you may be asking is, what the heck is a Rails engine, anyway? In short, it allows you to wrap up a Rails application or a subset of its functionality in a way that makes it easy to share it with other applications. This plug-and-play sort of functionality is quite similar to how Ruby gems work. In fact, prior to Rails 3.0, all Ruby gems automatically behaved as engines, and since Rails 3.0 all Rails applications are just engines. And just like a Rails application, a Rails engine is also a Railtie, so it has access to rake tasks and generators that can be used in the engine. Since Rails 3.0 has come out, if you want a gem to automatically behave as a Rails engine, you have to define an engine somewhere inside of the gem’s lib folder. module MyEngine class Engine < Rails::Engine end end Types of Engines When creating a Rails engine, there is one special thing to take note of, and this is the difference between a full engine and a mountable one. In a full engine, the parent application inherits all of the routes defined in the engine, so it is not necessary to define anything in parent/config/routes.rb. Simply specifying the Engine in the gem file of the parent application is enough for it to have access to all of the engines models, controllers, routes, etc. For a mountable engine, its namespace is isolated by default: module MyEngine class Engine < Rails::Engine isolate_namespace MyEngine end end The routes of the engines are namespaces and it needs to be mounted in the parent app’s routes file to be used. Parent::Application.routes.draw do mount MyEngine::Engine => '/engine', as: 'my_engine' end Helpers Once you have your engine mounted inside of the parent application, some helpers are defined to help specify the routes. Inside of the parent app above there would he a helper named ‘my_engine’ that would allow you to access its routes like: my_engine.root_url From the engine, there is also a helper named ‘main_app’ that is defined that allows the engine to access the parent app’s routes. MIGRATIONS AND SEEDING DATA The parent application also needs to be able to install the migrations from the Rails engine. In order to copy over the migration files from the engine to the parent app you can run: rake MyEngine:install:migrations A migration would be skipped if one with the same name already exists within the application. Once the migrations have been copied over they can be loaded by running rake db:migrate If the engine has any seed data in the db/seeds.rb file it can be loaded by running MyEngine::Engine.load_seed tests Finally, testing a Rails engine is a little different than just testing a Rails application. Inside of your test directory there is a dummy app, which is a Rails application that is used during testing. Your engine is automatically loaded into the dummy app and all of your tests are run from the dummy app’s environment. If you find it necessary, you can generate controllers, models or views in the dummy app to use while testing your engine. Special consideration must be taken when writing controller tests. Since the requests are going through the dummy application you need to be more specific when using the get, post, etc. methods. This is where the :use_route option comes in for in these methods. get :index, use_route: :my_engine This will perform a get request to the index action of the controller, but it specifies that you want to use the routes from my_engine to get there rather than those in the dummy application. summary Working with Rails engines has been an insightful experience and I have learned quite a bit about how they work. It is always fun to find out about new technologies to use, and I’m looking forward to continuing my exploration of Rails Engines and finding uses for them in my future projects. Resources: Rails Api Railscast
http://www.bignerdranch.com/blog/intro-to-rails-engines/
CC-MAIN-2014-52
refinedweb
764
67.08
I just installed the latest Intel 13 comipiler on MAC OSX but it crashes when run. Any suggestionswhat might be wrong? Here the details: lyngby:~ root# icc -V Intel(R) C Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 13.0.3.198 Build 20130606 lyngby:~ root# cat test.c int main() { return ( 1 ); } lyngby:~ root# icc test.c -o test Segmentation fault: 11 As my example icc test.c -o test all options are shown. This cause a segmentation fault and I assume the code 11 is related to that fault. From it is in my initial post you can do exactly what I did. Maybe there something special about computer but it is a fairly new machine running OSX 10.8. Sergey Kostrov wrote: >>...Segmentation fault: 11 What compiler options did you use? Also, could you take a look at a MAC OSX API manual for a description of error code 11? POSIX signal 11 is SIGSEGV, a.k.a segmentation fault a.k.a invalid memory reference. I do agree that the compiler must generate a segmentation fault. I have seen that on other systems when I run Intel C as nonroot the first time. But in this case I run it as root. But guess no one has clue what the issue is then. It should work on OSX 10.8 I suppose? In fact when I run icc under gdb I get (gdb) run test.c Starting program: /usr/bin/icc test.c Reading symbols for shared libraries ++++.................................. done Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000 0x000000010006caf9 in target_mac_requires_clang () (gdb) Can you post a reply with the output from these two commands? xcodebuild -version xcode-select -print-path Hi Erling, I can't reproduce this. Jeff's questions are appropriate, so if you could answer those, that would be great. I'm following up with our driver developer as well to see if there's anything he can speculate further on. Now I know what the issue is. When I run xcodebuild -version xcode asks me to accept some license agreements. After I havde done that things works. I never use the commandline version of xcode except when called from Intel. I know it is an xcode stupidity you most likly do not detect but may you could. Thanks, Erling, for that information. That was what we thought might be happening after looking at the code pointed to by your gdb traceback. Yes, the compiler will be modified to be to be more robust.
https://community.intel.com/t5/Intel-C-Compiler/Crash-of-latest-13-compiler-on-OSX-10-8/td-p/973803
CC-MAIN-2020-40
refinedweb
430
77.53
You can click on the Google or Yahoo buttons to sign-in with these identity providers, or you just type your identity uri and click on the little login button. Pascal Meunier reported... files hierarchy -module_a \-a.py -b.py -__init__.py b.py: from module_a.a import my_class a.py contains a syntax error. $ pylint module_a/b.py No config file found, using default configuration ************* Module module_a.b C: 1: Missing docstring E: 1: No name 'a' in module 'module_a' W: 1: Unused import my_class Which I took to mean that there was no file a.py inside the directory "module_a" or some problem with the filesystem or the names... The problem was quite different (a syntax error in a.py). The Python error message is just as misleading. I was scrambling for quite a while trying to find out what was wrong in the filesystem or the names I had given to the files. I think that a Python syntax error inside a file should generate something more appropriate and helpful than something that sounds like the claim that there is no such file! I understand now that the syntax error prevented the name from appearing in the namespace, so from that oblique point of view the error message is correct. However, why on earth not report syntax errors as such? I found no option to increase the verbosity of PyLint. next step is to report the syntax error, but already no more "No name 'a' in module 'module_a'" message Ticket #9837 - latest update on 2009/10/07, created on 2009/07/28 by Sylvain Thenault
https://www.logilab.org/ticket/9837
CC-MAIN-2017-04
refinedweb
268
73.37
CSPICE_WNRELD compares two double precision windows. For important details concerning this module's function, please refer to the CSPICE routine wnreld_c. Given: a, b scalar, double precision windows, each of which contains zero or more intervals. The user must create 'a' and 'b' using cspice_celld. op the scalar, string comparison operator, indicating the way in which the input sets are to be compared. 'op' may be any of the following: Operator Meaning -------- ------------------------------------- "=" a = b is TRUE if a and b are equal (contain the same intervals). "<>" a <> b is TRUE if a and b are not equal. "<=" a <= b is TRUE if a is a subset of b. "<" a < b is TRUE is a is a proper subset of b. ">=" a >= b is TRUE if b is a subset of a. ">" a > b is TRUE if b is a proper subset of a. the call: boolean = cspice_wnreld( a, op, b ) returns: a scalar boolean describing the result of the comparison. Any numerical results shown for this example may differ between platforms as the results depend on the SPICE kernels used as input and the machine specific arithmetic implementation. ;; ;; Create a cell containing a double precision ;; 8-vector. ;; win1 = cspice_celld( 8 ) win2 = cspice_celld( 8 ) ;; ;; Define two darray = [ [ 1.d, 2.0], [ 9.0, 9.0], [24.0, 27.0] ] ;; ;; Add the window data to the cell. ;; for i=0, 2 do begin cspice_wninsd, darray[0,i], darray[1,i], win2 endfor ops = [ '=', '<>', '<=', '<', '>=', '>' ] ;; ;; Loop over each operation token in 'ops', apply that ;; operation to 'win1' and 'win2'. ;; for i=0, n_elements(ops) -1 do begin if( cspice_wnreld( win1, ops[i], win2 ) ) then begin print, "Operation succeeded : ", ops[i] endif else begin print, "Operation failed : ", ops[i] endelse endfor IDL outputs: Operation failed : = Operation succeeded : <> Operation failed : <= Operation failed : < Operation succeeded : >= Operation succeeded : >) compare two d.p. windows Wed Apr 5 17:58:05 2017
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/IDL/icy/cspice_wnreld.html
CC-MAIN-2019-35
refinedweb
312
64.41
This action might not be possible to undo. Are you sure you want to continue?... Technical topics Evaluation software Community Events Introduction to Android development The open source appliance platform Frank Ableson, Software designer Summary: Android is a complete operating environment based upon the Linux® V2.6 kernel. Initially, the deployment target for Android was the mobile-phone arena, including smart phones and lower-cost flip-phone devices.. Date: 12 May 2009 Level: Introductory Also available in: Korean Russian Japanese Vietnamese Portuguese Activity: 215431 views Comments: 4 (View | Add comment - Sign in) Average rating (143 votes) Rate this article. A brief history of Android 1 of 12 Monday 14 February 2011 03:18 PM The UI subsystem includes: Windows Views Widgets for displaying common elements such as edit boxes. and 3G). which in turn resides within a Linux-kernel managed process. Bluetooth. Support for location-based services (such as GPS) and accelerometers is also available in the Android software stack. There is also camera support. Android addresses the graphics challenge with built-in support for 2-D and 3-D graphics. including the OpenGL library. Figure 1 shows a simplified view of the Android software layers. The data-storage burden is eased because the Android platform includes the popular open source SQLite database. lists. Each Android application runs within an instance of the Dalvik VM. Android is a layered environment built upon a foundation of the Linux kernel. two areas where mobile applications have struggled to keep pace with their desktop counterparts are graphics/media. Figure 2. though not all Android devices are equipped with the required hardware.Introduction to Android development platform entered the public arena. and it includes rich functions. and wireless data over a cellular connection (for example. EDGE. and they run within a virtual machine (VM). Android runs atop a Linux kernel.ibm. but is the Dalvik Virtual Machine. Android software layers Application architecture As mentioned. Dalvik VM 2 of 12 Monday 14 February 2011 03:18 PM . The Android platform. It's important to note that the VM is not a JVM as you might expect. Historically. an open source technology.com/developerworks/opensource/library/o. Android applications are written in the Java programming language. With Android's breadth of capabilities. the same open source browser engine powering the iPhone's Mobile Safari browser.. A popular technique in Android applications is to link to Google Maps to display an address directly within an application. Android boasts a healthy array of connectivity options. it would be easy to confuse it with a desktop operating system.. Figure 1. GPRS. including WiFi. and data storage methods. as shown below. and drop-down lists Android includes an embeddable browser built upon WebKit. . an activity is started. but you would need to know your way around the Android SDK. you might not necessarily create a content provider. The Android SDK is distributed as a ZIP file that unpacks to a directory on your hard drive. Mac OS X. is deployed to a device. For example. Content providers You can think of content providers as a database server. Once your Java code is compiled cleanly.jar Java archive file containing all of the Android SDK classes necessary to build your application. If you're building a larger application. a content provider is the means of accessing your data.xml. including the AndroidManifest. Android development can take place on Microsoft® Windows®. or one that makes data available to multiple activities or applications. such as the receipt of a text message. including context-sensitive help and code suggestion hints. and the required permissions the application needs to run. Coding in the Java language within Eclipse is very intuitive. or Linux.com/developerworks/opensource/library/o. If your application is very simple.ibm. Services A service should be used for any application that needs to persist for a long time. for example — this permission must be explicitly stated in the manifest file. 3 of 12 Monday 14 February 2011 03:18 PM . Android applications are written in the Java language. The next section discusses the development environment required to build an Android application.xml contains the necessary configuration information to properly install it to the device. Many applications may have this specific permission enabled. Broadcast receivers An Android application may be launched to process a element of data or respond to an event. the Android Developer Tools make sure the application is packaged properly. such as a SQLite database. it is recommended that you keep your development environment well organized so you can easily switch between SDK installations. An Android application. if an application requires access to the network — to download a file. The SDK includes: android. along with a file called AndroidManifest. When a user selects an application from the home screen or application launcher. but compiled and executed in the Dalvik VM (a non-Java virtual machine). Since there have been several SDK updates. It includes the required class names and types of events the application is able to process. A content provider's job is to manage access to persisted data. It's possible to develop Android applications without Eclipse and the Android Developer Tools plug-in. Such declarative security helps reduce the likelihood that a rogue application can cause damage on your device.Introduction to Android development file. Required tools The easiest way to start developing Android applications is to download the Android SDK and the Eclipse IDE (see Resources). This article assumes you are using the Eclipse IDE and the Android Developer Tools plug-in for Eclipse. such as a network monitor or update-checking application.. Eclipse provides a rich Java environment. AndroidManifest. An Android application consists of one or more of the following classifications: Activities An application that has a visible UI is implemented with an activity. Samples directory The samples subdirectory contains full source code for a variety of applications.. Figure 3 shows the Android Emulator's home screen. The most commonly employed and useful tool is the adb utility (Android Debug Bridge). such as the G1 or the Android Dev 1 unlocked development phone.ibm. Figure 3. making it easy to navigate the many packages in the SDK. The documentation also includes a high-level Development Guide and links to the broader Android community. which exercises many APIs. such as copying files to and from the device. Android Emulator Android Debug Bridge The adb utility supports several optional command-line arguments that provide powerful features.com/developerworks/opensource/library/o. including ApiDemo. These files are only required for developers using the Windows platform. The shell command-line argument lets you connect to the phone itself and 4 of 12 Monday 14 February 2011 03:18 PM . The sample application is a great place to explore when starting Android application development. which ships with the Android SDK. It's largely in the form of JavaDocs. Tools directory Contains all of the command-line tools to build Android applications. Android applications may be run on a real device or on the Android Emulator. usb_driver Directory containing the necessary drivers to connect the development environment to an Android-enabled device..html and docs directory The SDK documentation is provided locally and on the Web.Introduction to Android development. documention. which starts the New Android Project wizard.Introduction to Android development issue rudimentary shell commands. considering you're connected to a telephone. you'll create a simple Android application. Note the multiple network connections: lo is the local or loopback connection. tiwlan0 is the WiFi connection with an address provisioned by a local DHCP server. Execute the su command to become the super-user. In the next section. Coding a basic application This section provides a whirlwind tour of building an Android application. Figure 4 shows the Windows laptop with a USB cable. you can: Display the network configuration that shows multiple network connections. The example application is about as simple as you can imagine: a modified "Hello Android" application. The extension is apk.. and many other system-level tasks. Display the contents of the PATH environment variable. Figure 5. select File > New > Android project. To create an application in Eclipse. Android application files are actually archive files that are viewable with WinZip or equivalent. You'll add a minor modification to make the screen background color all white so you can use the phone as a flashlight. Not very original.com/developerworks/opensource/library/o. This is fairly remarkable function. Change the directory to /data/app..com is available. New Android project wizard 5 of 12 Monday 14 February 2011 03:18 PM . From this same command-prompt environment. where user applications are stored. start programs. you can also interact with SQLite databases. Download the full source code.ibm. but it will be useful as an example. Figure 4. Issue a ping command to see if Google. shell command against a real device connected to a adb adb Within this shell environment. Using the shell command. Do a directory listing where you see a single application. xml <?xml version="1. In the strings. you see that all_white is 6 of 12 Monday 14 February 2011 03:18 PM . Next. The simple layout is shown below. along with a UI layout stored in main.ibm. Listing 1.xml. Listing 2.xml file. all_white. you create a simple application with a single activity.Introduction to Android development. Color in strings.0" encoding="utf-8"?> <LinearLayout xmlns:Android FlashLight</string> <string name="app_name">FlashLight</string> <color name="all_white">#FFFFFF</color> <color name="all_black">#000000</color> </resources> The main screen layout has a background color defined as defined as an RGB triplet value of #FFFFFF..com/apk/res/android" android: <TextView android: </LinearLayout> Create a couple of color resources in strings.com/developerworks/opensource/library/o.android.xml. Running the application presents a white screen with black text. import android. it is not editable.java package com. setContentView(R.flashlight..flashlight.msi.java source file. it is used when an activity is suspended and then resumed. } } The code is boiler-plate directly from the New Project wizard: It is part of a Java package called com. public class FlashLight extends Activity { /** Called when the activity is first created.main).Activity. Never edit this file directly.Introduction to Android development. The text is set to be black and is centered horizontally with the gravity attribute.com/developerworks/opensource/library/o. passing in a savedInstanceState. as it is changed upon every build.onCreate(savedInstanceState). A call to setContentView() associates the UI layout defined in the file main.xml and strings. The layout contains a single TextView. It has two imports: One for the activity class One for the bundle class When this activity is initiated. */ public void onCreate(Bundle savedInstanceState) { super.java. White screen of flashlight 7 of 12 Monday 14 February 2011 03:18 PM .msi. which is really just a piece of static text. The onCreate method is an override of the activity class method of the same name.xml..os. Flashlight. Don't be concerned with this bundle for our purposes. Figure 6. The application has a Java source file called FlashLight. as shown below.layout.Bundle. import android.ibm.xml gets automatically mapped to constants defined in the R. Listing 3.app. It calls the super class's onCreate method. Anything in main. the onCreate method is invoked. action.xml for FlashLight <?xml version="1.0.android.intent. The AndroidManifest.MAIN" /> <category android: <application android: <activity android: <intent-filter> <action android: </intent-filter> </activity> </application> </manifest> This file was created automatically by the Android Developer Tools plug-in for Eclipse.category. But it could come in handy if you want to do some reading 8 of 12 Monday 14 February 2011 03:18 PM .intent. the first complete. the example got you excited enough to explore more of the Android platform. tools. Stay current with developerWorks' Technical events and webcasts. trade shows. less expensive. downloads. Get the latest Eclipse IDE. and more. Visit the developerWorks Open source zone for extensive how-to information. and better mobile experience. check out developerWorks podcasts. or if you need to find your way to the fuse box in the basement during a power outage. Android promises to be a marketmoving open source platform that will be useful well beyond cell phones. you learned about Android at a very high level and built a small application.zip Size 22KB Download method HTTP Information about download methods Resources Learn The Open Handset Alliance is a group of 47 technology and mobile companies who have come together to accelerate innovation in mobile and offer consumers a richer. Unlocking Android: A Developer's Guide provides concise.com/developerworks/opensource/library/o. and free mobile platform. open.. Check out the tutorials hosted on YouTube that discuss the internals of the Dalvik VM. Summary In this article. and project updates to help you develop with open source technologies and use them with IBM's products. hands-on instruction for the Android operating system and development tools. Hopefully.. blogs.Introduction to Android development. Download Description FlashLight source code Name os-android-devel-FlashLight. The Android developers site offers documentation. without disturbing your sleeping spouse. and other Events around the world that are of interest to IBM open source developers. Watch and learn about IBM and open source technologies and product functions with the no-cost developerWorks On demand demos. webcasts. Innovate your next open source development project with IBM trial software. To listen to interesting interviews and discussions for software developers. Learn more about the Dalvik Virtual Machine. 9 of 12 Monday 14 February 2011 03:18 PM . they have developed Android. Follow developerWorks on Twitter. Together. available for download or on DVD.ibm. Check out upcoming conferences. Get products and technologies Download the Android SDK. IBM ID: Forgot your IBM ID? Password: Forgot your password? Change your password? After sign in: Stay on the current page By clicking Submit. When not working. particularly in the areas of communications and hardware interfacing. last name. register here. but you may edit the information at any time. you agree to the developerWorks terms of use. Display name: (Must be between 3 – 31 characters. last name (unless you choose to hide them). Selected information in your My developerWorks profile is displayed to the public. Lakers.Introduction to Android development. 10 of 12 Monday 14 February 2011 03:18 PM .) Note: Please choose a display name between 3-31 characters. Your first name. he can be found spending time with his wife Nikki and their children.com. and WebSphere®. so you need to choose a display name. Rational®. Discuss Participate in developerWorks blogs and get involved in the developerWorks community. This profile includes the first name. you agree to the developerWorks terms of use. Submit Cancel The first time you sign into developerWorks. About the author After his college basketball career came to an end without a multiyear contract to play for the L.. Close [x] developerWorks: Sign in If you do not have an IBM ID and password. Lotus®. All information submitted is secure.A. Download IBM product evaluation versions or explore the online trials in the IBM SOA Sandbox and get your hands on application development tools and middleware products from DB2®. and display name will accompany the content that you post. Close [x] Choose your display name The first time you sign in to developerWorks a profile is created for you.. By clicking Submit. Tivoli®. and display name contained in the profile you created when you registered with My developerWorks. a My developerWorks profile is created for you. Your display name must be unique in the developerWorks community and should not be your email for privacy reasons. He enjoys solving complex problems.com/developerworks/opensource/library/o. Your display name accompanies the content you post on developerWorks.ibm. You can reach Frank at frank@cfgsolutions. Frank Ableson shifted his focus to computer software design. .Introduction to Android development. Note: HTML elements are not supported within comments.2 is best :D Posted by Rupeshr00n3y on 09 July 2010 Report abuse Just wanted to post a thank you for a very nice ariticle.co Posted by go2amitech on 11 February 2011 Report abuse Excellent Article to get started... It help me get my brain around what Android is and is 11 of 12 Monday 14 February 2011 03:18 PM ... Once you have a hands on this making a simple application you will require additional tools to develop UI Please find this article for additional information Regards.in/2010/10/20/android-ui-development-tools/ Posted by sohilr on 21 October 2010 Report abuse Nice Article.com/developerworks/opensource/library/o.ibm. Notify me when a comment is added1000 characters left Post Total comments (4) Nice article. After reading this i developed my own android application please have a look at this and give me reviews and ratings:. Average rating (143 votes) 1 star 2 stars 3 stars 4 stars 5 stars 1 star 2 stars 3 stars 4 stars 5 stars Submit Add comment: Sign in or register to leave a comment. Submit Cancel All information submitted is secure. Android 2. Amit Panchal. not. Posted by Russell Ray on 21 February 2010 Report abuse Print this page Share this page Follow developerWorks Technical topics AIX and UNIX Related resources Students Business partners Product information Redbooks Privacy Accessibility More.. The history section provided a clear understanding why others in the industry are advocating this technology.ibm.com/developerworks/opensource/library/o. Cloud computing Industries 12 of 12 Monday 14 February 2011 03:18 PM ..Introduction to Android development. More..... This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/49158755/android-dw
CC-MAIN-2017-04
refinedweb
2,987
52.15