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
Reproduced at: We often see the file "_init_. Py" in the module directory of python, so what is its function? 1. Identify that the directory is a python module package If you use python's IDE for development, if the file exists in the directory, the directory will be recognized as module package. 2. Simplify module import operation Suppose the directory structure of our module package is as follows: . └── mypackage ├── subpackage_1 │ ├── test11.py │ └── test12.py ├── subpackage_2 │ ├── test21.py │ └── test22.py └── subpackage_3 ├── test31.py └── test32.py If we use the most direct import method, copy the whole file to the project directory, and then import it directly: from mypackage.subpackage_1 import test11 from mypackage.subpackage_1 import test12 from mypackage.subpackage_2 import test21 from mypackage.subpackage_2 import test22 from mypackage.subpackage_3 import test31 from mypackage.subpackage_3 import test32 Of course, there are few files in this example. If the module is large and the directory is deep, you may not remember how to import it. (it is very likely that even if you want to import only one module, you have to look in the directory for a long time) In this case, init.py is very useful. Let's first look at how the file works. 2.1 how does init.py work? In fact, if the directory contains__ init__.py, when importing the directory with import, the__ init__.py inside the code. We add one in the mypackage directory__ init__.py file to do an experiment: . └── mypackage ├── __init__.py ├── subpackage_1 │ ├── test11.py │ └── test12.py ├── subpackage_2 │ ├── test21.py │ └── test22.py └── subpackage_3 ├── test31.py └── test32.py Add a print in mypackage/init.py. If the file is executed, it will output: print("You have imported mypackage") Next, import directly in interactive mode >>> import mypackage You have imported mypackage Obviously, init.py is executed when the package is imported. 2.2 control module import Let's do another experiment and add the following statement in mypackage/init.py: from subpackage_1 import test11 Let's try importing mypackage: >>> import mypackage Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/taopeng/Workspace/Test/mypackage/__init__.py", line 2, in <module> from subpackage_1 import test11 ImportError: No module named 'subpackage_1' Wrong report... What's going on? Originally, when we execute import, the current directory will not change (even if it is a file executing a subdirectory), but we still need a complete package name. from mypackage.subpackage_1 import test11 To sum up, we can specify the modules to be imported by default in init.py 2.3 lazy introduction method Sometimes when we import, we will be lazy and import all the contents in the package from mypackage import * How did this happen__ all__ That's what variables do. __ all__ A module list is associated. When from xx import * is executed, the modules in the list will be imported. We will__ init__.py is modified to: __all__ = ['subpackage_1', 'subpackage_2'] Subpackage is not included here_ 3. To prove__ all__ Works instead of importing all subdirectories. >>> from mypackage import * >>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'subpackage_1', 'subpackage_2'] >>> >>> dir(subpackage_1) ['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__'] Modules in subdirectory are not imported!!! The import in this example is equivalent to: from mypackage import subpackage_ 1, subpackage_ two Therefore, the import operation continues to look for subpackages_ 1 and subpackage_2__ init__.py and execute. (however, import * will not be executed at this time.) We are in the subpackage_ Add under 1__ init__.py file: __all__ = ['test11', 'test12'] # By default, only test11 is imported from mypackage.subpackage_1 import test11 Try importing again >>> from mypackage import * >>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'subpackage_1', 'subpackage_2'] >>> >>> dir(subpackage_1) ['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'test11'] If you want to import all modules of a sub package, you need to specify them more precisely. >>> from mypackage.subpackage_1 import * >>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'test11', 'test12'] 3. Initialization of configuration module I understand__ init__. After the working principle of python, you should understand that the file is a normal Python code file. Therefore, you can put the initialization code into this file.
https://programmer.group/python-__-init__-detailed-explanation-of-py-action.html
CC-MAIN-2021-49
refinedweb
689
50.84
Synopsis edit - - proc name arguments body Documentation edit See Also edit - apply - command - corp - generate a script to reproduce a proc - Creating Commands - enumerates and compares the commands which create commands - lego proc manipulation - a sort of proc templating facility - Local procedures - a discussion on limiting the lifespan of a proc inside another proc - overloading proc - Guarded proc - Lambda in Tcl - un-named/anonymous procedures - Steps towards functional programming - Jimulation - an overloaded proc that also takes a set of static variables - Printing proc sequence - a mechanism to trace what procs are called - Procedure calling timed - timing proc calls - proc alias - how to make an alias for a procedure - Procs as data structures - Procs as objects - Runtime creation of procs - scope - Simple proc tracing - mkproc - If we had no proc - saving all procedures - Wrapping a procedure - wrap a procedure and call the original, which is stored in $next, at any time - wrapping commands - various approaches to wrapping commands Description editproc creates a new Tcl procedure named name, replacing any existing command having the same name. Whenever the new command is evaluated, the contents of body are evaluated in the namespace where the procedure is defined, at a new level where the only accessible variables are those created to hold the arguments passed to the procedure. global, upvar, namespace upvar, and variable can be used to link in namespace variables and variables at other levels. Similarly, uplevel and namespace eval can be used to evaluate scripts in namespaces or at other levels. Command names in body are resolved as described in name resolution.When name is unqualified (does not include the names of any containing namespaces), the new command is created in the current namespace. If name includes any namespace qualifiers, the command is created in the specified namespace. A partially-qualified name is resolved relative to the current namespace.arguments is a list, possibly empty, of arguments to the procedure. If any list item itself contains two items, the second item becomes the default value for that argument. When the command is evaluated, each actual argument is stored in the variable named by the argument.Any argument that follows an argument having a default value must itself have a default value.A procedure may accept a variable number of arguments by naming the last argument args: proc myvarproc {foo bar args} { puts "<$foo> <$bar> <$args>" } myvarproc a b c d e # => <a> <b> <c d e> myvarproc a b # => <a> <b> <>When the command is evaluated, all additional words are added to a list which is then assigned to $args. If there are no additional words, $args is empty. If args is the only argument, $args is a list of all the words after the command name. Thus, list can be implemented as: proc List args {set args}An argument named args only has this special behaviour if it is the last argument.The value of a procedure is the value of the last command evaluated in body . return can be used to end a procedure at some point other than the last command in body.When a procedure is renamed, any existing procedure by that name is overwritten, and no warning is given. To guard against such an event, see overloading proc with a Guarded proc.Because body is a script to be evaluated by the interpreter, a command created by proc does not extend Tcl. Procedure Results editSilas 2005-08-18: I think the best way to return multiple values is to use a list. For example: proc v {} { set value1 somevalue set value2 anothervalue return [list $value1 $value2] }arjen told me would be a good idea to use upvar. See (I haven't tested it): proc v {name1 name2} { upvar 1 $name1 n1 upvar 1 $name2 n2 set n1 1 set n2 2 } v N1 N2 puts "$N1 $N2"RS: The first approach, returning a list of the results, is "cleaner" in the functional programming sense. The upvar approach creates side effects as it changes the value of variables.Lars H: In real life, which approach is preferable varies quite a lot. There are on the whole at least three possibilities to consider: - Return the list of the results. - Return one result as the return value of the proc, and the others using upvared variables. - Return all results in variables. foreach {first second third} [makeThreeResults $input] breakLarry Smith: I still think let is more readable: let a b c @= 1 2 3DKF: Use lassign from 8.5 onwards. lassign [makeThreeResults $input] first second third Procs Always Bind to a Namespace editEven when they are created from with the body of another function, procs are bound to the current namespace, and exist for the life of that namespace, or until they are deleted: namespace eval foo { proc one {} { puts -nonewline {Eat } proc two {} { puts -nonewline {more } proc three {} { puts chicken. } } } } foo::one foo::two foo::three Default Values edit - Selected Topics in Tcl/Tk , Changhai Lu - a a discussion of Tcl proc's default argument capability. schlenk 2004-08-03: Here's a little proc to check if defaults were used or actual arguments were present, this can be handy if a default value is used as a don't care token. proc defaultvalues? {} { puts "hey: [info level -1]" expr {[llength [info args [lindex [info level -1] 0]]] - ([llength [info level -1]]-1)} }Trying it out: proc test {a {b 1} {c 2}} {puts [defaultvalues?]} test 1 ;# -> 2 test 1 2;# -> 1 test 1 2 3;# -> 0HaO 2011-03-16: The above is very good. I have seen an in-proc variant like that: proc c {a {b {}}} { if {2 == [llength [info level 0]]} { # code when optional argument b was not passed } } Doing nonsensical things with default args: proc defaultargs {{def a} undef} { puts [format {def: "%s", undef: "%s"} $def $undef] } defaultargs x y ;# -> def: "x", undef: "y" catch {defaultargs x} msg puts $msg ;#-> wrong # args: should be "defaultargs ?def? undef" Determine the Name of the Current Proc edit proc foo {args} { puts "proc = [lindex [info level 0] 0]" }See: info level Clobbering Existing Procedures editThe name of a procedure may be any string, including the empty string.When creating a new procedure, no warning is given when it replaces an existing procedure by the same name. If, for example, in a Tk applicaiton, you were to code: proc . {} {}you would find that you have destroyed the default toplevel, likely causing the app to exit.This is because each widget, there exists a command whose name is the path of the widget. Defining a proc of the name of any existing widget is going to result (in the very best of cases) potentially strange behavior and, in worse cases, catastrophe. Procedure Compilation edit - bytecode - the main page on the subject - Proc to bytecodes: when, how does it happen The Empty Name editAMG PYK: The proc name can even be the empty string, {}, but this has a weird interaction with rename and the way we abuse it for deleting procs. proc {} {} { puts "my name is [info level 0]" } {} ;# -> my name is {} rename {} {} catch {{}} msg einfo puts hello puts $msg ;# invalid command name ""Also strange: you can create a proc named "" but you can't use rename to do it.DKF: You can, but only by renaming to a fully-qualified name, like ::. Illegal Names editAs CMcC noted in the Tcl Chatroom, 2014-11-28, the name of a procedure in any namespace other than the global namespace may not begin with :. This is a consequence of designating :: as the namespace delimiter, which is considered an unfortunate development by some Tcl programmers who would have rather seen lists used for that purpose. Pass by Reference edit - Implicit upvar - RS's take on the matter - deref - Larry Smith's approach proc proc2 {name arglist body} { set header {} foreach a $arglist { if {[string first * $a] == 0} { append header "upvar 1 \[set $a] [string range $a 1 end];" } } proc $name $arglist $header$body } proc2 test {a *b c} {puts "a=$a, b=$b c=$c"} set quantity 4 test 1 quantity 3 ;# -> a=1, b=4, c=3 Naming Hacks editAny string is potentially valid proc name.RS: "Any string" includes things that look like array elements (but aren't), with which you can emulate "arrays of function pointers": % proc f(1) {} {puts hello} % proc f(2) {} {puts world} % proc f(3) {} {puts again} % for {set i 1} {$i<=3} {incr i} {f($i)} hello world againAnd a certain introspection is possible too: info proc f(*) => f(1) f(2) f(3)Update 2002-11-15: You don't have to stop at simulating - you can just have arrays of function pointers! A proc name that starts with a hash character # can be called by somehow ensuring the # isn't the first character: proc #test {} {puts [lindex [info level 0] 0]} \#test ;# -> #test {#test} ;# -> #test \x23test;# -> #test [namespace current]::#test ;# -> ::::#testRemember that comments are detected prior to the evaluation of a script. # has no importance when commands are being evaluated. Misc editEvery set of cards made for any formula will at any future time recalculate that formula with whatever constants may be required. Thus the Analytical Engine will possess a library of its own. - - - Charles Babbage, 1864
https://wiki.tcl.tk/463
CC-MAIN-2017-47
refinedweb
1,543
52.12
Team Services Extensions Roundup – April April 30, 2017 A 6 month high of 30 new Visual Studio Team Services extensions got added to the Marketplace in April. It was really hard to only pick two from such a big set so I encourage everyone to check them all out on the ‘Recently Added’ section of our Marketplace. There are two extensions I want to highlight this month. One is from a well known Visual Studio IDE publisher, the other is the first step our ecosystem has organically taken to fill the AWS integration gap. NDepend Extension for TFS 2017 and VSTS You may recognize this publisher from their successful Visual Studio extension, NDepend. NDepend has excelled in helping you estimate technical debt and manage .NET code quality in Visual Studio. Now they bring all of that, and more, to your continuous integration processes in Visual Studio Team Services. NDepend is a static analysis tool for .NET managed code, and comes with a large library of code metrics, as well as a very rich dashboard and dependency graphs. What you can expect from the extension: - A new build task that does the code analysis and code coverage data analysis. - A rich Hub Dashboard that shows the latest diff-able data set for your code quality metrics, with each item allowing drill-down. - Quality Gates is a check of code quality which must be enforced before committing and releasing is allowed. NDepend comes with 12 default suggested Quality Gates. - Over 150 default Rules that check your code against best practices. Write additional custom rules using Code Query over LINQ - Technical Debt and Issues offers a rich interactive drill-down view of your issues and the rules defining them. Group and sort your issues on a varying set of pivots. - Trends charts are provided displaying your tracked Trends for each build. The extension comes with 70 default trend metrics, with the ability to add new ones. - Code Metrics are displayed in a panel for each assembly, namespace, class or method. - Build Summary Recaps are included in each build showing the analysis recap. - Support is provided from a publisher that is fantastic to work with! AWS S3 Upload This extension comes as advertised. It adds a useful Build Task allowing you to upload a file to a S3 bucket in AWS. This extension has quickly become a Trending item and gotten great early reviews. There is a big hunger in our ecosystem for more Amazon integration, and this is a good step in the right direction. There are a few setup steps things you’ll need to take care of, but it’s worth it. Requirements - AWS Tools for Windows PowerShell installed on build machine and script execution enabled. All Windows Amazon Machine Images (AMIs) have the AWS Tools for Windows PowerShell pre-installed. - Profile containing keys on build machine (if role is not configured): Run aws configureand set Access Key and Secret Key Are you using (or building) an extension you think should be featured here? I’ll be on the lookout for extensions to feature in the future, so if you’d like to see yours (or someone else’s) here, then let me know on Twitter!
https://blogs.msdn.microsoft.com/devops/2017/04/30/team-services-extensions-roundup-april/
CC-MAIN-2017-26
refinedweb
535
62.68
Posted Dec 15, 2003 By DatabaseJournal.com Staff In my previous article, I showed you how to write a very simple function in Visual Basic .NET and then call it from T-SQL code in SQL Server "Yukon." But that's only part of the CLR integration story for the next version of SQL Server. One important part of the story that I left out is the in-process managed provider, an ADO.NET provider that CLR functions can use to talk directly to the instance of SQL Server that invoked them. In this article, I'll show you some of the basics of using this plumhing. A word of caution before I begin, though: Microsoft is giving us a public look at Yukon at a very early stage in its development. Though it's been demonstrated at the PDC and copies are in the hands of many beta testers, this is far from final code. Likely many details will change on the way to the final product, including namespaces, attribute names, and so on. But even though I would be astounded if the code from this article were to run with the release version of the product, it seems likely that the general patterns of working with SQL Server and the CLR will remain intact. It's time to start thinking about what you could do with this, not time to start writing code for production. The article continues at Database News Archives Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email Subject (Maximum characters: 1200). You have characters left.
http://www.databasejournal.com/news/article.php/3289241/SQL-Server-Yukon-and-the-CLR-Using-Server-Data.htm
CC-MAIN-2015-40
refinedweb
272
71.75
No CrossRef data available. Published online by Cambridge University Press: 29 February 2016 Ipsa autem, bonorum temporalium liberalissima ac spiritualium avida beneficiorum … — 1293 charter of Oxford University, describing Ela Longespee In 1293, the elderly and twice-widowed Ela Longespee, countess of Warwick, or someone acting on her behalf, gathered together eighteen charters that had been issued to her over the past dozen years and sent them to the bishop of Lincoln, to be confirmed and copied into a single roll. The original charters have long since vanished, but the enrolled copy survives in The National Archives at Kew. Its component documents, all of them detailed grants to Ela by religious institutions in the Oxford area, are highly unusual; even when compared to the few surviving parallels, they stand out for their specific content. The roll itself, comprising eighteen such documents in a private archive created for a thirteenth-century laywoman, is unique. And when it is examined along with other surviving evidence of Ela's religious activities, it provides us with an extraordinary perspective on the reciprocal nature of religious patronage at this time. What is especially unusual about Ela's case is that we know much more about what the religious promised to Ela than what she granted to them. Thus Ela Longespee's records tell us the side of the story that is seldom told when we look at records of religious patronage; they reveal the return that donors expected in the late thirteenth century, with increasing precision and urgency. Using a chronological framework, this essay will examine the surviving documents, tell the story of Ela's life, and explore the most interesting dimension of that story: her startlingly explicit reciprocal relationships with religious institutions. 1 Kew, The National Archives (TNA), PRO E132/2/18. Three of the component documents in the roll, the three charters from Oxford University, also survive in a register made for the University ( Munimenta Academica, or Documents Illustrative of Academical Life and Studies at Oxford , ed. Anstey, Henry, 2 vols. [London, 1868], 1:62–67). The roll was not copied into or noted in the bishop's register that survives (Lincoln, Lincolnshire Archives, Bishop's Register 1). I am grateful to Bruce Venarde, Barbara Harvey, Janet Sorrentino, and Benjamin Thompson for helpful comments on this work at various stages. My research was partially funded by a Hodson Fellowship from Hood College; was carried out in part while I was in residence at Studium, St. Benedict's Monastery, St. Peter, Minnesota; and was first presented at the College of St. Benedict, Minnesota. 2 Oxford Dictionary of National Biography , ed. Matthew, H. C. G. and Harrison, Brian, 60 vols. (Oxford, 2004), 34:385–88. 3 Calendar of the Charter Rolls Preserved in the Public Record Office , 6 vols. (London, 1903–27), 2 (42 Henry III–28 Edward I, 1257–1300): 29, and The Early Rolls of Merton College Oxford , ed. Highfield, J. R. L. (Oxford, 1964), 447. 4 Oxford Dictionary of National Biography , 18:1, and Knowles, David and Neville Hadcock, R., Medieval Religious Houses: England and Wales, 2nd ed. (Harlow, , 1971), 134, 281. 5 Oxford Dictionary of National Biography , 34:388–89. 6 Bowles, W. L. and Nichols, John Gough, Annals and Antiquities of Lacock Abbey. … (London, 1835), app., p. ii. If the elder Ela (who bore her eldest surviving son ca. 1209) reached puberty around age fourteen, in 1204, and immediately bore three surviving daughters at intervals of a year or so, her third daughter, the younger Ela, could have been born as early as 1207 or 1208, but this scenario is improbable. If, at the other extreme, the son born ca. 1209 was the first child, followed by three more sons and then three daughters, all at two-yearly intervals, Ela the younger could have been born as late as 1219, and married at age ten in 1229. 7 The manors were Canford (Dorset) and Chitterne (Wilts) (Calendar of the Patent Rolls Preserved in the Public Record Office, Henry III , 6 vols. [London, 1901–13], 2 [1225–32]: 255). 8 Bowles, and Nichols, , Annals and Antiquities , 305, 321. 9 Mason, Emma, “The Resources of the Earldom of Warwick in the Thirteenth Century,” Midland History 3 (1975–76): 67–75, and Crouch, David, “The Local Influence of the Earls of Warwick, 1088–1242: A Study in Decline and Resourcefulness,” Midland History 21 (1996): 1–22.CrossRefGoogle Scholar 10 Close Rolls of the Reign of Henry III Preserved in the Public Record Office , 14 vols. (London, 1902–38), 1 (1227–31): 220, 2 (1231–34): 219; C[ockayne], G. E., The Complete Peerage of England, Scotland, Ireland, Great Britain, and the United Kingdom, 13 vols. (London, 1910–59), 12.2:365. 11 She acquired land in Wiltshire in a settlement with the earl of Hereford in 1228–29 ( Complete Peerage , 6:460). Her husband was knighted and belted as an earl in 1233; her mother entered Lacock as a nun in 1237 and then was appointed to the abbacy of that house around 1239 (Complete Peerage, 12.2:365, and Close Rolls Henry III, 2 [1231–34]: 219). 12 Mason, , “Earldom of Warwick,” 73. 13 Close Rolls Henry III , 4 (1237–42): 454–55, 5 (1242–47): 10, 69; Curia Regis Rolls Preserved in the Public Record Office, 20 vols. (1922–2006), 17 (1242–43): 103, 116–17, 227–28, 257–59, 431, 437, 18 (1243–45): 22–23, 30–32. 14 Cal. Patent Rolls Henry III , 3 (1232–47): 505–7, 509, 4 (1247–58): 42. “Neweton” cannot be identified. 15 Close Rolls Henry III , 6 (1247–51): 86, 378, 471; Cal. Charter Rolls, 1 (11–41 Henry III, 1226–57): 369. 16 Cal. Patent Rolls Henry III , 3 (1232–47): 510, 4 (1247–58): 133; Close Rolls Henry III, 7 (1251–53): 136. 17 Close Rolls Henry III , 9 (1254–56): 170. Abraham of Berkhamstead was one of the Jews whose debts were to be collected and assigned to Richard of Cornwall, and among the Jews Abraham was especially close to Richard (Denholm-Young, N., Richard of Cornwall [Oxford, 1947], 22 n. 1, 69–70, 108). It is possible that Ela's marriage to Richard's associate Philip Basset at about this time led to the eventual forgiveness of her debt. 18 In 1242×48 Ela quitclaimed to her brother William land in Chitterne (Wilts), which he then granted to Lacock ( Lacock Abbey Charters , ed. Rogers, Kenneth H. [Devizes, 1979], nos. 266, 269). In 1249, the two Elas, mother and daughter, made a legal arrangement concerning the manor of Hatherop (Glos) — the countess of Warwick recognizing it to be Lacock's by right and leasing it back from the abbess for 100s. per year (Lacock Abbey Charters, nos. 418–19). No. 419 is dated 1249; no. 418, undated, is witnessed by Philip Basset and some of his associates, suggesting a possible date after Ela's second marriage. Hatherop certainly belonged to the younger Ela, so this agreement may be the remaining trace of a benefaction by her to the nuns (Cal. Charter Rolls, 1 [11–41 Henry III, 1226–57]: 369). In 1287, the younger Ela would quitclaim Hatherop to Lacock, receiving an annual income of £20 in return (Lacock Abbey Charters, no. 423). 19 Lacock Abbey Charters , no. 271, and Calendar of the Close Rolls of Edward I Preserved in the Public Record Office , 5 vols. (1900–1908), 2 (1279–88): 139. In 1255, Ela was listed among the “Oxfordshire and Berkshire” debtors of Abraham of Berkhamstead (Close Rolls Henry III, 9 [1254–56]: 170). In 1287, Ela exchanged her dower manor of Sutton Coldfield (Warwick) for Spilsbury in Oxfordshire (Victoria County History, Warwickshire, 4:233). 20 Calendar of Entries in the Papal Registers Relating to Great Britain and Ireland: Papal Letters , vol. 1 (1198–1304), ed. Bliss, W. H. (London, 1893), 307, 312–13, 345–46. 21 Oxford Dictionary of National Biography (n. 2 above), 4:267–68, 34:389, and Sir Christopher Hatton's Book of Seals , ed. Loyd, Lewis C. and Stenton, Doris Mary (Oxford, 1950), no. 437 and note. Philip may also have been acquainted with Ela because of an earlier association of his with Abbey, Lacock (Lacock Abbey Charters, no. 418). 22 Cal. Patent Rolls Henry III , 4 (1247–58): 529, 539, and Close Rolls Henry III, 10 (1256–59): 54–55. 23 Cal. Charter Rolls , 2 (42 Henry III–28 Edward I, 1257–1300): 35. In 1257 Ela was granted five dead oaks from the royal forest of Wychwood (Oxon) (Close Rolls Henry III, 10 [1256–59]: 72). 24 Oxford Dictionary of National Biography , 4:267–68. 25 Kingsford, , The Grey Friars of London , 150, and Röhrkasten, Jens, The Mendicant Houses of Medieval London, 1221–1539 (Berlin, 2004), 46, 389–90. 26 Hinnebusch, William A., The Early English Friars Preachers (Rome, 1951), 24, and Röhrkasten, , Mendicant Houses, 32–33. 27 They specifically exempted the land that the friars had appropriated and enclosed when they quitclaimed land in Warwick to a third party in 1268×71 (BL Add. 28,024 [Warwick Register], fol. 63r). 28 Cartulary of Oseney Abbey , ed. Salter, H. E., 6 vols. (Oxford, 1929–36), 2:401, no. 993. 29 Lacock Abbey Charters , no. 23; Cal. Charter Rolls, 1 (11–41 Henry III, 1226–57): 29; Oseney Cartulary, 1:192, no. 206; The English Register of Godstow Nunnery, Near Oxford , ed. Clark, Andrew (London, 1905–11), no. 645; Kew, TNA, PRO E164/20 (Godstow Latin Cartulary), fol. 115. 30 Godstow English Register , no. 105; PRO E164/20, fol. 160–160v. 31 Early Rolls of Merton College , 27, 41, 52; Oxford, Merton College Archives, nos. 646, 647, 648. 32 Cal. Close Rolls Edward I , 2 (1279–88): 139. She owed a debt of wool to a London merchant in 1276; complained in 1278 that her reeve had been imprisoned when she sent him to collect a relief owed to her in Warwickshire, and of a break-in and poaching at a park of hers in Hampshire; and appointed attorneys in lawsuits in 1279 (Cal. Close Rolls Edward I, 1 [1272–79]: 355, 570; Victoria County History, Warwickshire, 6:276; Cal. Patent Rolls Edward I, 1 [1272–81]: 287). 33 Kew, TNA/PRO E40/45. 34 The revenue was augmented by a royal grant of a daily cartload of firewood from old oaks in either Bernwood (Berks) or Wychwood (Oxon) forest, at pleasure. Calendar of the Patent Rolls of Edward I Preserved in the Public Record Office , 4 vols. (1893–1901), 2 (1281–92): 269, 338, 349. She had received ten live deer from Odiham park in 1276 (Cal. Close Rolls Edward I, 1 [1272–79]: 365). 35 They are printed in Munimenta Academica (n. 1 above), 1:62–67. 36 Except the last three Godstow charters, all from the same year, but enrolled in reverse order. The three Oseney charters, two of whose year-dates are illegible, appear to be out of chronological order; as they come first in the roll, this may indicate that the scribe had not yet decided on the chronological scheme. 37 Victoria County History, Oxfordshire , 2:77–79. 38 Longespee Roll, no. 6: Godstow charter 1 (see Appendix 1). Because the thirty masses of St. Gregory's Trental, as it was practiced in England, were spread out over the course of a full year, this would amount to a continuous state of St. Gregory's Trental being sung for Ela at Godstow. Given that this “great” trental, in which the masses were accompanied by a demanding regime of additional devotional practices, was sometimes confused with the simple or “lesser” trental of thirty masses on consecutive days, one might suspect the latter here, except that the Godstow charter notes after each mention of the trental “quod plenarie sine omissione celebrare faciemus,” as if to emphasize its length or complexity. All three of Ela's charters promising her St. Gregory's Trental were issued in 1282, suggesting that it was a devotional idea in which she was interested that year. For the Trental, see Pfaff, Richard, “The English Devotion of St. Gregory's Trental,” Speculum 49 (1974): 75–90, and Duffy, Eamon, The Stripping of the Altars: Traditional Religion in England, c. 1400– c. 1580 (New Haven and London, 1992), 370–75. The references to the trental in the Longespee roll predate most of those adduced by Pfaff.CrossRefGoogle Scholar 39 The latter two were certainly copied from the Rewley document. This, along with the general standardization of phrasing from one charter to the next, suggests that Ela's own clerk or clerks wrote many, if not all, of these documents, just as the beneficiary's scribe often wrote the charter in the case of donation to a religious house. 40 BL Harl. Ch. 54 D.15; printed in Dugdale, William, Monasticon Anglicanum: A History of the Abbies and Other Monasteries, Hospitals, Frieries, and Cathedral and Collegiate Churches, with their Dependencies, in England and Wales , 6 vols. (London, 1846), 4:45, no. xxvi, and Victoria County History, Cambridgeshire, 4:112. A near-duplicate, now lost, is printed in Book of Seals, no. 327, where the editors argue for a date of December 1284×90. However, B. R. Kemp assumes the grant was shortly before 6 January 1280 (Reading Abbey Cartularies , ed. Kemp, , 2 vols. [London, 1986–87], 1: no. 84 n.). 41 “unde totus conventus … habeat singulis diebus dominicis unam bonam pietanciam per quoquinarium domus et conventus Rading' in honorem Sancte Trinitatis, et aliam bonam pietanciam singulis diebus Jovis per eundem quoquinarium in honorem sacrosancte Assencionis inperpetuum” (Kew, TNA/PRO C146/3589). Another of the additional gifts in this second charter to Reading was a revenue of 20s. to be put toward the perpetual observation of Ela's anniversary at Reading. 42 “duo monachi … pro predicta domina Ela celebrantes cotidie et inperpetuum celebraturi, prout sibi per scriptum nostrum communi sigillo nostro signatum concessimus” (BL Add. Ch. 19,633). The two chaplains celebrating masses for “the countess” were mentioned in an account written at Reading in 1305 (BL Harl. 82, fol. 2v). 43 Calendar of Charters and Documents Relating to Selborne and Its Priory , Preserved in the Muniment Room of Magdalen College, Oxford, ed. Dunn Macray, W. (London 1891), 72. What prompted Ela to forge a relationship with Selborne is unknown, though Oseney charter 3 in the Longespee Roll mentions Selborne as a house in close relationship with Oseney.Google Scholar 44 The evidence is a debt of 300 marks owed by Ela to Stanley, recorded in the Rolls, Close ( Cal. Close Rolls Edward I , 1 [1272–79]: 338). In documents where Ela makes gifts to other houses, the language is sometimes that of debt, with enforcement clauses, e.g., at Selborne Priory, where she indebted herself to Selborne, promised to pay within five years, and authorized the distraint of her lands and goods in Oxfordshire and Hampshire to guarantee the debt (Calendar of Charters and Documents Relating to Selborne, 72). Alternatively, the debt to Stanley may simply be in connection with Philip's burial. Philip had been a benefactor of Stanley, whereas Ela does not appear in its muniments (Birch, W. de G., “Collections towards the History of the Cistercian Abbey of Stanley in Wiltshire,” The Wiltshire Magazine 15 [1875]: 239–307, at 256, 268, 274). 45 Rous, John, The Rous Roll , ed. Ross, Charles (Gloucester, 1980), cap. 36, and Dugdale, William, Antiquities of Warwickshire, 2nd ed., ed. Thomas, W. (London, 1730), 383. 46 Boynton, Susan, Shaping a Monastic Identity: Liturgy and History at the Imperial Abbey of Farfa, 1000–1125 (Ithaca, 2006), 144. 47 Burgess, Clive, “‘A fond thing vainly invented’: An Essay on Purgatory and Pious Motive in Later Medieval England,” in Parish, Church and People: Local Studies in Lay Religion, 1350–1750 , ed. Wright, S. J. (London, 1988), 56–83; Colvin, Howard, “The Origin of Chantries,” Journal of Medieval History 26 (2000): 163–73, at 169; Goff, Jacques Le, The Birth of Purgatory , trans. Goldhammer, Arthur (Chicago, 1984), 130–208, 289–333; Southern, R. W., “Between Heaven and Hell,” review of The Birth of Purgatory , by Goff, Jacques Le, Times Literary Supplement, 18 June 1982, 651–52; Horrox, Rosemary, “Purgatory, Prayer and Plague: 1150–1380,” in Death in England: An Illustrated History , ed. Jupp, Peter C. and Gittings, Clare (New Brunswick, NJ, 1999), 90–118, at 109–12.Google Scholar 48 Colvin, , “Origin of Chantries,” 163–73; Wood-Legh, K. L., Perpetual Chantries in Britain (Cambridge, 1965), 5; Cook, G. H., Mediaeval Chantries and Chantry Chapels (London, 1947), 6, 17; Kreider, Alan, English Chantries: The Road to Dissolution (Cambridge, MA, 1979), 72–76; Brown, Andrew D., Popular Piety in Late Medieval England: The Diocese of Salisbury, 1250–1550 (Oxford, 1995), 33–34, 93–95. Crouch, Cf. David, “The Origin of Chantries: Some Further Anglo-Norman Evidence,” Journal of Medieval History 27 (2001): 159–80. 49 Wood-Legh, , Perpetual Chantries , 8–11, and Colvin, , “Origin of Chantries,” 171. 50 Wood-Legh, , Perpetual Chantries , 11. Crouch adduces evidence of lay demand for daily commemorative masses in monasteries from the eleventh century on (Crouch, “Origin of Chantries,” 162–63, 170–71). Similar to Ela's enrolled charters (though much less detailed) is an early thirteenth-century charter from Waltham Abbey promising a daily mass for a layman (Kew, TNA, PRO DL 36/1/247, printed in Hector, L. C., The Handwriting of English Documents [London, 1966], 110 [transcription] and plate 5[a] [p. 73]). 51 The Itinerary of John Leland the Antiquary , ed. Hearne, Thomas, 3rd ed. (Oxford, 1770), 2:125–28, and Munby, Julian, Simmonds, Andy, Tyler, Ric, and Wilkinson, David R. P., From Studium to Station: Rewley Abbey and Rewley Road Station, Oxford (Oxford, 2007), 8, plate 1. 52 Roll, Longespee, no. 12, Rewley, charter (see Appendix 1). 53 Leland, John, The Itinerary of John Leland in or about the Years 1535–1543 , ed. Smith, Lucy Toulmin (Carbondale, IL, 1964), 1:124. Leland, also recorded, accurately, that Ela gave “riche giftes” to Reading Abbey. 54 One of the witnesses recalled that “cartam de feoffamentam … vidit, et in presencia dicte domine Ele, et parochianorum de Mapeldrewelle, eandem cartam verbis Anglicis audivit exponi” ( The Registers of John de Sandale and Rigaud de Asserio, Bishops of Winchester [A.D. 1316–1323] , ed. Baigent, Francis Joseph [London, 1897], 143, 145). 55 The land was in Nately Eastrop, now known as Up Nately; the village is a mile from Maplederwell. Kew, TNA, PRO C143/8/16 and C143/9/30. Ela was granted the manor of Maplederwell by her stepdaughter Alina Basset in 1272 ( Victoria County History, Hampshire , 4:150). 56 Calendar of Charters and Documents Relating to Selborne , 72. In the Longespee Roll, Godstow charter 5 says that the two chaplains saying mass for Ela are supported by a combined revenue of £7 7s.; in Godstow charter 3, an endowment of 200 marks purchases an annual revenue of 15 marks (£10). 57 Wood-Legh, , Perpetual Chantries , 281–90, using mostly fourteenth-century examples. 58 Of these, the designation for Wednesday is the one made least often in Ela's documents. Additionally, in one case the Sunday mass was to be the mass of the day (Longespee Roll, no. 6: Godstow charter 1 [see Appendix 1]), and in another case the Saturday mass was to be that of the Virgin after Ela's death (Longespee Roll, no. 5: St. Frideswide's charter 1 [see Appendix 1]). 59 Wood-Legh, , Perpetual Chantries (n. 48 above), 282, 284, 288. Most of the evidence is from later centuries. 60 Roll, Longespee, no. 3: Oseney charter 2 (see Appendix 1). 61 Roll, Longespee, nos. 6, 16: Godstow charter 1 and Studley (see Appendix 1). 62 Roll, Longespee, nos. 7, 9: Godstow charters 2 and 4 (see Appendix 1). 63 Roll, Longespee, nos. 5, 6, 15: St. Frideswide's charters 1 and 2 and Godstow charter 1 (see Appendix 1). 64 See Wood-Legh, , Perpetual Chantries , 290, for fifteenth-and sixteenth-century examples. 65 Clark-Maxwell, W. G., “Some Letters of Confraternity,” Archaeologia 75 (1926): 19–60, esp. 23–26, for examples of confraternity granted to lay benefactors in return for their gifts, and noted in the charter of gift, sometimes in language similar to that used in Ela's charter; Clark-Maxwell, , “Some Further Letters of Fraternity,” Archaeologia 79 (1929): 179–216; Knowles, David, The Monastic Order in England (Cambridge, 1966), 472–79; Cowdrey, H. E. J., “Unions and Confraternity with Cluny,” The Journal of Ecclesiastical History 16 (1965): 152–62; Clark, James G., “Monastic Confraternity in Medieval England: The Evidence from the St. Albans Abbey Liber Benefactorum,” in Religious and Laity in Western Europe, 1000–1400: Interaction, Negotiation, and Power , ed. Jamroziak, Emilia and Burton, Janet (Brepols, 2006), 315–31. For some attempts to quantify the proportion of donors granted confraternity and other benefits, see Christopher Holdsworth, The Piper and the Tune: Medieval Patrons and Monks (Reading, 1991), 12–14.CrossRefGoogle Scholar 66 See discussions in Brown, , Popular Piety , 32–33; Thompson, Benjamin, “From ‘Alms’ to ‘Spiritual Services’: The Function and Status of Monastic Property in Medieval England,” Monastic Studies: The Continuity of Tradition , ed. Loades, Judith, vol. 2 (Ipswich, 1991), 227–61, esp. 227–37, 250–54; Thompson, , “Monasteries and Their Patrons at Foundation and Dissolution,” Transactions of the Royal Historical Society 6 (1994): 103–25, at 107–11. 67 example, For, Reading Abbey Cartularies , nos. 803, 1079, 1193, and Stoke by Clare Cartulary: BL Cotton Appx. xxi , ed. Harper-Bill, Christopher and Mortimer, Richard, 3 vols. (Woodbridge, Suffolk, 1982–84), 1: nos. 11, 14. 68 BL Harl. Ch. 54 D.15; printed in Monasticon Anglicanum (n. 40 above), 4:45, no. xxvi, and Victoria County History, Cambridgeshire, 4:112; for its date, see Reading Abbey Cartularies, 1:84 n. 69 It is not unusual for charters to refer in this way to a fuller document in the donor's hands, but as far as I know this is the only such existing reference in the context of confraternity. 70 Cheney, C. R., “A Monastic Letter of Fraternity to Eleanor of Aquitaine,” English Historical Review 51 (1936): 488–93.Google Scholar 71 Colvin, , “Origin of Chantries” (n. 47 above), 167. 72 Harvey, Barbara, Living and Dying in England, 1100–1540: The Monastic Experience (Oxford, 1993), 10–11; Harvey, , “Monastic Pittances in the Middle Ages,” in Food in Medieval England: Diet and Nutrition , ed. Woolgar, C. M., Serjeantson, D., and Waldron, T. (Oxford, 2006), 215–27, at 216, 219–20. 73 “nichil eisdem causa predicte pietancie in cibatus discrescat nec sit diminutum” (BL Add. Ch. 19,633). 74 Longespee Roll, no. 8: Godstow charter 3 (see Appendix 1). 75 Longespee Roll, no. 11: Godstow charter 6 (see Appendix 1). 76 Oxford, Bodleian Library, MS Ch. Northants. 53. 77 BL Add. Ch. 19,633. 78 Godstow was founded for twenty-four nuns and is never recorded as having that many, whereas Reading had at least sixty-five monks in 1305; Knowles, and Hadcock, , Medieval Religious Houses (n. 4 above), 74, 259. 79 Longespee Roll, nos. 7, 9: Godstow charters 2 and 4 (see Appendix 1). 80 Longespee Roll, 17, 18, University charters 1 and 2 (see Appendix 1); Munimenta Academica (n. 1 above), 1:62–64, 66–67; and Rous, , The Rous Roll, cap. 36. Ela's fund is the third such endowment known to have been established in the medieval University, and was modeled on the first loan chest, established in 1240 and located at St. Frideswide's (Aston, T. H. and Faith, Rosamond, “The Endowments of the Universities and Colleges to circa 1348,” in The Early Oxford Schools , ed. Catto, J. I., vol. 1 of The History of the University of Oxford , ed. Aston, T. H. [Oxford, 1984], 267, 275–79). 81 Kew, TNA, PRO C146/3589. 82 Swanson, R. N., Indulgences in Late Medieval England: Passports to Paradise? (Cambridge, 2007), 11–15. 83 Swanson, , Indulgences , 56–57, 224–28. 84 Longespee Roll, nos. 3, 5, 6: Oseney charter 2, St. Frideswide's charter 1, and Godstow, charter 1 (see Appendix 1). 85 Longespee Roll, nos. 17, 19: University charters 1 and 3 (see Appendix 1); Munimenta Academica , 1:62–63, 65. 86 Denholm-Young, , Medieval Archives of Christ Church (Oxford, 1931), 7, and Oseney Cartulary (n. 28 above), 3:24. Denholm-Young dates the indulgence to 1272, Salter to 1282; Nicholas Cusack became bishop in 1279. Cusack was probably acting here as a suffragan bishop in an English diocese (Swanson, , Indulgences, 36–37). There is no indication of what Ela paid for or did to earn this privilege. 87 Swanson, , Indulgences , 57. 88 Book of Seals (n. 22 above), no. 339. 89 Early Rolls of Merton College , 445–46. 90 The fact that Ela retired to Godstow rather than her mother's foundation of Lacock is not surprising, given the overall shape of her religious patronage, with its focus on the Oxford area, and her apparent residence in or near that city in the later part of her life; she also seems to have had relatively little interest in Lacock or in her mother. 91 Ela's kinswoman was one of two anonymous nuns involved in the elopement of a third Godstow nun in 1290 in what the bishop later determined had been a staged abduction, on the road near High Wycombe in 1290 ( The Rolls and Register of Bishop Oliver Sutton, 1280–1299 , ed. Hill, Rosalind M. T., [Lincoln, 1954], 3:132–33). We do not know who this kinswoman was, but there was a nun named Isolda Lovel at Godstow in 1283, and Philip Basset's sister Katherine had married into the Lovel family (strictly speaking, though, a Lovel woman could not be called Ela's consanguinea) (Cal. Patent Rolls Edward I, 2 [1281–92]: 89). Alternatively, the nun who was Ela's kinswoman may have been a Longespee, related to Ela through one of her many siblings; in 1445 there would be a nun at Godstow named Alice Longspey, possibly indicating a continuing family connection (Visitations of Religious Houses in the Diocese of Lincoln, vol. 2, part 1, Records of Visitations Held by William Alnwick, Bishop of Lincoln, A.D. 1436–1449 , ed. Hamilton Thompson, A. [Lincoln, 1919], 114). 92 Longespee Roll, no. 6: Godstow charter 1 (see Appendix 1). 93 Longespee Roll, nos. 7–11: Godstow charters 2–6 (see Appendix 1); Oxford, Bodleian Library, MS Ch. Northants. 53. 94 Jones, John, Balliol College: A History , 2nd ed. (Oxford, 1997), 13–14; The Rolls and Register of Bishop Oliver Sutton, 1280–1299 , ed. Hill, Rosalind M. T., vol. 4 (Lincoln, 1958), 83–85, 94–95, 97, 132; Emden, A. B., “The Last Pre-Reformation ‘Rotulus Benefactorum’ and List of Obits of Balliol College,” Balliol College Record (1967), supplement, 6. 95 Early Rolls of Merton College , 445–46, and Merton Muniments , ed. Allen, P. S. and Garrod, H. W. (Oxford, 1928), plate 8c. 96 Early Rolls of Merton College , 223, 254, 258–59. As Ela had already been in residence for some years, the last item (“in datis hominibus Comitisse operantibus circa cameram construendam apud Godestowe”) may have meant she was remodeling her own rooms, or that she was helping with some other work at the abbey. 97 Oseney Cartulary (n. 28 above), 1:xix, and Early Rolls of Merton College, 262. Allen, and Garrod, (Merton Muniments, 28) stated without attribution that she died at Headington, but I have been unable to find any evidence for this, and I believe it is probably an error resulting from a confusion of Ela with Philippa Basset, lady of Headington, and also a dowager countess of Warwick (see, e.g., Victoria County History, Oxfordshire, 5:160). Ela almost certainly died at Godstow. 98 Westerhof, Danielle, Death and the Noble Body in Medieval England (Woodbridge, Suffolk, 2008), 75–95, 141–49; Golding, Brian, “Burials and Benefactions: An Aspect of Monastic Patronage in Thirteenth-Century England,” England in the Thirteenth Century: Proceedings of the 1984 Harlaxton Symposium , ed. Ormrod, W. M. (Woodbridge, Suffolk, 1985), 64–75, at 66–70, 73; Bradford, Charles Angell, Heart Burial (London, 1933), 22–25, 38–52, 63–101; Horrox, , “Purgatory, Prayer and Plague” (n. 47 above), 99–100; Park, Katharine, “The Life of the Corpse: Division and Dissection in Late Medieval Europe,” Journal of the History of Medicine, 50 (1995): 111–32; Brown, Elizabeth A. R., “Authority, the Family, and the Dead in Late Medieval France,” French Historical Studies 16 (1990): 803–32, at 809–14. Pope Boniface VIII banned the practice in 1299; see Brown, Elizabeth A. R., “Death and the Human Body in the Later Middle Ages: The Legislation of Boniface VIII on the Division of the Corpse,” Viator 12 (1981): 221–70; Brown, , “Authority, the Family, and the Dead,” 824–29. 99 Book of Lacock , appendix, p. ii. 100 Parsons, John Carmi, Eleanor of Castile: Queen and Society in Thirteenth-Century England (New York, 1998), 59–60, 208–9. 101 Horrox, , “Purgatory, Prayer and Plague,” 99–100. 102 See, e.g., Golding, , “Burials and Benefactions,” 66–70. 103 Westerhof, , Death and the Noble Body , 75–77. 104 Brown, , “Authority, the Family, and the Dead,” 820, and Horrox, , “Purgatory, Prayer and Plague,” 100. 105 The exception is a passing but correct reference by Greening Lamborn, E. A., “Suum Cuique,” Notes and Queries , 188 (1945): 158–61, at 161. Ela is not included in published lists of multiple burials such as that by Westerhof, , Death and the Noble Body, 141–49.Google Scholar 106 “Ele dowghter to sir Wm. Lonspe Eorl of Salisbury … is buryed a fore the hygh aulterre of Osney of Oxneforde” (Rous, , The Rous Roll , cap. 36). 107 Leland, , ed. Smith, Toulmin (n. 53 above), 1:124. The tomb at Oseney was no doubt Ela's corporal tomb, given its depiction of her whole body on the metal plate. Leland's description of the plate as “copper” should probably not be taken literally, as the words “copper” and “brass” were sometimes used interchangeably in the early modern period; see, e.g., Deut. 8:9; Burgess, Frederick William, Chats on Old Copper and Brass (London, 1914; repr. 2008), 27–28; Middle English Dictionary , ed. Kurath, Hans (Ann Arbor, MI, 1959), 3:590. Nor need we take seriously Leland's description of Ela as being depicted “in the habite of a woues.” This is the only evidence for Ela as a vowess (i.e., a widow vowed to chastity), and it seems to be a sixteenth-century misinterpretation of a thirteenth-century image of a widow. Medieval vowesses wore mantles, but no other special habit. While it is possible that Ela took vows, there is no credible evidence that she did, and even without vows she could have been a valued member of the community at Godstow. See Erler, Mary, “English Vowed Women at the End of the Middle Ages,” Mediaeval Studies 57 (1995): 155–204, at 156, 162 (for the confusion of widows and vowesses on memorial brasses), 174–75, 177, 181; Erler, , Women, Reading, and Piety in Late Medieval England (Cambridge, 2002), 9. 108 Horrox, , “Purgatory, Prayer and Plague” (n. 47 above), 108, and Saul, Nigel, Death, Art, and Memory in Medieval England: The Cobham Family and Their Monuments, 1300–1500 (Oxford, 2001), 61–67. 109 Stukeley, William, Itinerarium curiosum, or An Account of the Antiquities, and Remarkable Curiosities in Nature or Art, Observed in Travels through Great Britain (London, 1776), 1:45. For the conversion of Rewley into a brewhouse, see Munby, et al., From Studium to Station (n. 51 above), 9. 110 Hearne, , Itinerary , 2:128; Stukeley, , Itinerarium curiosum, 1:45; Munby, et al., From Studium to Station, 8. 111 Merton Muniments (n. 95 above), 28. 112 Merton Muniments , 28. 113 When a body was divided for burial in two places, the second burial was usually of the heart (unless the entrails were removed only because the body had to be transported a long distance, which was not the case for Ela); Bradford, , Heart Burial (n. 98 above), passim. However, Westerhof assumes that the heart and viscera were often buried together and that the latter included the former (Death and the Noble Body [n. 98 above], 88). 114 Early Rolls of Merton College , 261–62. Wanting, John, the College's warden, was one of Ela's executors (Martin, G. H. and Highfield, J. R. L., A History of Merton College, Oxford [Oxford, 1997], 70). 115 Thompson, Benjamin, “From ‘Alms’ to ‘Spiritual Services,’” 236, 252, and The Statutes of the Realm (1225–1713) , ed. Luders, A., Edlyn Tomlins, T., France, J., Taunton, W. E. and Raithby, J., 9 vols. (1810–22), 1:91–92. 116 Longespee Roll, no. 19: University charter 3 (see Appendix 1). 117 No copies of the charters have been found in surviving books from any of the religious houses. 118 Donovan, Claire, The de Brailes Hours: Shaping the Book of Hours in Thirteenth-Century Oxford (Toronto, 1991), 132–43, and Duffy, Eamon, Marking the Hours: English People and Their Prayers, 1240–1570 (New Haven, 2006), 8–11. 119 Lacock Abbey Charters , no. 271. 120 Donovan, , The de Brailes Hours , 136–43, 148–49, 155–56. Alternatively, Ela may have preferred to delegate her devotions to those saying masses and prayers on her behalf. 121 See, for example, Erler, , Women, Reading, and Piety (n. 107 above); Annette Grise, C., “Women's Devotional Reading in Late-Medieval England and the Gendered Reader,” Medium Ævum 71 (2002): 209–25; Meale, Carol M., “‘… alle the bokes that I haue of latyn, englisch, and frensch’: Laywomen and Their Books in Late Medieval England,” in Women and Literature in Britain, 1150–1500 (Cambridge, 1993), 128–58. 122 In addition, charters in the Longespee Roll record these donations to Godstow by Ela: an annual revenue of 10 marks (Godstow no. 2), a one-time gift of 200 marks (Godstow no. 3), a one-time payment of 25 marks (Godstow no. 4), and a one-time payment of £100 and 10 marks (Godstow no. 6). 123 For Bicester, only individual charters remain: Victoria County History, Oxfordshire , 2:93–94; Monasticon Anglicanum (n. 40 above), 6.1:434–35; Kennett, White, Parochial Antiquities Attempted in the History of Ambrosden, Burcester, and Other Adjacent Parts in the Counties of Oxford and Bucks (Oxford, 1818), 185–226, 241–305, 327–42, 386–407. Extracts of a lost Studley cartulary are found in Oxford, Bodleian Library, Twyne MS. 24, 642–61; some Studley charters are printed in Dunkin, John, History and Antiquities of the Hundreds of Bullingdon and Ploughley (London, 1823), 130–40. 124 For another example of significant non-land donations, see Clark, , “Monastic Confraternity in Medieval England” (n. 65 above), 324–25. 125 And like the one given by Waltham Abbey to Hugh de Neville, Kew, TNA, PRO DL 36/1/247. 126 Below, , Longespee Roll, no. 17, University charter 1. 127 Kew, TNA, PRO DL25/138. 128 In a charter of Waltham Abbey to Hugh de Neville, 1229×30, Hugh's late wife and their heirs are co-beneficiaries (Kew, TNA, PRO DL 36/1/247, printed in Hector, L. C., The Handwriting of English Documents [London, 1966], 110 [transcription] and plate 5[a] [p. 73]). A charter from Ankerwyke Priory, 1239×41, promised masses for Master Nicholas of Farnham and others (Wood-Legh, , Perpetual Chantries [n. 48 above], 285–86, and for later examples see 288–90). 129 Early Rolls of Merton College , ed. Highfield, , 446. 130 I owe the latter suggestion to Bruce Venarde. 131 BL Harl. 82, fol. 2v. 132 Munimenta Academica (n. 1 above), 2:370–72. 133 Monasticon Anglicanum , 4:370, and Valor ecclesiasticus tempore Henrici VIII auctoritate regia institutus , ed. Caley, John and Hunter, Joseph, 6 vols. (London, 1810–34), 2:187, 215, 250, 255. 134 Walworth, Julia (Fellow Librarian, Merton College), personal communication to author, 21 November 2006. 135 MS ebdomodomodam 136 MS altari 137 MS sconfessoris 138 missing through damage 139 MS Reliqus 140 MS colecta 141 MS celebratur 142 followed by me cancelled 143 sic 144 MS consessisse 145 MS reditus 146 sic 147 sic 148 MS arcamus 149 sic 150 sic 151 MS arcamus 152 MS precuniem 153 de inserted above line 154 sic 155 MS cuncis 156 MS adunatis 157 sic 158 sic 159 MS meus 160 See Corpus Orationum , ed. Moeller, Eugene, Clément, Joanna Maria, and 't Wallant, Bertrand Coppieters, 14 vols. (Turnhout, 1992–2004), 1:84–88. 161 Corpus Orationum , 1:94, no. 174. 162 Repertorium hymnologicum: Catalogue des chants, hymnes, proses, séquences, tropes en usage de l'église Latine depuis les origines jusqu'à nos jours , ed. Chevalier, Ulysse, 6 vols. (Louvain, 1892–1912), 1:108, no. 1812. 163 Breviarium ad usum insignis ecclesiae Sarum , ed. Procter, Francis and Wordsworth, Christopher, 3 vols. (Cambridge, 1886), 3:1073. 164 Corpus Orationum , 4:275, 279, nos. 2956b, 2958b. 165 Corpus Orationum , 5:164–65, nos. 3366, 3367. 166 Corpus Orationum , 6:73, no. 3859. 167 Corpus Orationum , 6:165–66, no. 4064. 168 Missale Romanum: Mediolani, 1474 , ed. Lippe, Robert, 2 vols. (London, 1899–1907), 2:287. 169 Corpus Orationum , 7:260, no. 4843. 170 Guéranger, Prosper, The Liturgical Year: Advent , trans. Shepherd, Laurence, 2nd ed. (Dublin, 1870), 361–62. 171 Corpus Orationum , (n. 160 above), 9:9, no. 5553a.
https://www.cambridge.org/core/journals/traditio/article/abs/ela-longespees-roll-of-benefits-piety-and-reciprocity-in-the-thirteenth-century/37ECDA62D6104FD74B62103032D61BD1
CC-MAIN-2022-05
refinedweb
6,220
65.93
From: Jeff Squyres (jsquyres_at_[hidden]) Date: 2005-09-15 15:39:51 On Sep 15, 2005, at 4:32 PM, Jeff Squyres wrote: > This allows the components themselves to pull in shared libraries when > they are dlopened -- if they need to. If the symbols can be resolved > in the parent process' public symbol namespace, they still will be (as > in the standalone executable example, above). But if they can't be > resolved that way, this gives the ability to explicitly find and pull > in a shared library and resolve the symbols that way (as in the Eclipse > plugin example, above). I forgot to include the simple example that shows this. Here's how our components are today (this is the paffinity linux component, but they're all this way): [15:15] odin:~/svn/ompi/opal/mca/paffinity/linux % ldd .libs/mca_paffinity_linux.so libm.so.6 => /lib/libm.so.6 (0x0000002a9566b000) libutil.so.1 => /lib/libutil.so.1 (0x0000002a957f1000) libnsl.so.1 => /lib/libnsl.so.1 (0x0000002a958f4000) libc.so.6 => /lib/libc.so.6 (0x0000002a95a0b000) /lib64/ld-linux-x86-64.so.2 (0x000000552aaaa000) You can see that there's no mention of libopal, even though the paffinity linux component makes libopal function calls. Here's how they are after I have fixed the Makefile.am and re-linked it: [15:16] odin:~/svn/ompi/opal/mca/paffinity/linux % ldd .libs/mca_paffinity_linux.so libopal.so.0 => /u/jsquyres/bogus/lib/libopal.so.0 (0x0000002a9565a000) libm.so.6 => /lib/libm.so.6 (0x0000002a957c8000) libutil.so.1 => /lib/libutil.so.1 (0x0000002a9594e000) libnsl.so.1 => /lib/libnsl.so.1 (0x0000002a95a52000) libc.so.6 => /lib/libc.so.6 (0x0000002a95b68000) libdl.so.2 => /lib/libdl.so.2 (0x0000002a95d8d000) /lib64/ld-linux-x86-64.so.2 (0x000000552aaaa000) Notice the explicit mention of libopal.so. This is what allows the component to resolve symbols independent of the parent process, if necessary. Hope that all makes sense! And if it doesn't, what do you care? :-) -- {+} Jeff Squyres {+} The Open MPI Project {+}
https://www.open-mpi.org/community/lists/devel/2005/09/0361.php
CC-MAIN-2016-18
refinedweb
333
52.66
NAME ftok - convert a pathname and a project identifier to a System V IPC key SYNOPSIS #include <sys/types.h> #include <sys/ipc.h> key_t ftok(const char *pathname, int proj_id); DESCRIPTION The ftok() function uses the identity of the file named by the given pathname (which must refer to an existing, accessible file) and the least significant 8 bits of proj_id (which must be nonzero) to generate a key_t type System V IPC key, suitable for use with msgget(2), semget(2), or shmget(2). The resulting value is the same for all pathnames that name the same file, when the same value of proj_id is used. The value returned should be different when the (simultaneously existing) files or the project IDs differ. RETURN VALUE On success the generated key_t value is returned. On failure -1 is returned, with errno indicating the error as for the stat(2) system call. CONFORMING TO POSIX.1-2001. NOTES Under libc4 and libc5 (and under SunOS 4.x) the prototype was: key_t ftok(char *pathname, char proj_id);. SEE ALSO msgget(2), semget(2), shmget(2), stat(2), svipc(7) COLOPHON This page is part of release 2.77 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/hardy/man3/ftok.3.html
CC-MAIN-2015-06
refinedweb
216
64.61
DOM::HTMLCollection #include <html_misc.h> Inherited by DOM::HTMLFormCollection. Detailed Description An HTMLCollection is a list of nodes. An individual node may be accessed by either ordinal index or the node's name or id attributes. Note: Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed. Definition at line 133 of file html_misc.h. Member Function Documentation Definition at line 195 of file html_misc.cpp. This method retrieves a node specified by ordinal index. Nodes are numbered in tree order (depth-first traversal order). - Parameters - - Returns - The Nodeat the corresponding position upon success. A value of nullis returned if the index is out of range. Definition at line 179 of file html_misc.cpp. This attribute specifies the length or size of the list. Definition at line 171 of file html_misc.cpp. This method retrieves a Node using a name. It first searches for a Node with a matching id attribute. If it doesn't find one, it then searches for a Node with a matching name attribute, but only on those elements that are allowed a name attribute. - Parameters - - Returns - The Nodewith a nameor idattribute whose value corresponds to the specified string. Upon failure (e.g., no node with this name exists), returns null. Definition at line 187 of file html_misc.cpp. The documentation for this class was generated from the following files: Documentation copyright © 1996-2021 The KDE developers. Generated on Fri Apr 9 2021 22:46:14 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/frameworks/khtml/html/classDOM_1_1HTMLCollection.html
CC-MAIN-2021-17
refinedweb
271
52.36
In this article, we will get familiar with APIs and REST APIs and then later build up our very own Flask REST API Application. What is an API? API or Application Programming Interface provides an interface to interact with different applications. Using APIs, we can retrieve, process, and send data – values from other applications. For example, consider a Web application. A client sends in some data as a request, the server then processes it, and then sends the appropriate response data back to the client. This whole process of interaction is done via the API. So let’s take a look at this example again and see where the APIs role is. Hence, what the client sends is an API containing the request data to the server. The server processes it and then sends back another API containing the appropriate response data to the Client. CRUD operators and HTTP methods While using an API, the Client can send request data to the server in many ways. These types are called CRUD Operations. Each CRUD (Create Retrieve Update Delete) operator has an HTTP method associated with it. Let us look at them now: - GET HTTP Method– Retrieves specific information (for viewing purpose) from the server. - POST – Sends/Creates new information in the Server Database. - PUT – Edits/Updates information in the Database or else adds it if not present already. - DELETE – Deletes information from the Server Database. Okay, now that we know the methods, let’s understand when to use each of them. Consider the following example: We have a student database containing information like Names, Class, Age, etc. - To see the list of students – Use GET HTTP method - To add a new student information – Use POST HTTP method - To edit certain information( Class /Age) of a student – Use PUT HTTP method - To delete a Student’s information from the Database – Use the DELETE HTTP method What is a REST API? A REST (Representational State Transfer) API is similar to the standard API. Here when we send the server a request, unlike an API which responds with data, REST API responds with resources. REST API Resources Now what are resources ?? Well, resources are data, but the way we see it changes. The resources are similar to Object-Oriented Programming. Let us understand it with the following example: Consider a Flask View – “/Book/Book123” Here, the same View Endpoint can perform 4 actions. - GET Book/Book123: Shows the information about the “Book123.“ - POST Book/Book123: Creates a new book, “Book123.” - PUT Book/Book123: Updates/edits the information about the book “Book123.” - DELETE Book/Book123: Deletes “Book123” from the database Since a single entity has several functionalities( OOP methods), it can be thought of as a Book resource. Therefore, now the interaction between the Client and server is not with individual endpoint requests but with resources (with the same endpoint for different actions) Statelessness of REST APIs Another feature of the REST API is its statelessness. What this means is that after the server completes one action, it forgets about it. Let’s understand this with an example. Consider the Book Resource we saw above. Let’s say, I send data about a Book – ” A Brief History Of Time ” by Stephen Hawkings using the POST method. The server will add this information to the Database and then forget the action. That is next time I use a GET request to retrieve the Book; the server will not have any memory of the previous POST method action. The server will first go to the Database and search for the Book. And once it finds the Book, it will respond with that data. Again after it completes the action, it will forget about it. Use of JSON in Client-Server API Interaction APIs use JSON format for accepting and returning requests. That is, the client sends the request data to the server as a JSON text. Similarly, the server processes the data and returns back the response again as a JSON text. Therefore, the whole process of a Web Application based on REST API is as follows: - The user sends the request data to the server as JSON. - The server first converts the JSON into a python-readable format. - Then the server processes the request and creates the response data again as a JSON - Then the webpage Template converts the JSON response to a user-readable format and displays it on the webpage. Therefore, real exchange of information between the client-side (FRONT-END) and the server (BACK-END) in API happens using JSON text. JSON format is similar to a Python Dictionary: { 'student1':{ 'name':'XYZ', 'age' : 21 } } Installing POSTMAN Postman is a collaboration platform for API development. Postman’s features simplify each step of building an API and streamline collaboration so you can create better APIs—faster. Click here to download POSTMAN. Once its installed, it will look like this: Okay, coders! Enough with the reading, let us now start building our REST API. Building a Flask REST API Application In this section, we will build a simple Book REST API application using the Flask RESTFul library. So let’s get started !! 1. Installing Flask_restful into your system To install the Flask_RestFull package, run the pip command: pip install flask_restful Now that it is installed, lets move on to the Database part 2. Coding the DB Models using SQLAlchemy Here we will use SQLite Database to store our Models. To use them first install flask_sqlalchemy pip install flask_sqlalchemy Now create a models.py file and add the following} Here, the BookModel has a name, price, and author fields. Since the APIs are in JSON, we create an Object method .json() to return a JSON book object. We first have to instantiate a DB instance to create the DB model. Check out our SQLAlchemy Tutorial if you have any doubts regarding SQLAlchemy. Now that we have our Models, lets now code the main Flask application. 3. Coding the Flask Application For the Flask REST API, we need to include an extra API(app) instance to indicate Flask that this is a REST API web app. from flask import Flask from flask_restful import Api app = Flask(__name__) api = Api(app) #Flask REST Api code if __name__ == '__main__': app.run(host='localhost', port=5000) Next, we need to give SQLite information to SQLAlchemy and link the DB instance (form models.py) with this application file. So for that, add the code: app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<db_name>.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) Here, replace <db_name> with the name you want for your DB. SQLALCHEMY_TRACK_MODIFICATIONS is kept False just for simplicity. The third line links the DB instance with the app. We need the DB file in place so that webpage users can use it. Also, we require that before the first user request itself. So to create the file we use the function: @app.before_first_request def create_table(): db.create_all() Add this below the above given codes itself. Okay with that in place, lets code our Flask REST API Resource Classes. 4. Adding a Books List Resource This resource would do the following: - GET method : Show the list of Books in the DB - POST method : Add a new Book information into the DB So the code would look like: class BooksList(Resource): def get(self): #get all objects from BookModel #return the JSON text of all objects pass def post(self): #convert the JSON data sent by the user to python-format #create a new bookModel object and send in the data #save to DB pass So the code should be able to do the tasks written above. Let’s now replace the comments with the actual code: class BooksList(Resource): def get(self): books = BookModel.query.all() return {'Books':list(x.json() for x in books)} def post(self): data = request.get_json() new_book = BookModel(data['name'],data['price'],data['author']) db.session.add(new_book) db.session.commit() return new_book.json(),201 Here in the GET method, - Get the books present in DB using BookModle.query.all() - Display JSON text of the Book one by one as a list In the POST Method, - Convert the JSON data, using request.get_json() - Create and Add the new Book Information to the DB That’s it; finally, we need to mention the URL endpoint for the BooksList Resource api.add_resource(BooksView, '/books') 5. Adding a Book Resource Now, we will create a resource that will: - GET Method: Display only a specific book requested by the user - PUT Method: Edit the information of the particular book. If not present, create one - DELETE Method: Delete the particular Book Here the code would look like: class Book(Resource): def get(self,name): #get the book with the name given by the user #if book exists, return it else return 404 not found def put(self,name): #convert the JSON data sent by the user to python-format #Search if the book exists #if it exists, update it with the data given by the user #if does not exists, create and add the book into DB def delete(self,name): #Search if the book exists in the DB #delete it The code should be able to do all the above tasks. So add the code: class Book(Resource): def get(self,name): book = BookModel.query.filter_by(name=name).first() if book: return book.json() return {'message':'book not found'},404 def put(self,name): data = request.get_json() Here in the GET method, - BookModel.query.filter_by(name=name).first() returns the first book it gets from the DB. It returns None, if nothing with the name was found. - Returns the JSON text of the Book if found. Or else returns 404 In PUT method, - Convert the JSON data using request.get_json() - If exists, replace the older data with the newly sent data - Or else create a new Book object - Add it to the DB In DELETE method, - Get the book with the name given by the user - Delete it That’s it. Finally add the URL endpoint for this Resource api.add_resource(BookView,'/book/<string:name>') And we are done !! Final Code of the Flask Rest API Application Therefore, the combined Flask main application is given below: from flask import Flask,request from flask_restful import Api, Resource, reqparse from models import db, BookModel app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False api = Api(app) db.init_app(app) @app.before_first_request def create_table(): db.create_all() class BooksView(Resource): ''' parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=True, help = "Can't leave blank" ) parser.add_argument('price', type=float, required=True, help = "Can't leave blank" ) parser.add_argument('author', type=str, required=True, help = "Can't leave blank" )''' def get(self): books = BookModel.query.all() return {'Books':list(x.json() for x in books)} def post(self): data = request.get_json() #data = BooksView.parser.parse_args() new_book = BookModel(data['name'],data['price'],data['author']) db.session.add(new_book) db.session.commit() return new_book.json(),201 class BookView(Resource): ''' parser = reqparse.RequestParser() parser.add_argument('price', type=float, required=True, help = "Can't leave blank" ) parser.add_argument('author', type=str, required=True, help = "Can't leave blank" )''' def get(self,name): book = BookModel.query.filter_by(name=name).first() if book: return book.json() return {'message':'book not found'},404 def put(self,name): data = request.get_json() #data = BookView.parser.parse_args() api.add_resource(BooksView, '/books') api.add_resource(BookView,'/book/<string:name>') app.debug = True if __name__ == '__main__': app.run(host='localhost', port=5000) The models.py} Let us now run our server and check them using POSTMAN. Implementing the Flask REST API application using POSTMAN Run the server and go to POSTMAN. 1. BooksList Resource : POST method Go to “/books” endpoint using POST method In the body, select raw – JSON and add the JSON data in the body { "name":"book1", "price":123, "author":"author1" } Hit send The Book – book1 is created 2. BooksList Resource : POST method Go to “books/” using the GET method and hit send. You will get the list of Books in the DB Since we have only book1, it is showing only 1 object in the list. 3. Book Resource : GET method Now go to “/books/book1” using GET and hit send See, it is showing the informatio of Book1 4. Book Resource : PUT method Go to “/books/book1” using PUT method and in the body, add the following JSON. { "price": 100, "author":"author123" } Since the name is already sent through the URL request, We need to send the price and author JSON. Hit send The price and author values have changed !! Try to check them using the GET method as well. 5. Book Resource : DELETE method Go to “/books/book1” using the DELETE method See it is deleted! Conclusion That’s it guys! I hope you have gained enough knowledge about the Flask REST API framework. Do try out the above codes yourselves for better understanding. See you guys next time !!
https://www.askpython.com/python-modules/flask/flask-rest-api
CC-MAIN-2021-31
refinedweb
2,157
65.52
How and when is MSIL code compiled to native binary? The MSIL code is compiled into binary at run time. Only methods that are called are compiled into binary. This is part of a larger procedure called process execution. Most of the information in this section is obtained from the Shared Source CLI, which is an open source implementation of the Common Language Infrastructure (CLI). The Shared Source CLI is often referred to as Rotor. For more information on Rotor, visit this page: msdn.microsoft.com/net/sscli. This section explains method compilation in the examination of how the entry point method is executed. Process execution begins when a managed application is launched. At that time, the CLR is bootstrapped into the application. The CLR is bootstrapped as the mscoree.dll library. This library starts the process of loading the CLR into the memory of the application. _CorExeMain is the starting point in mscoree.dll. Every managed application includes a reference to mscoree.dll and _CorExeMain. You can confirm this with the dumpbin.exe tool. Execute the following command line on any managed application for confirmation: dumpbin /imports application.exe Figure 11-2 shows the result of the dumpbin command. Managed applications have an embedded stub. The stub fools the Windows environment into loading a managed application. The stub temporarily masks the managed application as a native Windows application. The stub calls _CorExeMain in moscoree.dll. _CorExeMain then delegates to _CorExeMain2 in mscorwks. _CorExeMain2 eventually calls SystemDomain::ExecuteMainMethod. As the name implies, ExecuteMainMethod is responsible for locating and executing the entry point method. The entry point method is a member of a class. The first step in executing the method is locating that class. During process execution, classes are represented as EECLASS structures internally. ExecuteMainMethod calls ClassLoader::LoadTypeHandleFromToken to obtain an instance of the EECLASS for the class that has the entry point method. LoadTypeHandleFromToken is provided the metadata token for the class and returns an instance of an EECLASS as an out parameter. In a managed application, only classes that are touched have a representative EECLASS structure. The important members of the EECLASS are a pointer to the parent class, a list of fields, and a pointer to a method table. The method table contains an entry for each function in the class. The entries are called method descriptors. The method descriptor is subdivided into parts. The first part is m_CodeOrIL. Before a method is jitted, m_CodeOrIL contains the relative virtual address to the MSIL code of the method. The second part is a stub containing a thunk to the JIT compiler. The first time the method is called, the jitter is invoked through the stub. The jitter used the IL RVA part to locate and then compile the implementation of the method into binary. The resulting native binary is cached in memory. In addition, the stub and m_CodeOrIL parts are updated to reference the virtual address of the native binary. This is an optimization and prevents additional jitting of the same method. Future calls to the function simply invoke the native binary. Roundtripping is disassembling an application, modifying the code through the disassembly, and then reassembling the application. This provides a mechanism for maintaining or otherwise updating an application without the original source code. The following C# application simply totals two numbers, where the project name is "Add". The result is displayed in the console window. using System; namespace Donis.CSharpBook{ public class Starter{ public static void Main(string [] args){ if(args.Length<2) { Console.WriteLine("Not enough parameters."); Console.WriteLine("Program exiting..."); return; } try { byte value1=byte.Parse(args[0]); byte value2=byte.Parse(args[1]); byte total=(byte) (value1+value2); Console.WriteLine("{0} + {1} = {2}", value1, value2, total); } catch(Exception e) { Console.WriteLine(e.Message); } } } } Let us assume that the above program was purchased from a third-party vendor for quintillion dollars. Of course, the source code was not included with the application—even for quintillion dollars. Almost immediately, a bug is discovered in the application. When the program is executed, the total is sometimes incorrect. Look at the following example: C:\ >add 200 150 200 + 150 = 94 The result should not be 350, not 94. How is this problem fixed without the source code? Roundtripping is the answer. This begins by disassembling the application. For convenience, the ILDASM disassembler is used: ildasm /out=newadd.il add.exe Open newall.il in a text editor. In examining the MSIL code, we can easily find the culprit. The addition instruction adds two byte variables. The result is cached in another byte variable. This is an unsafe action that occasionally causes an overflow in the total. Instead of notifying the application of the overflow event, the value is cycled. This is the reason for the errant value. Add the ovf suffix to the conv instruction to correct the problem. The exception is now raised when the overflow occurs. You can use roundtripping to add features not otherwise available directly in C#. C# supports general exception handling but not exception filters. When an exception is raised, the exception filter determines whether the exception handler executes. If the exception filter evaluates to one, the handler runs. If zero, the handler is skipped. Here is a partial listing of the disassembled program. It is modified to throw an exception when the additional overflows the total. An exception filter has also been added to the exception handling. Changes in the code are highlighted: IL_0035: ldelem.ref IL_0036: call uint8 [mscorlib]System.Byte::Parse(string) IL_003b: stloc.1 IL_003c: ldloc.0 IL_003d: ldloc.1 IL_003e: add IL_003f: conv.ovf.u1 IL_0040: stloc.2 IL_0041: ldstr "{0} + {1} = {2}" IL_0046: ldloc.0 IL_0047: box [mscorlib]System.Byte IL_004c: ldloc.1 IL_004d: box [mscorlib]System.Byte IL_0052: ldloc.2 IL_0053: box [mscorlib]System.Byte IL_0058: call void [mscorlib]System.Console::WriteLine(string, object, object, object) IL_005d: nop IL_005e: nop IL_005f: leave.s IL_0072 } // end .try filter { pop ldc.i4.1 endfilter } // catch [mscorlib]System.Exception { IL_0061: stloc.3 IL_0062: nop IL_0063: ldloc.3 Because the filter returns one, the exception is always handled. The ILASM compiler can reassemble the application, which completes the roundtrip. Here is the command: ilasm newadd.il Run and test the newadd application. The changed program is more robust. Roundtripping has been a success!
http://etutorials.org/Programming/programming+microsoft+visual+c+sharp+2005/Part+IV+Debugging/Chapter+11+MSIL+Programming/Process+Execution/
CC-MAIN-2022-21
refinedweb
1,053
53.88
Eclipse Community Forums - RDF feed Eclipse Community Forums XWT and GUI related classes in a third-party jar <![CDATA[I have a third party OSGi enabled jar. It exports a layout class. Its a modified MigLayout jar. I was creating a XWT declarative GUI. After defining the namespace and adding the layout to my composite, I am unable to get the MigLayout class to be found by the XWT engine and I keep getting a class not found error. Most of the demos use classes defined in the same jar as the .xwt file itself, but MigLayout is another jar altogether, the XWT bundle cannot find the layout class. Any ideas on resolving this? Or do I have something else potentially wrong? It looks like a standard class loading problem but its not clear how to resolve it using the usual tricks (no eclipse-buddy mechanism can be added to xwt and I cannot declare everything in an application to be a fragment). Also, the XWT visual editor does not use the layout dynamically (I have added the mig jar so it is found by my application plugin of course).]]> No real name 2009-07-25T12:37:19-00:00
http://www.eclipse.org/forums/feed.php?mode=m&th=176433&basic=1
CC-MAIN-2016-30
refinedweb
200
65.01
What is python and what are its benefits Python is a high-level programming language that is used to code everything from web applications to machine learning algorithms. It’s easy for beginners to learn and has some unique features such as an interactive environment and automatic memory management. Python is incredibly popular and widely used because of its ease to use, powerful libraries and a friendly community. What is Python? Python (from ‘python’s eye’) is a general-purpose programming language that has first been created by Guido Van Helten in 1991. The name ‘Python’ stands for ‘Python Programming Language’. Python is a simple, elegant and powerful programming language that can be used to code anything from websites to complex software applications. Easy coding How to install python on your computer Windows: Download and run the Python setup installer. Mac OSX/Linux: Open up a terminal, cd to the directory you downloaded the Python installer to and type run python3.3.5.If you get an error, try using the file name instead of the full path, or try using python3 instead. Once you have Python installed, you can make a new file for your first program. Type in your code and run it! import random print (random . randint ( 1 , 20 )) import time start = 0 end = 20 num_seconds = 7 sec = 0 while start <= end : sec += 1 if sec > num_seconds : break start += 1 print ( “Time: ” , time . strftime ( “%H:%M:%S” , time . localtime ()), “Secs” , sec ) print ( ‘Program finished in’ , num_seconds , ‘seconds.’ ) Basic syntax and programming concepts In Python, you type everything in lowercase. Indentation is used to determine the syntax of a program and should be used as it is in the example below. A triple underscore (“__”) at the beginning of a case means that whatever is there is hidden. A single underscore (“_”) on the other hand means it is something you can see and change. Strings begin and end with quotation marks. Numbers do not, but they should be surrounded by either a single or double quotation mark. Arithmetic operations are performed on numbers. However, you can use a single letter or group of letters to denote an operation as well. So “+” would add two numbers, “-” would subtract one number from another, “*” would multiply numbers and so on. The operators are all lowercase and you can mix operators with numbers or other operators in the same statement. You can also use Python to make functions. You can therefore think of a function as something that you do within a program to add or subtract certain values or perform mathematical operations or create lists. A function can take as many or as few arguments as you wish. It is like putting a function in a box and taking out whatever it needs to do the job. Examples of programs that can be written in python The following is an example of a program written in Python. It is a simple program that prints the numbers 1, 2 and 3. It does this by having a for loop, which means “for each” and a while loop. A for loop is used to run through a section of code over and over again. When it reaches the end of the “for” statement, it looks at what comes next and keeps running the inner while loop until it reaches the end of that statement or breaks out with a break statement. The new statement tells it to create a new iteration of the loop and keep going. The break statement stops the loop and goes to the next part of the code. So in this example, it keeps looping until all the numbers have been printed. An example of a program written in Python: import sys for i in range(1,4): sys.stdout.write(str(i) + ” “) break Below is a definition of each term used in the above example: import sys statement: This tells Python to use a module called sys that has extra commands. statement: This tells Python to use a module called that has extra commands. range(1,4): This tells Python to go through the list of numbers 1 2 3 4 and choose which one to pick: This tells Python to go through the list of numbers and choose which one to pick: sys.stdout.write(str(i) + ” “): This takes the number i , puts it into a variable called str and then uses that variable as output. This takes the number , puts it into a variable called and then uses that variable as output. break: This tells Python to stop the loop. How to find help and further resources for learning python The first place to turn to is the official Python website. This is a great place to go for help and further resources. The site even has a forums where you can ask questions and receive help from Python developers around the world (or at least those who use the website and are willing to give advice). Another great resource is Python’s official documentation. It’s a thorough guide to Python, its syntax and overall use. It also serves as an excellent reference. Another useful resource is the Python wiki. This is a database of Python’s documentation that anyone can edit and contribute to. The information on this database is up to date and very helpful, especially in finding help and further resources for learning the language. As a site like this grows in size, it will become even better (both for finding help and further resources for learning python, but also for its own sake).
https://cecileparkmedia.com/python-for-beginners-everything-you-need-to-know/
CC-MAIN-2022-27
refinedweb
933
71.65
Building a Habit Tracker with Prisma 2, Chakra UI, and React In June 2019, Prisma 2 Preview was released. Prisma 1 changed the way we interact with databases. We could access databases through plain JavaScript methods and objects without having to write the query in the database language itself. Prisma 1 acted as an abstraction in front of the database so it was easier to make CRUD (create, read, update and delete) applications. Prisma 1 architecture looked like this: Notice that there’s an additional Prisma server required for the back end to access the database. The latest version doesn’t require an additional server. It’s called The Prisma Framework (formerly known as Prisma 2) which is a complete rewrite of Prisma. The original Prisma was written in Scala, so it had to be run through JVM and needed an additional server to run. It also had memory issues. The Prisma Framework is written in Rust so the memory footprint is low. Also, the additional server required while using Prisma 1 is now bundled with the back end, so you can use it just like a library. The Prisma Framework consists of three standalone tools: - Photon: a type-safe and auto-generated database client (“ORM replacement”) - Lift: a declarative migration system with custom workflows - Studio: a database IDE that provides an Admin UI to support various database workflows. Photon is a type-safe database client that replaces traditional ORMs, and Lift allows us to create data models declaratively and perform database migrations. Studio allows us to perform database operations through a beautiful Admin UI. Why use Prisma? Prisma removes the complexity of writing complex database queries and simplifies database access in the application. By using Prisma, you can change the underlying databases without having to change each and every query. It just works. Currently, it only supports mySQL, SQLite and PostgreSQL. Prisma provides type-safe database access provided by an auto-generated Prisma client. It has a simple and powerful API for working with relational data and transactions. It allows visual data management with Prisma Studio. Providing end-to-end type-safety means developers can have confidence in their code, thanks to static analysis and compile-time error checks. The developer experience increases drastically when having clearly defined data types. Type definitions are the foundation for IDE features — like intelligent auto-completion or jump-to-definition. Prisma unifies access to multiple databases at once (coming soon) and therefore drastically reduces complexity in cross-database workflows (coming soon). It provides automatic database migrations (optional) through Lift, based on a declarative datamodel expressed using GraphQL’s schema definition language (SDL). Prerequisites For this tutorial, you need a basic knowledge of React. You also need to understand React Hooks. Since this tutorial is primarily focused on Prisma, it’s assumed that you already have a working knowledge of React and its basic concepts. If you don’t have a working knowledge of the above content, don’t worry. There are tons of tutorials available that will prepare you for following this post. Throughout the course of this tutorial, we’ll be using yarn. If you don’t have yarn already installed, install it from here. To make sure we’re on the same page, these are the versions used in this tutorial: - Node v12.11.1 - npm v6.11.3 - npx v6.11.3 - yarn v1.19.1 - prisma2 v2.0.0-preview016.2 - react v16.11.0 Folder Structure Our folder structure will be as follows: streaks-app/ client/ server/ The client/ folder will be bootstrapped from create-react-app while the server/ folder will be bootstrapped from prisma2 CLI. So you just need to create a root folder called streaks-app/ and the subfolders will be generated while scaffolding it with the respective CLIs. Go ahead and create the streaks-app/ folder and cd into it as follows: $ mkdir streaks-app && cd $_ The Back End (Server Side) Bootstrap a new Prisma 2 project You can bootstrap a new Prisma 2 project by using the npx command as follows: $ npx prisma2 init server Alternatively, you can install prisma2 CLI globally and run the init command. The do the following: $ yarn global add prisma2 // or npm install --global prisma2 $ prisma2 init server Run the interactive prisma2 init flow & select boilerplate Select the following in the interactive prompts: - Select Starter Kit - Select JavaScript - Select GraphQL API - Select SQLite Once terminated, the init command will have created an initial project setup in the server/ folder. Now open the schema.prisma file and replace it with the following: generator photon { provider = "photonjs" } datasource db { provider = "sqlite" url = "file:dev.db" } model Habit { id String @default(cuid()) @id name String @unique streak Int } schema.prisma contains the data model as well as the configuration options. Here, we specify that we want to connect to the SQLite datasource called dev.db as well as target code generators like photonjs generator. Then we define the data model Habit, which consists of id, name and streak. id is a primary key of type String with a default value of cuid(). name is of type String, but with a constraint that it must be unique. streak is of type Int. The seed.js file should look like this: const { Photon } = require('@generated/photon') const photon = new Photon() async function main() { const workout = await photon.habits.create({ data: { name: 'Workout', streak: 49, }, }) const running = await photon.habits.create({ data: { name: 'Running', streak: 245, }, }) const cycling = await photon.habits.create({ data: { name: 'Cycling', streak: 77, }, }) const meditation = await photon.habits.create({ data: { name: 'Meditation', streak: 60, }, }) console.log({ workout, running, cycling, meditation, }) } main() .catch(e => console.error(e)) .finally(async () => { await photon.disconnect() }) This file creates all kinds of new habits and adds it to the SQLite database. Now go inside the src/index.js file and remove its contents. We’ll start adding content from scratch. First go ahead and import the necessary packages and declare some constants: const { GraphQLServer } = require('graphql-yoga') const { makeSchema, objectType, queryType, mutationType, idArg, stringArg, } = require('nexus') const { Photon } = require('@generated/photon') const { nexusPrismaPlugin } = require('nexus-prisma') Now let’s declare our Habit model just below it: const Habit = objectType({ name: 'Habit', definition(t) { t.model.id() t.model.name() t.model.streak() }, }) We make use of objectType from the nexus package to declare Habit. The name parameter should be the same as defined in the schema.prisma file. The definition function lets you expose a particular set of fields wherever Habit is referenced. Here, we expose id, name and streak field. If we expose only the id and name fields, only those two will get exposed wherever Habit is referenced. Below that, paste the Query constant: const Query = queryType({ definition(t) { t.crud.habit() t.crud.habits() // t.list.field('habits', { // type: 'Habit', // resolve: (_, _args, ctx) => { // return ctx.photon.habits.findMany() // }, // }) }, }) We make use of queryType from the nexus package to declare Query. The Photon generator generates an API that exposes CRUD functions on the Habit model. This is what allows us to expose t.crud.habit() and t.crud.habits() method. t.crud.habit() allows us to query any individual habit by its id or by its name. t.crud.habits() simply returns all the habits. Alternatively, t.crud.habits() can also be written as: t.list.field('habits', { type: 'Habit', resolve: (_, _args, ctx) => { return ctx.photon.habits.findMany() }, }) Both the above code and t.crud.habits() will give the same results. In the above code, we make a field named habits. The return type is Habit. We then call ctx.photon.habits.findMany() to get all the habits from our SQLite database. Note that the name of the habits property is auto-generated using the pluralize package. It’s therefore recommended practice to name our models singular — that is, Habit and not Habits. We use the findMany method on habits, which returns a list of objects. We find all the habits as we have mentioned no condition inside of findMany. You can learn more about how to add conditions inside of findMany here. Below Query, paste Mutation as follows: const Mutation = mutationType({ definition(t) { t.crud.createOneHabit({ alias: 'createHabit' }) t.crud.deleteOneHabit({ alias: 'deleteHabit' }) t.field('incrementStreak', { type: 'Habit', args: { name: stringArg(), }, resolve: async (_, { name }, ctx) => { const habit = await ctx.photon.habits.findOne({ where: { name, }, }) return ctx.photon.habits.update({ data: { streak: habit.streak + 1, }, where: { name, }, }) }, }) }, }) Mutation uses mutationType from the nexus package. The CRUD API here exposes createOneHabit and deleteOneHabit. createOneHabit, as the name suggests, creates a habit whereas deleteOneHabit deletes a habit. createOneHabit is aliased as createHabit, so while calling the mutation we call createHabit rather than calling createOneHabit. Similarly, we call deleteHabit instead of deleteOneHabit. Finally, we create a field named incrementStreak, which increments the streak of a habit. The return type is Habit. It takes an argument name as specified in the args field of type String. This argument is received in the resolve function as the second argument. We find the habit by calling ctx.photon.habits.findOne() while passing in the name parameter in the where clause. We need this to get our current streak. Then finally we update the habit by incrementing the streak by 1. Below Mutation, paste the following: const photon = new Photon() new GraphQLServer({ schema: makeSchema({ types: [Query, Mutation, Habit], plugins: [nexusPrismaPlugin()], }), context: { photon }, }).start(() => console.log( `🚀 Server ready at:\n⭐️ See sample queries:`, ), ) module.exports = { Habit } We use the makeSchema method from the nexus package to combine our model Habit, and add Query and Mutation to the types array. We also add nexusPrismaPlugin to our plugins array. Finally, we start our server at localhost:4000. Port 4000 is the default port for graphql-yoga. You can change the port as suggested here. Let’s start the server now. But first, we need to make sure our latest schema changes are written to the node_modules/@generated/photon directory. This happens when you run prisma2 generate. If you haven’t installed prisma2 globally, you’ll have to replace prisma2 generate with ./node_modules/.bin/prisma2 generate. Then we need to migrate our database to create tables. Migrate your database with Lift Migrating your database with Lift follows a 2-step process: - Save a new migration (migrations are represented as directories on the file system) - Run the migration (to migrate the schema of the underlying database) In CLI commands, these steps can be performed as follows (the CLI steps are in the process of being updated to match): $ prisma2 lift save --name 'init' $ prisma2 lift up Again, you’d have to replace prisma2 with ./node_modules/.bin/prisma2 if you haven’t installed it globally. Now the migration process is done. We’ve successfully created the table. Now we can seed our database with initial values. Go ahead and run the following command in the terminal: $ yarn seed This will seed our database with eight habits, as specified in our seed.js file. Now you can run the server by typing: $ yarn dev This will run your server at localhost:4000, which you can open and query all the APIs you’ve made. List all habits query habits { habits { id name streak } } Find habit by name query findHabitByName { habit(where: { name: "Workout" }) { id name streak } } Create habit mutation createHabit { createHabit(data: { name: "Swimming", streak: 10 }) { id name streak } } Delete habit mutation deleteHabit { deleteHabit(where: { id: "ck2kinq2j0001xqv5ski2byvs" }) { id name streak } } Increment streak mutation incrementStreak { incrementStreak(name: "Workout") { streak } } This is all we need for the back end. Let’s work on the front end now. Front End (Client Side) Bootstrap a new React project Bootstrap a new React project by using create-react-app. Use npx to bootstrap a new project without having to install create-react-app globally by doing the following: $ npx create-react-app client Alternatively, you can install create-react-app globally and bootstrap a new React Project, then do this: $ yarn global add create-react-app // or npm install --global create-react-app $ create-react-app client This bootstraps a new React project using create-react-app. Now go into the client/ directory, run the project, and type this: $ cd client $ yarn start This will run the client side on localhost:3000. It should now look like this: Now go into the src/ directory and remove unneeded files like App.css, App.test.js, index.css and logo.svg: $ cd src $ rm App.css App.test.js index.css logo.svg Remove the references to the removed files from index.js and App.js. index.js should now look like this:(); And make sure your App.js looks like this: import React from 'react' function App() { return <div>Streaks App</div> } export default App urql: Universal React Query Language Go ahead and first install urql, which is an alternative of Apollo Client. We also need to install graphql, as it’s a peer dependency of urql. You can do so by typing the following command in the terminal: $ cd .. // come out of the 'src/' directory and into the 'client/' directory $ yarn add urql graphql Now connect urql to the Prisma GraphQL back end by changing App.js to the following: import React from 'react' import { createClient, Provider } from 'urql' const client = createClient({ url: '' }) const App = () => ( <Provider value={client}> <div>Streaks App</div> </Provider> ) export default App Here, we use urql‘s createClient function by passing in our back-end url and then passing it as a value prop to the Provider component. This allows us to query, mutate or subscribe to any component which is the child of the Provider component. It should now look like this: Chakra UI In this tutorial, we’ll be using Chakra UI as our component library to make beautiful applications faster. This is a different kind of component library built for accessibility and speed in mind. It is completely themeable and composable. To install it, type the following in the terminal: $ yarn add @chakra-ui/core @emotion/core @emotion/styled emotion-theming Chakra uses Emotion under the hood, so we need to install it and its peer dependencies. In this tutorial, we also need graphql-tag to parse our GraphQL queries, react-icons to show beautiful icons, @seznam/compose-react-refs to compose multiple refs and react-hook-form to create Forms. Make sure to install them as well by typing the following in the terminal: $ yarn add graphql-tag react-icons @seznam/compose-react-refs react-hook-form Now go ahead and change App.js to the following: import { Text, ThemeProvider } from '@chakra-ui/core' import React from 'react' import { createClient, Provider } from 'urql' const client = createClient({ url: '' }) const App = () => ( <Provider value={client}> <ThemeProvider> <> <Text fontSize='5xl' textAlign='center'> Streaks App </Text> </> </ThemeProvider> </Provider> ) export default App We imported Text and ThemeProvider from @chakra-ui/core. Text component is used to render text and paragraphs within an interface. It renders a <p> tag by default. We make our Text components fontSize as 5xl and we align it to the center. We also wrap the whole thing inside ThemeProvider. ThemeProvider lets us add a theme to our application by passing in the theme object as a prop. Chakra UI comes with a default theme which we see if we wrap ThemeProvider on top of our components. The layout now looks like this: Try removing ThemeProvider to see how it affects the layout. It looks like this: Put it back in. Now, let’s code our application. Now go ahead and create a components and a graphql folder: $ mkdir components graphql Go inside the graphql folder and create files named createHabit.js, deleteHabit.js, incrementStreak.js, listAllHabits.js and index.js. $ cd graphql $ touch createHabit.js deleteHabit.js incrementStreak.js listAllHabits.js index.js List all habits query Open up listAllHabits.js and paste the following: import gql from 'graphql-tag' export const LIST_ALL_HABITS_QUERY = gql` query listAllHabits { habits { id name streak } } ` Notice that the above query is similar to what we typed in the GraphiQL editor. This is how GraphQL is used. First, we type the query or mutation in the GraphiQL editor and see if it gives the data that we need and then we just copy-paste it into the application. Create habit mutation Inside createHabit.js, paste the following: import gql from 'graphql-tag' export const CREATE_HABIT_MUTATION = gql` mutation createHabit($name: String!, $streak: Int!) { createHabit(data: { name: $name, streak: $streak }) { id name streak } } ` Again we have copied the mutation from our GraphiQL editor above. The main difference is we have replaced the hardcoded value with a variable noted by $ so we can type in whatever user has specified. The above mutation will be used to create a habit. Delete habit mutation Paste the following in deleteHabit.js: import gql from 'graphql-tag' export const DELETE_HABIT_MUTATION = gql` mutation deleteHabit($id: ID!) { deleteHabit(where: { id: $id }) { id name streak } } ` The above mutation will be used to delete a habit. Increment streak mutation Paste the following in incrementStreak.js: import gql from 'graphql-tag' export const INCREMENT_STREAK_MUTATION = gql` mutation incrementStreak($name: String) { incrementStreak(name: $name) { streak } } ` The above mutation will be used to increment the streak of a given habit. Finally, to make it easy to import everything from one file, paste the following in index.js: export * from './createHabit' export * from './deleteHabit' export * from './incrementStreak' export * from './listAllHabits' This lets us import stuff from a single file instead of four different files. This is beneficial when we have 10s of queries and mutations. Now go inside of components/ directory and create files named CreateHabit.js, DeleteHabit.js, Habit.js, ListAllHabits.js and index.js. $ cd ../components/ $ touch CreateHabit.js DeleteHabit.js Habit.js ListAllHabits.js index.js We will touch the rest of the files later in this tutorial, but for now open up index.js and paste the following: export * from './Common/Error' export * from './Common/Loading' export * from './CreateHabit' export * from './DeleteHabit' export * from './Habit' export * from './ListAllHabits' Now create a Common/ folder and inside that create Error.js: $ mkdir Common && cd $_ $ touch Loading.js Error.js cd $_ allows us to go inside the Common directory immediately after it’s created. Then we create Error.js inside it. Now create a utils/ folder inside the src/ directory with two files inside it — getIcon.js and index.js: $ cd ../../ $ mkdir utils/ && cd $_ $ touch getIcon.js index.js Create icons for habits Now open up getIcon.js and paste the following: import { AiOutlineQuestion } from 'react-icons/ai' import { FaCode, FaRunning, FaSwimmer } from 'react-icons/fa' import { FiPhoneCall } from 'react-icons/fi' import { GiCycling, GiMeditation, GiMuscleUp, GiTennisRacket, } from 'react-icons/gi' import { MdSmokeFree } from 'react-icons/md' const icons = [ { keywords: ['call', 'phone'], pic: FiPhoneCall, }, { keywords: ['workout', 'muscle', 'body-building', 'body building'], pic: GiMuscleUp, }, { keywords: ['cycling', 'cycle'], pic: GiCycling, }, { keywords: ['running', 'run'], pic: FaRunning, }, { keywords: ['swimming', 'swim'], pic: FaSwimmer, }, { keywords: ['racket', 'tennis', 'badminton'], pic: GiTennisRacket, }, { keywords: [ 'smoke', 'smoking', 'no smoking', 'no-smoking', 'smoke free', 'no smoke', ], pic: MdSmokeFree, }, { keywords: ['code', 'code everyday', 'program', 'programming'], pic: FaCode, }, { keywords: ['meditate', 'meditation'], pic: GiMeditation, }, ] export const getIcon = name => { let icon = AiOutlineQuestion for (let i = 0; i < icons.length; i++) { const { keywords, pic } = icons[i] const lowerCaseName = name.toLowerCase() const doesKeywordExistInName = keywords.some(keyword => lowerCaseName.includes(keyword), ) if (doesKeywordExistInName) { icon = pic break } } return icon } This is a helper file that contains a single function named getIcon. It takes in a habit name and returns an appropriate icon. To add more icons, you need to add an object to the icons array with an appropriate keywords and pic, which can be imported from react-icons. Let’s import this function from index.js so we can easily import it without having to remember the file name. This isn’t required here but it’s helpful when the application gets big. Open index.js and paste the following one-liner: export * from './getIcon' Go ahead and open up import { Flex, Spinner } from '@chakra-ui/core' import React from 'react' export const Loading = () => ( <Flex justify='center' flexWrap='wrap'> <Spinner thickness='4px' speed='0.65s' emptyColor='gray.200' color='blue.800' size='xl' /> </Flex> ) We show a nice Spinner which we imported from the Chakra UI library. We wrap it in a Flex component which makes it easy to apply Flexbox without having to write CSS. In my opinion, Chakra makes it easy to make beautiful applications faster without having to write custom CSS. Now open up Error.js and paste the following: import { Alert, AlertDescription, AlertIcon, AlertTitle, Flex, } from '@chakra-ui/core' import React from 'react' export const Error = () => ( <Flex justify='center' flexWrap='wrap'> <Alert status='error'> <AlertIcon /> <AlertTitle mr={2}>Whoops,</AlertTitle> <AlertDescription> there has been an error. Please try again later! </AlertDescription> </Alert> </Flex> ) Here, we show an error box. You can easily find the above code on the Chakra UI docs. No rocket science here. Just plain old copy-paste. Display a single habit Open up Habit.js and paste the following: import { Badge, Box, Flex, Text } from '@chakra-ui/core' import React from 'react' import { useMutation } from 'urql' import { INCREMENT_STREAK_MUTATION } from '../graphql/index' import { getIcon } from '../utils> </Text> </Flex> ) } The Habit component displays a single habit with a streak badge. It takes in index and habit. We use index to rotate the background colors of a habit from the colors array. Once the last color is displayed it will go back to the first one. Inside the Flex component, we display an icon by calling in the Box component with an as prop. The as prop is used to replace the Box component’s default div with anything that is specified in the as prop. So in this case, we’ll replace it with the return value of getIcon, which is an icon from react-icons. Next up, we display the name inside the Text component and wrap the streak with the Badge component. The streak, when clicked, calls the INCREMENT_STREAK_MUTATION, which we’ve defined above with urql‘s useMutation function. We pass the appropriate habit name to the function so that we can increment that specific habit. Display a list of habits Open ListAllHabits.js and paste the following: import { Flex, Text } from '@chakra-ui/core' import React from 'react' import { useQuery } from 'urql' import { LIST_ALL_HABITS_QUERY } from '../graphql/index' import {> )} {data.habits.map((habit, i) => ( <Habit key={habit.id} index={i} habit={habit} /> ))} </Flex> ) } Here, we fetch all habits by calling in urql‘s useQuery function by passing in LIST_ALL_HABITS_QUERY. It gives back fetching, error and data. When fetching is true, we display the Spinner. When error is true, we display the Error component, which displays an Alert. Later, we check if there exist any habits, and if there aren’t any habits then we display You currently track 0 habits. Add one. If we have any habits, we display them so it looks like this: Try clicking on the streak badge to see it increase. Delete a habit Now, go ahead and open up DeleteHabit.js and paste the following: import { AlertDialog, AlertDialogBody, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, Button, IconButton, } from '@chakra-ui/core' import React from 'react' import { useMutation } from 'urql' import { DELETE_HABIT_MUTATION } from '../graphql/index' export const DeleteHabit = ({ id, name }) => { const [isOpen, setIsOpen] = React.useState() const onClose = () => setIsOpen(false) const cancelRef = React.useRef() const [res, executeMutation] = useMutation(DELETE_HABIT_MUTATION) // eslint-disable-line no-unused-vars const deleteHabit = () => { executeMutation({ id }) onClose() } return ( <> <IconButton variantColor='red' border='1px solid white' aria- Delete “{name}” Habit </AlertDialogHeader> <AlertDialogBody> Are you sure? You can't undo this action afterwards. </AlertDialogBody> <AlertDialogFooter> <Button ref={cancelRef} onClick={onClose}> Cancel </Button> <Button variantColor='red' onClick={deleteHabit} ml={3}> Delete </Button> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </> ) } Most of this code is grabbed from Chakra UI’s AlertDialog. The main objective of this component is to show a trash icon when clicked alerts a modal with two buttons Cancel and Delete. On clicking Cancel, it calls the onClose function, which makes the modal disappear, and on clicking Delete it calls the deleteHabit function. The deleteHabit function calls the DELETE_HABIT_MUTATION while passing it the id it gets from the parent component and closes the modal by calling onClose. Now again open up Habit.js and add the following import to the top: import { DeleteHabit } from './index' And now just below closing Badge component, add the following code: <DeleteHabit id={id} name={name} /> The whole Habit.js file should now look like this: import { Badge, Box, Flex, Text } from '@chakra-ui/core' import React from 'react' import { useMutation } from 'urql' import { INCREMENT_STREAK_MUTATION } from '../graphql/index' import { getIcon } from '../utils/index' import { DeleteHabit } from '.> <DeleteHabit id={id} name={name} /> </Text> </Flex> ) } It should now look like this: Now try clicking the trash icon on any of the habits. It should open up a modal as follows: If you click Cancel, it will just close the modal. If you click Delete, the habit will be removed from the UI and the Prisma Database itself as follows: Create a habit Now let’s open up CreateHabit.js and paste the following: import { Button, Flex, FormControl, FormLabel, Icon, Input, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, useDisclosure, } from '@chakra-ui/core' import composeRefs from '@seznam/compose-react-refs' import React, { useRef } from 'react' import useForm from 'react-hook-form' import { useMutation } from 'urql' import { CREATE_HABIT_MUTATION } from '../graphql/index' export const CreateHabit = () => { const { handleSubmit, register } = useForm() const { isOpen, onOpen, onClose } = useDisclosure() const [res, executeMutation] = useMutation(CREATE_HABIT_MUTATION) // eslint-disable-line no-unused-vars const initialRef = useRef() const finalRef = useRef() const onSubmit = (values, e) => { const { name, streak } = values executeMutation({ name, streak: +streak, }) e.target.reset() onClose() } return ( <Flex width='300px' height='300px' borderRadius='40px' margin='16px' padding='16px' justify='center' flexWrap='wrap' > <Icon name='small-add' onClick={onOpen} <Modal initialFocusRef={initialRef} finalFocusRef={finalRef} isOpen={isOpen} onClose={onClose} > <ModalOverlay /> <ModalContent> <ModalHeader>Create Habit</ModalHeader> <ModalCloseButton /> <form onSubmit={handleSubmit(onSubmit)}> <ModalBody pb={6}> <FormControl> <FormLabel htmlFor='name'>Habit name</FormLabel> <Input name='name' ref={composeRefs(initialRef, register)} </FormControl> <FormControl mt={4}> <FormLabel htmlFor='streak'>Streak</FormLabel> <Input name='streak' type='number' placeholder='Enter your streak' width='90%' ref={register} /> </FormControl> </ModalBody> <ModalFooter> <Button type='submit' rounded='md' bg='green.500' color='white' mr={3} > Save </Button> <Button onClick={onClose}>Cancel</Button> </ModalFooter> </form> </ModalContent> </Modal> </Flex> ) } Again, most of this content is copied from Chakra UI’s FormControl. Here, we show a + icon to the user, which we bring in from Chakra’s own Icon component. When the + icon is clicked, we open up a modal that uses react-hook-form. React Hook Form is the easiest way to build forms with Hooks. We just need to pass in register to the refs of the inputs we want to track. We get the register when we call the hook useForm from react-hook-form. We also get handleSubmit, which we need to pass to the form component. We need to pass handleSubmit a function. In our case, we pass onSubmit and the first parameter values of this function are the values we get, which are entered by the user. One important thing to note here is that we use composeRefs from @seznam/compose-react-refs to compose multiple refs. This is needed because we need to provide the register ref to register our React Hook Form and to keep track of the value. And the second ref initialRef is needed because we need it to focus on the first input as soon as the popup appears. This is necessary for accessibility as well for those who are using screen readers. Finally, when we call onSubmit we check if it’s not empty and then we call the mutation with two parameters name and streak. +streak means the String is coerced into a Number. Basically, all values returned from React Hook Form are strings, but in our back end, we’re expecting a number. Lastly, we reset the form to clear all the values and input states. And then we close the modal. Now go ahead and import CreateHabit into ListAllHabits.js at the top: import { CreateHabit, Error, Habit, Loading } from './index' Also, make sure to include it just above where you list all habits using Array.map() as follows: <CreateHabit /> The ListAllHabits.js file must now look like this: import { Flex, Text } from '@chakra-ui/core' import React from 'react' import { useQuery } from 'urql' import { LIST_ALL_HABITS_QUERY } from '../graphql/index' import { CreateHabit,> )} <CreateHabit /> {data.habits.map((habit, i) => ( <Habit key={habit.id} index={i} habit={habit} /> ))} </Flex> ) } It should now show the + sign as follows: Now click the + sign and add our Workout habit with 50 streaks that we deleted. Once you click Save, notice it immediately gets added. You can add a bunch of other habits that you want to track. After adding a bunch of habits, it now looks like: Conclusion In this tutorial, we built a complete habit tracker app “Streaks” from scratch. We used Chakra UI as our React component library to make a beautiful, accessible application with speed. Chakra UI helped us create alerts, modals, and spinners by just adding the built-in building blocks so we could focus on writing the logic rather than writing CSS. We used React Hooks Form to create simple and easy forms by using React Hooks. It allowed us to keep our forms DRY without writing a lot of code. In our back end, we used The Prisma Framework. We used Prisma’s own Photon to create data-models declaratively and Lift to perform database migrations. Prisma makes it simple to query the database by using static typing, which allows us to code with confidence. The built-in autocompletion allows us to write applications at a lightning speed. While The Prisma Framework is in beta, you can have fun with it in your side projects. It will soon be out, so stay tuned. Now go on and create your own full-stack applications with confidence.
https://www.sitepoint.com/habit-tracker-prisma-2-chakra-ui-react/
CC-MAIN-2020-16
refinedweb
4,980
56.76
Created on 2002-11-25 23:37 by terry.reedy, last changed 2008-08-31 12:46 by ncoghlan. This issue is now closed. The lookup of special methods invoked implicitly by syntax other than explicit instance.attribute changed to *not* use __gettattr__ when normal lookup failed. This is contrary to docs, which consistently say __getattr__ is unchanged. New special method __getattribute__ is also bypassed, contrary to implication of doc-essay. This was reported on c.l.p by Jan Decaluwe using 2.2.2 on Red Hat Linux. On Win98, 2.2.1, I get same behavior (I added test of __getattribute__): class Iold: def __init__(self,ob): self.ob = ob def __getattr__(self,name): return getattr(self.ob,name) class Inew(object): def __init__(self,ob): self.ob = ob def __getattr__(self,name): return getattr(self.ob,name) a = Iold(1) #2 b = Inew(1) #2 a.__add__(1) #2 b.__add__(1) #2 a+1 #2 b+1 #error #TypeError: unsupported operand types for +: 'Inew' and 'int' Inew.__getattribute__ = Inew.__getattr__ b+1 #same error, no loop #TypeError: unsupported operand types for +: 'Inew' and 'int' b.__add__(1) # WARNING starts 'infinite' loop def _(self,other): print 'hello' Inew.__add__ = _ b+1 #prints 'hello', __getattribute__ bypassed. says: "Note that while in general operator overloading works just as for classic classes, there are some differences. (The biggest one is the lack of support for __coerce__; new-style classes should always use the new-style numeric API, which passes the other operand uncoerced to the __add__ and __radd__ methods, etc.) " Was lookup change meant to be one of differences? "There's a new way of overriding attribute access. The __getattr__ hook, if defined, works the same way as it does for classic classes: it is only called if the regular way of searching for the attribute doesn't find it." But it is different. "But you can now also override __getattribute__, a new operation that is called for all attribute references." Except for implicit special methods. I did not classify discrepancy because I don't know whether interpreter or docs are off. Logged In: YES user_id=593130 Print-style 'debugging' output provided by Bengt Richter in a follow-up in the c.l.p. thread "Issue with new-style classes and operators" showed that 'a+1' worked because of a __getattr__ call getting '__coerce__' (rather than '__add__') and that 'b+1' did not trigger such a call. So I presume the quoted parenthesized statement about __coerce__ and 'new-style numeric API' was meant to explain as least this part of the change in behavior. However, it is still not clear to me, even after reading the development (2.3a) version of the ref manual, why failure to find '__add__' in 'the usual places' (to quote RefMan 3.3.2 __getattr__ entry) does not trigger a call to __getattr__, nor why the initial attempt to find it did not trigger __getattribute__. The sentence 'For objects x and y, first x.__op__(y) is tried' (3.3.7) implies to me that there is an attempt to find __op__ as an attribute of x. Unless I missed something I should have found, a bit more clarification might be usefully added. Logged In: YES user_id=1038590 FWIW, this is still true for Python 2.4 (i.e. the search for '__add__' by '+' invokes neither __getattr__ nor __getattribute__). The 'infinite loop' is courtesy of the call to 'self.ob' inside __getattr__. Also of interest - int(b) fails with a TypeError, and str(b) returns the generic object representation of b, rather than delegating to the contained object. So it looks like these methods are not invoked when looking up any 'magic methods' recognised by the interpreter. Inspection of PyNumber_Add shows that this is the case - the objects' method pointers are inspected directly at the C level. To me, this looks like a documentation bug. Magic methods are found by checking if the associated slot in the method structure is not NULL, rather than by actually looking for the relevant magic 'attribute'. In order to change the 'implicit' behaviour of the object, it is necessary to change the contents of the underlying method slot - a task which is carried out by type whenever an attribute is set, or when a new instance of type is created. I was just bit by this today in converting a proxy class from old style to new style. The official documentation was of no help in discoverting that neither __getattr__ or __getattribute__ are used to look up magic attribute names. Even the link to "New-style Classes" off the development documentation page is useless, as none of the resources there () mention the incompatible change. This seems like an issue that is going to come up more frequently as python 3000 pushes everyone to using only new style classes. It'd be very useful if whatever conversion tool we get, or the python 3000 standard library includes a proxy class or metaclass that is able to help with this conversion, such as this one: Though preferably with some knowledge of all exising magic names. The 2.6 and 3.0 documentation has already been updated appropriately. The forward compatible way to handle this is to inherit from object and override the special methods explicitly in the 2.x version (Yes this can make writing proxy objects more tedious, but from our experience with the tempfile module, I would say that the bulk of proxy objects that aren't overriding special methods on a case-by-case basis are probably broken anyway). It may be appropriate to add a -3 warning that is triggered whenever a special method is retrieved via __getattr__ on a classic class. I assume when you say that the documentation has already been updated, you mean something other than what's shown at:- classic-classes or- classic-classes ? As both of those claim to still not be up to date in relation to new style classes, and the __getattr__ & __getattribute__ sections under special names make no reference to how magic methods are handled. Additionally, the "Class Instances" section under the type heirachy makes mention of how attributes are looked up, but doesn't mention the new style differences even in the 3.0 documentation. Sure, there's this note under "Special Method Names": For new-style classes, special methods are only guaranteed to work if defined in an object’s class, not in the object’s instance dictionary. But that only helps you figure it out if you already know what the problem is, and it's hardly comprehensive. I'm not arguing that this is something that's going to change, as we're way past the point of discussion on the implementation, but this looks far more annoying if you're looking at it from the perspective of proxying to container classes or numeric types in a generic fashion. My two use cases I've had to convert are for lazy initialization of an object and for building an object that uses RPC to proxy access to an object to a remote server. In both cases, since they are generic proxies that once initialized are supposed to behave exactly like the proxied instance, the list of magic methods to pass along is ridiculously long. Sure, I have to handle __copy__ & __deepcopy__, and __getstate__ & __setstate__ to make sure that they return instances of the proxy rather than the proxied object, but other than that there's over 50 attributes to override for new style classes just to handle proxying to numeric and container types. It's hard to get fancy about it too, as I can't just dynamically add the needed attributes to my instances by looking at the object to be proxied, it really has to be a static list of everything that python supports on the class. Additionally, while metaclasses might help here, there's still the problem that while my old style proxy class has continued to work fine as magic attributes have been added over python revisions, my new style equivalent will have to be updated work currectly as magic methods are added. Which, given the 2.x track seems to happen pretty frequently. Some of the bugs from that would have been quite tricky to track down too, such as the __cmp__ augmentation with the rich comparison methods. None of the solutions really seem ideal, or at least as good as what old style classes provided, which is why I was hoping for some support in the 3.0 standard library or the conversion tool. Agreed that section of the docs should be more explicit in pointing out that __getattr__ and __getattribute__ won't work for proxying special methods for new-style classes. It's also true that there are quite a few special methods where nothing special is needed to correctly proxy the methods. That said, defining all of the methods blindly is also bad (as a lot of informal type testing is done by checking for certain special methods as attributes). Perhaps it would be useful to have a method on type instances that could be explicitly invoked to tell the type to run through all the tp_* slots and populate them based on doing getattr(self, "__slotname__"). (Note that it's only those methods with dedicated slots in the C type structure that are a problem here - those which are implemented solely as normal Python methods like __enter__, __exit__ or the pickle module's special methods can typically be overridden as expected through the use of __getattr__ and __getattribute__) I've started a discussion on the Py3k development list regarding the possibility of adding a new method to type to aid in converting proxy classes from classic- to new-style. I spent an enlightening evening browsing through the source code for weakref.proxy. The way that code works is to define every slot, delegating to the proxied object to handle each call (wrapping and unwrapping the proxied object as needed). This is normally transparent to the user due to the fact that __getattribute__ is one of the proxied methods (and at the C level, the delegated slot invocations return NotImplemented or set the appropriate exceptions). The only way it shows through is the fact that operator.isNumber and operator.isMapping will always return True for the proxy instance, and operator.isSequence will always return False - this is due to the proxy type filling in the number and mapping slots, but not the sequence slots. However, this prompted me to try an experiment (Python 2.5.1), and the results didn't fill me with confidence regarding the approach of expecting 3rd party developers to explicitly delegate all of the special methods: >>> class Demo: ... def __index__(self): ... return 1 ... >>> a = Demo() >>> b = weakref.proxy(a) >>> operator.index(a) 1 >>> operator.index(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'weakproxy' object cannot be interpreted as an index Oops. Somewhat related: #2605 (descriptor __get__/__set__/__delete__) I've been following the py3k maliing list disscussion for this issue, and wanted to add a note about the proposed solution described here: The reason I think this approach is valuable is that in all of the proxy classes I've written, I'm concerned about which behaviour of the proxied class I want to override, not which behaviour I want to keep. In other words, when I proxy something, my mental model has always been, okay, I want something that behaves just like X, except it does this (usually small bit) differently. This is also why I expect my proxies to keep working the same when I change the proxied class, without having to go and update the proxy to also use the new behaviour. So, yeah, very much in favor of a base proxy class in the standard library. I've attached a sample ProxyBase class that delegates all of the special methods handled by weakref.proxy (as well as the tp_oct and tp_hex slots, which weakref.proxy ignores). While there are other special methods in CPython (e.g. __enter__ and __exit__), those don't bypass the normal lookup mechanism, so the __getattribute__ override should handle them. For lack of a better name, I called the module typetools (by analogy to functools). Note that correctly implementing a proxy class as a new-style class definitely turns out to be a fairly non-trivial exercise (and since this one is still sans-tests, I don't make any promises that even it is 100% correct at this point) Is there any reason not to name it ProxyMixin, ala DictMixin? Attached a new version of the module, along with a unit test file. The unit tests caught a bug in the __gt__ implementation. I've also changed the name to ProxyMixin as suggested by Adam and switched to using a normal __init__ method (there was no real gain from using __new__ instead). Added documentation, and assigned to Barry as release manager for 2.6/3.0. Also bumped to 'release blocker' status because I think the loss of classic classes transparent proxying capabilities is a fairly substantial issue that needs to be addressed explicitly before the first 3.0 beta. If I get the go-ahead from Barry or Guido, I'll add the new module to 2.6 (from whence it will be migrated to 3.0 as part of the normal merge process). Also changed to a library issue instead of a docs issue. _deref won't work for remote objects, will it? Nor _unwrap, although that starts to get "fun". Correct, this isn't intended to be an all-singing, all-dancing proxy implementation - it's meant to be a simple solution for local proxies that want to change the behaviour of a few operations while leaving other operations unaffected. The proposed documentation I uploaded covers some of its limitations. However, even for those cases, ProxyMixin and/or test_typetools.TestProxyMixin can be used as a reference to make sure a custom proxy implementation correctly handles all the special method invocations that can bypass __getattribute__. If it's so specialized then I'm not sure it should be in the stdlib - maybe as a private API, if there was a user. Having a reference implementation is noble, but this isn't the right way to do it. Maybe as an example in Doc or in the cookbook. Better yet, add the unit test and define the ProxyMixin directly in that file. Specialised? What's specialised about it? It's designed to serve as a replacement for the simple delegation use cases that are currently met quite adequately by classic classes, since those are no longer available in 3.0. As to the rationale for having it in the standard library: it's because of the coupling with the implementation of the type() builtin. If a new slot is added to type() that the interpreter may access without consulting __getattribute__, then ProxyMixin can be updated to correctly delegate that slot. If alternate implementations such as Jython or IronPython have additional such slots, they can also provide their own version of ProxyMixin. If ProxyMixin doesn't become the development responsibility of the same group that is responsible for the implementation of the type object then it may as well not exist (since it can't be trusted to be kept up to date with the development process). Surely remote proxies fall under what would be expected for a "proxy mixin"? If it's in the stdlib it should be a canonical implementation, NOT a reference implementation. At the moment I can think up 3 use cases: * weakref proxies * lazy load proxy * distributed object The first two could be done if _deref were made overridable. The third needs to turn everything into a message, which would could either do directly, or we could do by turning everything into normal method lookups which then get handled through __getattribute__. The way to override _deref/_unwrap is to make _target a property on a ProxyMixin subclass (which reminds me, I want to put in an explicit test case to make sure that works as intended - I'll use the weakref-proxy-in-Python as the example, so I'll also need to fix the docs to indicate that such a thing doesn't actually require rewriting the whole class). And there are a lot more use cases than just the ones you listed, primarily in the area of interface adaptation (i.e. the programmer just wants to fiddle with the visible API of the object a bit, rather than doing anything clever with the way the proxy's target is referenced). The reason I'm wary of attempting to provide direct support for the distributed communications use case, is that distributed computing needs to deal with all sorts of issues in relation to serialisation and transport of arguments and return values, that a local proxy of any kind simply doesn't have to deal with (since it can just pass direct references around). Note that merely diverting everything through __getattribute__ isn't even close to enough, due to the argument and return value transport problem - the RPC mechanism needs to understand the methods that are being invoked as well. So I'm quite happy leaving all those issues to tools that are actually designed to handle them (CORBA, XML-RPC, etc). Updated test cases and documentation to cover use of a descriptor for _target in a subclass, and uploaded most recent local copies of all 3 files. I've attached the latest version of the module as an actual patch against Python SVN. It differs slightly from the last version uploaded as separate files, in that in-place operations on a proxied object will no longer strip the proxy wrapper off the object. Instead, either the same proxy object will be returned if the target returned itself from the in-place operation (mutable objects), or a new proxy wrapper around the result of the target returned a different object (immutable objects). Example with a mutable target: >>> from typetools import ProxyMixin as p >>> x = p([]) >>> last_x = x >>> x += [1] >>> x <ProxyMixin for [1]> >>> last_x <ProxyMixin for [1]> Example with an immutable target: >>> from typetools import ProxyMixin as p >>> x = p(1) >>> last_x = x >>> x += 1 >>> x <ProxyMixin for 2> >>> last_x <ProxyMixin for 1> Note that I'll be offline for the next few days, so I want be able to respond to any comments until some time next week. The inplace operators aren't right for weakref proxies. If a new object is returned there likely won't be another reference to it and the weakref will promptly be cleared. This could be fixed with another property like _target, which by default type(self)(result). Weakref proxies could override it to raise an exception instead. Ah, that would answer my #XXX comment regarding that in the patch. Agreed, the best answer will be to factor out the _rewrap operation into a new class method. (Next week though...) This is a huge thread and I don't have time to look at the entire patch. However, it seems like the main purpose of the proxy class is to work around a basic deficiency in Python. Now, if this is a purposeful omissions (i.e. defined as part of the language), then a proxy class makes sense. If not, then you should probably work to fix the implementation. In general, the concept of a base proxy mixin makes sense if it's generic enough and flexible enough to be of wider use to Python programmers. One measure of that might be to re-implement the existing proxy-like classes to use this mixin class. If that can't be done, then this is too specialized (or too unproven) and should probably be a cheeseshop module first. I'm also uncomfortable with adding a new typestool module, mostly because we have a types module. I know they're there for different purposes, but still, it seems ugly to me. On top of that, adding a module for a single class seems like overkill. Do you have any ideas about where this might go in an existing module? Overall, I'm -0 on adding this to Python. Guido should have the final say though. I'm knocking this down to critical so it won't hold up the betas. Other than the refactoring, it seems like adding a proxy class, while being a new feature, is isolated enough that it could go in after beta. Unfortunately, the standard library doesn't tend to do this kind of delegation (aside from weakref.proxy, which implements the equivalent code directly in C), so there isn't a lot of standard library code that will benefit from it directly. However, maintaining such a class on PyPI is also fairly undesirable, due to the extremely tight coupling between the list of methods it needs to delegate explicitly and the tp_* slots in the PyType method definitions - add a new tp_* slot, and it's necessary to add the same methods to the proxy class. Different Python implementations are going to have different needs as to which slots they have to delegate explicitly, and which can be left to the __getattribute__ catch-all delegation. As far as adding a module for a single class goes, I wouldn't expect it to remain that way forever. E.g., I'd hope to eventually see a CallableMixin that defined __get__ the same way a function does, making it easier to create callables that behave like functions when stored as a class attribute. That said, I'd be happy enough with adding the ProxyMixin to the types module instead, but I thought we were still trying to get rid of that module. And (mainly for Barry's benefit) a quick recap of why I think this is necessary for Python 3.0: For performance or correctness reasons, the interpreter is permitted to bypass the normal __getattribute__ when looking up special methods such as __print__ or __index__. Whether or not the normal attribute lookup machinery is bypassed for a specific special method is an application independent decision. In CPython's case, this bypassing can occur either because there is a tp_* slot dedicated to the method, or because the interpreter uses Py_TYPE(obj) and _PyType_Lookup instead of PyObject_GetAttr to find the method implementation (or type(obj).meth instead of obj.meth for special method lookups implemented in Python code). This behaviour creates a problem for value-based delegation such as that provided by weakref.proxy: unlike overriding __getattr__ on a classic class, merely overriding __getattribute__ on a new-style class instance is insufficient to be able to correctly delegate all of the special methods. The intent of providing a typetools.ProxyMixin (or alternatively a types.ProxyMixin class) is to allow fairly simply conversion of classic classes that implement value-based delegation to new-style classes by inheriting from ProxyMixin rather than inheriting from object directly. Given the close proximity of the beta perhaps I should PEP'ify this to get a formal yea or nay from Guido? I haven't managed to get much response to previous python-dev posts about it. bleh, "application independent decision" in my last post should read "interpreter implementation dependent decision". and "__print__" was meant to be "__unicode__"... New patch (proxymixin.diff) uploaded that correctly delegates __format__, as well as using an overridable return_inplace() method to generate the inplace operation return values. The _target attribute has also been made formally part of the public API (as 'target'), although you obviously need to explicitly invoke object.__getattribute__ in order for it to be visible. The name of the attribute is also available at the module level as _PROXY_TARGET_ATTR. Note that I don't make any promises about the correctness of the ReST formatting in that latest patch - my Doc build is misbehaving at the moment, and I haven't had a chance to look at what is wrong with it. The name Proxy seems too vague. This class is all about targeted delegation. Am curious, has this been out as a recipe; has it been used in combat yet? I want to make this "bypass getattr" behavior mandatory for those operations that currently use it, forcing the issue for other implementations of Python. That's a doc change (but an important one!). There are probably many random places where the docs imply that getattr is used where it isn't. I am not sure that we need a proxy implementation in the stdlib; usually when proxying there is some intentional irregularity (that's why you're proxying) and I'm not sure how useful the mix-in class will be in practice. We should wait and see how effective it is in some realistic situations before accepting it into the stdlib. Also, typetools strikes me as a horrible name. Thanks for the pronouncement Guido. We will not let this issue hold up the beta releases. The outcome of discussion of this issue on python-dev was that the lookup methodology for the special methods needs to be better documented, especially for those cases where the instance *must* be bypassed in order to avoid metaclass confusion for special methods that apply to both types and instances (see issue 2517 for such a problem that currently afffects the lookup of __unicode__). However, we're not prepared to add a standard delegation mixin to the standard library at this stage (I may still add a cleaned up version of mine to the SVN sandbox as an executable reference source for the relevant section of the documentation though). While I offered to write that new section of the docs during the python-dev discussion, I'm not sure when I'll be able to get to it (My Python time lately has mostly been spent investigating __hash__ fun and games). Hi, I was trying to implement a generic proxy class with some restricting behaviors and then I bumped into this complication. May I ask what the conclusion is going to be in the long run? I guess my question is that 1> is it just going to be a documentation change (first)? 2> is it technically difficult(other things are going to be broken because of this change) or very inefficient to make the behavior of special method lookup same as normal methods? 2> Otherwise, what is the rationale behind keeping the differences? thank you. There are both speed and correctness reasons for special methods being looked up the way they are, so the behaviour isn't going to change. Aside from providing additional details in the language reference on how special methods are looked up (and the reasons things are done that way), the only change that might eventually happen in this area is the inclusion of a mixin class in the standard library to assist in writing classes which delegate most operations to another object. That part won't happen before 2.7/3.1 though (if it happens at all). Attaching a documentation patch for the moment until I get some info back from Georg as to why I can't build the docs locally. Once I get my local doc build working again, I'll check the formatting and check it in. Committed for 2.6 as r65487. I also blocked the automatic merge to 3.0 since the references to old-style classes don't make sense there. But don't the docs with patch describe the behavior of new-style classes better? I meant to say that I will be merging it manually to avoid bringing the old-style class specific parts over (that's why I left the issue open and assigned to me). Ah, I'm sorry for the noise then. Docs updated for 3.0 in r66084 (and I was right in thinking the automatic merge didn't have a hope of getting this right - there were conflicts all the way through the file). Closing this issue after a mere 5 years and 9 months - any requests for better proxying/special method delegation support in the standard library should be raised in a new tracker issue as a feature request for 2.7/3.1.
http://bugs.python.org/issue643841
CC-MAIN-2017-30
refinedweb
4,731
60.14
Odoo Help This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers. TypeError: Object has no method 'split' Hello, I have a method where I am trying to append a set of ids to a many2one field base on certain criteria. I get the set of ids just fine, but when I return the list using an onchange method, then I get this error TypeError: Object 61 has no method 'split' This is the method that I am using def on_change_get_sql_ver_set(self, cr, uid, ids, sql_ver_id, context=None): if sql_ver_id: sql_ver_obj = self.pool.get('product.sql.version') sql_rec = sql_ver_obj.browse(cr, uid, sql_ver_id) ids_set = sql_ver_obj.search(cr, uid, [('database_server','=', sql_rec.database_server)]) # raise osv.except_osv('UserError',ids_set) recs = {} recs['product_sql_version_id'] = ids_set #check ids_set return {'value': recs} I will need to add more search conditions to this method to do what I need, but right now I just want to try and add this set to the many2one field on the form. does anyone know how I can add the set of returned data/ids to the many2one!
https://www.odoo.com/forum/help-1/question/typeerror-object-has-no-method-split-46593
CC-MAIN-2016-50
refinedweb
196
70.33
In the changing landscape of technology, new tools emerge. Azure Databricks has been a prominent option for end-to-end analytics in the Microsoft Azure stack. In 2019, Microsoft introduced Azure Synapse. With it came Azure Synapse Analytics. We wrote about the philosophy behind Synapse back then. Here is our article on the same: Azure Synapse Analytics: Azure SQL Data Warehouse revamped. So what are the nuances that one needs care for migrating from Azure Databricks to Azure Synapse? We covered one of the aspects of moving from Azure Data Factory to Azure Synapse Integration here: Migrating from Azure Data Factory to Azure Synapse Integration. Firstly, this is not a comparison article between Azure Databricks and Azure Synapse Analytics. In fact, we are not even touching upon the performance or cost aspects. We assume that you have decided to migrate from Azure Databricks to Azure Synapse Analytics and there is no turning back. So what are the changes you need to make your spark code? Note that Azure Synapse is built on top of open-source Spark as opposed to Databricks that has built some additional modules. This forms the basis of three important features of Databricks that need an alternative in the synapse: 1. Replacing Azure Key vault backed Databricks secret scope. Writing secure code is a key aspect any developer needs to know. At no place, the sensitive information like passwords can be exposed. Azure Key vault is a Microsoft Azure service that can store sensitive data in form of secrets. To access these secrets, Azure Databricks has a feature called Azure Key vault backed secret scope. To know more about how to set it up for your Azure Databricks workspace, read this tutorial by Microsoft. Coming to Synapse, it does not have the concept of secret scopes. So, how do we access secrets? Turns out that there is a way by using a module named TokenLibrary. However, the following steps need to be performed beforehand: - Create a linked service to the Azure Key Vault in Azure Synapse Analytics. - The Synapse workspace has a managed identity like all the other Azure services. Grant the GET permission to it on the key-vault. - Use the getSecret() method to access the requisite key-vault secret. Following is the reference code snippet: import sys from pyspark.sql import SparkSession sc = SparkSession.builder.getOrCreate() token_library = sc._jvm.com.microsoft.azure.synapse.tokenlibrary.TokenLibrary connection_string = token_library.getSecret("<AZURE KEY VAULT NAME>", "<SECRET KEY>", "<LINKED SERVICE NAME>") print(connection_string) 2. Replacing dbutils in the Azure Synapse Analytics. As aforementioned, Databricks has added certain flavours on top of open-source spark. One of the very useful features that Databricks has built is dbutils, also called Databricks Utilities. It comprises functions to manage file systems, notebooks, secrets, etc. This is especially very useful in file system tasks like copy, remove, etc. To know more, refer to this link. On the other hand, Azure has its own version of dbutils called Microsoft Spark Utilities. To dive deep into it, refer to this link. 3. No Databricks Magic commands available in the Azure Synapse Analytics. Finally, code reusability is one of the most important Software Engineering paradigms. Imagine that you want to re-use some commonly occurring functions across different notebooks. In Databricks this can be achieved easily using magic commands like %run. Alternately, you can also use dbutils to run notebooks. This helps us create notebook workflows easily. Unfortunately, Azure Synapse Analytics does not have the same feature. This creates code redundancy across notebooks. Hopefully, Microsoft will add this feature in the future. Update: The %run feature exists in Synapse notebook (although in preview). Thanks to one of our readers who pointed it out. Here is the link for the same: Magic commands. Conclusion Hope you find this article useful. We do not guarantee its completeness or accuracy. However, this article will evolve since both platforms are evolving rapidly. For something written so recently, odd to say Synapse doesn’t have the %run feature We have edited the same now. Thanks for bringing this up. Microsoft Spark Utilities could be used to run notebooks. With this, you don’t have to create the same code in different notebooks in Azure Synapse Analytics. Yes. We made that Modification.
https://www.data4v.com/migrating-from-azure-databricks-to-azure-synapse-analytics/
CC-MAIN-2022-05
refinedweb
710
68.26
How would you rewrite this Python code? Dustin King ・2 min read I ran across this problem while writing some code for a challenge. I have some code that I want to write to a particular file if a filename is provided, or standard output if not: with (open(filename, 'w') if filename else sys.stdout) as file: do_something(file) That with line is a bit long, and doesn't seem readable at a glance. I could put the open outside the with: f = open(filename, 'w') if filename else sys.stdout with f as file: do_something(file) The file should be closed when the with is exited. I'm done with stdout in this case, but I could just have well have wanted to use it for other things later on in the program. But the worst thing about this way of doing it seems to be that making a habit of using open outside a with expression could lead to forgetting to close files. I could go the try/finally route: try: f = open(filename, 'w') if filename else sys.stdout do_something(f) finally: if f is not sys.stdout: f.close() But this seems a bit verbose and reminds me too much of Java, which, as a rule of thumb, probably means it's not Pythonic. I could write a context manager to hide the "check if it's stdout and close it" logic: from contextlib import contextmanager @contextmanager def file_or_stdout(fname): if fname: f = open(fname, 'w') yield f f.close() else: yield sys.stdout with file_or_stdout(filename) as file: do_something(file) This seems pretty clear, but it also might be overkill. I'm leaning toward this though, as it leaves the do_something block plenty of room for clarity, and I could extract the file_or_stdout function into a utility library so it's not cluttering up the file. Any thoughts? The 10 most popular dev.to posts of 2018 I took the 10 most popular posts in the year section of dev.to and added some t... I think the simplest is the first one :D Or you can wrap that if in a normal function if you plan to use it more than once: I don't think you need to use a context manager in this case because there are no other operations between the opening and closing of the file. Anyway I wouldn't do it like that. Keep in mind that if you use sys.stdout this way you will close it which means that any attempt to write on it after your withstatement will result in an error: So why do you need to hide stdout this way? It's probably easier to use StringIO, write to it and then use a print to display it on stdout. I'm just trying to keep the code clear and non-repetitive. In terms of level of effort and maintainability, if it needs to be able to optionally write to a file, breaking the inner logic out into a function as inspired by @thinkslynk is probably best. But if it's a one-off project it might be even better to only write to stdout and pipe it to a file in the shell if needed. (Sometimes it's fun to over-engineer though.) Actually the context manager solves this by only opening/closing the fp if it isn't to stdout so it might be the best solution Oh yes, you're right :-) +1 to the context manager, though it might be overkill if the function is used only once. I think the cleanest way is this: Certainly works if do_something is just a function call. I meant it as a stand-in for a larger block of code. But maybe that block should actually be a function. Yes, it should be a function. stdout/stderr/stdin are different from other streams in that they're managed outside (by the OS and Python, not by your app) whereas an open should be used with within simple cases if possible. You can start treating them the same when you start writing to / reading from them and stop when you stop doing that. All that can nicely be stuck away in a function. That also enables you to call the actual I/O part with a different file-like thing, say a StringIO instance when testing. I don't think I'd heard of CQS before. I'll have to think more about it. It does make the code clear in this case. On first examination, one issue I have with the general concept is that it seems that functions that act like constructors, such as file_or_stdout()in my example, or even just output = open(...)would violate it because they both do something (e.g. open the file, build a context manager) and return a reference to the thing they've opened or created. CQS seems similar to a rule of thumb that parameters are for input and return values are for output, which I'm violating with do_something(), because it was a stand-in for a couple lines in the original code. Maybe the larger takeaway of this exercise is that mutability has its pitfalls. I'll tell you as my old Python sensei used to tell me: When in doubt, import this. I think your second solution is the one. It is both concise and does not messes with PEP 8. What do you mean by "import this"? Just type "import this" I'm your interpreter, you will understand :) Ah yes, the good ol' Zen of Python. How is the first one harder to read then the rest that more lines and more complicated? If a Python coder can't read an inline expression, how is turning it into a context manager helping? I'm confused by this entire article. There is a lot of subjectivity involved in deciding which code is "better", and that line may be perfectly readable for you. To me it seemed like there was too much happening in that one line, which would mean someone has to stop on it for a few seconds to figure out what it's doing. Having a more complicated withclause also seemed to distract from the code after with(...):. This isn't shown very well here, since I just used do_something(file)as a stand-in, instead of the couple lines in the linked code this was derived from. But you may have a point in that one or two long lines might be preferable to a lot of short lines. The point of this post was that I ran across a situation in which the clearest way to write the code wasn't obvious, and I thought it would be valuable to hear peoples opinions on different ways to do it, and the tradeoffs between them. TIL building a context manager is so simple and clean.
https://dev.to/cathodion/how-would-you-rewrite-this-python-code-27lc
CC-MAIN-2019-39
refinedweb
1,156
78.08
chai 0.2.0 Easy to use mocking/stub framework. Overview Chai provides a very easy to use api for mocking/stubbing your python objects, patterned after the Mocha library for Ruby. Example The following is an example of a simple test case which is mocking out a get method on the CustomObject. The Chai api allows use of call chains to make the code short, clean, and very readable. It also does away with the standard setup-and-replay work flow, giving you more flexibility in how you write your cases. from chai import Chai class CustomObject (object): def get(self, arg): pass class TestCase(Chai): def test_mock_get(self): obj = CustomObject() self.expect(obj.get).args('name').returns('My Name') self.assert_equals(obj.get('name'), 'My Name') self.expect(obj.get).args('name').returns('Your Name') self.assert_equals(obj.get('name'), 'Your Name') def test_mock_get_with_at_most(self): obj = CustomObject() self.expect(obj.get).args('name').returns('My Name').at_most(2) self.assert_equals(obj.get('name'), 'My Name') self.assert_equals(obj.get('name'), 'My Name') self.assert_equals(obj.get('name'), 'My Name') # this one will fail if __name__ == '__main__': import unittest2 unittest2.main() API All of the features are available by extending the Chai class, itself a subclass of unittest.TestCase. If unittest2 is available Chai will use that, else it will fall back to unittest. Chai also aliases all of the assert* methods to lower-case with undersores. For example, assertNotEquals can also be referenced as assert_not_equals. Additionally, Chai loads in all assertions, comparators and mocking methods into the module in which a Chai subclass is declared. This is done to cut down on the verbosity of typing self. everywhere that you want to run a test. The references are loaded into the subclass' module during setUp, so you're sure any method you call will be a reference to the class and module in which a particular test method is currently being executed. Methods and comparators you define locally in a test case will be globally available when you're running that particular case as well. class ProtocolInterface(object): def _private_call(self, arg): pass def get_result(self, arg): self._private_call(arg) return 'ok' class TestCase(Chai): def assert_complicated_state(self, obj): return True # ..or.. raise AssertionError() def test_mock_get(self): obj = ProtocolInterface() data = object() expect(obj._private_call).args(data) assert_equals('ok', obj.get_result(data)) assert_complicated_state(data) Stubbing The simplest mock is to stub a method. This replaces the original method with a subclass of chai.Stub, the main instrumentation class. All additional stub and expect calls will re-use this stub, and the stub is responsible for re-installing the original reference when Chai.tearDown is run. Stubbing is used for situations when you want to assert that a method is never called. class CustomObject (object): def get(self, arg): pass @property def prop(self): pass class TestCase(Chai): def test_mock_get(self): obj = CustomObject() stub(obj.get) assert_raises( UnexpectedCall, obj.get ) In this example, we can reference obj.get directly because get is a bound method and provides all of the context we need to refer back to obj and stub the method accordingly. There are cases where this is insufficient, such as module imports, special Python types, and when module attributes are imported from another (like os and posix). If the object can't be stubbed with a reference, UnsupportedStub will be raised and you can use the verbose reference instead. class TestCase(Chai): def test_mock_get(self): obj = CustomObject() stub(obj, 'get') assert_raises( UnexpectedCall, obj.get ) Stubbing an unbound method will apply that stub to all future instances of that class. class TestCase(Chai): def test_mock_get(self): stub(CustomObject.get) obj = CustomObject() assert_raises( UnexpectedCall, obj.get ) Some methods cannot be stubbed because it is impossible to call setattr on the object, typically because it's a C extension. A good example of this is the datetime.datetime class. In that situation, it is best to mock out the entire module (see below). Finally, Chai supports stubbing of properties on classes. In all cases, the stub will be applied to a class and individually to each of the 3 property methods. Because the stub is on the class, all instances need to be addressed when you write expectations. The first interface is via the named attribute method which can be used on both classes and instances. class TestCase(Chai): def test_prop_attr(self): obj = CustomObject() stub( obj, 'prop' ) assert_raises( UnexpectedCall, lambda: obj.prop ) stub( stub( obj, 'prop' ).setter ) Using the class, you can directly refer to all 3 methods of the property. To refer to the getter you use the property directly, and for the methods you use its associated attribute name. You can stub in any order and it will still resolve correctly. class TestCase(Chai): def test_prop_attr(self): stub( CustomObject.prop.setter ) stub( CustomObject.prop ) stub( CustomObject.prop.deleter ) assert_raises( UnexpectedCall, lambda: CustomObject().prop ) Expectation Expectations are individual test cases that can be applied to a stub. They are expected to be run in order (unless otherwise noted). They are greedy, in that so long as an expectation has not been met and the arguments match, the arguments will be processed by that expectation. This mostly applies to the "at_least" and "any_order" expectations, which (may) stay open throughout the test and will handle any matching call. Expectations will automatically create a stub if it's not already applied, so no separate call to stub is necessary. The arguments and edge cases regarding what can and cannot have expectations applied are identical to stubs. The expect call will return a new chai.Expectation object which can then be used to modify the expectation. Without any modifiers, an expectation will expect a single call without arguments and return None. class TestCase(Chai): def test_mock_get(self): obj = CustomObject() expect(obj.get) assert_equals( None, obj.get() ) assert_raises( UnexpectedCall, obj.get ) Modifiers can be applied to the expectation. Each modifier will return a reference to the expectation for easy chaining. In this example, we're going to match a parameter and change the behavior depending on the argument. This also shows the ability to incrementally add expectations throughout the test. class TestCase(Chai): def test_mock_get(self): obj = CustomObject() expect(obj.get).args('foo').returns('hello').times(2) assert_equals( 'hello', obj.get('foo') ) assert_equals( 'hello', obj.get('foo') ) expect(obj.get).args('bar').raises( ValueError ) assert_raises( ValueError, obj.get, 'bar' ) It is very common to need to run expectations on the constructor for an object, possibly including returning a mock object. Chai makes this very simple. def method(): obj = CustomObject('state') obj.save() return obj class TestCase(Chai): def test_method(self): obj = mock() expect( CustomObject ).args('state').returns( obj ) expect( obj.save ) assert_equals( obj, method() ) Lastly, the arguments modifier supports several matching functions. For simplicity in covering the common cases, the arg expectation assumes an equals test for instances and an instanceof test for types. All rules that apply to positional arguments also apply to keyword arguments. class TestCase(Chai): def test_mock_get(self): obj = CustomObject() expect(obj.get).args(is_a(float)).returns(42) assert_raises( UnexpectedCall, obj.get, 3 ) assert_equals( 42, obj.get(3.14) ) expect(obj.get).args(str).returns('yes') assert_equals( 'yes', obj.get('no') ) expect(obj.get).args(is_arg(list)).return('yes') assert_raises( UnexpectedCall, obj.get, [] ) assert_equals( 'yes', obj.get(list) ) Modifiers Expectations expose the following public methods for changing their behavior. - args(*args, **kwargs) - Add a test to the expectation for matching arguments. - any_args - Any arguments are accepted. - returns(object) - Add a return value to the expectation when it is matched and executed. - raises(exception) - When the expectation is run it will raise this exception. Accepts type or instance. - times(int) - An integer that defines a hard limit on the minimum and maximum number of times the expectation should be executed. - at_least(int) - Sets a minimum number of times the expectation should run and removes any maximum. - at_least_once - Equivalent to at_least(1). - at_most(int) - Sets a maximum number of times the expectation should run. Does not affect the minimum. - at_most_once - Equivalent to at_most(1). - once - Equivalent to times(1), also the default for any expectation. - any_order - The expectation can be called at any time, independent of when it was defined. Can be combined with at_least_once to force it to respond to all matching calls throughout the test. - side_effect(callable, *args, **kwargs) - Called with a function argument. When the expectation passes a test, the function will be executed. The side effect will be executed even if the expectation is configured to raise an exception. If the side effect is defined with arguments, then those arguments will be passed in when it's called, otherwise the arguments passed in to the expectation will be passed in. - teardown - Will remove the stub after the expectation has been met. This is useful in cases where you need to mock core methods such as open, but immediately return its original behavior after the mocked call has run. Argument Comparators Argument comparators are defined as classes in chai.comparators, but loaded into the Chai class for convenience (and by extension, a subclass' module). Chai handles the common case of a type object by using the is_a comparator, else defaults to the equals comparator. Users can create subclasses of Comparator and use those for custom argument processing. Comparators can also be used inside data structures. For example: expect( area ).args( {'pi':almost_equals(3.14), 'radius':is_a(int,long,float)} ) - equals(object) - The default comparator, uses standard Python equals operator - almost_equals(float, places) - Identical to assertAlmostEquals, will match an argument to the comparator value to a most places digits beyond the decimal point. - is_a(type) - Match an argument of a given type. Supports same arguments as builtin function isinstance. - is_arg(object) - Matches an argument using the Python is comparator. - any_of(comparator_list) - Matches an argument if any of the comparators in the argument list are met. Uses automatic comparator generation for instances and types in the list. - all_of(comparator_list) - Matches an argument if all of the comparators in the argument list are met. Uses automatic comparator generation for instances and types in the list. - not_of(comparator) - Matches an argument if the supplied comparator does not match. - matches(pattern) - Matches an argument using a regular expression. Standard re rules apply. - func(callable) - Matches an argument if the callable returns True. The callable must take one argument, the parameter being checked. - ignore - Matches any argument. - in_arg(in_list) - Matches if the argument is in the in_list. - contains(object) - Matches if the argument contains the object using the Python in function. - like(container) - Matches if the argument contains all of the same items as in container. Insists that the argument is the same type as container. Useful when you need to assert a few values in a list or dictionary, but the exact contents are not known or can vary. - var(name) - A variable match against the first time that the argument is called. In the case of multiple calls, the second one must match the previous value of name. After your tests have run, you can check the value against expected arguments through var(name).value. This is really useful when you're testing a deep stack and it's simpler to assert that "value A was used in method call X". A note of caution If you are using the func comparator to produce side effects, be aware that it may be called more than once even if the expectation you're defining only occurs once. This is due to the way Stub.__call__ processes the expectations and determines when to process arguments through an expectation. Context Manager An expectation can act as a context manager, which is very useful in complex mocking situations. The context will always be the return value for the expectation. For example: def get_cursor(cname): return db.Connection( 'host:port' ).collection( cname ).cursor() def test_get_cursor(): with expect( db.Connection ).any_args().returns( mock() ) as connection: with expect( connection.collection ).args( 'collection' ).returns( mock() ) as collection: expect( collection.cursor ).returns( 'cursor' ) assert_equals( 'cursor', get_cursor('collection') ) Mock Sometimes you need a mock object which can be used to stub and expect anything. Chai exposes this through the mock method which can be called in one of two ways. Without any arguments, Chai.mock() will return a chai.Mock object that can be used for any purpose. If called with arguments, it behaves like stub and expect, creating a Mock object and setting it as the attribute on another object. Any request for an attribute from a Mock will return a new Mock object, but setattr behaves as expected so it can store state as well. The dynamic function will act like a stub, raising UnexpectedCall if no expectation is defined. class CustomObject(object): def __init__(self, handle): _handle = handle def do(self, arg): return _handle.do(arg) class TestCase(Chai): def test_mock_get(self): obj = CustomObject( mock() ) expect( obj._handle.do ).args('it').returns('ok') assert_equals('ok', obj.do('it')) assert_raises( UnexpectedCall, obj._handle.do_it_again ) The stub and expect methods handle Mock objects as arguments by mocking the __call__ method, which can also act in place of __init__. # module custom.py from collections import deque class CustomObject(object): def __init__(self): self._stack = deque() # module custom_test.py import custom from custom import CustomObject class TestCase(Chai): def test_mock_get(self): mock( custom, 'deque' ) expect( custom.deque ).returns( 'stack' ) obj = CustomObject() assert_equals('stack', obj._stack) Here we can see how to mock an entire module, in this case replacing the deque import in custom.py with a Mock. Mock objects, because of the getattr implementation, can also support nested attributes. class TestCase(Chai): def test_mock(self): m = mock() m.id = 42 expect( m.foo.bar ).returns( 'hello' ) assert_equals( 'hello', m.foo.bar() ) assert_equals( 42, m.id ) In addition to implementing __call__, Mock objects implement __nonzero__, the container and context manager interfaces are defined. Nonzero will always return True; other methods will raise UnexpectedCall. The __getattr__ method cannot be itself stubbed. Installation You can install Chai either via the Python Package Index (PyPI) or from source. To install using pip,: $ pip install chai Downloading and installing from source Download the latest version of Chai from You can install it by doing the following,: $ tar xvfz chai-*.*.*.tar.gz $ cd chai-*.*.*.tar.gz $ python setup.py install # as root Using the development version You can clone the repository by doing the following: $ git clone git://github.com/agoragames/chai.git Bug tracker If you have any suggestions, bug reports or annoyances please report them to our issue tracker at License This software is licensed under the New BSD License. See the LICENSE file in the top distribution directory for the full license text. Contributors Special thank you to the following people for contributions to Chai - Jason Baker () - Downloads (All Versions): - 185 downloads in the last day - 968 downloads in the last week - 3533 downloads in the last month - Author: Vitaly Babiy, Aaron Westendorf - Keywords: python,test,mock - License: LICENSE.txt - Categories - Development Status :: 4 - Beta - Intended Audience :: Developers - License :: OSI Approved :: BSD License - Operating System :: POSIX - Programming Language :: Python - Programming Language :: Python :: 2.6 - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 3 - Programming Language :: Python :: 3.0 - Programming Language :: Python :: 3.1 - Programming Language :: Python :: 3.2 - Topic :: Communications - Topic :: Software Development :: Libraries - Topic :: Software Development :: Libraries :: Python Modules - Package Index Owner: vbabiy, aaron.westendorf, Ola.Mork - DOAP record: chai-0.2.0.xml
https://pypi.python.org/pypi/chai/0.2.0
CC-MAIN-2014-10
refinedweb
2,568
51.04
Consuming external WCF Services from Dynamics AX 2009 X++ code (Dynamics AX “5.0”)!!. 🙂(): I have highlighted in bold letters the most important code lines, I mean, the WCF Service proxy object variable, when instantiating the WCF Service class and, of course, when calling the “GeCompanyNameByStockSymbol()” Service method. NOTE: In AX 2009 CTP3, it generated the same public class name that you have in your .NET WCF Service. But in the RTM version (AX 2009 Release), it seems it generates a class with the name of the interface plus the postfix “Client”, in this case “IStockExchangeServiceClient” instead “StockExchangeService“. Underneath, it is using an internal class which is kind of “.NET WCF Client way”, called “StockExchangeServiceClient“, but you don’t need to use this one. So, for instance, this is the code I was using in CTP3, you can compare it with the one (up above) that works with AX 2009 Release version (RTM): …. StockExchangeWcfService.StockExchangeService proxy; ; // Call the WCF method. proxy = new StockExchangeWcfService.StockExchangeService(); …. That’s it, really simple!, those are the most important steps we gotta make (beware we have not finished yet… keep on reading… ;-)). So, just to test our “Service Agent” class, we create a new Job, like the following: And if we just run this Job, guess what… We’ll get a cute error!!, something like: Yep, not very descriptive, right?. :-), ok, but then, we may get these other errors:!! 🙂 ..
https://devblogs.microsoft.com/cesardelatorre/consuming-external-wcf-services-from-dynamics-ax-2009-x-code-dynamics-ax-5-0/
CC-MAIN-2022-27
refinedweb
234
64.51
Update (2013-12-11): I decided to use JavaScript and the HTML5 <canvas>. You can see the project I made here: VGA Simulator I decided to post up this simple script that generates an animated (scrolls horizontally) sine wave. I built both versions because I need to use a canvas and some bare-bone pixel manipulation for a future project and want to find the best solution. The first one is made with pygame, which runs smooth and is straight forward efficient. The second version made with tkinter is slow and laggy. I even had to batch edit pixels which does not help much. Both of them function exactly the same but the tkinter version is just not as fast. All you need is Python 2.7 and pygame installed. If you are on Windows, you might consider getting a nice binary from here. This is also a great project to get started with pygame. import pygame import time import math # Some config width height settings canvas_width = 640 canvas_height = 480 # Just define some colors we can use color = pygame.Color(255, 255, 0, 0) background_color = pygame.Color(0, 0, 0, 0) pygame.init() # Set the window title pygame.display.set_caption("Sine Wave") # Make a screen to see screen = pygame.display.set_mode((canvas_width, canvas_height)) screen.fill(background_color) # Make a surface to draw on surface = pygame.Surface((canvas_width, canvas_height)) surface.fill(background_color) # Simple main loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Redraw the background surface.fill(background_color) # Update sine wave frequency = 4 amplitude = 50 # in px speed = 1 for x in range(0, canvas_width): y = int((canvas_height/2) + amplitude*math.sin(frequency*((float(x)/canvas_width)*(2*math.pi) + (speed*time.time())))) surface.set_at((x, y), color) # Put the surface we draw on, onto the screen screen.blit(surface, (0, 0)) # Show it. pygame.display.flip() NOTE: For python 3.x: change the import statement at the top to from tkinter import ... ("..." is the rest of that line) - The package changes to lowercase T in 3.x. The uppercase Tkinter package is for python 2.x from Tkinter import Tk, Canvas, PhotoImage, mainloop import math import time # Used to store debug file #import os #BASE_DIR = os.path.realpath(os.path.dirname(__file__)) # Some config width height settings canvas_width = 640 canvas_height = 480 # Create a window window = Tk() # Set the window title window.wm_title("Sine Wave") # Put a canvas on the window canvas = Canvas(window, width=canvas_width, height=canvas_height, bg="#000000") canvas.pack() # Create a image, this acts as the canvas img = PhotoImage(width=canvas_width, height=canvas_height) # Put the image on the canvas canvas.create_image((canvas_width/2, canvas_height/2), image=img, state="normal") def sine_wave_anim(): # Update sine wave frequency = 4 amplitude = 50 # in px speed = 1 # We create a blank area for what where we are going to draw color_table = [["#000000" for x in range(0, canvas_width)] for y in range(0, amplitude*2)] # And draw on that area for x in range(0, canvas_width): y = int(amplitude + amplitude*math.sin(frequency*((float(x)/canvas_width)*(2*math.pi) + (speed*time.time())))) color_table[y][x] = "#ffff00" # Don't individually put pixels as tkinter sucks at this #img.put("#ffff00", (x, y)) # Then batch put it on the canvas # tkinter is extremely inefficient doing it one by one img.put(''.join("{" + (" ".join(str(color) for color in row)) + "} " for row in color_table), (0, int(canvas_height/2 - amplitude))) # Debug the color_table #with open(os.path.join(BASE_DIR, 'output.txt'), "w+") as text_file: # text_file.write(''.join("{" + (" ".join(str(color) for color in row)) + "} " for row in color_table)) # Continue the animation as fast as possible. A value of 0 (milliseconds), blocks everything. window.after(1, sine_wave_anim) # Start off the anim sine_wave_anim() mainloop()
https://ericeastwood.com/blog/7/animated-sine-wave-two-ways-with-pygame-and-tkinter
CC-MAIN-2018-51
refinedweb
623
58.79
* Fix spelling with codespell[1] and manually review it. [1] --- boot/boot.c | 2 +- bsdfsck/fsck.h | 2 +- bsdfsck/preen.c | 2 +- bsdfsck/utilities.c | 2 +- console-client/bdf.c | 4 ++-- console-client/bdf.h | 8 ++++---- console-client/driver.c | 2 +- console-client/ncursesw.c | 2 +- console-client/pc-kbd.c | 6 +++--- console-client/vga-dynacolor.c | 2 +- console/display.c | 2 +- console/hurd.ti | 2 +- daemons/lmail.c | 14 +++++++------- daemons/runttys.c | 2 +- doc/hurd.texi | 2 +- exec/do-bunzip2.c | 2 +- exec/exec.c | 2 +- ext2fs/balloc.c | 2 +- ext2fs/dir.c | 2 +- ext2fs/pager.c | 2 +- fatfs/dir.c | 2 +- fatfs/fat.h | 2 +- fatfs/pager.c | 2 +- ftpfs/dir.c | 4 ++-- ftpfs/ftpfs.h | 4 ++-- hostmux/leaf.c | 2 +- hurd/console.h | 2 +- hurd/hurd_types.h | 2 +- hurd/io.defs | 2 +- isofs/lookup.c | 4 ++-- isofs/rr.c | 2 +- libfshelp/fshelp.h | 4 ++-- libfshelp/perms-checkdirmod.c | 2 +- libftpconn/fname.c | 2 +- libftpconn/ftpconn.h | 4 ++-- libftpconn/reply.c | 2 +- libftpconn/unix.c | 2 +- libpager/pager.h | 4 ++-- libpipe/pipe.h | 6 +++--- libpipe/pq.h | 4 ++-- libports/bucket-iterate.c | 2 +- libports/manage-one-thread.c | 2 +- libps/fmt.c | 12 ++++++------ libps/procstat.c | 6 +++--- libps/ps.h | 14 +++++++------- libshouldbeinlibc/cacheq.c | 2 +- libshouldbeinlibc/idvec.c | 2 +- libshouldbeinlibc/idvec.h | 2 +- libshouldbeinlibc/ugids.c | 4 ++-- libstore/argp.c | 2 +- libstore/kids.c | 4 ++-- libstore/store.h | 4 ++-- libthreads/mig_support.c | 2 +- libtrivfs/trivfs.h | 2 +- login/utmp.c | 4 ++-- mach-defpager/default_pager.c | 2 +- nfs/rpc.c | 2 +- pfinet/linux-src/arch/sparc/lib/checksum.S | 2 +- pfinet/linux-src/include/linux/b1lli.h | 2 +- pfinet/linux-src/include/linux/cdk.h | 2 +- pfinet/linux-src/include/linux/cdrom.h | 2 +- pfinet/linux-src/include/linux/coda_opstats.h | 2 +- pfinet/linux-src/include/linux/cyclades.h | 4 ++-- pfinet/linux-src/include/linux/isdn.h | 4 ++-- pfinet/linux-src/include/linux/isdn_ppp.h | 2 +- pfinet/linux-src/include/linux/isdnif.h | 4 ++-- pfinet/linux-src/include/linux/ixjuser.h | 4 ++-- pfinet/linux-src/include/linux/loop.h | 2 +- pfinet/linux-src/include/linux/module.h | 2 +- pfinet/linux-src/include/linux/notifier.h | 2 +- pfinet/linux-src/include/linux/poll.h | 2 +- pfinet/linux-src/include/linux/rtnetlink.h | 2 +- pfinet/linux-src/include/linux/socket.h | 2 +- pfinet/linux-src/include/linux/soundcard.h | 2 +- pfinet/linux-src/include/linux/telephony.h | 4 ++-- pfinet/linux-src/include/linux/tpqic02.h | 6 +++--- pfinet/linux-src/include/linux/tty_ldisc.h | 2 +- pfinet/linux-src/include/linux/wavefront.h | 2 +- pfinet/linux-src/include/linux/wireless.h | 2 +- pfinet/linux-src/include/net/pkt_sched.h | 2 +- pfinet/linux-src/include/net/tcp.h | 2 +- pfinet/linux-src/net/core/dev.c | 2 +- pfinet/linux-src/net/core/sock.c | 4 ++-- pfinet/linux-src/net/ipv4/fib_semantics.c | 2 +- pfinet/linux-src/net/ipv4/icmp.c | 2 +- pfinet/linux-src/net/ipv4/ip_fw.c | 2 +- pfinet/linux-src/net/ipv4/ip_gre.c | 2 +- pfinet/linux-src/net/ipv4/ip_masq_quake.c | 4 ++-- pfinet/linux-src/net/ipv4/ip_output.c | 2 +- pfinet/linux-src/net/ipv4/ipconfig.c | 2 +- pfinet/linux-src/net/ipv4/ipip.c | 2 +- pfinet/linux-src/net/ipv4/raw.c | 2 +- pfinet/linux-src/net/ipv4/tcp.c | 2 +- pfinet/linux-src/net/ipv4/tcp_input.c | 8 ++++---- pfinet/linux-src/net/ipv4/tcp_ipv4.c | 2 +- pfinet/linux-src/net/ipv4/tcp_output.c | 2 +- pfinet/linux-src/net/ipv6/addrconf.c | 4 ++-- pfinet/linux-src/net/ipv6/af_inet6.c | 2 +- pfinet/linux-src/net/ipv6/icmpv6.c | 4 ++-- pfinet/linux-src/net/ipv6/ip6_fib.c | 2 +- pfinet/linux-src/net/ipv6/ip6_input.c | 2 +- pfinet/linux-src/net/ipv6/ip6_output.c | 2 +- pfinet/linux-src/net/ipv6/ndisc.c | 4 ++-- pfinet/linux-src/net/ipv6/udp_ipv6.c | 2 +- pfinet/main.c | 2 +- pfinet/options.c | 2 +- pflocal/pf.c | 2 +- pflocal/socket.c | 2 +- release/SOURCES.0.0 | 2 +- release/mkfsimage.sh | 6 +++--- storeio/dev.c | 6 +++--- storeio/pager.c | 4 ++-- sutils/clookup.c | 2 +- sutils/fsck.c | 2 +- tasks | 2 +- term/munge.c | 4 ++-- tmpfs/pager-stubs.c | 4 ++-- ufs/alloc.c | 6 +++--- ufs/dir.c | 2 +- ufs/inode.c | 2 +- utils/devprobe.c | 2 +- utils/ftpcp.c | 2 +- utils/ftpdir.c | 2 +- utils/login.c | 2 +- utils/mount.c | 2 +- utils/vmstat.c | 2 +- utils/w.c | 2 +- 127 files changed, 189 insertions(+), 189 deletions(-) diff --git a/boot/boot.c b/boot/boot.c index 68ba246..2b14384 100644 --- a/boot/boot.c +++ b/boot/boot.c @@ -827,7 +827,7 @@ read_reply () if (! spin_try_lock (&readlock)) return; - /* Since we're commited to servicing the read, no one else need do so. */ + /* Since we're committed to servicing the read, no one else need do so. */ should_read = 0; ioctl (0, FIONREAD, &avail); diff --git a/bsdfsck/fsck.h b/bsdfsck/fsck.h index c418f66..04bb769 100644 --- a/bsdfsck/fsck.h +++ b/bsdfsck/fsck.h @@ -209,7 +209,7 @@ struct inodesc { * To check if a block has been found as a duplicate it is only * necessary to search from duplist through muldup. To find the * total number of times that a block has been found as a duplicate - * the entire list must be searched for occurences of the block + * the entire list must be searched for occurrences of the block * in question. The following diagram shows a sample list where * w (found twice), x (found once), y (found three times), and z * (found once) are duplicate block numbers: diff --git a/bsdfsck/preen.c b/bsdfsck/preen.c index 7893a5e..5650f90 100644 --- a/bsdfsck/preen.c +++ b/bsdfsck/preen.c @@ -51,7 +51,7 @@ struct part { struct part *next; /* forward link of partitions on disk */ char *name; /* device name */ char *fsname; /* mounted filesystem name */ - long auxdata; /* auxillary data for application */ + long auxdata; /* auxiliary data for application */ } *badlist, **badnext = &badlist; struct disk { diff --git a/bsdfsck/utilities.c b/bsdfsck/utilities.c index 2141e7f..1c281b1 100644 --- a/bsdfsck/utilities.c +++ b/bsdfsck/utilities.c @@ -520,7 +520,7 @@ errexit(s1, s2, s3, s4) } /* - * An unexpected inconsistency occured. + * An unexpected inconsistency occurred. * Die if preening, otherwise just print message and continue. */ /* VARARGS1 */ diff --git a/console-client/bdf.c b/console-client/bdf.c index 30501f4..f62a247 100644 --- a/console-client/bdf.c +++ b/console-client/bdf.c @@ -154,7 +154,7 @@ next_line (char **line, int *size, FILE *file, int *count) } -/* Isolate the next white-space seperated argument from the current +/* Isolate the next white-space separated argument from the current line, and set ARGP to the beginning of the next argument. It is an error if there is no further argument. */ static bdf_error_t @@ -178,7 +178,7 @@ find_arg (char **argp) /* Read the font from stream FILE, and return it in FONT. If LINECOUNT is not zero, it will contain the number of lines in the - file at success, and the line an error occured at failure. */ + file at success, and the line an error occurred at failure. */ bdf_error_t bdf_read (FILE *filep, bdf_font_t *font, int *linecount) { diff --git a/console-client/bdf.h b/console-client/bdf.h index 1f0bce4..17cd023 100644 --- a/console-client/bdf.h +++ b/console-client/bdf.h @@ -32,17 +32,17 @@ types of the arguments, so we treat a string as an 8-bit string which must not contain a binary null, and a number like an integer as an int. Leading and trailing white space are removed, multiple - spaces that seperate arguments are replaced by a single white + spaces that separate arguments are replaced by a single white space, and empty lines are ignored. */ /* Possible error values returned by the BDF functions. */ typedef enum { - /* No error occured. This is guaranteed to be zero. */ + /* No error occurred. This is guaranteed to be zero. */ BDF_NO_ERROR = 0, - /* A system error occured. The caller should consult errno. */ + /* A system error occurred. The caller should consult errno. */ BDF_SYSTEM_ERROR, /* All following errors indicate that the file is not a valid BDF @@ -200,7 +200,7 @@ typedef struct bdf_font *bdf_font_t; /* Read the font from stream FILE, and return it in FONT. If LINECOUNT is not zero, it will contain the number of lines in the - file at success, and the current line an error occured at + file at success, and the current line an error occurred at failure. */ bdf_error_t bdf_read (FILE *file, bdf_font_t *font, int *linecount); diff --git a/console-client/driver.c b/console-client/driver.c index 2a56729..7f799f0 100644 --- a/console-client/driver.c +++ b/console-client/driver.c @@ -83,7 +83,7 @@ driver_fini (void) /* Load, intialize and (if START is non-zero) start the driver DRIVER under the given NAME (which must be unique among all loaded - drivers) with arguments ARGZ with length ARGZ_LEN. This funtion + drivers) with arguments ARGZ with length ARGZ_LEN. This function will grab the driver list lock. The driver itself might try to grab the display, input source and bell list locks as well. */ error_t driver_add (const char *const name, const char *const driver, diff --git a/console-client/ncursesw.c b/console-client/ncursesw.c index 8b55901..a34026a 100644 --- a/console-client/ncursesw.c +++ b/console-client/ncursesw.c @@ -47,7 +47,7 @@ static WINDOW *conspad; static unsigned int padx; static unsigned int pady; -/* Autoscroll is on or off. Autoscroll makes scrolling dependant on +/* Autoscroll is on or off. Autoscroll makes scrolling dependent on the cursor position. */ static int autoscroll; diff --git a/console-client/pc-kbd.c b/console-client/pc-kbd.c index 35e2561..d66e94b 100644 --- a/console-client/pc-kbd.c +++ b/console-client/pc-kbd.c @@ -583,7 +583,7 @@ gnumach_v1_input_next () error_t err = device_read_inband (kbd_dev, 0, -1, sizeof (kd_event), (void *) &data_buf, &data_cnt); - /* XXX The error occured likely because KBD_DEV was closed, so + /* XXX The error occurred likely because KBD_DEV was closed, so terminate. */ if (err) return 0; @@ -661,7 +661,7 @@ input_next () error_t err = device_read_inband (kbd_dev, 0, -1, 1, (void *) &next, &data_cnt); - /* XXX The error occured likely because KBD_DEV was closed, so + /* XXX The error occurred likely because KBD_DEV was closed, so terminate. */ if (err) return 0; @@ -761,7 +761,7 @@ input_loop (any_t unused) /* The virtual console to switch to. */ int vc = 0; - /* Check if a funtion key was pressed. + /* Check if a function key was pressed. Choose the virtual console corresponding to that key. */ switch (sc) { diff --git a/console-client/vga-dynacolor.c b/console-client/vga-dynacolor.c index 7b81e2f..9289e1e 100644 --- a/console-client/vga-dynacolor.c +++ b/console-client/vga-dynacolor.c @@ -177,7 +177,7 @@ dynacolor_replace_colors (dynacolor_t *dc, based on pairs, but that increases the number of cases a lot. */ /* Note that no color must occur twice in one replacement list, - and that the color to be replaced must not occure either. */ + and that the color to be replaced must not occur either. */ static signed char pref[16][9] = { /* Replacements for CONS_COLOR_BLACK. */ diff --git a/console/display.c b/console/display.c index 26786c1..e807c50 100644 --- a/console/display.c +++ b/console/display.c @@ -454,7 +454,7 @@ do_mach_notify_msg_accepted (mach_port_t notify, mach_port_t send) mutex_unlock (&display->lock); return 0; } - /* The message was succesfully queued, fall through. */ + /* The message was successfully queued, fall through. */ } /* Remove request from pending queue. */ *preq = req->next; diff --git a/console/hurd.ti b/console/hurd.ti index 504192b..2508482 100644 --- a/console/hurd.ti +++ b/console/hurd.ti @@ -116,7 +116,7 @@ hurd|The GNU Hurd console server, kpp=\E[5~, knp=\E[6~, # Keycode for center of keypad area. kb2=\E[G, -# Mouse event has occured. +# Mouse event has occurred. kmous=\E[M, # Text attribute capabilities. diff --git a/daemons/lmail.c b/daemons/lmail.c index ef61686..23c7b49 100644 --- a/daemons/lmail.c +++ b/daemons/lmail.c @@ -60,7 +60,7 @@ static const char doc[] = "Deliver mail to the local mailboxes of USER..."; #define HDR_PFX "From " /* Header, at the beginning of a line, starting each msg in a mailbox. */ -#define ESC_PFX ">" /* Used to escape occurances of HDR_PFX in +#define ESC_PFX ">" /* Used to escape occurrences of HDR_PFX in the msg body. */ #define BMAX (64*1024) /* Chunk size for I/O. */ @@ -71,7 +71,7 @@ struct params char *mail_dir; /* Mailbox directory. */ }; -/* Convert the system error code ERR to an appropiate exit value. This +/* Convert the system error code ERR to an appropriate exit value. This function currently only returns three sorts: success, temporary failure, or error, with exit codes 0, EX_TEMPFAIL, or EX_UNAVAILABLE. The table of temporary failures is from the bsd original of this program. */ @@ -116,7 +116,7 @@ err_to_ex (error_t err) } /* Print and syslog the given error message, with the system error string for - ERRNO appended. Return an appropiate exit code for ERRNO. */ + ERRNO appended. Return an appropriate exit code for ERRNO. */ #define SYSERR(fmt, args...) \ ({ syslog (LOG_ERR, fmt ": %m" , ##args); err_to_ex (errno); }) @@ -126,7 +126,7 @@ err_to_ex (error_t err) ({ syslog (LOG_ERR, fmt , ##args); EX_UNAVAILABLE; }) /* Print and syslog the given error message, with the system error string for - CODE appended. Return an appropiate exit code for CODE. */ + CODE appended. Return an appropriate exit code for CODE. */ #define SYSERRX(code, fmt, args...) \ ({ error_t _code = (code); \ syslog (LOG_ERR, fmt ": %s" , ##args , strerror (_code)); \ @@ -225,7 +225,7 @@ write_header (int out, char *out_name, struct params *params) /* Copy from file descriptor IN to OUT, making any changes needed to make the contents a valid mailbox entry. These include: (1) Prepending a `From ...' line, and appending a blank line. - (2) Replacing any occurances of `From ' at the beginning of lines with + (2) Replacing any occurrences of `From ' at the beginning of lines with `>From '. An exit status is returned. */ static int @@ -326,7 +326,7 @@ process (int in, char *in_name, int out, char *out_name, struct params *params) #define D_REWIND 0x2 /* Rewind MSG before using it. */ /* Deliver the text from the file descriptor MSG to the mailbox of the user - RCPT in MAIL_DIR. FLAGS is from the set D_* above. An exit appropiate + RCPT in MAIL_DIR. FLAGS is from the set D_* above. An exit appropriate exit code is returned. */ static int deliver (int msg, char *msg_name, char *rcpt, int flags, struct params *params) @@ -437,7 +437,7 @@ cache (int in, char *in_name, struct params *params, int *cached) int main (int argc, char **argv) { - int rcpt = 0; /* Index in ARGV of next recepient. */ + int rcpt = 0; /* Index in ARGV of next recipient. */ char *file = 0; /* File containing message. */ int remove = 0; /* Remove file after successful delivery. */ int in = 0; /* Raw input file descriptor. */ diff --git a/daemons/runttys.c b/daemons/runttys.c index 1afd558..7efb7b7 100644 --- a/daemons/runttys.c +++ b/daemons/runttys.c @@ -190,7 +190,7 @@ init_ttys (void) return 0; } -/* Free everyting in the terminal array */ +/* Free everything in the terminal array */ void free_ttys (void) { diff --git a/doc/hurd.texi b/doc/hurd.texi index 098bebf..ea73a4c 100644 --- a/doc/hurd.texi +++ b/doc/hurd.texi @@ -1759,7 +1759,7 @@ new reference port. (FIXME: xref the C library manual for information on how to send sig_post messages.) The server then sends one @code{SIGIO} signal to each registered async -user everytime I/O becomes possible. I/O is possible if at least one +user every time I/O becomes possible. I/O is possible if at least one byte can be read or written immediately. The definition of ``immediately'' must be the same as for the implementation of the @code{O_NONBLOCK} flag (@pxref{Open Modes}). In addition, every time a diff --git a/exec/do-bunzip2.c b/exec/do-bunzip2.c index 17bbf91..716a0cd 100644 --- a/exec/do-bunzip2.c +++ b/exec/do-bunzip2.c @@ -150,7 +150,7 @@ bz2_fclose (void *stream) with *all* the algorithms contained herein, and with the consequences of modifying them, you should NOT meddle with the compression or decompression machinery. Incorrect changes can - and very likely *will* lead to disasterous loss of data. + and very likely *will* lead to disastrous loss of data. DISCLAIMER: I TAKE NO RESPONSIBILITY FOR ANY LOSS OF DATA ARISING FROM THE diff --git a/exec/exec.c b/exec/exec.c index 01d22e7..4c2fcec 100644 --- a/exec/exec.c +++ b/exec/exec.c @@ -1061,7 +1061,7 @@ load (task_t usertask, struct execdata *e) if (e->info.elf.phdr[i].p_type == PT_LOAD) load_section (&e->info.elf.phdr[i], e); - /* The entry point address is relative to whereever we loaded the + /* The entry point address is relative to wherever we loaded the program text. */ e->entry += e->info.elf.loadbase; } diff --git a/ext2fs/balloc.c b/ext2fs/balloc.c index a53e111..7333123 100644 --- a/ext2fs/balloc.c +++ b/ext2fs/balloc.c @@ -44,7 +44,7 @@ #include "ext2fs.h" #include "bitmap.c" -/* Returns a pointer to the first occurence of CH in the buffer BUF of len +/* Returns a pointer to the first occurrence of CH in the buffer BUF of len LEN, or BUF + LEN if CH doesn't occur. */ static inline void * memscan (void *buf, unsigned char ch, size_t len) diff --git a/ext2fs/dir.c b/ext2fs/dir.c index 66d8c8a..d70dbf3 100644 --- a/ext2fs/dir.c +++ b/ext2fs/dir.c @@ -698,7 +698/ext2fs/pager.c b/ext2fs/pager.c index 3f4674b..082537c 100644 --- a/ext2fs/pager.c +++ b/ext2fs/pager.c @@ -119,7 +119,7 @@ free_page_buf (void *buf) /* Find the location on disk of page OFFSET in NODE. Return the disk block in BLOCK (if unallocated, then return 0). If *LOCK is 0, then a reader - lock is aquired on NODE's ALLOC_LOCK before doing anything, and left + lock is acquired on NODE's ALLOC_LOCK before doing anything, and left locked after the return -- even if an error is returned. 0 is returned on success otherwise an error code. */ static error_t diff --git a/fatfs/dir.c b/fatfs/dir.c index aa38999..762320f 100644 --- a/fatfs/dir.c +++ b/fatfs/dir.c @@ -681,7 +681/fatfs/fat.h b/fatfs/fat.h index 87af27d..58b45c6 100644 --- a/fatfs/fat.h +++ b/fatfs/fat.h @@ -72,7 +72,7 @@ Data The data region occupies the rest of the filesystem and stores - the actual file and directory data. It is seperated in clusters, + the actual file and directory data. It is separated in clusters, which are indexed in the FAT. The size of the data region is stored in the word at offset 19 diff --git a/fatfs/pager.c b/fatfs/pager.c index 22adb08..e617af0 100644 --- a/fatfs/pager.c +++ b/fatfs/pager.c @@ -91,7 +91,7 @@ free_page_buf (void *buf) /* Find the location on disk of page OFFSET in NODE. Return the disk cluster in CLUSTER. If *LOCK is 0, then it a reader - lock is aquired on NODE's ALLOC_LOCK before doing anything, and left + lock is acquired on NODE's ALLOC_LOCK before doing anything, and left locked after return -- even if an error is returned. 0 on success or an error code otherwise is returned. */ static error_t diff --git a/ftpfs/dir.c b/ftpfs/dir.c index fb35a45..8ef719d 100644 --- a/ftpfs/dir.c +++ b/ftpfs/dir.c @@ -485,7 +485,7 @@ ftpfs_refresh_node (struct node *node) } else if (*(entry->name)) { - /* The root node is treated seperately below. */ + /* The root node is treated separately below. */ struct ftp_conn *conn; err = ftpfs_get_ftp_conn (dir->fs, &conn); @@ -775,7 +775,7 @@ ftpfs_dir_lookup (struct ftpfs_dir *dir, const char *name, } /*/ftpfs/ftpfs.h b/ftpfs/ftpfs.h index d1d816d..0eef5bd 100644 --- a/ftpfs/ftpfs.h +++ b/ftpfs/ftpfs.h @@ -138,7 +138,7 @@ struct netnode /* Various parameters that can be used to change the behavior of an ftpfs. */ struct ftpfs_params { - /* Amount of time name existance is cached. */ + /* Amount of time name existence is cached. */ time_t name_timeout; /* Amount of time stat information is cached. */ @@ -240,7 +240,7 @@ error_t ftpfs_dir_lookup (struct ftpfs_dir *dir, const char *name, struct node **node); /*/hostmux/leaf.c b/hostmux/leaf.c index aba32b8..fb53622 100644 --- a/hostmux/leaf.c +++ b/hostmux/leaf.c @@ -53,7 +53,7 @@ netfs_get_translator (struct node *node, char **argz, size_t *argz_len) *argz = 0; /* Initialize return value. */ *argz_len = 0; - /* Return a copy of MUX's translator template, with occurances of + /* Return a copy of MUX's translator template, with occurrences of HOST_PAT replaced by the canonical hostname. */ err = argz_append (argz, argz_len, mux->trans_template, mux->trans_template_len); diff --git a/hurd/console.h b/hurd/console.h index 4634cc2..baf0394 100644 --- a/hurd/console.h +++ b/hurd/console.h @@ -122,7 +122,7 @@ struct cons_display ever increased by the server, so clients can optimize scrolling. */ uint32_t scr_lines; /* Number of lines in scrollback buffer - preceeding CUR_LINE. */ + preceding CUR_LINE. */ uint32_t height; /* Number of lines in visible area following (and including) CUR_LINE. */ uint32_t matrix; /* Index (in uint32_t) of the beginning of diff --git a/hurd/hurd_types.h b/hurd/hurd_types.h index 86b9bcb..e1a644f 100644 --- a/hurd/hurd_types.h +++ b/hurd/hurd_types.h @@ -201,7 +201,7 @@ enum term_bottom_type remap - TY, FL, NR NR * (OFFS, LEN) - 1 (BS and SIZE are that of the child) copy - TY, FL, SIZE - DATA - - (DATA is preceeded by padding to the next page boundary, and is + (DATA is preceded by padding to the next page boundary, and is SIZE bytes long itself) For ileave, concat, and layer, the children are encoded following the parent. diff --git a/hurd/io.defs b/hurd/io.defs index d30233e..9119b05 100644 --- a/hurd/io.defs +++ b/hurd/io.defs @@ -101,7 +101,7 @@ routine io_clear_some_openmodes ( when appropriate, to the designated port using sig_post. A port is also returned which will be used as the reference port in sending such signals (this is the "async IO ID" port). The async - call is cancelled by deleting all refernces to the async_id_port. + call is cancelled by deleting all references to the async_id_port. Each call to io_async generates a new ASYNC_ID_PORT. */ routine io_async ( diff --git a/isofs/lookup.c b/isofs/lookup.c index f3e7581..8daa546 100644 --- a/isofs/lookup.c +++ b/isofs/lookup.c @@ -50,11 +50,11 @@ isonamematch (const char *dirname, size_t dnamelen, if (dnamelen == unamelen) return 1; - /* User has ommitted the version number */ + /* User has omitted the version number */ if (dirname[unamelen] == ';') return 1; - /* User has ommitted an empty extension */ + /* User has omitted an empty extension */ if (dirname[unamelen] == '.' && (dirname[unamelen+1] == '\0' || dirname[unamelen+1] == ';')) return 1; diff --git a/isofs/rr.c b/isofs/rr.c index f26d9e4..be4395d 100644 --- a/isofs/rr.c +++ b/isofs/rr.c @@ -505,7 +505,7 @@ rrip_work (struct dirrect *dr, struct rrip_lookup *rr, we got here from the exit point of the function, then VALID_NM is actually clear. */ - /* Save these, becuase rrip_work will clear them. */ + /* Save these, because rrip_work will clear them. */ savename = (rr->valid & VALID_NM) ? rr->name : 0; realdir = rr->realdirent; diff --git a/libfshelp/fshelp.h b/libfshelp/fshelp.h index 5c43c54..9f4fa67 100644 --- a/libfshelp/fshelp.h +++ b/libfshelp/fshelp.h @@ -38,7 +38,7 @@ or the ports library. */ /* A callback used by the translator starting functions, which should be a - function that given some open flags, opens the appropiate file, and + function that given some open flags, opens the appropriate file, and returns the node port. */ typedef error_t (*fshelp_open_fn_t) (int flags, file_t *node, @@ -253,7 +253,7 @@ error_t fshelp_access (io_statbuf_t *st, int op, struct iouser *user); /* (io_statbuf_t *dir, io_statbuf_t *st, struct iouser *user); diff --git a/libfshelp/perms-checkdirmod.c b/libfshelp/perms-checkdirmod.c index db4b2e4..823c9f6 100644 --- a/libfshelp/perms-checkdirmod.c +++ b/libfshelp/perms-checkdirmod.c @@ -23,7 +23,7 @@ /* (struct stat *dir, struct stat *st, struct iouser *user) diff --git a/libftpconn/fname.c b/libftpconn/fname.c index afa0852..3be6eee 100644 --- a/libftpconn/fname.c +++ b/libftpconn/fname.c @@ -23,7 +23,7 @@ #include "ftpconn.h" /*, diff --git a/libftpconn/ftpconn.h b/libftpconn/ftpconn.h index e445130..558ff8f 100644 --- a/libftpconn/ftpconn.h +++ b/libftpconn/ftpconn.h @@ -91,7 +91,7 @@ struct ftp_conn_syshooks ftp_conn_add_stat_fun_t add_stat, void *hook); /* Give a name which refers to a directory file, and a name in that - directory, this should return in COMPOSITE the composite name refering + directory, this should return in COMPOSITE the composite name referring to that name in that directory, in malloced storage. */ error_t (*append_name) (struct ftp_conn *conn, const char *dir, const char *name, @@ -371,7 +371,7 @@ error_t ftp_conn_get_names (struct ftp_conn *conn, const char *name, ftp_conn_add_name_fun_t add_name, void *hook); /*, const char *dir, const char *name, diff --git a/libftpconn/reply.c b/libftpconn/reply.c index 4f30f75..d39cdb0 100644 --- a/libftpconn/reply.c +++ b/libftpconn/reply.c @@ -78,7 +78,7 @@ ftp_conn_getline (struct ftp_conn *conn, const char **line, size_t *line_len) offs = nl + 1 - l; /* Consume the line */ /* Null terminate the result by overwriting the newline; if - there's a CR preceeding it, get rid of that too. */ + there's a CR preceding it, get rid of that too. */ if (nl > *line && nl[-1] == '\r') nl--; *nl = '\0'; diff --git a/libftpconn/unix.c b/libftpconn/unix.c index d279a7a..28efefd 100644 --- a/libftpconn/unix.c +++ b/libftpconn/unix.c @@ -732,7 +732,7 @@ finished: } /*_unix_append_name (struct ftp_conn *conn, diff --git a/libpager/pager.h b/libpager/pager.h index d3f1162..99fb384 100644 --- a/libpager/pager.h +++ b/libpager/pager.h @@ -151,7 +151,7 @@ pager_memcpy (struct pager *pager, memory_object_t memobj, /*, @@ -160,7 +160/libpipe/pipe.h b/libpipe/pipe.h index d6c5ae8..701cc91 100644 --- a/libpipe/pipe.h +++ b/libpipe/pipe.h @@ -98,7 +98,7 @@ struct pipe PACKET_TYPE_CONTROL. Each data packet represents one datagram for protocols that maintain record boundaries. Control packets always represent the control information to be returned from one read - operation, and will be returned in conjuction with the following data + operation, and will be returned in conjunction with the following data packet (if any). Reads interested only in data just skip control packets until they find a data packet. */ struct pq *queue; @@ -139,7 +139,7 @@ pipe_is_readable (struct pipe *pipe, int data_only) return (packet != NULL); } -/* Waits for PIPE to be readable, or an error to occurr. If NOBLOCK is true, +/* Waits for PIPE to be readable, or an error to occur. If NOBLOCK is true, this operation will return EWOULDBLOCK instead of blocking when no data is immediately available. If DATA_ONLY is true, then `control' packets are ignored. */ @@ -156,7 +156,7 @@ pipe_wait_readable (struct pipe *pipe, int noblock, int data_only) return 0; } -/* Waits for PIPE to be readable, or an error to occurr. This call only +/* Waits for PIPE to be readable, or an error to occur. This call only returns once threads waiting using pipe_wait_readable have been woken and given a chance to read, and if there is still data available thereafter. If DATA_ONLY is true, then `control' packets are ignored. */ diff --git a/libpipe/pq.h b/libpipe/pq.h index 3a26aa8..2f8311e 100644 --- a/libpipe/pq.h +++ b/libpipe/pq.h @@ -219,8 +219,8 @@ pq_tail (struct pq *pq, unsigned type, void *source) int pq_dequeue (struct pq *pq); /* Returns the next available packet in PQ, without removing it from the - queue, or NULL if there is none, or the next packet isn't appropiate. - A packet is inappropiate if SOURCE is non-NULL its source field doesn't + queue, or NULL if there is none, or the next packet isn't appropriate. + A packet is inappropriate if SOURCE is non-NULL its source field doesn't match it, or TYPE is non-NULL and the packet's type field doesn't match it. */ PQ_EI struct packet * diff --git a/libports/bucket-iterate.c b/libports/bucket-iterate.c index d376e6f..e439cb1 100644 --- a/libports/bucket-iterate.c +++ b/libports/bucket-iterate.c @@ -31,7 +31,7 @@ _ports_bucket_class_iterate (struct port_bucket *bucket, error_t (*fun)(void *)) { /* This is obscenely ineffecient. ihash and ports need to cooperate - more closely to do it effeciently. */ + more closely to do it efficiently. */ struct item { struct item *next; diff --git a/libports/manage-one-thread.c b/libports/manage-one-thread.c index 57b8a9a..4ea740b 100644 --- a/libports/manage-one-thread.c +++ b/libports/manage-one-thread.c @@ -69,7 +69,7 @@ ports_manage_port_operations_one_thread (struct port_bucket *bucket, } else { - /* No need to check cancel threshhold here, because + /* No need to check cancel threshold here, because in a single threaded server the cancel is always handled in order. */ status = demuxer (inp, outheadp); diff --git a/libps/fmt.c b/libps/fmt.c index 3a47338..0465555 100644 --- a/libps/fmt.c +++ b/libps/fmt.c @@ -370,8 +370,8 @@ ps_fmt_clone (struct ps_fmt *fmt, struct ps_fmt **copy) return 0; } -/* Write an appropiate header line for FMT, containing the titles of all its - fields appropiately aligned with where the values would be printed, to +/* Write an appropriate header line for FMT, containing the titles of all its + fields appropriately aligned with where the values would be printed, to STREAM (without a trailing newline). If count is non-NULL, the total number number of characters output is added to the integer it points to. If any fatal error occurs, the error code is returned, otherwise 0. */ @@ -461,9 +461,9 @@ ps_fmt_write_proc_stat (struct ps_fmt *fmt, struct proc_stat *ps, struct ps_stre } /*)) { @@ -540,8 +540,8 @@ps/procstat.c b/libps/procstat.c index eac4ae4..ba92378 100644 --- a/libps/procstat.c +++ b/libps/procstat.c @@ -288,7 +288,7 @@ add_preconditions (ps_flags_t flags, struct ps_context *context) flags |= PSTAT_PROC_INFO; if (flags & PSTAT_SUSPEND_COUNT) /* We just request the resources require for both the thread and task - versions, as the extraneous info won't be possible to aquire anyway. */ + versions, as the extraneous info won't be possible to acquire anyway. */ flags |= PSTAT_TASK_BASIC | PSTAT_THREAD_BASIC; if (flags & (PSTAT_CTTYID | PSTAT_CWDIR | PSTAT_AUTH | PSTAT_UMASK) && !(flags & PSTAT_NO_MSGPORT)) @@ -774,7 +774,7 @@ proc_stat_set_flags (struct proc_stat *ps, ps_flags_t flags) /* Returns true if (1) FLAGS is in NEED, and (2) the appropriate preconditions PRECOND are available; if only (1) is true, FLAG is added - to the INAPP set if appropiate (to distinguish it from an error), and + to the INAPP set if appropriate (to distinguish it from an error), and returns false. */ #define NEED(flag, precond) \ ({ \ @@ -1090,7 +1090,7 @@ _proc_stat_create (pid_t pid, struct ps_context *context, struct proc_stat **ps) resulting proc_stat isn't fully functional -- most flags can't be set in it. It also contains a pointer to PS, so PS shouldn't be freed without also freeing THREAD_PS. If N was out of range, EINVAL is returned. If a - memory allocation error occured, ENOMEM is returned. Otherwise, 0 is + memory allocation error occurred, ENOMEM is returned. Otherwise, 0 is returned. */ error_t proc_stat_thread_create (struct proc_stat *ps, unsigned index, struct proc_stat **thread_ps) diff --git a/libps/ps.h b/libps/ps.h index b85ede4..91fdc70 100644 --- a/libps/ps.h +++ b/libps/ps.h @@ -475,7 +475,7 @@ error_t proc_stat_set_flags (struct proc_stat *ps, ps_flags_t flags); PS (N should be between 0 and the number of threads in the process). The resulting proc_stat isn't fully functional -- most flags can't be set in it. If N was out of range, EINVAL is returned. If a memory allocation - error occured, ENOMEM is returned. Otherwise, 0 is returned. */ + error occurred, ENOMEM is returned. Otherwise, 0 is returned. */ error_t proc_stat_thread_create (struct proc_stat *ps, unsigned n, struct proc_stat **thread_ps); @@ -769,7 +769,7 @@ struct ps_fmt this procstat. */ char *inapp; - /* The string displayed by default for fields which are appropiate, but + /* The string displayed by default for fields which are appropriate, but couldn't be fetched due to some error. */ char *error; }; @@ -822,7 +822,7 @@ void ps_fmt_free (struct ps_fmt *fmt); instance, you would like squash a format without destroying the original. */ error_t ps_fmt_clone (struct ps_fmt *fmt, struct ps_fmt **copy); -/* Write an appropiate header line for FMT, containing the titles of all its +/* Write an appropriate header line for FMT, containing the titles of all its fields appropiately aligned with where the values would be printed, to STREAM (without a trailing newline). If count is non-NULL, the total number number of characters output is added to the integer it points to. @@ -837,14 +837,14 @@ error_t ps_fmt_write_proc_stat (struct ps_fmt *fmt, struct proc_stat *ps, struct ps_stream *stream); /*shouldbeinlibc/cacheq.c b/libshouldbeinlibc/cacheq.c index eb41c6e..5649903 100644 --- a/libshouldbeinlibc/cacheq.c +++ b/libshouldbeinlibc/cacheq.c @@ -106,7 +106,7 @@ cacheq_set_length (struct cacheq *cq, int length) th->next = next_th; } - /* Call user hooks as appropiate. */ + /* Call user hooks as appropriate. */ if (fh && th) { if (cq->move_entry) diff --git a/libshouldbeinlibc/idvec.c b/libshouldbeinlibc/idvec.c index 692c478..24adeb8 100644 --- a/libshouldbeinlibc/idvec.c +++ b/libshouldbeinlibc/idvec.c @@ -202,7 +202,7 @@ idvec_merge (struct idvec *idvec, const struct idvec *new) return idvec_merge_ids (idvec, new->ids, new->num); } -/* Remove any occurances of ID in IDVEC after position POS. +/* Remove any occurrences of ID in IDVEC after position POS. Returns true if anything was done. */ int idvec_remove (struct idvec *idvec, unsigned pos, uid_t id) diff --git a/libshouldbeinlibc/idvec.h b/libshouldbeinlibc/idvec.h index 4144125..3c70a5d 100644 --- a/libshouldbeinlibc/idvec.h +++ b/libshouldbeinlibc/idvec.h @@ -131,7 +131,7 @@ int idvec_subtract (struct idvec *idvec, const struct idvec *sub); anything was changed. */ int idvec_keep (struct idvec *idvec, const struct idvec *keep); -/* Remove any occurances of ID in IDVEC after position POS> Returns true if +/* Remove any occurrences of ID in IDVEC after position POS> Returns true if anything was done. */ int idvec_remove (struct idvec *idvec, unsigned pos, uid_t id); diff --git a/libshouldbeinlibc/ugids.c b/libshouldbeinlibc/ugids.c index 057dcf8..2b9b6b7 100644 --- a/libshouldbeinlibc/ugids.c +++ b/libshouldbeinlibc/ugids.c @@ -49,7 +49,7 @@ ugids_add_gid (struct ugids *ugids, gid_t gid, int avail) error_t err = idvec_add_new (avail ? &ugids->avail_gids : &ugids->eff_gids, gid); if (! err) - /* Since this gid is now explicit, remove it from the appropiate implied + /* Since this gid is now explicit, remove it from the appropriate implied set. */ idvec_remove (avail ? &ugids->imp_avail_gids : &ugids->imp_eff_gids, 0, gid); @@ -70,7 +70,7 @@ ugids_add_user (struct ugids *ugids, uid_t uid, int avail) idvec_merge_implied_gids (&imp_gids, &uids); /* Now remove any gids we already know about from IMP_GIDS. For gids - that weren't in the appropiate implied set before, this will + that weren't in the appropriate implied set before, this will ensure that they remain out after we merge IMP_GIDS into it, and ones that *were*, they will remain so. */ idvec_subtract (&imp_gids, gids); diff --git a/libstore/argp.c b/libstore/argp.c index 9af7ae5..6ed7996 100644 --- a/libstore/argp.c +++ b/libstore/argp.c @@ -365,7 +365,7 @@ parse_opt (int opt, char *arg, struct argp_state *state) break; case ARGP_KEY_ERROR: - /* Parsing error occured, free everything. */ + /* Parsing error occurred, free everything. */ store_parsed_free (parsed); break; case ARGP_KEY_SUCCESS: diff --git a/libstore/kids.c b/libstore/kids.c index f254bcd..901a7f8 100644 --- a/libstore/kids.c +++ b/libstore/kids.c @@ -103,7 +103,7 @@ store_decode_children (struct store_enc *enc, int num_children, return err; } -/* Set FLAGS in all children of STORE, and if successfull, add FLAGS to +/* Set FLAGS in all children of STORE, and if successful, add FLAGS to STORE's flags. */ error_t store_set_child_flags (struct store *store, int flags) @@ -127,7 +127,7 @@ store_set_child_flags (struct store *store, int flags) return err; } -/* Clear FLAGS in all children of STORE, and if successfull, remove FLAGS from +/* Clear FLAGS in all children of STORE, and if successful, remove FLAGS from STORE's flags. */ error_t store_clear_child_flags (struct store *store, int flags) diff --git a/libstore/store.h b/libstore/store.h index 5b48504..fd25044 100644 --- a/libstore/store.h +++ b/libstore/store.h @@ -262,11 +262,11 @@ error_t store_set_flags (struct store *store, int flags); /* Remove FLAGS from STORE's currently set flags. */ error_t store_clear_flags (struct store *store, int flags); -/* Set FLAGS in all children of STORE, and if successfull, add FLAGS to +/* Set FLAGS in all children of STORE, and if successful, add FLAGS to STORE's flags. */ error_t store_set_child_flags (struct store *store, int flags); -/* Clear FLAGS in all children of STORE, and if successfull, remove FLAGS from +/* Clear FLAGS in all children of STORE, and if successful, remove FLAGS from STORE's flags. */ error_t store_clear_child_flags (struct store *store, int flags); diff --git a/libthreads/mig_support.c b/libthreads/mig_support.c index 01e5deb..cd0d412 100644 --- a/libthreads/mig_support.c +++ b/libthreads/mig_support.c @@ -53,7 +53,7 @@ * Revision 2.3 90/08/07 14:27:48 rpd * When we recycle the global reply port by giving it to the first * cthread, clear the global reply port. This will take care of - * someone accidently calling this twice. + * someone accidentally calling this twice. * [90/08/07 rwd] * * Revision 2.2 90/06/02 15:14:04 rpd diff --git a/libtrivfs/trivfs.h b/libtrivfs/trivfs.h index 6e087f3..798e0b3 100644 --- a/libtrivfs/trivfs.h +++ b/libtrivfs/trivfs.h @@ -96,7 +96,7 @@ extern int trivfs_cntl_nportclasses; /* The user must define this function. This should modify a struct stat (as returned from the underlying node) for presentation to - callers of io_stat. It is permissable for this function to do + callers of io_stat. It is permissible for this function to do nothing. */ void trivfs_modify_stat (struct trivfs_protid *cred, io_statbuf_t *); diff --git a/login/utmp.c b/login/utmp.c index e56f2c5..c7c1ac0 100644 --- a/login/utmp.c +++ b/login/utmp.c @@ -134,7 +134,7 @@ next_device(char *dev) /* ---------------------------------------------------------------- */ -/* Try and start the translator for CTL_PORT on NODE. If succesful, this +/* Try and start the translator for CTL_PORT on NODE. If successful, this call will not return until the translator is stopped; otherwise it returns an error code describing the reason why it couldn't start. */ static error_t @@ -163,7 +163,7 @@ start_translator(file_t node, fsys_t ctl_port) } /* Find an unoccupied (one with no active translator) filename starting with - NAME_PFX, and start the translator for CTL_PORT on it. If succesful, this + NAME_PFX, and start the translator for CTL_PORT on it. If successful, this call will not return until the translator is stopped; otherwise it returns an error code describing the reason why it couldn't start. When successful, this function sets UTMP_NODE_NAME to the name of the file we diff --git a/mach-defpager/default_pager.c b/mach-defpager/default_pager.c index 41c2768..5944e4e 100644 --- a/mach-defpager/default_pager.c +++ b/mach-defpager/default_pager.c @@ -476,7 +476,7 @@ choose_partition(size, cur_part) mutex_lock(&all_partitions.lock); for (i = 0; i < all_partitions.n_partitions; i++) { - /* the undesireable one ? */ + /* the undesirable one ? */ if (i == cur_part) continue; diff --git a/nfs/rpc.c b/nfs/rpc.c index f5e1906..0b0444d 100644 --- a/nfs/rpc.c +++ b/nfs/rpc.c @@ -75,7 +75,7 @@ generate_xid () credential structure with UID, GID, and SECOND_GID; any of these may be -1 to indicate that it does not apply, however, exactly zero or two of UID and GID must be -1. The returned address is a pointer - to the start of the payload. If NULL is returned, an error occured + to the start of the payload. If NULL is returned, an error occurred and the code is set in errno. */ int * initialize_rpc (int program, int version, int rpc_proc, diff --git a/pfinet/linux-src/arch/sparc/lib/checksum.S b/pfinet/linux-src/arch/sparc/lib/checksum.S index d02b6df..3dc5825 100644 --- a/pfinet/linux-src/arch/sparc/lib/checksum.S +++ b/pfinet/linux-src/arch/sparc/lib/checksum.S @@ -336,7 +336,7 @@ C_LABEL(__csum_partial_copy_sparc_generic): bne cc_dword_align ! yes, we check for short lengths there andcc %g1, 0xffffff80, %g0 ! can we use unrolled loop? 3: be 3f ! nope, less than one loop remains - andcc %o1, 4, %g0 ! dest aligned on 4 or 8 byte boundry? + andcc %o1, 4, %g0 ! dest aligned on 4 or 8 byte boundary? be ccdbl + 4 ! 8 byte aligned, kick ass 5: CSUMCOPY_BIGCHUNK(%o0,%o1,%g7,0x00,%o4,%o5,%g2,%g3,%g4,%g5,%o2,%o3) CSUMCOPY_BIGCHUNK(%o0,%o1,%g7,0x20,%o4,%o5,%g2,%g3,%g4,%g5,%o2,%o3) diff --git a/pfinet/linux-src/include/linux/b1lli.h b/pfinet/linux-src/include/linux/b1lli.h index 72cae4d..388ff80 100644 --- a/pfinet/linux-src/include/linux/b1lli.h +++ b/pfinet/linux-src/include/linux/b1lli.h @@ -129,7 +129,7 @@ typedef struct avmb1_extcarddef { #define AVMB1_LOAD_AND_CONFIG 3 /* load image and config to card */ #define AVMB1_ADDCARD_WITH_TYPE 4 /* add a new card, with cardtype */ #define AVMB1_GET_CARDINFO 5 /* get cardtype */ -#define AVMB1_REMOVECARD 6 /* remove a card (usefull for T1) */ +#define AVMB1_REMOVECARD 6 /* remove a card (useful for T1) */ #define AVMB1_REGISTERCARD_IS_OBSOLETE diff --git a/pfinet/linux-src/include/linux/cdk.h b/pfinet/linux-src/include/linux/cdk.h index 2180e43..2fab894 100644 --- a/pfinet/linux-src/include/linux/cdk.h +++ b/pfinet/linux-src/include/linux/cdk.h @@ -149,7 +149,7 @@ typedef struct cdkhdr { /* * Define the memory mapping structure. This structure is pointed to by * the memp field in the stlcdkhdr struct. As many as these structures - * as required are layed out in shared memory to define how the rest of + * as required are laid out in shared memory to define how the rest of * shared memory is divided up. There will be one for each port. */ typedef struct cdkmem { diff --git a/pfinet/linux-src/include/linux/cdrom.h b/pfinet/linux-src/include/linux/cdrom.h index a8c028f..4bbdbd4 100644 --- a/pfinet/linux-src/include/linux/cdrom.h +++ b/pfinet/linux-src/include/linux/cdrom.h @@ -75,7 +75,7 @@ #define CDROM_GET_MCN 0x5311 /* Obtain the "Universal Product Code" if available (struct cdrom_mcn) */ #define CDROM_GET_UPC CDROM_GET_MCN /* This one is depricated, - but here anyway for compatability */ + but here anyway for compatibility */ #define CDROMRESET 0x5312 /* hard-reset the drive */ #define CDROMVOLREAD 0x5313 /* Get the drive's volume setting (struct cdrom_volctrl) */ diff --git a/pfinet/linux-src/include/linux/coda_opstats.h b/pfinet/linux-src/include/linux/coda_opstats.h index fdf3fac..167490d 100644 --- a/pfinet/linux-src/include/linux/coda_opstats.h +++ b/pfinet/linux-src/include/linux/coda_opstats.h @@ -85,7 +85,7 @@ struct cfs_op_stats { /* - * With each call to the minicache, we'll bump the counters whenver + * With each call to the minicache, we'll bump the counters whenever * a call is satisfied internally (through the cache or through a * redirect), and whenever an operation is caused internally. * Then, we can add the total operations caught by the minicache diff --git a/pfinet/linux-src/include/linux/cyclades.h b/pfinet/linux-src/include/linux/cyclades.h index 008254e..4e8333c 100644 --- a/pfinet/linux-src/include/linux/cyclades.h +++ b/pfinet/linux-src/include/linux/cyclades.h @@ -134,7 +134,7 @@ struct CYZ_BOOT_CTRL { /****************** ****************** *******************/ /* * The data types defined below are used in all ZFIRM interface - * data structures. They accomodate differences between HW + * data structures. They accommodate differences between HW * architectures and compilers. */ @@ -167,7 +167,7 @@ struct CUSTOM_REG { uclong fpga_version; /* FPGA Version Number Register */ uclong cpu_start; /* CPU start Register (write) */ uclong cpu_stop; /* CPU stop Register (write) */ - uclong misc_reg; /* Miscelaneous Register */ + uclong misc_reg; /* Miscellaneous Register */ uclong idt_mode; /* IDT mode Register */ uclong uart_irq_status; /* UART IRQ status Register */ uclong clear_timer0_irq; /* Clear timer interrupt Register */ diff --git a/pfinet/linux-src/include/linux/isdn.h b/pfinet/linux-src/include/linux/isdn.h index a0a0b0f..742fe14 100644 --- a/pfinet/linux-src/include/linux/isdn.h +++ b/pfinet/linux-src/include/linux/isdn.h @@ -23,7 +23,7 @@ * $Log: isdn.h,v $ * Revision 1.81 1999/10/27 21:21:18 detabc * Added support for building logically-bind-group's per interface. - * usefull for outgoing call's with more then one isdn-card. + * useful for outgoing call's with more then one isdn-card. * * Switchable support to dont reset the hangup-timeout for * receive frames. Most part's of the timru-rules for receiving frames @@ -192,7 +192,7 @@ * Added changes for recent 2.1.x kernels: * changed return type of isdn_close * queue_task_* -> queue_task - * clear/set_bit -> test_and_... where apropriate. + * clear/set_bit -> test_and_... where appropriate. * changed type of hard_header_cache parameter. * * Revision 1.28 1997/03/07 01:33:01 fritz diff --git a/pfinet/linux-src/include/linux/isdn_ppp.h b/pfinet/linux-src/include/linux/isdn_ppp.h index 06d7179..e7682fb 100644 --- a/pfinet/linux-src/include/linux/isdn_ppp.h +++ b/pfinet/linux-src/include/linux/isdn_ppp.h @@ -77,7 +77,7 @@ struct isdn_ppp_comp_data { * * We use this same struct for the reset entry of the compressor to commu- * nicate to its caller how to deal with sending of a Reset Ack. In this - * case, expra is not used, but other options still apply (supressing + * case, expra is not used, but other options still apply (suppressing * sending with rsend, appending arbitrary data, etc). */ diff --git a/pfinet/linux-src/include/linux/isdnif.h b/pfinet/linux-src/include/linux/isdnif.h index 07e3b82..7380b32 100644 --- a/pfinet/linux-src/include/linux/isdnif.h +++ b/pfinet/linux-src/include/linux/isdnif.h @@ -73,7 +73,7 @@ * Added changes for recent 2.1.x kernels: * changed return type of isdn_close * queue_task_* -> queue_task - * clear/set_bit -> test_and_... where apropriate. + * clear/set_bit -> test_and_... where appropriate. * changed type of hard_header_cache parameter. * * Revision 1.19 1997/03/25 23:13:56 keil @@ -189,7 +189,7 @@ /* */ /* The proceed command holds a incoming call in a state to leave processes */ /* enough time to check whether ist should be accepted. */ -/* The PROT_IO Command extends the interface to make protocol dependant */ +/* The PROT_IO Command extends the interface to make protocol dependent */ /* features available (call diversion, call waiting...). */ /* */ /* The PROT_IO Command is executed with the desired driver id and the arg */ diff --git a/pfinet/linux-src/include/linux/ixjuser.h b/pfinet/linux-src/include/linux/ixjuser.h index a701953..1ee0ee9 100644 --- a/pfinet/linux-src/include/linux/ixjuser.h +++ b/pfinet/linux-src/include/linux/ixjuser.h @@ -31,7 +31,7 @@ static char ixjuser_h_rcsid[] = "$Id: ixjuser.h,v 3.4 1999/12/16 22:18:36 root E /*************************************************************************** If you use the IXJCTL_TESTRAM command, the card must be power - cycled to reset the SRAM values before futher use. + cycled to reset the SRAM values before further use. ***************************************************************************/ #define IXJCTL_DSP_RESET _IO ('q', 0xC0) @@ -332,7 +332,7 @@ typedef struct { * This group of IOCTLs deal with the Acoustic Echo Cancellation settings * of the DSP * -* Issueing the IXJCTL_AEC_START command with a value of AEC_OFF has the +* Issuing the IXJCTL_AEC_START command with a value of AEC_OFF has the * same effect as IXJCTL_AEC_STOP. This is to simplify slider bar * controls. IXJCTL_AEC_GET_LEVEL returns the current setting of the AEC. ******************************************************************************/ diff --git a/pfinet/linux-src/include/linux/loop.h b/pfinet/linux-src/include/linux/loop.h index d276911..43b3bd6 100644 --- a/pfinet/linux-src/include/linux/loop.h +++ b/pfinet/linux-src/include/linux/loop.h @@ -63,7 +63,7 @@ typedef int (* transfer_proc_t)(struct loop_device *, int cmd, #endif /* - * This uses kdev_t because glibc currently has no appropiate + * This uses kdev_t because glibc currently has no appropriate * conversion version for the loop ioctls. * The situation is very unpleasant */ diff --git a/pfinet/linux-src/include/linux/module.h b/pfinet/linux-src/include/linux/module.h index 94cce87..585a8d1 100644 --- a/pfinet/linux-src/include/linux/module.h +++ b/pfinet/linux-src/include/linux/module.h @@ -230,7 +230,7 @@ extern struct module *module_list; In the kernel, the symbol is added to the kernel's global symbol table. In a module, it controls which variables are exported. If no - variables are explicitly exported, the action is controled by the + variables are explicitly exported, the action is controlled by the insmod -[xX] flags. Otherwise, only the variables listed are exported. This obviates the need for the old register_symtab() function. */ diff --git a/pfinet/linux-src/include/linux/notifier.h b/pfinet/linux-src/include/linux/notifier.h index 42facea..1e8bf70 100644 --- a/pfinet/linux-src/include/linux/notifier.h +++ b/pfinet/linux-src/include/linux/notifier.h @@ -106,7 +106,7 @@ extern __inline__ int notifier_call_chain(struct notifier_block **n, unsigned lo #define SYS_POWER_OFF 0x0003 /* Notify of system power off */ /* - * Publically visible notifier objects + * Publicly visible notifier objects */ extern struct notifier_block *boot_notifier_list; diff --git a/pfinet/linux-src/include/linux/poll.h b/pfinet/linux-src/include/linux/poll.h index 7eb5733..991204f 100644 --- a/pfinet/linux-src/include/linux/poll.h +++ b/pfinet/linux-src/include/linux/poll.h @@ -51,7 +51,7 @@ extern inline void poll_wait(struct file * filp, struct wait_queue ** wait_addre typedef unsigned long kernel_fd_set[KFDS_NR/__NFDBITS]; /* - * Scaleable version of the fd_set. + * Scalable version of the fd_set. */ typedef struct { diff --git a/pfinet/linux-src/include/linux/rtnetlink.h b/pfinet/linux-src/include/linux/rtnetlink.h index 4fda960..548a9b1 100644 --- a/pfinet/linux-src/include/linux/rtnetlink.h +++ b/pfinet/linux-src/include/linux/rtnetlink.h @@ -138,7 +138,7 @@ enum */ #define RTPROT_GATED 8 /* Apparently, GateD */ -#define RTPROT_RA 9 /* RDISC/ND router advertisments */ +#define RTPROT_RA 9 /* RDISC/ND router advertisements */ #define RTPROT_MRT 10 /* Merit MRT */ #define RTPROT_ZEBRA 11 /* Zebra */ #define RTPROT_BIRD 12 /* BIRD */ diff --git a/pfinet/linux-src/include/linux/socket.h b/pfinet/linux-src/include/linux/socket.h index 837a3e4..b427f99 100644 --- a/pfinet/linux-src/include/linux/socket.h +++ b/pfinet/linux-src/include/linux/socket.h @@ -53,7 +53,7 @@ struct cmsghdr { }; /* - * Ancilliary data object information MACROS + * Ancillary data object information MACROS * Table 5-14 of POSIX 1003.1g */ diff --git a/pfinet/linux-src/include/linux/soundcard.h b/pfinet/linux-src/include/linux/soundcard.h index 2d5128d..2041b4d 100644 --- a/pfinet/linux-src/include/linux/soundcard.h +++ b/pfinet/linux-src/include/linux/soundcard.h @@ -1204,7 +1204,7 @@ extern int OSS_write_patch2(int fd, unsigned char *buf, int len); #define SEQ_PANNING(dev, voice, pos) SEQ_CONTROL(dev, voice, CTL_PAN, (pos+128) / 2) /* - * Timing and syncronization macros + * Timing and synchronization macros */ #define _TIMER_EVENT(ev, parm) {_SEQ_NEEDBUF(8);\ diff --git a/pfinet/linux-src/include/linux/telephony.h b/pfinet/linux-src/include/linux/telephony.h index 082b885..0e4a95a 100644 --- a/pfinet/linux-src/include/linux/telephony.h +++ b/pfinet/linux-src/include/linux/telephony.h @@ -168,8 +168,8 @@ typedef enum { * indicate the current state of the hookswitch. The pstn_ring bit * indicates that the DAA on a LineJACK card has detected ring voltage on * the PSTN port. The caller_id bit indicates that caller_id data has been -* recieved and is available. The pstn_wink bit indicates that the DAA on -* the LineJACK has recieved a wink from the telco switch. The f0, f1, f2 +* received and is available. The pstn_wink bit indicates that the DAA on +* the LineJACK has received a wink from the telco switch. The f0, f1, f2 * and f3 bits indicate that the filter has been triggered by detecting the * frequency programmed into that filter. * diff --git a/pfinet/linux-src/include/linux/tpqic02.h b/pfinet/linux-src/include/linux/tpqic02.h index fe13ad6..790e0e5 100644 --- a/pfinet/linux-src/include/linux/tpqic02.h +++ b/pfinet/linux-src/include/linux/tpqic02.h @@ -588,7 +588,7 @@ */ #define TP_REWCLOSE(d) ((MINOR(d)&0x01) == 1) /* rewind bit */ - /* rewind is only done if data has been transfered */ + /* rewind is only done if data has been transferred */ #define TP_DENS(dev) ((MINOR(dev) >> 1) & 0x07) /* tape density */ #define TP_UNIT(dev) ((MINOR(dev) >> 4) & 0x07) /* unit number */ @@ -633,8 +633,8 @@ struct tpstatus { /* sizeof(short)==2), LSB first */ #define EXC_WP 3 /* Write protected */ #define EXC_EOM 4 /* EOM */ #define EXC_RWA 5 /* read/write abort */ -#define EXC_XBAD 6 /* read error, bad block transfered */ -#define EXC_XFILLER 7 /* read error, filler block transfered */ +#define EXC_XBAD 6 /* read error, bad block transferred */ +#define EXC_XFILLER 7 /* read error, filler block transferred */ #define EXC_NDT 8 /* read error, no data */ #define EXC_NDTEOM 9 /* read error, no data & EOM */ #define EXC_NDTBOM 10 /* read error, no data & BOM */ diff --git a/pfinet/linux-src/include/linux/tty_ldisc.h b/pfinet/linux-src/include/linux/tty_ldisc.h index 501ea07..4e904f8 100644 --- a/pfinet/linux-src/include/linux/tty_ldisc.h +++ b/pfinet/linux-src/include/linux/tty_ldisc.h @@ -62,7 +62,7 @@ * void (*set_termios)(struct tty_struct *tty, struct termios * old); * * This function notifies the line discpline that a change has - * been made to the termios stucture. + * been made to the termios structure. * * int (*poll)(struct tty_struct * tty, struct file * file, * poll_table *wait); diff --git a/pfinet/linux-src/include/linux/wavefront.h b/pfinet/linux-src/include/linux/wavefront.h index f96c52d..f816f94 100644 --- a/pfinet/linux-src/include/linux/wavefront.h +++ b/pfinet/linux-src/include/linux/wavefront.h @@ -667,7 +667,7 @@ typedef struct wf_fx_info { /* Allow direct user-space control over FX memory/coefficient data. In theory this could be used to download the FX microprogram, - but it would be a little slower, and involve some wierd code. + but it would be a little slower, and involve some weird code. */ #define WFFX_MEMSET 69 diff --git a/pfinet/linux-src/include/linux/wireless.h b/pfinet/linux-src/include/linux/wireless.h index 868f812..61f8515 100644 --- a/pfinet/linux-src/include/linux/wireless.h +++ b/pfinet/linux-src/include/linux/wireless.h @@ -146,7 +146,7 @@ * The "flags" member indicate if the ESSID is active or not (promiscuous). */ -/* Other parameters usefull in 802.11 and some other devices */ +/* Other parameters useful in 802.11 and some other devices */ #define SIOCSIWRATE 0x8B20 /* set default bit rate (bps) */ #define SIOCGIWRATE 0x8B21 /* get default bit rate (bps) */ #define SIOCSIWRTS 0x8B22 /* set RTS/CTS threshold (bytes) */ diff --git a/pfinet/linux-src/include/net/pkt_sched.h b/pfinet/linux-src/include/net/pkt_sched.h index 9911464..c2ef865 100644 --- a/pfinet/linux-src/include/net/pkt_sched.h +++ b/pfinet/linux-src/include/net/pkt_sched.h @@ -119,7 +119,7 @@ struct qdisc_rate_table The result: [34]86 is not good choice for QoS router :-( - The things are not so bad, because we may use artifical + The things are not so bad, because we may use artificial clock evaluated by integration of network data flow in the most critical places. diff --git a/pfinet/linux-src/include/net/tcp.h b/pfinet/linux-src/include/net/tcp.h index 0e7e4bb..8072324 100644 --- a/pfinet/linux-src/include/net/tcp.h +++ b/pfinet/linux-src/include/net/tcp.h @@ -713,7 +713,7 @@ extern __inline__ __u32 tcp_recalc_ssthresh(struct tcp_opt *tp) /* TCP timestamps are only 32-bits, this causes a slight * complication on 64-bit systems since we store a snapshot - * of jiffies in the buffer control blocks below. We decidely + * of jiffies in the buffer control blocks below. We decidedly * only use of the low 32-bits of jiffies and hide the ugly * casts with the following macro. */ diff --git a/pfinet/linux-src/net/core/dev.c b/pfinet/linux-src/net/core/dev.c index 5b4c625..92e105a 100644 --- a/pfinet/linux-src/net/core/dev.c +++ b/pfinet/linux-src/net/core/dev.c @@ -187,7 +187,7 @@ int netdev_nit=0; * * BEWARE!!! Protocol handlers, mangling input packets, * MUST BE last in hash buckets and checking protocol handlers - * MUST start from promiscous ptype_all chain in net_bh. + * MUST start from promiscuous ptype_all chain in net_bh. * It is true now, do not change it. * Explantion follows: if protocol handler, mangling packet, will * be the first on list, it is not able to sense, that packet diff --git a/pfinet/linux-src/net/core/sock.c b/pfinet/linux-src/net/core/sock.c index e0eb41a..c47c935 100644 --- a/pfinet/linux-src/net/core/sock.c +++ b/pfinet/linux-src/net/core/sock.c @@ -138,7 +138,7 @@ __u32 sysctl_rmem_max = SK_RMEM_MAX; __u32 sysctl_wmem_default = SK_WMEM_MAX; __u32 sysctl_rmem_default = SK_RMEM_MAX; -/* Maximal space eaten by iovec or ancilliary data plus some space */ +/* Maximal space eaten by iovec or ancillary data plus some space */ int sysctl_optmem_max = sizeof(unsigned long)*(2*UIO_MAXIOV + 512); /* @@ -693,7 +693,7 @@ struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, * 1003.1g draft 6.4. If we (the user) did a shutdown() * call however we should not. * - * Note: This routine isnt just used for datagrams and + * Note: This routine isn't just used for datagrams and * anyway some datagram protocols have a notion of * close down. */ diff --git a/pfinet/linux-src/net/ipv4/fib_semantics.c b/pfinet/linux-src/net/ipv4/fib_semantics.c index b78f7eb..b7edb29 100644 --- a/pfinet/linux-src/net/ipv4/fib_semantics.c +++ b/pfinet/linux-src/net/ipv4/fib_semantics.c @@ -291,7 +291,7 @@ int fib_nh_match(struct rtmsg *r, struct nlmsghdr *nlh, struct kern_rta *rta, Attempt to reconcile all of these (alas, self-contradictory) conditions results in pretty ugly and hairy code with obscure logic. - I choosed to generalized it instead, so that the size + I chose to generalize it instead, so that the size of code does not increase practically, but it becomes much more general. Every prefix is assigned a "scope" value: "host" is local address, diff --git a/pfinet/linux-src/net/ipv4/icmp.c b/pfinet/linux-src/net/ipv4/icmp.c index 6c1edfd..7fad478 100644 --- a/pfinet/linux-src/net/ipv4/icmp.c +++ b/pfinet/linux-src/net/ipv4/icmp.c @@ -730,7 +730,7 @@ static void icmp_unreach(struct icmphdr *icmph, struct sk_buff *skb, int len) */ /* - * Check the other end isnt violating RFC 1122. Some routers send + * Check the other end isn't violating RFC 1122. Some routers send * bogus responses to broadcast frames. If you see this message * first check your netmask matches at both ends, if it does then * get the other vendor to fix their kit. diff --git a/pfinet/linux-src/net/ipv4/ip_fw.c b/pfinet/linux-src/net/ipv4/ip_fw.c index 400f46c..73af70a 100644 --- a/pfinet/linux-src/net/ipv4/ip_fw.c +++ b/pfinet/linux-src/net/ipv4/ip_fw.c @@ -239,7 +239,7 @@ struct ip_chain ip_chainlabel label; /* Defines the label for each block */ struct ip_chain *next; /* Pointer to next block */ struct ip_fwkernel *chain; /* Pointer to first rule in block */ - __u32 refcount; /* Number of refernces to block */ + __u32 refcount; /* Number of references to block */ int policy; /* Default rule for chain. Only * * used in built in chains */ struct ip_reent reent[0]; /* Actually several of these */ diff --git a/pfinet/linux-src/net/ipv4/ip_gre.c b/pfinet/linux-src/net/ipv4/ip_gre.c index 6a7546f..4b03c22 100644 --- a/pfinet/linux-src/net/ipv4/ip_gre.c +++ b/pfinet/linux-src/net/ipv4/ip_gre.c @@ -436,7 +436,7 @@ void ipgre < grehlen+68) return; diff --git a/pfinet/linux-src/net/ipv4/ip_masq_quake.c b/pfinet/linux-src/net/ipv4/ip_masq_quake.c index 995c3a0..646348d 100644 --- a/pfinet/linux-src/net/ipv4/ip_masq_quake.c +++ b/pfinet/linux-src/net/ipv4/ip_masq_quake.c @@ -92,7 +92,7 @@ masq_quake_in (struct ip_masq_app *mapp, struct ip_masq *ms, struct sk_buff **sk iph = skb->nh.iph; uh = (struct udphdr *)&(((char *)iph)[iph->ihl*4]); - /* Check for lenght */ + /* Check for length */ if(ntohs(uh->len) < 5) return 0; @@ -178,7 +178,7 @@ masq_quake_out (struct ip_masq_app *mapp, struct ip_masq *ms, struct sk_buff **s iph = skb->nh.iph; uh = (struct udphdr *)&(((char *)iph)[iph->ihl*4]); - /* Check for lenght */ + /* Check for length */ if(ntohs(uh->len) < 5) return 0; diff --git a/pfinet/linux-src/net/ipv4/ip_output.c b/pfinet/linux-src/net/ipv4/ip_output.c index c8f416e..d85ba6b 100644 --- a/pfinet/linux-src/net/ipv4/ip_output.c +++ b/pfinet/linux-src/net/ipv4/ip_output.c @@ -782,7 +782,7 @@ void ip_fragment(struct sk_buff *skb, int (*output)(struct sk_buff*)) /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; - /* IF: we are not sending upto and including the packet end + /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; diff --git a/pfinet/linux-src/net/ipv4/ipconfig.c b/pfinet/linux-src/net/ipv4/ipconfig.c index 0770bad..bb95824 100644 --- a/pfinet/linux-src/net/ipv4/ipconfig.c +++ b/pfinet/linux-src/net/ipv4/ipconfig.c @@ -844,7 +844,7 @@ int __init ip_auto_config(void) } /* - * Use defaults whereever applicable. + * Use defaults wherever applicable. */ if (ic_defaults() < 0) return -1; diff --git a/pfinet/linux-src/net/ipv4/ipip.c b/pfinet/linux-src/net/ipv4/ipip.c index 0aeef4a..119d756 100644 --- a/pfinet/linux-src/net/ipv4/ipip.c +++ b/pfinet/linux-src/net/ipv4/ipip.c @@ -365,7 +365,7 @@ void ipip < hlen+68) return; diff --git a/pfinet/linux-src/net/ipv4/raw.c b/pfinet/linux-src/net/ipv4/raw.c index 5e7910d..a0aaa82 100644 --- a/pfinet/linux-src/net/ipv4/raw.c +++ b/pfinet/linux-src/net/ipv4/raw.c @@ -379,7 +379,7 @@ static void raw_close(struct sock *sk, long timeout) sk->state = TCP_CLOSE; raw_v4_unhash(sk); /* - B. Raw sockets may have direct kernel refereneces. Kill them. + B. Raw sockets may have direct kernel references. Kill them. */ ip_ra_control(sk, 0, NULL); diff --git a/pfinet/linux-src/net/ipv4/tcp.c b/pfinet/linux-src/net/ipv4/tcp.c index cf8cee2..8cde385 100644 --- a/pfinet/linux-src/net/ipv4/tcp.c +++ b/pfinet/linux-src/net/ipv4/tcp.c @@ -1218,7 +1218,7 @@ int tcp_recvmsg(struct sock *sk, struct msghdr *msg, break; /* We need to check signals first, to get correct SIGURG - * handling. FIXME: Need to check this doesnt impact 1003.1g + * handling. FIXME: Need to check this doesn't impact 1003.1g * and move it down to the bottom of the loop */ if (signal_pending(current)) { diff --git a/pfinet/linux-src/net/ipv4/tcp_input.c b/pfinet/linux-src/net/ipv4/tcp_input.c index 7f5cc4e..e84eaf4 100644 --- a/pfinet/linux-src/net/ipv4/tcp_input.c +++ b/pfinet/linux-src/net/ipv4/tcp_input.c @@ -130,7 +130,7 @@ static __inline__ void tcp_remember_ack(struct tcp_opt *tp, struct tcphdr *th, { tp->delayed_acks++; - /* Tiny-grams with PSH set artifically deflate our + /* Tiny-grams with PSH set artificially deflate our * ato measurement, but with a lower bound. */ if(th->psh && (skb->len < (tp->mss_cache >> 1))) { @@ -989,7 +989,7 @@ tcp_timewait_state_process(struct tcp_tw_bucket *tw, struct sk_buff *skb, /* Check RST or SYN */ if(th->rst || th->syn) { - /* This is TIME_WAIT assasination, in two flavors. + /* This is TIME_WAIT assassination, in two flavors. * Oh well... nobody has a sufficient solution to this * protocol bug yet. */ @@ -1931,7 +1931,7 @@ int tcp_rcv_established(struct sock *sk, struct sk_buff *skb, * Dave!!! Phrase above (and all about rcv_mss) has * nothing to do with reality. rcv_mss must measure TOTAL * size, including sacks, IP options etc. Hence, measure_rcv_mss - * must occure before pulling etc, otherwise it will flap + * must occur before pulling etc, otherwise it will flap * like hell. Even putting it before tcp_data is wrong, * it should use skb->tail - skb->nh.raw instead. * --ANK (980805) @@ -1939,7 +1939,7 @@ int tcp_rcv_established(struct sock *sk, struct sk_buff *skb, * BTW I broke it. Now all TCP options are handled equally * in mss_clamp calculations (i.e. ignored, rfc1122), * and mss_cache does include all of them (i.e. tstamps) - * except for sacks, to calulate effective mss faster. + * except for sacks, to calculate effective mss faster. * --ANK (980805) */ tcp_measure_rcv_mss(sk, skb); diff --git a/pfinet/linux-src/net/ipv4/tcp_ipv4.c b/pfinet/linux-src/net/ipv4/tcp_ipv4.c index ab6db9b..9919423 100644 --- a/pfinet/linux-src/net/ipv4/tcp_ipv4.c +++ b/pfinet/linux-src/net/ipv4/tcp_ipv4.c @@ -1516,7 +1516,7 @@ struct sock * tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb, #ifdef CONFIG_IP_TRANSPARENT_PROXY /* The new socket created for transparent proxy may fall * into a non-existed bind bucket because sk->num != newsk->num. - * Ensure existance of the bucket now. The placement of the check + * Ensure existence of the bucket now. The placement of the check * later will require to destroy just created newsk in the case of fail. * 1998/04/22 Andrey V. Savochkin <address@hidden> */ diff --git a/pfinet/linux-src/net/ipv4/tcp_output.c b/pfinet/linux-src/net/ipv4/tcp_output.c index 2ac5e8a..9ea4b7a 100644 --- a/pfinet/linux-src/net/ipv4/tcp_output.c +++ b/pfinet/linux-src/net/ipv4/tcp_output.c @@ -257,7 +257,7 @@ static int tcp_fragment(struct sock *sk, struct sk_buff *skb, u32 len) for TCP options, but includes only bare TCP header. tp->mss_clamp is mss negotiated at connection setup. - It is minumum of user_mss and mss received with SYN. + It is minimum of user_mss and mss received with SYN. It also does not include TCP options. tp->pmtu_cookie is last pmtu, seen by this function. diff --git a/pfinet/linux-src/net/ipv6/addrconf.c b/pfinet/linux-src/net/ipv6/addrconf.c index e3ca6d7..d392b3f 100644 --- a/pfinet/linux-src/net/ipv6/addrconf.c +++ b/pfinet/linux-src/net/ipv6/addrconf.c @@ -373,9 +373,9 @@ static void ipv6_del_addr(struct inet6_ifaddr *ifp) } /* - * Choose an apropriate source address + * Choose an appropriate source address * should do: - * i) get an address with an apropriate scope + * i) get an address with an appropriate scope * ii) see if there is a specific route for the destination and use * an address of the attached interface * iii) don't use deprecated addresses diff --git a/pfinet/linux-src/net/ipv6/af_inet6.c b/pfinet/linux-src/net/ipv6/af_inet6.c index fb5d395..ca42818 100644 --- a/pfinet/linux-src/net/ipv6/af_inet6.c +++ b/pfinet/linux-src/net/ipv6/af_inet6.c @@ -551,7 +551,7 @@ __initfunc(void inet6_proto_init(struct net_proto *pro)) /* * ipngwg API draft makes clear that the correct semantics * for TCP and UDP is to consider one TCP and UDP instance - * in a host availiable by both INET and INET6 APIs and + * in a host available by both INET and INET6 APIs and * able to communicate via both network protocols. */ diff --git a/pfinet/linux-src/net/ipv6/icmpv6.c b/pfinet/linux-src/net/ipv6/icmpv6.c index f7bebe0..8a33c9c 100644 --- a/pfinet/linux-src/net/ipv6/icmpv6.c +++ b/pfinet/linux-src/net/ipv6/icmpv6.c @@ -567,14 +567,14 @@ int icmpv6_rcv(struct sk_buff *skb, unsigned long len) default: if (net_ratelimit()) - printk(KERN_DEBUG "icmpv6: msg of unkown type\n"); + printk(KERN_DEBUG "icmpv6: msg of unknown type\n"); /* informational */ if (type & 0x80) break; /* - * error of unkown type. + * error of unknown type. * must pass to upper level */ diff --git a/pfinet/linux-src/net/ipv6/ip6_fib.c b/pfinet/linux-src/net/ipv6/ip6_fib.c index d190834..9468c02 100644 --- a/pfinet/linux-src/net/ipv6/ip6_fib.c +++ b/pfinet/linux-src/net/ipv6/ip6_fib.c @@ -234,7 +234,7 @@ static __inline__ void rt6_release(struct rt6_info *rt) /* * Routing Table * - * return the apropriate node for a routing tree "add" operation + * return the appropriate node for a routing tree "add" operation * by either creating and inserting or by returning an existing * node. */ diff --git a/pfinet/linux-src/net/ipv6/ip6_input.c b/pfinet/linux-src/net/ipv6/ip6_input.c index 54a3f45..c4a5183 100644 --- a/pfinet/linux-src/net/ipv6/ip6_input.c +++ b/pfinet/linux-src/net/ipv6/ip6_input.c @@ -246,7 +246,7 @@ int ip6_mc_input(struct sk_buff *skb) deliver = 1; /* - * IPv6 multicast router mode isnt currently supported. + * IPv6 multicast router mode isn't currently supported. */ #if 0 if (ipv6_config.multicast_route) { diff --git a/pfinet/linux-src/net/ipv6/ip6_output.c b/pfinet/linux-src/net/ipv6/ip6_output.c index f67e3e9..e06ad59 100644 --- a/pfinet/linux-src/net/ipv6/ip6_output.c +++ b/pfinet/linux-src/net/ipv6/ip6_output.c @@ -481,7 +481,7 @@ int ip6_build_xmit(struct sock *sk, inet_getfrag_t getfrag, const void *data, if (err) { #if IP6_DEBUG >= 2 printk(KERN_DEBUG "ip6_build_xmit: " - "no availiable source address\n"); + "no available source address\n"); #endif goto out; } diff --git a/pfinet/linux-src/net/ipv6/ndisc.c b/pfinet/linux-src/net/ipv6/ndisc.c index 3b3d3f4..61f950d 100644 --- a/pfinet/linux-src/net/ipv6/ndisc.c +++ b/pfinet/linux-src/net/ipv6/ndisc.c @@ -554,7 +554,7 @@ static void ndisc_router_discovery(struct sk_buff *skb) if (skb->nh.ipv6h->hop_limit != 255) { printk(KERN_INFO - "NDISC: fake router advertisment received\n"); + "NDISC: fake router advertisement received\n"); return; } @@ -694,7 +694,7 @@ static void ndisc_router_discovery(struct sk_buff *skb) ND_PRINTK0("got illegal option with RA"); break; default: - ND_PRINTK0("unkown option in RA\n"); + ND_PRINTK0("unknown option in RA\n"); }; optlen -= len; opt += len; diff --git a/pfinet/linux-src/net/ipv6/udp_ipv6.c b/pfinet/linux-src/net/ipv6/udp_ipv6.c index 1886e8a..f6968ae 100644 --- a/pfinet/linux-src/net/ipv6/udp_ipv6.c +++ b/pfinet/linux-src/net/ipv6/udp_ipv6.c @@ -335,7 +335,7 @@ ipv4_connected: ip6_dst_store(sk, dst, fl.fl6_dst); - /* get the source adddress used in the apropriate device */ + /* get the source adddress used in the appropriate device */ err = ipv6_get_saddr(dst, daddr, &saddr); diff --git a/pfinet/main.c b/pfinet/main.c index c1e080a..b4af267 100644 --- a/pfinet/main.c +++ b/pfinet/main.c @@ -288,7 +288,7 @@ main (int argc, /* Parse options. When successful, this configures the interfaces before returning; to do so, it will acquire the global_lock. - (And when not sucessful, it never returns.) */ + (And when not successful, it never returns.) */ argp_parse (&pfinet_argp, argc, argv, 0,0,0); task_get_bootstrap_port (mach_task_self (), &bootstrap); diff --git a/pfinet/options.c b/pfinet/options.c index d0a1ff2..21a35c6 100644 --- a/pfinet/options.c +++ b/pfinet/options.c @@ -479,7 +479,7 @@ parse_opt (int opt, char *arg, struct argp_state *state) /* Fall through to free hook. */ case ARGP_KEY_ERROR: - /* Parsing error occured, free everything. */ + /* Parsing error occurred, free everything. */ free_hook: free (h->interfaces); free (h); diff --git a/pflocal/pf.c b/pflocal/pf.c index 852aabb..32c12e1 100644 --- a/pflocal/pf.c +++ b/pflocal/pf.c @@ -114,7 +114,7 @@ S_socket_fabricate_address (mach_port_t pf, } /* Implement socket_whatis_address as described in <hurd/socket.defs>. - Since we cannot tell what our adress is, return an empty string as + Since we cannot tell what our address is, return an empty string as the file name. This is primarily for the implementation of accept and recvfrom. The functions getsockname and getpeername remain unsupported for the local namespace. */ diff --git a/pflocal/socket.c b/pflocal/socket.c index c5c4e1d..faa9951 100644 --- a/pflocal/socket.c +++ b/pflocal/socket.c @@ -309,7 +309,7 @@ S_socket_send (struct sock_user *user, struct addr *dest_addr, int flags, if (dest_sock) /* Grab the destination socket's read pipe directly, and stuff data into it. This is not quite the usage sock_acquire_read_pipe was - intended for, but it will work, as the only inappropiate errors + intended for, but it will work, as the only inappropriate errors occur on a broken pipe, which shouldn't be possible with the sort of sockets with which we can use socket_send... XXXX */ err = sock_acquire_read_pipe (dest_sock, &pipe); diff --git a/release/SOURCES.0.0 b/release/SOURCES.0.0 index 1f561ad..673f8dd 100644 --- a/release/SOURCES.0.0 +++ b/release/SOURCES.0.0 @@ -107,5 +107,5 @@ sh-utils (1.12m from alpha.gnu.ai.mit.edu) [ copy libc's time/strftime.c into lib/strftime.c to fix a date bug. ] make (3.74.5 from alpha.gnu.ai.mit.edu; unmodified) gdb (Modified from Cygnus snapshot of 960526) -mach4 (UK22, slighly hacked) [already includes `serverboot' program.] +mach4 (UK22, slightly hacked) [already includes `serverboot' program.] libc (1.93, with modifications) diff --git a/release/mkfsimage.sh b/release/mkfsimage.sh index 181928f..07b142f 100644 --- a/release/mkfsimage.sh +++ b/release/mkfsimage.sh @@ -75,7 +75,7 @@ while :; do --help Display this help and exit --version Output version information and exit -If multiple SRCs are specified, then each occurance of --files pertains only to +If multiple SRCs are specified, then each occurrence of --files pertains only to the corresponding SRC. Each FILE named in a --copy-rules option contains lines of the form: @@ -83,8 +83,8 @@ Each FILE named in a --copy-rules option contains lines of the form: [gzip] [rename TARGET] COPY-OP NAME and says to copy NAME from the source tree to the destination, using the -method specified by COPY-OP. A preceeding "\`"rename TARGET"\'" says to give -NAME a different name in the target tree, and a preceeding "\`"gzip"\'" says +method specified by COPY-OP. A preceding "\`"rename TARGET"\'" says to give +NAME a different name in the target tree, and a preceding "\`"gzip"\'" says to compress the result (appending .gz to the name). COPY-OP may be one of the following: diff --git a/storeio/dev.c b/storeio/dev.c index a7a1dd8..31b084f 100644 --- a/storeio/dev.c +++ b/storeio/dev.c @@ -226,7 +226,7 @@ dev_sync(struct dev *dev, int wait) } /* Takes care of buffering I/O to/from DEV for a transfer at position OFFS, - length LEN; the amount of I/O sucessfully done is returned in AMOUNT. + length LEN; the amount of I/O successfully done is returned in AMOUNT. BUF_RW is called to do I/O that's entirely inside DEV's internal buffer, and RAW_RW to do I/O directly to DEV's store. */ static inline error_t @@ -312,8 +312,8 @@ dev_rw (struct dev *dev, off_t offs, size_t len, size_t *amount, /* Some non-aligned I/O has been done, or is needed, so we need to deal with DEV's buffer, which means getting an exclusive lock. */ { - /* Aquire a writer lock instead of a reader lock. Note that other - writers may have aquired the lock by the time we get it. */ + /* Acquire a writer lock instead of a reader lock. Note that other + writers may have acquired the lock by the time we get it. */ rwlock_reader_unlock (&dev->io_lock); err = buffered_rw (dev, offs, len, amount, buf_rw, raw_rw); } diff --git a/storeio/pager.c b/storeio/pager.c index 0ad126c..1fb1d07 100644 --- a/storeio/pager.c +++ b/storeio/pager.c @@ -33,7 +33,7 @@ /* For pager PAGER, read one page from offset PAGE. Set *BUF to be the address of the page, and set *WRITE_LOCK if the page must be provided - read-only. The only permissable error returns are EIO, EDQUOT, and + read-only. The only permissible error returns are EIO, EDQUOT, and ENOSPC. */ error_t pager_read_page (struct user_pager_info *upi, @@ -65,7 +65,7 @@ pager_read_page (struct user_pager_info *upi, } /* For pager PAGER, synchronously write one page from BUF to offset PAGE. In - addition, vm_deallocate (or equivalent) BUF. The only permissable error + addition, vm_deallocate (or equivalent) BUF. The only permissible error returns are EIO, EDQUOT, and ENOSPC. */ error_t pager_write_page (struct user_pager_info *upi, diff --git a/sutils/clookup.c b/sutils/clookup.c index 8fe015e..0107799 100644 --- a/sutils/clookup.c +++ b/sutils/clookup.c @@ -36,7 +36,7 @@ any passive translators. If a node with an unstarted passive translator is encountered, ENXIO is returned in ERRNO; other errors are as for file_name_lookup. Note that checking for an active translator currently - requires fetching the control port, which is a priveleged operation. */ + requires fetching the control port, which is a privileged operation. */ file_t file_name_lookup_carefully (const char *name, int flags, mode_t mode) { diff --git a/sutils/fsck.c b/sutils/fsck.c index 424e3f1..1ab9caa 100644 --- a/sutils/fsck.c +++ b/sutils/fsck.c @@ -41,7 +41,7 @@ Although it knows something about the hurd, this fsck still uses /etc/fstab, and is generally not very integrated. That will have to wait - until the appropiate mechanisms for doing so are decided. */ + until the appropriate mechanisms for doing so are decided. */ #include <stdlib.h> #include <string.h> diff --git a/tasks b/tasks index 0637a88..871bde1 100644 --- a/tasks +++ b/tasks @@ -94,7 +94,7 @@ Please discuss proposed microkernel work with address@hidden can be device_open'd, as well as to get the type of a device. * A way to have the kernel send a message on some designated port - everytime a new task is started. + every time a new task is started. * OSF has enhanced the exception_raise protocol to include thread_state information. This code should be merged into the kernel; OSF people diff --git a/term/munge.c b/term/munge.c index 74d8288..660a99b 100644 --- a/term/munge.c +++ b/term/munge.c @@ -582,7 +582,7 @@ input_character (int c) echo_char (c, 0, 0); if (CCEQ (cc[VEOF], c) && (lflag & ECHO)) { - /* Special bizzare echo processing for VEOF character. */ + /* Special bizarre echo processing for VEOF character. */ int n; n = echo_double (c, 0) ? 2 : output_width (c, output_psize); while (n--) @@ -642,7 +642,7 @@ input_break () enqueue_quote (qp, '\0'); } -/* Called when a character is recived with a framing error. */ +/* Called when a character is received with a framing error. */ void input_framing_error (int c) { diff --git a/tmpfs/pager-stubs.c b/tmpfs/pager-stubs.c index 361724a..25d70fe 100644 --- a/tmpfs/pager-stubs.c +++ b/tmpfs/pager-stubs.c @@ -24,7 +24,7 @@ the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ /*, @@ -37,7 +37/ufs/alloc.c b/ufs/alloc.c index 48ee60c..d8f9225 100644 --- a/ufs/alloc.c +++ b/ufs/alloc.c @@ -215,7 +215,7 @@ release_cg (struct cg *cgp) * 3) allocate a block in the same cylinder group. * 4) quadradically rehash into other cylinder groups, until an * available block is located. - * If no block preference is given the following heirarchy is used + * If no block preference is given the following hierarchy is used * to allocate a block: * 1) allocate a block in the cylinder group that contains the * inode for the file. @@ -472,7 +472,7 @@ nospace: * logical blocks to be made contiguous is given. The allocator attempts * to find a range of sequential blocks starting as close as possible to * an fs_rotdelay offset from the end of the allocation for the logical - * block immediately preceeding the current range. If successful, the + * block immediately preceding the current range. If successful, the * physical block numbers in the buffer pointers and in the inode are * changed to reflect the new allocation. If unsuccessful, the allocation * is left unchanged. The success in doing the reallocation is returned. @@ -638,7 +638,7 @@ fail: * 2) allocate an inode in the same cylinder group. * 3) quadradically rehash into other cylinder groups, until an * available inode is located. - * If no inode preference is given the following heirarchy is used + * If no inode preference is given the following hierarchy is used * to allocate an inode: * 1) allocate an inode in cylinder group 0. * 2) quadradically rehash into other cylinder groups, until an diff --git a/ufs/dir.c b/ufs/dir.c index 7a8cfa5..3c5f152 100644 --- a/ufs/dir.c +++ b/ufs/dir.c @@ -664,7 +664,7 @@ diskfs_direnter_hard(struct node *dp, /*, diff --git a/ufs/inode.c b/ufs/inode.c index 1a8a709..77a45ed 100644 --- a/ufs/inode.c +++ b/ufs/inode.c @@ -181,7 +181,7 @@ diskfs_lost_hardrefs (struct node *np) spin_unlock (&_libports_portrefcntlock); /* Right now the node is locked with no hard refs; - this is an anomolous situation. Before messing with + this is an anomalous situation. Before messing with the reference count on the file pager, we have to give ourselves a reference back so that we are really allowed to hold the lock. Then we can do the diff --git a/utils/devprobe.c b/utils/devprobe.c index b5ebafe..d702032 100644 --- a/utils/devprobe.c +++ b/utils/devprobe.c @@ -35,7 +35,7 @@ static const struct argp_option options[] = { {0} }; static const char *args_doc = "DEVNAME..."; -static const char *doc = "Test for the existance of mach device DEVNAME..." +static const char *doc = "Test for the existence of mach device DEVNAME..." "\vThe exit status is 0 if any devices were found."; int diff --git a/utils/ftpcp.c b/utils/ftpcp.c index 4c4c151..67ccb1a 100644 --- a/utils/ftpcp.c +++ b/utils/ftpcp.c @@ -240,7 +240,7 @@ efinish (struct epoint *e) } /* Give a name which refers to a directory file, and a name in that - directory, this should return in COMPOSITE the composite name refering to + directory, this should return in COMPOSITE the composite name referring to that name in that directory, in malloced storage. */ error_t eappend (struct epoint *e, diff --git a/utils/ftpdir.c b/utils/ftpdir.c index 9b496ad..4ccb821 100644 --- a/utils/ftpdir.c +++ b/utils/ftpdir.c @@ -39,7 +39,7 @@ static struct argp_option options[] = {"account", 'a', "ACCT",0, "Account to login as"}, {"separator",'S', "SEP", 0, "String to separate multiple listings"}, {"prefix", 'P', "PFX", 0, "String to proceed listings; the first and second" - " occurances of %s are replace by HOST and DIR"}, + " occurrences of %s are replace by HOST and DIR"}, {"host", 'h', "HOST",0, "Use HOST as a default host"}, {"debug", 'D', 0, 0, "Turn on debugging output for ftp connections"}, {"intepret", 'i', 0, 0, "Parse the directory output"}, diff --git a/utils/login.c b/utils/login.c index aefc218..cad3b1e 100644 --- a/utils/login.c +++ b/utils/login.c @@ -663,7 +663,7 @@ main(int argc, char *argv[]) if (ugids.eff_uids.num + ugids.avail_uids.num == 0) /* We're transiting from having some uids to having none, which means this is probably a new login session. Unless specified otherwise, - set a timer to kill this session if it hasn't aquired any ids by + set a timer to kill this session if it hasn't acquired any ids by then. Note that we fork off the timer process before clearing the process owner: because we're interested in killing unowned processes, proc's in-same-login-session rule should apply to us diff --git a/utils/mount.c b/utils/mount.c index e9f64d8..8b059c2 100644 --- a/utils/mount.c +++ b/utils/mount.c @@ -48,7 +48,7 @@ static const struct argp_option argp_opts[] = {"timeout", 'T', "MILLISECONDS", 0, "Timeout for translator startup"}, {"format", 'p', "mount|fstab|translator", OPTION_ARG_OPTIONAL, "Output format for query (no filesystem arguments)"}, - {"options", 'o', "OPTIONS", 0, "A `,' seperated list of options"}, + {"options", 'o', "OPTIONS", 0, "A `,' separated list of options"}, {"readonly", 'r', 0, 0, "Never write to disk or allow opens for writing"}, {"writable", 'w', 0, 0, "Use normal read/write behavior"}, {"update", 'u', 0, 0, "Flush any meta-data cached in core"}, diff --git a/utils/vmstat.c b/utils/vmstat.c index 86494dc..bc3f2d4 100644 --- a/utils/vmstat.c +++ b/utils/vmstat.c @@ -456,7 +456,7 @@ main (int argc, char **argv) if (field->standard) output_fields |= (1 << (field - fields)); - /* Returns an appropiate SIZE_UNITS for printing FIELD. */ + /* Returns an appropriate SIZE_UNITS for printing FIELD. */ #define SIZE_UNITS(field) \ (size_units >= 0 \ ? size_units \ diff --git a/utils/w.c b/utils/w.c index 43bce02..3755508 100644 --- a/utils/w.c +++ b/utils/w.c @@ -253,7 +253,7 @@ static void add_utmp_procs (struct proc_stat_list *procs, struct utmp *u) { /* The tty name, with space for '\0' termination and an - appropiate prefix. */ + appropriate prefix. */ char tty[sizeof _PATH_DEV + sizeof u->ut_line]; io_t tty_node; error_t err; -- 1.7.5.4
http://lists.gnu.org/archive/html/bug-hurd/2011-08/msg00039.html
CC-MAIN-2015-06
refinedweb
13,526
52.36
Server-Side Rendering is a method of loading and parsing frontend elements and codes of web applications on the hosted server itself. Back in the day, browsers were not that advanced and only rendered the content of the HTML documents to present a static version of a web page to users. The basic idea was to render all the elements on the server so that browsers don’t have to compile much. This was fast and efficient. However, the advent of JavaScript-based frameworks changed the face of rendering frontends altogether. For fast-loading frontend, it is necessary to deliver essential data and content to the browser. And as mentioned, server-side rendering perfectly does the job. Here are some frameworks with included support for SSR for web software development. We can create our Next.js project with its provided command-line program. To create the project, we just run: npx create-next-app or: yarn create next-app to create our project. Then to start the dev server, we run: npm run dev Then we go to and our app. Now we can create a component in the pages folder to add our page. We go into the pages folder, create an hello.js file and add: function Hello() { return <div>hello world</div>; } export default Hello; to it. We’ve to remember to export the component so that it’ll be rendered. Then we can go to and see our page. Next.js does routing automatically by the file name so we don’t have to worry about that. Pages with Dynamic Routes If we want to create pages with dynamic routes, we just put them in the folder structure and the URLs will follow the same structure. For example, we can create a posts folder and create our files. We create 1.js in pages/posts and write: function Hello() { return <div>hello 1</div> } export default Hello Likewise, we create 2.js in the same folder and write: function Hello() { return <div>hello 2</div> } export default Hello Then when we go to and, we’ll see hello 1 and hello 2 respectively. Pre-rendering Next.js pre-renders every page by default. The HTML for each page are created in advanced. This is better for performance and SEO than rendering it on the client-side. The pages only come with the JavaScript it needs to load so that it loads faster. There’re 2 forms of pre-rendering. One is static generation and the other is server-side rendering. Static generation means that HTML is generated at build time and are reused on each request. Since it reuses the pages, it’ll be the fastest way to render pages, so this is the recommended option. The other option is server-side rendering, which renders the HTML no each request. We can choose between the 2 types of rendering. Static Generation with Data We can generate pages statically with data. To do this, we can write: pages/yesno.js function YesNo({ data }) { return <p>{data.answer}</p>; } export async function getStaticProps() { const res = await fetch(''); const data = await res.json(); return { props: { data, }, }; } export default YesNo; We created a new component file with the YesNo component. The getStaticProps function gets the data asynchronously from an API. Then we return the resolved value by return an object with the data in the props property. Then we can get that data from the props in the YesNo component. And in the JSX, we displayed the data. Next takes care of routing for you. //Next.js npx create-next-app@latest //SvelteKit npm init svelte@next my-app Routing determines what URL will be needed to access different pages on the website. All three frameworks use file-based routing, which is primarily what all meta-frameworks use. The URL is based on the name and location of the file for that particular page. Below, you’ll see some examples of how different files get mapped to URLs, including an example with URL params, which define a part of the URL as a variable that you can retrieve. Next.js / → pages/index.js /hello → pages/hello/index.js or pages/hello.js /use_param/:id → pages/use_param/[id].js SvelteKit / → src/routes/index.svelte /hello → src/routes/hello/index.svelte or src/routes/hello.svelte /use_param/:id → src/routes/use_param/[id].svelte A major benefit of using a meta-framework is handling a lot of data preparation prior to your page hydrating, like API calls, transformation, etc. When you use a meta-framework, you don’t have to prepare loaders or things like the useEffect Hook to deal with the asynchronous nature of these issues. In all three frameworks, there is a function on each page we can define that will be run from the server prior to shipping the page to the user’s browser. Next.js Similarly, in Next.js, you can export a function called getServerSideProps. The return value can then define the props to the page component: export const getServerSideProps = async ({ params, query }) => { // get a param from the url const id = params.id; // getting data from the url query string const limit = query.limit; return { props: { id, limit } }; }; export default function SomePage() { let { id, limit } = useLoaderData(); return ( <div> <h1>The params is: {id}</h1> <h1>The limit url query is: {limit}</h1> </div> ); } With SvelteKit, you define a function called load in a separately designated script block. Just like the previous examples, you can handle any API calls and data preparation, then return the data to be used as props to the page component: <script context="module"> // Load function to define data export function load({ page }) { // get params from url const id = page.params.id // get data from url query const limit = page.query.get("limit") return { props: { id, limit } }; } </script> <script> // normal client side javascript block export let id; export let limit </script> <div> <h1>The params is: {id}</h1> <h1>The limit url query is: {limit}</h1> </div> Pre-rendering pages as static site generators is probably the biggest diversion in feature sets. At the time of writing, Remix does not support pre-rendering of pages, while Next.js and SvelteKit do, meaning you can also use them as static site generators. Next.js If you prefer that your page is pre-rendered, simply export getStaticProps instead of getServerSideProps. Otherwise, we’ll observe the same pattern as before. SvelteKit If you want a page to be pre-rendered in the module script blog, just set the following code: export const prerender = true; The code above will tell SvelteKit to pre-render the page instead of rendering it on each request. While we can handle logic on the server side with the loader, getServerSideProps, or the load function, API keys and other data shouldn’t be in this code. You may still need dedicated API URLs with code that is only visible and run on the server side. Next.js If you create a route that exports a route function like in Express.js within the pages/api folder, it will be treated similarly to an API route: export default function handler(req, res) { res.status(200).json({ id: req.params.id }); } If you have a JavaScript or TypeScript file instead of a Svelte file, export a function, and it will be treated as an API route. The name of the function will determine what method it is a response to: export async function get({ params }) { return { body: { id: params.id }, }; } When it comes to styling, the both frameworks can differ quite a lot. Next.js You can use the helmet component to add link tags as well, but you can also use styled-components, JSS, Emotion, Sass, or any other CSS abstraction along with just importing standard CSS style sheets. SvelteKit Svelte, like Vue, uses single-file components, so the CSS is in the components file.
https://tkssharma.com/different-server-side-rendering-frameworks/
CC-MAIN-2022-40
refinedweb
1,321
64.71
In this post, we will see How To Convert Python Dictionary To JSON Tutorial With Example. In this example, we specifically go for Convert Python Dictionary To JSON. You can check out the Parse JSON in Python for general purpose. The json.dumps() converts the dictionary to str object, not the json(dictionary) object! so you have to load your string into a dict to use it by using the json.loads() method. JSON (JavaScript Object Notation) is the popular data format used for presenting the structured data. It’s prevalent practice to transmit and receive data between the server and web application in JSON format. Convert Python Dictionary To JSON If we want to work with JSON (string, or file containing the JSON object), you can use the Python’s json module. You need to import a module before you can use it. import json The json module makes it easy to parse the JSON strings and files containing the JSON object. Now, you can convert a dictionary to JSON string using the json.dumps() method. The process of encoding the JSON is usually called the serialization. That term refers to the transformation of data into the series of bytes (hence serial) to be stored or transmitted across the network. You may also hear the term marshaling, but that’s the whole other discussion. Naturally, deserialization is a reciprocal process of decoding data that has been stored or delivered in the JSON standard. See the following example. # app.py import json appDict = { 'name': 'messenger', 'playstore': True, 'company': 'Facebook', 'price': 100 } app_json = json.dumps(appDict) print(app_json) So, we have defined one dictionary and then convert that dictionary to JSON using json.dumps() method. The output is following. If you want to sort the keys, use the sort_keys as the second argument to json_dumps(). See the following example. # app.py import json personDict = { 'bill': 'tech', 'federer': 'tennis', 'ronaldo': 'football', 'woods': 'golf', 'ali': 'boxing' } app_json = json.dumps(personDict, sort_keys=True) print(app_json) The output is following. The json.dumps() returns the JSON string representation of the python dict. Writing JSON to a file If we want to write JSON to a file in Python, we can use json.dump() method. See the following code. # app.py import json personDict = { 'bill': 'tech', 'federer': 'tennis', 'ronaldo': 'football', 'woods': 'golf', 'ali': 'boxing' } with open('person.txt', 'w') as json_file: json.dump(personDict, json_file) In the above program, we have opened the file named person.txt in writing mode using ‘w.’ If a file doesn’t already exist, it will be created. Then, json_dump() transforms the personDict to the JSON string which will be saved in the person.txt file. When you run the above code, the person.txt file is created, and the json string inside that file is written. Finally, How To Convert Python Dictionary To JSON Tutorial With Example is over.
https://appdividend.com/2019/04/15/how-to-convert-python-dictionary-to-json-tutorial-with-example/
CC-MAIN-2019-18
refinedweb
479
66.84
I'm trying to wrap my head around why so many developers down PHP development like it is a second class language? Secondly, what are the better alternatives for web development? I'm trying to wrap my head around why so many developers down PHP development like it is a second class language? Secondly, what are the better alternatives for web development? Dakota Lewallen - Jess Lee (she/her) - Nick Taylor (he/him) - Dave Jacoby - Discussion Python is just a toy language. Ruby is just for small scripts and not big applications. Java is verbose and overengineers simple things... I could go on and on for any X language that has had mainstream following for the last few decades. People love to hate what's popular. If PHP 8 adds a solve_world_hunger()function, people will still hate it because why not. EDIT: For those not familiar, the quote is from the creator of C++: Bjarne Stroustrup. Ain't that neat? :D Just yesterday, these two tweets got me soooo pumped to be working with Ruby on Rails The future is bright and Ruby is every bit the small script language it always was. I'll be the first to say that Ruby is a weird language to have become such a staple for sprawling apps. But it's about so much more than the code. It's the ecosystems that spring up around it. No programming language is great or bad in and of itself. Nothing exists in a bubble. True. Being one of the people who did a good amount of PHP and still maintain existing projects (in my case, a couple of WordPress add-ons and a few websites), I think I can explain it: When PHP arrived, it was grown into "a better Perl" for web developers. The first PHP versions were based on Perl and its syntax still reminds us of the time. That was before "web development" was a major thing - everyone wrote guestbooks and visitor counters, almost nobody wrote anything else. However, being one of few languages for that niche (that was long before some doofus thought that running JavaScript on a server would be a brilliant idea), it exploded - it transformed into a "business language for beginners" in an astoundingly short time. More and more features were packed into a "beginner-friendly" syntax, which, in turn, made more beginners (including me) choose PHP as their web language of choice. To please as many people as possible, abstractions were added, leading to incompatible varieties of the same feature. PHP 7 has, in fact, reduced the number of "official" MySQL bindings from 3 to 2 ( mysqliand PDO) - which are still incompatible with each other. [But they improved the overall performance of the interpreter by a couple of magnitudes which is nice. Back to the topic!] PHP itself is not a "bad language". PHP is forgiving though - it lets you mix HTML with PHP in the same file (similar to what ASP does), it is not strongly typed and you need to enforce strict syntax warnings if you want to have better code. At least two generations of beginners (the same people who probably would choose Python today) started their "career" with PHP code - that implicitly leads to a huge amount of bad PHP code available online, written by people who don't know better. In my opinion, most people who talk badly about PHP should look into their own JavaScript projects. As if that would be a better language... :-) It depends. Generally, PHP is fine because (almost) every cheap web hoster lets you use it. If you absolutely want to avoid PHP because you are afraid of being beaten on the streets for that, here are my suggestions, based on personal experiences: I hope that inspires you a bit. PHP's a language people love to hate. It's messy, it's clunky, the standard library uses inconsistent nomenclature, it lends itself to a multitude of sins particularly in larger application architectures. It is often not taken seriously as a language, mostly for bad reasons, but the faults it does have do tend to make people who have used both PHP and other languages prefer those other languages to it (I among this number). As with other things people love to hate its objective badness is often performatively overplayed. Eventually this becomes part of the legend, as it were, and people with no hands-on experience begin to immediately dismiss what worth it does have and what it's possible to accomplish with it. I hear PHP 7 fixed a lot of the real problems with previous versions, which is great, but I am also sure that this will do little short- and medium-term to stem the tide of PHP hate. Modern web development is pick-your-poison. There's lots of interesting stuff happening with Node.js right now, to the point that the scene has become quite fragmented, but that process seems to be approaching stability as communities coalesce around a few major web and frontend frameworks. Ruby is also a substantial presence thanks to Rails' popularity, Elm is a thing, and there are of course still popular web frameworks in other languages like Python and Elixir. More server-centric web applications may still use a .Net or Java stack. I get everything you say! I've made those same observations. I do like your point in which you said people who haven't even coded in it already dismiss it. NodeJs is the new nice and shiny everyone is falling in love with. But ES5 currently doesn't even support classical OOP. So if the argument is that a language is fundamentally bad because it has faults, then why aren't languages like Javascript and NodeJS being looked at in the same light? Because they certainly do have their issues. Proven by the point that we needed to create Typescript. I hate to break it to you, but many of us consider this a feature, not a bug. If you value Composition over Inheritance then Javascript is for you. In any case I don't think it is fair to consider this a "fault", and many people (myself included) think that introducing classin ES5 was a big mistake. This isn't to open a flame war about OOP vs. Functional programming. Just that if your language is good at functional programming, you should double down on that, rather than adding functionality for OOP-driven developers who don't understand why Javascript is a powerful functional language, and how to leverage that. So you get people using classical inheritance patterns in a language that's meant for prototypal inheritance. The thing with Javascript is, you have no real choice about using it on the front end. I think a lot of the server-side momentum is driven by this fact. The thinking being that a dev can leverage the knowledge that already have for the server side too. I consider Javascript far worse than PHP (and I don't care for PHP that much after writing a lot of things in it). But that does not alter my lack of choice about whether to use Javascript. If I were coming at this thing fresh, I would be tempted to try to use the same non-optional language across the board too. Many people don't take JavaScript seriously either thanks to its checkered history and common usage on the frontend. PHP is just lower on the totem pole. For what it's worth, I consider prototypal inheritance and a lack of type safety reasons for using JavaScript. If I wanted classical OOP and static types, I'd use a language built around classical OOP and static types. Interesting. What scenario would you say a developer might want a prototype model over plain-old OOP? Many! Composability is a really powerful technique with a host of applications, and it's much, much easier to accomplish with a prototypal model than it is with classic object orientation. For a concrete example, I maintain a data access library which introspects a database to build an API over it. A database contains tables, views, functions, and schemas. Tables can be read and written; views can be read; functions can be executed; schemas act as namespaces and contain objects of the other three types. The first three object types have certain attributes in common: a name, a schema they belong to, et cetera. A classic OO approach would be to create an Entityclass which centralizes the common attributes, and have each of Table, View, and Functioninherit Entity. A method may act on any "real" database object (omitting schemas, which just contain things) as long as it takes an Entityand either only references Entityproperties and methods or performs the appropriate checks and casts. Then you get into the "building an API" stage. The goal is to return a Databasetree that lets you issue a statement like db.things.stuff.find(), where thingsis a schema and stuffa table, determining the query target by navigating the tree. This isn't so hard: simply ensure that you create namespaces and attach Entitiesat the appropriate path. However: the default schema is unnamespaced, so what happens when it also contains a table named things? What do you do now? Classic OOP has no easy answer. Do you create classes for TableWhichIsAlsoASchemaand TableWhichIsAlsoAFunctionand all the other possible collisions? Do you cross-contaminate your three base classes and gate alternative logic behind introspection checks? Good luck! With prototypal inheritance, resolving these collisions isn't just possible, it's easy: just keep applying prototypes as they come in! If you already have a Tableat a path which turns out to resolve to a schema as well, you can just hang the new stuff on the existing object. The only collisions that can't be resolved are due to (small-f) functions being overridden or becoming ambiguous, not due to simple pathing. Because it is, for many reasons (most of them I blame on the community): There are many reasons to not make it your first language: With a 7 year experience on it (and I loved it for many years), after I have exit my bubble where PHP was everything I realized that it deserves to be a second class language and it doesn't worth to be added to a professional career skillset. All of your points seemed to fit within the mold of what everyone else says bad about PHP. But I have not seen the statistics to prove the claims. Most people say it would be dead language as you made the same claim. How is it then, that it powers 88% of the web according to w3techs.com? w3techs.com/technologies/details/p... In benchmark tests I agree it is slow. There are plenty of resources out there to prove that. However, I have been on many projects, where PHP out performed Java applications they had running in the same house. My own personal experience has been that If you build PHP correctly, you can get 15ms response times. Java out of the box gives me 100ms response times running none of my code. There is not a direct correlation between "powering the net" (which can be said about bash and linux too) and how good PHP is as a language, the quality of the code and the number of jobs or its performance. One guy that does not know PHP can take care of 100 WordPress and joomla websites with no sweats. You can read the search for other statistics: most open positions, best payed positions, best cloud language, language popularity in 2018 and so on .. well it doesnt have to be sudden death. but when golang and alike will become simple enough for entry-level devs to comprehend and amount of tutorials on how to launch your blog in go will grow, php will die away. along with RoR. and Python&Flask. Some mentioned that you can run php on a hosting. Its 2018 and spinning up few containers with stack of your choice was never easier, so this argument doesnt hold anymore. also, looking at focus and rate of new libraries appearing for php, I predict it would miss next big thing with all these stream processing microservice setups. This. So many times this. One can think whatever comes to mind about PHP, but this bubble thing is especially hard to oversee. I started my career with other languages than PHP. Basically I started with (Visual)Basic. Some C(++) during school(s). Started "real" programming with Delphi. From there the journey continued to some VB .NET and finally C# professionally. For the web gigs involved I really enjoyed RoR for big projects and Django to some Degree. Even ASP.NET for corporate work is on the list. ASP.NET Core just feels like getting most of the rings right for now. But it mostly depends on the context of the project what the right choice of tool/framework is. Tried Phoenix (Elixir) for some toy project recently. FP is hard to grok if you come from OOP oriented school of thought, but the concepts and ideas make sense in a lot of places. Due unforeseen circumstances PHP is currently part of my day to day work. And what should I say? I hate it. I always hated it and will probably always hat it. Maybe you can write clean code with PHP. It is still dominant across the web. Unfortunately people still start new projects in PHP. But does that mean it does anything really well? It feels just mediocre every time you touch it. Eerytime. In any single place. Anyway, I try to keep my mind open and try to find and accept the good parts of PHP. But the most annoying thing is the ignorance of the people that live exclusively in their PHP bubble. They never saw anything else, but think PHP solves every problem the right way and try to convince you, that you are wrong criticizing things created by and in PHP. Don't get me wrong. I'm not generalizing all PHP folks. But I never experienced this bubble mindset in any other ecosystem as much as in the PHP bubble. I can just propose everybody to look left and right and learn new ideas and concepts. Even if you're profession is and will stay PHP. But my bet is that if more people would do that, PHP would certainly loose it's dominance. Dominance of ignorance as I'd like to call it. Here are just a handful of reasons why PHP is generally regarded as a badly designed language: Needless to say, PHP has its own advantages which makes it very easy to get a simple webpage up and running with little hassle - it mixes with HTML very well and its dynamic weak typing system doesn't "get in the way" unlike, say, Java (at least from the eyes of a total beginner). However, as one digs deeper into PHP, one will begin to find numerous inconsistencies in every aspect of the language - the inconsistent naming system of built-in PHP functions (e.g. the inverse function of htmlentities()is html_entity_decode()); the inconsistent naming conventions employed between different built-in PHP classes (e.g. classes related to reflection using camelCasefor method names while those in the mysqliclass using snake_casefor method names) ... In simple use cases such as a personal webpage, such inconsistencies rarely cause an inconvenience but when you start building larger projects such as a corporate website, such inconsistencies start to become obvious which reduces the productivity of the programmer and makes unexpected bugs more likely (unless you already know PHP inside out). What IDE are you using that doesn't autocomplete htm* ??? Similar problem exists when a library for one task was written by a camelcase fan and another by a snake case fan but I need to use both in 1 script. But it's not a problem when the IDE can autocomplete. Autocomplete may help you write code faster and reduce the burden of memorizing method names (for example) but it still doesn't change the fact that other developers will probably require slightly more effort reviewing/understanding your code just because there is a random mix of camelCaseand snake_case. The most likely person to review my php code is someone who also knows php. And if I'm using a library whose author preferred camel case along with another library whose author preferred snake case, the problem still exists independent of PHP's inconsistencies. So that being said. If you decide to open a business doing some type of software development. What is your choice? Probably Python or C#. Depending on the type of software I intend to develop, C++ (or even C) is not out of the question either. Or I could just stick with JavaScript (it's got its own problems as well but at least has a wider range of applications than PHP) :p some of it is not valid anymore, but gives you perspective, from where and from which mindset php is coming. And even though latest version might report another performance boost, and opcache became usable in cli commands (basically any non-web background processes) there is no php webserver - it relies on nginx, so no gRPC server, for example. As well as almost nothing from background processing or reactive/async patterns are available (kafka connectivity for example). PHP is still fine for Drupal/Wordpress, but if you are starting your own project, its very likely that sooner or later you would need something more than templating engine (which php at its core essentially is))), and here you will be dissapointed by what this platform can bring to the table. As alternatives for web-based projects I would name Ruby + Rails or Python and Flask, if you want to start fast, and virtually any all-purpose stack, if you are fine with learning it first (its extremely simple to start with ror or python, but this should not make you think its easy to handle complicated design descisions) The first two lines of the blog told me everything I need to know about writer... "I’m cranky. I complain about a lot of things." This hardly seems like an unbiased approach to reviewing a language. Your main point about it relying on a web server. I think most languages do and don't come bundled with one. Java (a very popular web language) relies on an external web server as well. its a pity that first two lines draw you away from a darn good writeup. anyway, my point was more about php not being able to run its own production-grade webserver, rather than having or not having built-in one per se PHP was my primary (bread-winning) language for a long time. I think a large part of it comes from the quality of a lot of the PHP code out there. Also the ease-of entry means there are a lot of people writing code that is not very good, and so it perpetuates the notion. However, you CAN write good PHP code. There are a lot of good developers writing a lot of good PHP applications. Still, there are probably many more developers out there writing bad PHP, so this reputation will probably carry on for a long time yet. If performance is not a big concern, then PHP is a half-decent language these days. The only reason to really dislike the language itself would be just the sheer amount of bad code out there that exists and is being written (for whatever reasons, popularity, ease-of-entry, or the platforms/CMSs written in it... who knows?). Elixir is my default language for web stuff these days unless I have a really good reason to not choose it. Go interests me and I have friends who love it. I think it would be great in some cases. People writing bad code is hardly a reason to hate a language. If that were the case, than by default we would be forced to hate all languages. It is something deeper than that I feel like. Maybe it's the fact that Devs, seem to overall, dislike and will look down on people who are just getting into coding? PHP is such an easy language to pick up so that's were a bunch of us start in web development. And maybe it also has to do with peer pressure somewhat? As if you tell another dev you are coding in PHP, you will automatically be looked down on. Yet we discount the fact that 80% of websites are powered on PHP. We somehow discount the fact that PHP has seen the tool to generate the most income out of any other language in the world. I don't really think most devs dislike beginners, but I could be wrong. I honestly just think it's an outdated (but well-earned) reputation from when PHP was a messy procedural language being reinforced by all the bad code in the wild. And also it's "cool" to hate on PHP. Many devs seem to dislike non English speakers, including a lot of php devs. As long as php is used heavily by the rest of the world, even after their code quality improves, people will hate on them and their chosen language. I see this argument in most threads when PHP is discussed. IMO you can switch pretty much any mainstream programming language in PHP's place and this will still hold true. That's true, but I am certain that PHP destroys all the others in ratio and just plain ole massive volume. They say PHP is behind 80% of the web and that scares me... and I like PHP. I think one of the reasons why Elixir is not more popular is its lack of support by popular Paas offers on cloud services. Lobby to fix that and you have a bigger community instantly :D For example Elixir is not present in the list of default languages for Heroku - heroku.com/languages - (yes, you can use custom buildpacks but you don't have the company support) nor in Elastic Beanstalk's - aws.amazon.com/elasticbeanstalk/faqs/ - nor in Google App Engine's - cloud.google.com/appengine/kb/ - nor in Azure App Service - docs.microsoft.com/en-us/azure/app... None of this has anything to do with the language, just needs a little support by the major vendors... You can write good, well-designed code in any language. Working in a good, well-designed, PHP codebase is probably as pleasant an experience as working in a good codebase in Javascript, Ruby, or Python. I would rather write in a good PHP codebase than in a bad Javascript, Ruby, or Python codebase. However I believe: For these reasons, I would strongly recommend against PHP for new programmers and new projects. I'll provide a couple concrete examples of how I have experienced this: a) Testing with mocks is difficult because you can't monkey-patch in PHP. I've had a lot of difficulty writing unit tests for PHP code that wasn't designed with unit testing in mind. In order to write a good unit test, you need to mock out your database calls, but that can be really tricky if you are calling methods that were not designed to injecting mocks them easy. In Javascript, this is not as much of a problem because you can literally monkey-patch anything. Here's an example: The "monkey patching it with a mock that when called replaces itself with a different mock" is kind of ugly, but it works and you can do it much more cleanly with a library like "sinon.js" -- an incredible library. In PHP, trying to monkey patch like this just fails. If you do something like and then call $database->query, it will still just end up invoking the original definition. There's a PHP library called "mockery" that can get you a little further than this, and gives you tools to inject your mocks in certain cases. But it's complicated. Mocking static methods gets especially hairy, and mocking final methods is nigh impossible. Overall you just really, really have to fight for it. b) Another example of how PHP actively leads the user into writing bad code is superglobals. If you want information about the HTTP request you are currently serving, PHP's default way of exposing this information to you is through the $_REQUEST superglobal. As experienced programmers know, global variables are a code smell, and they rapidly lead to unmaintainable code. In a healthy codebase, you should encapsulate the superglobals, access them only in one place, define some sort of wrapper object around them to control access to HTTP request data, and pass such objects as arguments to the functions/methods that need to access/operate on http request data. It's possible to do this sort of thing in PHP, but the language makes it difficult. The language itself is basically actively encouraging you to do the wrong thing and use these superglobals everywhere. Node.js does the right thing here. You instantiate the HTTP server yourself and you create handlers for HTTP requests that take HTTP requests object in as parameters. No global variables necessary. These are just two examples -- I could go on and on and write more, but I believe they speak to a general theme. It's possible to write good PHP -- if you know what you're doing and have a good design sense. But PHP the language and PHP the ecosystem is going to be fighting you every step of the way. Haven't posted here for a while, but obviously topic close to my heart, so here goes. Languages and frameworks are like religions - in the end they all do the same thing, yet the language one person uses is absolute single one everyone else should use, and every other option is bad, dying, dead, etc. As with any language, if things get tough, you find a solution. Maybe different algorithm works better for given problem? Maybe you need to change server setup a little bit? While these discussions still add to generic self doubt and impostor syndrome, I wouldn't pay too much attention on what other developers say, especially the ones that admit they don't use the current version of the language - they have their own reasons to prove that they do not need to use PHP, and that has nothing to do with you or your projects. However, the problem rises when non-technical people start to request language or framework changes purely based on trends or articles on tech blogs that are close to click-bitey. But as long as you keep your clients happy, no matter what tech you build your projects on, that's the only thing you need to worry about, IMHO. I guess what people do mean, when they arge about the language, if more about quality of stdlib, community, high-level concepts available in language - lambdas, pattern matching, type system, that allows you to expeess solution better (it is to some extent a matter of taste, and preferences of your team) Let me start with a blatant opinion: I'd rather use PHP than pre- awaitNode for writing a web application, because callback-oriented development is stupid. Node only became worth using when they added async- await, and even with that you end up having to write wrappers for outdated parts of the standard library just to write straightforward code. JavaScript just isn't that good of a programming language anyway. Now with that out of the way, PHP has two big problems: It's inconsistent. Like, blatantly inconsistent, for no obvious reason. Some functions have prefixes like array_map($arr, $fn), some of them don't like sort($arr), some of them are not actually functions like empty($arr), and PHP has method call syntax, but doesn't use it for any of the array stuff. And parts of the standard library use CamelCase, while others use snake_case. The classes stdClassand DateTimeare both in the standard library, too, just in case you were wondering what type of case class names should use. It has built-in affordances that are unusable in large, well-tested codebases. Superglobals, for example, make any functions that use them much harder to test, and php.ini is just one more piece of the environment that can affect whether a piece of code works right or not. And when PHP starts writing warning messages to the browser that get interleaved with the rest of your HTML, stuff can get really, really broken, so you have to turn that off, too, in production. PHP is the only language where I have seen development practices that are mind blowingly awful. I fully understand that you can write bad code in any language, but for some reason PHP devs manage to top any expectation of bad code one could have. Let me give you 3 examples. The switchstatement (or equivalent) is available in many languages. It is fine to use. The paradigm is that you switch on a variable and each case is a constant. There are two languages I am aware of that do not enforce that constraint. javascript and PHP. There is only one language I have seen this constraint ignored. PHP. In multiple places in the code they used switch(true)and the casestatements called functions. This was a well known company. Using comments as code. I was trying to use a CMS developed in house (different company to the one above, not well known) and I was trying to figure out how to change which the main page was. I had to change part of a comment. I realise this isn't a default part of the language, so I guess the dev must have felt really proud of themselves. Drupal 7 breaks PHP's raison d'etre. In my opinion PHP is a templating language for HTML. That's the best you can hope for it. Drupal 7 (maybe 8 is better, I don't know, I ran from PHP after this) is clunky, slow and confusing. But on top of that we had installed three themes, two were deactivated. Yet somehow a deactivated theme was able to interact with the active theme and break the templating it provided. Amazing. Why would Drupal allow deactivated themes to do that? So, sure, you get bad programmers everywhere, but the frequency and severity which they occur in PHP means I am never going near it again. It is a bad language. As an alternative, I find Django a lot easier to get into and use than Drupal. I think the impact of different syntax/grammar is much much bigger as in natural languages. Or could you easily express the same logic in assembler as in your favourite language. This should be very difficult and take much longer even if you really good in assembler. @okolbay I can get behind discussion on improvements / features of a language, but the OP stated about "downing PHP development like it's a secondhand language". That's not a topic that is built on level-headed reasoning and is something that will not garner fruitful responses either. how comes you say its a fallacy and then immediately admit that languages lack features? ) after few programming languages mastered you can express nearly any solution with any of them, however, its the best tool that makes solution clear for your teammates, easy to maintain and adjust, and not the sole fact of being Turing complete I must admit that my knowledge of PHP might be outdates (I haven't take a look on PHP for years). But if you once really dislike a language you rarely give it a second chance. Maybe that's one of the core reasons for the bad reputation of this language. So, I guess you are most likely right and I'm most likely wrong about the PHP of today. I would like to start by saying that people love to hate. To me it’s almost a fact, anything widely use by people will be criticized, always has been always will be. So even though I’d like to think myself different, there might be a little bit of that in my “hate” of PHP. In truth as long as I’m not forced to do PHP, I do not care what people code with. There are far worst issue existing in our industry today like the lack of professionalism or security concerns in project today… I try to be short about why I’m downing PHP. First : everything written here was true at the time and nothing of significance happens that change the core issue that this article presents : PHP is badly designed. This has the effect that you have to possess deep knowledge of PHP to build solid and maintainable solutions. Not knowing those quirks will put your project in some sort of issues at some point. Second : there are better options everywhere .NET platform, Java platform or even Node (which I also dislike) just to talk about major one. Now that one is a bit tricky to explains but I’ll give it a go. PHP has the cheapest cost of hosting that I know, also you do not require a dedicated host to make it run efficiently, to a lot of business out there, this matters most. I understand and respect that, I just also remember that businesses also loved IE6 meaning business is king, it’s not always working in its best interest … So when I say “better”, I am talking about the famous “cost/benefits” ratio from a technical and business point of view and here what I mean to say : there are no more benefits to PHP than its hosting cost for making websites comparing to its concurrents. On any other aspect, every major web platform does what PHP does while the reverse is often false. What’s worst is that while PHP specialize in web development, it never has the best solution. I am not even going to talk about distributed applications or web services since parallel processing, concurrency or asynchronism are just not what PHP does (no need to go further for me). Third : PHP 6 never got out and nothing on PHP 7 makes HHVM and Hack obsolete in fact, I often wonder why PHP 7 at all ?? Many reasons for PHP 6 failure, some technical other not but assure you it was not the skills of the people involved those people are seriously good developers. What matters to me, though is : that there was technical reasons. Check them out... Fourth : PHP does not scale and no amount of good practices can change that. Try writing a website in assembly with good practices For that one the Facebook example shows it best I think. They are not happy at all with PHP. Just to get certain things out of the way : All that being said I am against all bogus and dumb statement like « PHP is not a programming languages » or « PHP developers are not real developers ». You can write software in PHP and it works (Wordpress, Slack …) but all platforms are not equivalent, that’s just false IMHO, ** that’s why I’m downing PHP development** On the better alternative depends what you’re up to ? SPA or not ? There are a lot of people that explains why so I am not going to repeat it again. However, if you are just doing PHP on a low scale or have an API on low scaled PHP could be an amazing tool. On a large scale website/API, PHP might be hard to manage. In addition, a lot of popular CMS/frameworks written in PHP they focus more on having nice tools and performance is not the main priority. PHP is great for web development; however, if you are trying to do any type of heavy back-end process PHP might not be the best option for it. I would not recommend NodeJS either for other reason than I am not going to get today. If you need to do any type of heavy processing, I will recommend Go, Scala or Java. To be clear php 7 is pretty good, but here’s some reasons why php is used to be hated It’s poor support for OOP paradigm , wierd syntax also some build-in functions had unexpected behavior in some cases. Common Lisp is especially awesome for beginners. (It is not clear whether the OP is a beginner at all, by the way.) They don't need to adjust because every language is unusual to them. :) You might want to read blog.aurynn.com/2015/12/16-contemp... In addition to previous comment I would also point out a few things that everyone hates writing php: I disagree with the assumption that "everyone" would hate that. root. The other points: I agree. @tux0r Imo, don't prefix, don't use hungarian notation. If we get typed properties in PHP 7.4 (or any later version) there's very little ground to cover that isn't typed. Using type hints everywhere with declare(strict_types=1)fixes a lot of these issues. @lucafabbri I like the two different method call notations. Clear separation of calls to static methods and instance methods. Not sure what you're driving here, but if someone can't do OO design then what can i say? If you're talking about global functions like in_array()then i agree. Yes they are bad. But frankly, do they really differ that much from static method calls like Array.map()or Math.max()? Let's say that you are new to PHP and you are bugfixing someone else code. There is a lot of overhead understanding what belongs to global, to user functions and classes. This is not clean. While a class in other languages specifies all namespace in its header, in php you can come to a fall of includes that you need to drive back until you find where the function is. Namespace are actually more clean, easy to debug and extending. Ah, now i see. Yes, this is incredibly bad practice. PSR-4 autoloading with Composer is really the only sensible way to deal with imports. There should only be a couple of script files in a project that are not classes. Maybe some bootstrapping script if vendor/autoload.php doesn't cut it and a front controller. Most frameworks also ship some sort of console script to run different commands. That should be enough. There should be no need for require()s or include()s in other parts of the application. There is also type hinting available on method boundaries too, if that's an important feature to you. Of course, there's nothing stopping you from using a variable as a function name and then calling it. seriously...? I was thinking the same thing. I heard many JS devs saying the same thing. I'm not sure if you're replying because you think it's a weak argument against PHP or if it's because you're incredulous that you need such things. it's a weak argument against PHP Just make the some project in PHP, in C#, Java and Node.JS and let us know Let you know what? Have you also switched sometimes to PHP too? ;) Maybe it differs more then you thought... I'm one of the PHP haters :) This post is able to express the problems I see with PHP much better than I can: eev.ee/blog/2012/04/09/php-a-fract... Yeah this one was shared already. My response was basically the beginning states that the author is “cranky.” Which lended itself to mean this blog post is basically bias. In order to make an argument, you have to remain unbiased. After all the comments to this question, I still don’t have a clear answer other than people just don’t like it. And there are many reasons they don’t like it. Maybe it's the oppression complex? I kid, somewhat, but this is really a loaded/quora question. It seems like it just has a bad rep because it does. Devs are seeming to find their own reasons to fill the gap on why. None of which have any compelling reason behind them. I think what I've learned from the response here is that PHP is not inherently bad. One great leader I've met asked me once, "...well how much money has PHP made over the years as a whole?". He went on to explain "...that's its true value." That will be the way I look at it. As a business tool. Not a dev tool. Sadly, is just a meme that became a popular opinion and the arguments for it are so bad that applies to every language. that's why Spanish is the second ( or even the first ) spoken language, while German is the first hated :) Facebook was written in PHP Because PHP has no focus. It doesn't excel in any aspect of a programming language. It's not the fastest, the safest, the more consistent, the easier to learn, the more expressive, the more syntactic sugary, the most concise, the more human, the less human, the more concurrent. It's just there. When someone programs in PHP, it's almost like "I started with it when I was beggining and well, I still code on it and that's all". You simply don't have any good reason to pick PHP from languages that we have available on the present. PS: I don't wanna offend anyone tho, just wanna answer the question. I guess PHP focus is in the frameworks. There are a lot very easily frameworks that solve so many things in PHP than in other languages is not as standardized and/or easy to use.
https://practicaldev-herokuapp-com.global.ssl.fastly.net/joshualjohnson/whats-the-deal-with-downing-php-development-2bjf
CC-MAIN-2020-45
refinedweb
7,066
70.73
Let P be a finite set of points in an om-space. If the distances between different pairs of points in P are of different orders of magnitude, then the om-space imposes a unique tree-like hierarchical structure on P. The points will naturally fall into clusters, each cluster C being a collection of points all of which are much closer to one another than to any point in P outside C. The collection of all the clusters over P forms a strict tree under the subset relation. Moreover, the structure of this tree and the comparative sizes of different clusters in the tree captures all of the order-of-magnitude relations between any pair of points in P. The tree of clusters is thus a very powerful data structure for reasoning about points in an om-space, and it is, indeed, the central data structure for the algorithms we will develop in this paper. In this section, we give a formal definition of cluster trees and prove some basic results as foundations for our algorithms. Definition 2: Let P be a finite set of points in an om-space. A non-empty subset C subset P is called a cluster of P if for every x,y in C, z in P-C, od(x,y) << od(x,z). If C is a cluster, the diameter of C, denoted ``odiam(C)'', is the maximum value of od(x,y) for x,y in C. Note that the set of any single element of P is trivially a cluster of P. The entire set P is likewise a cluster of P. The empty set is by definition not a cluster of P. Lemma 1: If C and D are clusters of P, then either C subset D, D subset C, or C and D are disjoint. Proof: Suppose not. Then let x in C intersect D, y in C-D, z in D-C. Since C is a cluster, od(x,y) << od(x,z). Since D is a cluster, od(x,z) << od(x,y). Thus we have a contradiction. Q.E.D. By virtue of lemma 1, the clusters of a set P form a tree. We now develop a representation of the order of magnitude relations in P by constructing a tree whose nodes correspond to the clusters of P, labelled with an indication of the relative size of each cluster. Definition 3: A cluster tree is a tree T such that For any node N of T, the field ``N.symbols'' gives the set of symbols in the leaves in the subtree of T rooted at N, and the field ``N.label'' gives the integer label on node N. Thus, for example, in Figure 1, n3.label = 3 and n3.symbols = {a,d}; n1.label = 5 and n1.symbols = {a,b,c,d,e,f,g}. As we shall see, the nodes of the tree T represent the clusters of a set of points, and the labels represent the relative sizes of the diameters of the clusters. Definition 4: A valuation over a set of symbols is a function mapping each symbol to a point in an om-space. If T is a cluster tree, a valuation over T is a valuation over T.symbols. If N is any node in T and Z is a valuation over T, we will write Z(N) as an abbreviation for Z(N.symbols). We now define how a cluster tree T expresses the order of magnitude relations over a set of points P. Definition 5: Let T be a cluster tree and let Z be a valuation over T. Let P =Z(T), the set of points in the image of T under Z. We say that Z satisfies T (read Z satisfies or instantiates T) if the following conditions hold: The following algorithm generates an instantiation Z given a cluster tree T: procedure instantiate(in T : cluster tree; O : an om-space) return : array of points indexed on the symbols of T variable G[N] : array of points indexed on the nodes of T; Let k be the number of internal nodes in T; Choose d0 = 0 << d1 << d2 << ... << dk to be k+1 different orders of magnitude; /* Such values can be chosen by virtue of axiom A.7 */ pick a point x in O; G[root of T] := x; instantiate1(T,O, d1 ... dk, G); return the restriction of G to the symbols of T. end instantiate. instantiate1(in N : a node in a cluster tree; O : an om-space; d1 ... d od(xi, xj) = dq; /* Such points can be chosen by virtue of axiom A.8 */ for i = 1 ... p do G[Ci] := xi; instantiate1(Ci, O, d1 ... dk, G); endfor endif end instantiate1. Thus, we begin by picking orders of magnitude corresponding to the values of the labels. We pick an arbitrary point for the root of the tree, and then recurse down the nodes of the tree. For each node N, we place the children at points that all lie separated by the desired diameter of N. The final placement of the leaves is then the desired instantiation. Lemma 2: If T is a cluster tree and O is an om-space, then instantiate(T,O) returns an instantiation of T. The proof is given in the appendix. Moreover, it is clear that any instantiation Z of T can be generated as a possible output of instantiate(T, O). (Given an instantiation Z, just pick G[N] at each stage to be Z of some symbol of N.) Note that, given any valuation Z over a finite set of symbols S, there exists a cluster tree T such that T.symbols = S and Z satisfies T. Such a T is essentially unique up to an isomorphism over the set of labels that preserves the label 0 and the order of labels.
http://cs.nyu.edu/faculty/davise/om-dist/node4.html
CC-MAIN-2016-40
refinedweb
989
71.44
My Inspiration for a Chart class came from the trendet Python package My inspiration from the trendet Python package is to create a general method for a ChartCls class, that conveniently draws a span of vertical lines to highlight up and down trends on a given chart. Read to the end of article for the SPOILER. What is trendet? The trendet Python package comes with an easy trend detection tool. It conveniently plots a chart that highlights both the uptrend regions and downtrend regions, in green color and red color, respectively. Prerequisites - trendet — Python package to detect trends - matplotlib — Python package to plot charts - seaborn — Python package to plot lines Step 1 — Understand the trendet code sample trendet is a Python package to automatically detect trends for any given time series data, e.g. S&P 500. This package has been created to support investpy features when it comes to data retrieval. The full sample code can be found here. The identify_all_trends() function returns a DataFrame consisting of a time series data for a given symbol. df = trendet.identify_all_trends(stock='baba', country='united states', from_date='01/01/2020', to_date='09/07/2020', window_size=5, identify='both') In addition to the OHLC columns, the function returns two columns, i.e. “ Up Trend” and “ Down Trend”, both of type string. For example, the “ Up Trend “ column consists of either NaN or string values, such as “A”, “B”, “C”, etc. Rows that have the same values, e.g. “A”, belong to the same group. Both the “ Up Trend” and “ Down Trend “ columns can consists of multiple groups, where each group consists of the same consecutive value, e.g. “AAAA”. Step 2 — Preparing the data for a chart The matplotlib Python package contains a function axvspan() that draws a span of vertical lines for a range of index, which is typically Date, on the x-axis. The object ax is of type axes, which is a return object from matplotlib, when you create a figure. The for loop gets each unique label from labels, and passes the first argument to axvspan(). df[df['Up Trend'] == label].index[0] The first part before the dot (.) is a subset of the DataFrame, where “ Up Trend” equals label, while the second part after the dot, index[0], returns the Date of the first row of the subset. The second argument to axvspan() is similar to the first argument. df[df['Up Trend'] == label].index[-1] The second part after the dot, index[-1], returns the Date of the last row of the subset. The third and fourth parameters of the function axvspan() are straightforward, alpha of type float is the opacity (0–1), while color of type string is self-explanatory. The variable labels is assigned to a list of unique objects in column “ Up Trend”, e.g. [‘A’, ‘B’, ‘C’, ‘D’, ‘E’] labels = df['Up Trend'].dropna().unique().tolist() for label in labels: sns.lineplot(...) ax.axvspan(df[df['Up Trend'] == label].index[0], df[df['Up Trend'] == label].index[-1], alpha=0.2, color='green') After loop completes for “Up Trend” column, we perform the same function for “Down Trend column. labels = df['Down Trend'].dropna().unique().tolist() for label in labels: sns.lineplot(...) ax.axvspan(df[df['Down Trend'] == label].index[0], df[df['Down Trend'] == label].index[-1], alpha=0.2, color='red') Step 3 — Create method for a ChartCls We want to create a general method MainAddSpan(), for a ChartCls class, as part of a larger collection of methods for plotting time series data on a chart. You can read the article Object-oriented programming for data scientists to learn more about Python classes. We can then conveniently draw a span of vertical lines to highlight up and down trends on a given chart. This method MainAddSpan() takes four arguments, dfTag, lstTag, dblOpacity, strColor. - dfTag is a DataFrame that consists of tags in a time series format, i.e. index is of type Date - lstTag is a list of unique tags - dblOpacity is a double for alpha between 0.0 and 1.0 (Default=’0.2') - strColor is a string for color (Default=’green’) This method does not have a return value, however it draws a span of vertical lines to the chart object of the ChartCls class. def MainAddSpan(self, dfTag, lstTag, dblOpacity=0.2, strColor='green'): df = dfTag axs = self._axsMAIN for s in (lstTag): axs.axvspan(dates.date2num(dfTag[dfTag==s].index[0]), dates.date2num(dfTag[dfTag==s].index[-1]), alpha=dblOpacity, color=strColor) In this example, I create an object ChartCls, and call the method MainAddSpan(). # create ChartCls instance chart = ChartCls(test._dfDbs, intSub=2) # build indicator chart.BuildOscillator(1, test._dfDbs['Dbs'], intUpper=3, intLower=-3, strTitle="Dbs") chart.BuildOscillator(0, test._dfDbs['DbsMa'], intUpper=3.75, intLower=-3.75, strTitle="DbsMa") # get the chart axes ax = chart._axsMAIN # build tag column based on the indicator DbsMa lstTag = test.BuildTag('DbsMa', 3.75) # call the method MainAddSpan() chart.MainAddSpan(df['Tag'], lstTag[lstTag>0], 0.2, 'green') chart.MainAddSpan(df['Tag'], lstTag[lstTag<0], 0.2, 'red') # plot the chart chart.BuildMain(strTitle="SPY") Conclusion In this article, you have explored the trendet Python package. You have understood how draw a span of vertical lines for a range of index, which is typically Date, on the x-axis. This is typically performed to highlight an uptrend or downtrend on the chart, although it can also be used to highlight any region of importance. Further, you have created a general method MainAddSpan() for a ChartCls class, as part of a larger collection of methods for plotting time series data on a chart. This is so that you can conveniently draw a span of vertical lines to highlight up and down trends on a given chart. The DbsMa indicator, in the last chart above, actually predicted the S&P 500 [“SPY”] bear market during February 2020, a few weeks before it crashed. Both the last two regions have been uptrends, during the months of May and July 2020, respectively. The creation of the DbsMa indicator and how I used it is a story for another article. SPOILER From the snapshot above, you can see that both A200 and VAS ETF in my portfolio are up 11.7% and 10.5%, respectively. I started buying shares in the market during May 2020, and that was when the first uptrend region appeared after the crash. Get the Source Code You can download the above source code from GitHub repository trendet. What To Do Next You can further extend the trendet sample code in several meaningful ways: - Identify custom trends of investpy DataFrame. - Identify trends of custom DataFrame. - Reading the trendet’s documentation. PYTHON, R AND METATRADER FOR HAPPI TRADERS FREE $100 CREDIT BUY A COFFEE BE A HAPPI PATREON REACH OUT Dev.to: GitHub: Twitter: YouTube: Originally published at on June 4, 2020.
https://leetradetitan.medium.com/my-inspiration-for-a-chart-class-came-from-the-trendet-python-package-b771c53eb653?source=friends_link&sk=1c148a952a97654416b28b26532dbf7b
CC-MAIN-2021-39
refinedweb
1,152
66.03
You know the deal, you have your fantastic Django application and it’s working great and everything, but you need to make a small change which is too cumbersome to do in the shell, so you figure “duh, I’ll just write a script to do it”. You write your external script in two minutes and then struggle for two hours to figure out how to load the models and the rest of the context so it will work with your app’s settings and all your Django goodness. You visit StackOverflow and a bunch more sites, and they either tell you to use a management command, which is great advice, except your thing is a one-off and you don’t want to have to check it to git and go through all that hassle to get it deployed just to do this simple thing, or they give you some arcane lines that just don’t work. Fear not, for I am here. I will give you five simple lines that will make everything work perfectly. Perfectly, I say! Without further ado (all the previous ado was just so I could fill the paragraph so the side-box doesn’t look weird with short text), I give you the magic commands! Here they are: import os, sys proj_path = "/path/to/my/project/" # This is so Django knows where to find stuff. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") sys.path.append(proj_path) # This is so my local_settings.py gets loaded. os.chdir(proj_path) # This is so models get loaded. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() <your script goes here> I hope this saves you an hour or something. EDIT: My friend Josh points out that this is just wsgi.py, to which I reply “yeah thanks Josh, where were you two hours ago?” Join the conversation!
https://www.stavros.io/posts/standalone-django-scripts-definitive-guide/
CC-MAIN-2017-04
refinedweb
308
69.21
Wiki javarosa / buildxforms XForms Training Materials Learn how to build XForms for JavaRosa Set up your computer to build and test XForms Follow these instructions to install Notepad++, the sun wireless toolkit and the javarosa validator Install Notepad++ For the first JavaRosa Xform training day, we used Notepad++ as the XML text editor. Here we've included the steps for installing it, though any text editor can be used for editing XForms 1. Install [ Notepad++] on your machine 1. Install the XML Tools plugin from the [ Notepad++ download page]. Note that to install you will have to put all of the DLLs from the ext_lib directory in the Notepad++ directory (usually C:\Program Files\Notepad++), then copy the xml tools DLL to the plugins directory (C:\Program Files\Notepad++\plugins). 1. Once everything is installed, start up Notepad++. From the Plugins menu, there should be an option for XML Tools. We have found it useful to tick "Enable XML syntax auto-check" and "Tag auto-close". Also useful is using "Pretty print (XML only - with line breaks)". This will fix all of the indentation of your XML/XForm to make it more readable Install the Sun WTK 1. If you haven't already, install a java runtime. This can either be the JDK or JRE. Chances are you have Java installed already, but if not and you're only planning on making XForms (not recompiling JavaRosa), head over to [ get java]. If you are planning to do core javarosa development, look at the [ Getting Started] for developers. 1. Install the [ Sun Java Wireless Toolkit for CLDC v 2.5.2]. It is recommended to install to the default location of C:\WTK2.5.2 to avoid having to re-map libraries locations. JavaRosa XForm Validator 1. To avoid having instructions in multiple places, please follow the [ JavaRosa XForm Validator] setup instructions to both install and configure the validator software. Reference material on XForms What are XForms? "XForms" is a format for creating forms/questionnaires in XML. XForms are similar to forms in HTML, and are meant to be the next-generation replacement for HTML forms. XForms are much more powerful than HTML forms. An XForm is an XML document that describes your form, including what questions to ask (including the type of question and the question's caption or prompt), restrictions on the kinds of answers you can enter, and what you want your final data to look like. You author your XForm by hand in an XML editor. XForms are read and filled out by an XForms client, which presents the questions to a user and lets them enter answers, much like you use a web browser to fill out HTML forms. The XForms client we have built and use is JavaRosa. XForms is a very complicated specification; JavaRosa only supports a simple subset of XForms, but this subset is getting more powerful all the time. JavaRosa also supports some customizations beyond the original XForms spec, specific to the needs of mobile users. What is XML? XML is a generic mark-up language for adding meaning to text. It is very similar to HTML, but is more generic and has stricter requirements. In fact, XHTML is an XML version of HTML. XML is simply tags that surround text and other tags. The types of the tags used and their hierarchy add meaning to a document. The tags you use can be named anything you want (this is the major different between HTML, which has a set of allowed tag names). A collection of tag names, along with rules about how they can be used and what they mean is called a schema. XForms is an XML schema. XHTML is another schema. In fact, the submitted data of your XForm is also an XML schema, different for every form. XML Basics: - Tags can be self-closing ( <tag />) or come in opening and closing pairs ( <tag></tag>). Standalone tags like in HTML (a <br>that is never closed by a corresponding </br>) are not allowed. - Paired tags can have text or other tags inside them ( <tag>some text <another-tag /></tag>). Which tags can appear inside other tags is determined by the schema. - Tags must be closed in the reverse order they were opened ( <a><b></b></a>) ( <a><b></a></b>is invalid XML) - The entire document must be enclosed within a single tag. This is called the top-level element - Tags can have attributes ( <tag attribute="attribute value" another-) - Certain special characters must be escaped when used in text or attribute values: <must be replaced with <, >with >, and &with & Tags can belong to a namespace, and multiple namespaces can be used within a single XML document. Namespaces let us use multiple XML schemas in a single document without conflicts, as two different schemas may use the same tag name. A namespace is simply an abbreviation (that we choose ourselves in our XML document) that is assigned to a given XML schema. For example, if we declare xf as our namespace for the XForms XML schema, XForms tags will look like <xf:input> and <xf:bind>. An XML document can have one default namespace, for which you don't need to use the namespace prefix in the tags for that schema. Typically, we make XForms our default namespace, as most of the tags in our document are XForms tags. What is JavaRosa? JavaRosa is an XForms client for mobile phones, written in J2ME. JavaRosa is an application platform that programmers can customize to suit different projects. There is no one 'JavaRosa application'. But at the heart of every JavaRosa application is the XForms engine, which is an activity that reads your XForms, presents the questions to a user and lets them enter answers, and saves or sends off the final data for your form. JavaRosa is open source and is developed by members of the OpenRosa consortium around the world, with development teams in Tanzania, Kenya, South Africa, Uganda, Bangladesh, Pakistan, and USA. Anatomy of an XForm The skeleton of an XForm looks like this: <h:html <h:head> <h:title>[form title]</h:title> <model> <instance> [define the schema of your resulting data here] </instance> [define restrictions on your data (such as data types, range constraints, and skip logic) with bindings here] </model> </h:head> <h:body> [add controls that describe your questions here] </h:body> </h:html> The XForms schema is meant to be embedded in some other kind of XML schema, so note how our XForms tags are placed inside a skeleton HTML document. Also note our various namespace declarations at the top of the document, and how XForms is the default namespace. The XHTML namespace is given the prefix h. The namespace for JavaRosa customizations is given the prefix jr. There are three main components to an xform: 1. The '''instance''' The output of a filled-out XForm is itself another XML document. The schema of this XML document is custom to your XForm. You create a skeleton of this XML document and place it inside the <instance> tag. Questions refer to various parts of the instance and place their answers there as they are filled out. When your form is complete, the instance can be saved as a complete, self-contained XML document, and submitted from the phone to remote servers. Since the instance must be a complete XML document on its own, and an XML document must contain one, and only one top-level element, the <instance> element must contain only one child element. Sample instances: <patient xmlns=""> <name /> <sex /> <age /> <symptoms /> </patient> <water-quality-survey <location /> <well-id-number /> <measurements> <ABT /> <CC6 /> <PSM /> </measurements> <comments /> </water-quality-survey> Once filled out, these instances may look like: <patient xmlns=""> <name>DREW ROOS</name> <sex>male</sex> <age>25</age> <symptoms>cough fever rash</symptoms> </patient> <water-quality-survey <location>Mlandizi</location> <well-id-number>45</well-id-number> <measurements> <ABT>0.73</ABT> <CC6>4.32</CC6> <PSM>B</PSM> </measurements> <comments>QUALITY IS GOOD; WATER LEVEL LOW</comments> </water-quality-survey> Note how it's a good idea to make the tag names in your instance as descriptive as possible. Also note that since the top-level tag for your instance is the top-level element of an XML document, it should have an xmlns attribute, even if you leave it blank to start. 2. The '''bindings''' Bindings let us attach restrictions to the type of data that may be entered into into the instance. The restrictions may be: - Data types, for example, indicating that a given question is meant to store dates, so only dates will be allowed as answers to that question. This may also affect how the question appears to the user (see 'controls'). Another kind of data type is restricting answers to numbers only. - Skip logic: only allowing a question to be answered if another question has a certain value (e.g., only asking 'is patient pregnant' if 'sex' is female) - Required: requiring that a question be answered before you can complete the form - Range constraints: limiting the kinds of answers that may be accepted (e.g., rejecting body temperatures over 50 and under 30) Bindings are defined via a <bind> tag. The binding references a single tag in the instance via an XPath expression, and then defines the various restrictions on that question. Every question has it's own binding. Not every question needs a binding, though, such as if it uses the default data type (text) and has no other restrictions. The instance and the bindings together comprise the XForm '''model'''. 3. The '''controls''' The controls define the questions that the user actually sees. Each question presented to the user is its own control, and the user sees the questions in the same order listed in the XForm. A control is either an <input>, <select>, or <select1> tag. <input> is used for free-entry questions, such as text, numbers, and dates; <select1> is used for multiple-choice questions where you can pick only one choice; <select> is used for multiple-choice questions where you can pick many choices. A control must define the following things: - Where in the instance the answer is stored (via an XPath expression) - The caption or prompt of a question - For multiple choice questions, the available choices and their captions Note that most of the properties you associate with a question, such as whether it's required, the data type (text vs. numeric vs. date), and skip logic, are actually defined in the binding. The control and the binding have no direct knowledge about each other. The only thing that links a control and its binding is that they refer to the same destination tag in the instance. What is XPath? XPath is a mini-language for referring to nodes (tags) within an XML document. In XForms, we use XPath to address specific nodes/questions in the instance. The basic format of an XPath path is /a/b/c, where a refers to the top-level element of the XML document (which must be named <a> in this example), b refers to the tag <b> that is an immediate child of <a>, and c refers to the tag <c> which is an immediate child of <b>. To use the sample instance above, /patient/name and /water-quality-survey/measurements/ABT are valid XPath paths. XPath paths come in two varieties: absolute and relative. The paths above, and any path that starts with /, are absolute. This means to start searching for your node at the very top of the XML document. If there is no beginning slash, the path is relative, which means you begin searching from some node (called the 'context node') that varies depending on the context where you're using the path. In most cases in an XForm, the context node of a relative path is simply the top-level element of the instance. This means that we could shorten the paths above to simply name (as /patient is assumed as the context node) and measurements/ABT (where /water-quality-survey is the context node). The only exception is inside a binding when dealing with range constraints and skip logic. Here, the context node is the instance node that the binding refers to. There are two special kinds of relative paths that are useful in this situation: .refers to the context node itself ..refers to the parent tag of the context node We will see more examples of these as we cover constraints and skip logic. There is also the more general concept of an 'XPath expression', in which you can do computations or comparisons on the values of nodes identified by paths. The details of XPath expressions are an advanced topic we won't cover here, but we use XPath expressions to define the conditions for constraints and skip logic, so you will see some examples there. Basic controls As said before, there are three basic XForms controls. Use <input> for free-form questions such as text, number, or date. The format of the control is as follows: <input ref="name"> <label>What is your name?</label> </input> The value of the ref attribute is the path to the instance node where the answer to this question is stored. The content inside the <label> tag is the prompt presented to the user. When the question is answered, the value that gets stored in the XML instance is the literal text or number that was entered, or for dates, the date formatted in XML date format (e.g., 2009-03-02). Use <select> and <select1> for multiple choice questions ( <select> for multi-select and <select1> for single-select). The format for both controls is identical: <select ref="symptoms"> <label>What are your symptoms?</label> <item> <label>Cough</label> <value>cough</value> </item> <item> <label>Rash</label> <value>rash</value> </item> <item> <label>Fever</label> <value>fever</value> </item> <item> <label>Itching and Peeling</label> <value>itch-peel</value> </item> <item> <label>Other</label> <value>other</value> </item> </select> ref and the first <label> are the same as for <input>. The difference is that now we define the choices as well. Each choice is defined in its own <item> tag. An <item> contains both a <label> and a <value>. Like <label> before, this defines the captions that the user will see for this choice. <value> defines an internal code for the choice that will be stored in the XML instance if this choice is selected. As such, it should be human-readable, but short and terse. For a multi-select, the <value>s of all selected choices will be stored in the instance, as a list separated by spaces. Clearly, <value> should not contain spaces! (or much punctuation at all, for that matter). Bindings The format of a binding is: <bind nodeset="name" ... /> The nodeset attribute is just like ref for controls; it says which instance node this binding applies to. In addition to nodeset, the binding will contain one or more attributes to accomplish various goals, which we will now cover. Data types To restrict a question to a certain type, add the attribute type="[datatype]" to the binding, where [datatype] is string for text, int for integers, decimal for numbers with decimal points allowed, and date for dates. string is the default, so you don't need the type parameter for text questions or multiple-choice questions. Required questions To make a question required, add the attribute required="true()" to the binding (note the parenthesis). Skip Logic To make a question conditionally skipped based on the value of another question, we use the relevant attribute. We add this to the binding of the question that is conditionally skipped, not the question whose answer decides whether the other question is skipped. This is an important distinction that is confusing for many. For example, if we have a question A that decides whether questions B, C, and D are skipped, the bindings for B, C, and D will each have a relevant attribute that references the value of A. The value of the relevant attribute is an XPath expression that references the values of previously-answered questions. If this expression evaluates to true, the question will be shown; if it evaluates to false, it will be skipped. Here are some examples. Consider the following instance: <patient> <name /> <age /> <sex /> <pregnant /> <in-school /> </patient> <bind nodeset="pregnant" relevant="/patient/sex = 'f'" /> <bind nodeset="in-school" relevant="/patient/age >= 4 and /patient/age <= 25" /> .... <select1 ref="sex"> <label>Sex of patient</label> <item><label>Male</label><value>m</value></item> <item><label>Female</label><value>f</value></item> </select1> In this example, the 'are you pregnant' question is only asked if the 'sex' question was answered 'female'. The 'are you in school' question is only asked if the patient is between 4 and 25 years old. Important things to note: - The <=and >=comparisons for age had to be escaped into <=and >= - We only use absolute paths inside the relevantattribute; this is because the context node is now whichever node is specified in the nodesetattribute of the <bind>. Using relative paths like sexand agewould no longer give us what we want! - When checking for a certain answer of a multiple-choice question, we compare against the <value>for that choice, as this is what is stored in the instance. Also, we compare it as a string, so we must enclose the literal value ( fin this case) in single quotes. Conditions like these can get quite complicated, so it's best at first to try to adapt from existing examples. If you have any further questions, ask one of the instructors. It is also important to fully test all possibilities when building your form to make sure your condition works as expected. Range Constraints To limit the range of acceptable values for a question, we use the constraint attribute. The value of the attribute is an XPath expression that is evaluated after the question is answered. The expression must evaluate to true for the answer to be accepted. If it evaluates to false, the user will be notified and forced to enter a different answer. In order to be useful, the expression must actually reference the node to which the constraint (and the binding) applies. This is where the . relative path comes in useful, as it always refers to the node that the binding applies to (the node we are constraining). Examples: <bind nodeset="body-temperature" constraint=". > 32 and . < 45" /> <bind nodeset="birth-date" constraint=". <= today()" /> If the value is outside of the allowed ranges, the constraint expression will be false, and the answer will be rejected. By default, the user will receive a generic 'outside of allowed range' alert. You can change this to a custom alert by also adding the jr:constraintMsg parameter. For example: <bind nodeset="birth-date" constraint=". <= today()" jr: Default values and Hidden questions The XML instance is not required to be empty by default. The nodes in the instance may in fact contain data. This data will be used as default values for the questions. Example: <patient> <district>DAR ES SALAAM</district> <name /> <sex /> <age /> <symptoms /> </patient> DAR ES SALAAM will now be used as the default value for the 'district' question, but it may still be changed when the user answers the question. If they enter something different, the new answer will be written back to the instance, overwriting the default. Default data in the instance must be validly formatted for the data type of the associated question. This means that for date questions, the date must be in YYYY-MM-DD format, and for multiple-choice questions, the data must correspond to the <value>s for that question's available choices. In general, the default value must be in the same format you would get if you had entered that value when answering the question itself. Failure to do so may cause your form to crash. It is also possible to have default data in the instance, and no question control that actually references that data. This makes it impossible to change that data when filling out the form. This is how XForms does "hidden" questions (like you can do in HTML forms). This is useful for meta-data like form version – data that should change rarely throughout your deployment and that the user doesn't need to know about. Submission Traditional XForms (and HTML forms) let you describe how and where to submit the form as part of the XForm definition itself. The XForms spec itself supports this, however currently JavaRosa doesn't. In the JavaRosa platform, where, when, and how you submit your completed forms is defined through configuration settings at the application-level, not through any directives in the XForm itself. This will probably change in the future, with us supporting both methods. Sample Forms These forms illustrate the process of building an XForm. It starts with the most basic skeleton form with no questions, and gradually adds more capability with each revision. - Form 1: basic skeleton form with no questions; use this as the template for each form you create - Form 2: add 3 basic questions, including free-entry and multiple-choice - Form 3: add basic bindings and data types - Form 4: add default values - Form 5: add hidden fields - Form 6: add required questions - Form 7: add data constraints - Form 8: add skip logic Updated
https://bitbucket.org/javarosa/javarosa/wiki/buildxforms
CC-MAIN-2018-34
refinedweb
3,582
61.06
22 October 2008 07:36 [Source: ICIS news] By Judith Wang and Dolly Wu SHANGHAI (ICIS news)--The outlook for China’s petrochemical markets in the near future remains gloomy as most industry players have been hit hard by continuously falling prices and stagnant demand in the past few months, analysts and producers said on Wednesday. ?xml:namespace> Conditions may not improve soon as the country looks set to end five years of double-digit growth in 2008 and with slowing global demand unlikely to stem the fall in crude values any time soon, analysts said. “Falling crude oil prices cast a shadow on chemical products,” said industry analyst Yang Wei (in mandarin) with financial services firm Guotai Junan Securities. “We have to wait for demand recover, but who knows when the demand will turn better amid such a bad economic situation?” Yang said. Most petrochemical traders have been tracking crude’s plunge in search of the bottom of the market. Crude prices have lost over 50% of its value since the peak of $147/bbl hit on July 11 this year, and may continue to decline as the looming scenario of a world in recession would definitely curtail demand, analysts said. “It could be a case of the petchem bubble bursting in China as prices rose too much too fast in the first half of the year,” one melamine producer said in Mandarin. Taking its lead from crude prices, linear low density PE film grade prices plummeted about 26% from a month ago to CNY 8,700-10,400/tonne based on pricing data from chemical information service ICIS/Chemease. China, the world largest importer of polyethylene resin, continues to see weekly losses in its domestic markets with prices falling as much as yuan (CNY) 2,000/tonne in a week. Already some chemical companies are being forced to shut down plants, while others continue to cut operating rates given persisting weakness in demand and strong pressures on margins, market sources said. “Many small companies stand on the brink of bankruptcy. I think the chemical industry will need around one year to recover to the level before the financial crisis,” a melamine producer in Tianjin said in Mandarin. “I heard some small chemical plants in Shijiazhuang have shut down their plants. Decreasing prices squeezed their margins as they bought the feedstock prices at the time of high levels, so they can’t balance the cost and profit and they have to shut down to relieve losses,” he added. Even demand for high-value products such as synthetic rubber has been hit, with end-users purchasing power constrained by the credit crunch. Traders in Shandong province said local large tyre-makers operated only at 60-70% and even just at half capacity. Small units have closed down due to poor sales of tyres in light of the global financial crisis. Prices of styrene butadiene rubber (SBR) non-oiled 1502 grade plunged 40% to yuan (CNY) 15,500-16,000/tonne in mid-October from where it was in late July. Butadiene rubber (BR) prices also nosedived by the same magnitude for the period to CNY 15,600-16,200/tonne. Purified terephthalic acid (PTA), a key feedstock for polyester production, plunged 38% from mid-June to CNY 5,800/tonne as downstream polyester plants operated at a low sales-output ratio of only 20-40% due to weak demand from the textile industry. “It is true, it is a tough year for export-oriented textile makers. Many small textile plants have closed in Shaoxing,” a trader in Zhejiang province said with regards to the textile production centre in eastern China. "Export orders to the US and Europe have fallen, it is a very bad year for our company," she added, but declined to provide specifics. The outlook remained bleak, with the majority of analysts and producers expecting a slow recovery which would be demand driven. “At the moment, I am also totally confused for the outlook. We should pin the hope on the demand recovery and the economic rebound in the US and the Europe,” Pei Lijun, an analyst from Industrial Securities said. Global economies have just started to feel the pinch of the financial crisis that originated in the US, with the weakness likely to prevail or even be aggravated in 2009 according to economists. Dolly Wu, Vivien Lu, Vivian Liu and Kino Zhu
http://www.icis.com/Articles/2008/10/22/9165332/china-petchems-struggle-amid-economic-gloom.html
CC-MAIN-2014-52
refinedweb
735
54.56
Table of Contents Record Tab Plugins Record tab plugins are used to control which tabs appear on the record view. They can also be used to store convenience methods for use by the template used to render tab contents. Key Plugin Details Default Namespace: \VuFind\RecordTab Interface: \VuFind\RecordTab\TabInterface Base Class: \VuFind\RecordTab\AbstractBase Service Locator Configuration Section in module.config.php: ['vufind']['plugin_managers']['recordtab'] Service Manager Name for Service Locator: VuFind\RecordTabPluginManager (VuFind 2.x-4.x), VuFind\RecordTab\PluginManager (VuFind 5.0+) Template Name: VuFind loads tab templates from the subdirectory of the RecordTab folder of the current theme whose name corresponds with the lowercased class of the plugin (ignoring the namespace). For example, the template for \VuFind\RecordTab\TOC can be found in RecordTab/toc.phtml within your theme. Template Context: Templates are rendered with $this→tab set to the controlling tab object and $this→driver set to the associated record driver. Both of these objects may be used to pull data needed for rendering. See the General Plugin Information page for more details on VuFind plugins. Notes - Since VuFind 6.0, record tabs are loaded based on configurations found in the RecordTabs.ini configuration file. In prior releases, record tabs were loaded based on a mapping found in the ['vufind']['recorddriver_tabs'] section of module.config.php. See the comments in the appropriate file for more details.
https://vufind.org/wiki/development:plugins:record_tabs
CC-MAIN-2020-45
refinedweb
231
50.02
This concludes the test drive for the api. I needed to make some final adjustments. The purpose of this session was to navigate to the last page and store all users articles. And while this work was easy I started realizing how broken my filtering for new articles was. The returned articles are in order of publication, I knew this, the implications is that article ID has no guaranteed order. This is why I included the date pulled, I had just thought I found a shortcut. The unpublished articles create their own set of challenges. These articles are more likely to be changing and Dev provides a different slug than what the published article will be. At this point I'm not solving this problem. Implications - unpublished articles are always written - an unpublished article which gets published will result in a new article file One of the more challenging parts of this was keeping the isNewerArticle function pure and nothrow. It would have been easy to just perform the string conversion on the spot, but since I marked the method nothrow this action was denied. Remember the original statement I said was my code wasn't better for adding attributes. Well now I am paying for it and I think it is for the better. Placing the conversation in the isNewerArticlefunction causes a delay in reporting an issue. I'm now required to validate and setup my data before beginning to process it. auto data = res.readJson().get!(Json[]); data.each!(x => x["published_timestamp"] = x["published_timestamp"].get!string.empty ? SysTime.init.toISOExtString : x["published_timestamp"].get!string); When writing the unittests for the range got a little bit out of hand. See nested functions actually come out as delegates, so I created an alias to a lambda so the compiler can determine context does not require a delegate. But like most writings, I had forgotten static nested functions aren't delegates. alias fakeArticles = (uint page) @safe { return () @trusted { static iteration = 0; if(iteration++ < 2) return generate!fakeArticleMe .map!(x => cast(immutable(ArticleMe))x.deserializeJson!(ArticleMe)) .take(3) .array; return generate!fakeArticleMe .map!(x => cast(immutable(ArticleMe))x.deserializeJson!(ArticleMe)) .take(0) .array; }(); }; I also used some unsafe calls so I wrapped the body in a trusted lambda. I've included a readme now that a have a reasonably usable application for pulling articles. I've also registered with D's code registry. My unittests still don't cover the unpublished articles. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/jessekphillips/hobby-project-pull-all-your-dev-to-articles-3kg2
CC-MAIN-2021-10
refinedweb
412
56.96
Writing code any other way, once you've embraced the Redux-Saga way of implementing asynchronous operations, is difficult. Everything starts looking like a saga. You add a feature, and another, and another... and, soon, your project has 50+ sagas in it. (I just counted -- my current project has 52 sagas). But have you ever added a saga and jumped over to your app only to find that your saga doesn't seem to be running? What's going on? webpack --watch is running, the bundle was updated... One downside to having a boatload of sagas is that each saga has to be registered with the redux-saga middleware in order to run. But fifty-two lines of repetitive code? I don't think there's a JavaScripter alive that wouldn't cry foul over all that 'boilerplate'. Here's how I managed to manage all those sagas without too much repetition. I have one directory that holds all my saga files and each saga file is composed of a logical grouping of individual sagas. For instance, I have a userSagas.ts file that contains all my user-related sagas, a sessionSagas.ts file that contains all my session-related sagas, etc. This makes them easy to find. In the same saga directory I have an index.ts file that imports all the sagas from the neighbouring saga files and then registers the sagas programmatically. This saves me from having to remember to type out each saga manually. import * as buildingUser from './buildingUserSagas';import * as deviceType from './deviceTypeSagas';import * as building from './buildingSagas';import * as session from './sessionSagas';import * as editor from './editorSagas';import * as device from './deviceSagas';import * as layout from './layoutSagas';import * as theme from './themeSagas';import * as user from './userSagas';const sagas = { ...buildingUser, ...deviceType, ...building, ...session, ...editor, ...device, ...layout, ...theme, ...user,};export function registerWithMiddleware(middleware: { run: Function }) { for (let name in sagas) { middleware.run(sagas[name]); }} All new sagas I write are included automatically because I habitually add the export keyword when defining my sagas. There's no possibility of a saga going unregistered. I just need to remember to add new saga groups into the index file as I create them, which hasn't been a problem yet. Then I call the registration function with the saga middleware object from my bootstrapping code (both on the client and the server for universal rendering): // Other imports...import createSagaMiddleware from 'redux-saga';import sagas from '../app/sagas';const sagaMiddleware = createSagaMiddleware();const storeWithMiddleware = compose( applyMiddleware( sagaMiddleware, routerMiddleware(browserHistory) ))(createStore);sagas.registerWithMiddleware(sagaMiddleware);// ... // Other imports...import createSagaMiddleware from 'redux-saga';import sagas from '../app/sagas';export function webRequestHandler(req: Request, res: Response) { const sagaMiddleware = createSagaMiddleware(); const store: Store<any> = compose( applyMiddleware( sagaMiddleware ) )(createStore)(appReducer); sagas.registerWithMiddleware(sagaMiddleware); // ... One of my saga files has a factory method that creates parameterized sagas. But the function itself isn't a saga and, therefore, can't be registered with redux-saga middleware. JavaScript allows us to delete from an object and, through the magic of webpack, we're just going to be deleting the function from our module's private copy of the import. The function we 'delete' will still exist and is callable from where it needs to be called from. import * as buildingSagas;// This is not a generator function and it will break// if we try to register it with the middleware.delete buildingSagas.makeBuildingSubRouteSaga;const sagas = { /* ...all the sagas... */}; This tip isn't for everyone since I've got a special case here. Note: I don't need to register the parameterized sagas that the factory function produces because they're all subordinate sagas that are only called from higher level sagas. But this reminds me... When you have a hierarchy of sagas (i.e. top-level sagas that call into sub-sagas), you will want to avoid registering the sub-sagas or else you will probably experience unwanted behaviour in your app. On the other hand, if you need to export sub-sagas for unit testing, then I'd suggest grouping the top-level sagas into an object that gets exported. For example, export function* mainSaga1() { /* ... */ }export function* mainSaga2() { /* ... */ }export function* mainSaga3() { /* ... */ }export function* subSaga1() { /* ... */ }export function* subSaga2() { /* ... */ }export function* subSaga3() { /* ... */ }export const sagas = { mainSaga1, mainSaga2, mainSaga3}; Put these four tips into practice and managing your sagas will be simple. Have you had success with any other tricks? I'd love to hear about it.
https://decembersoft.com/posts/4-tips-for-managing-many-sagas-in-a-react-redux-saga-app/
CC-MAIN-2018-09
refinedweb
735
51.55
from IPython.display import display import spot spot.setup(show_default='.bans') This notebook demonstrates how to use the decompose_scc() function to split an automaton in up to three automata capturing different behaviors. This is based on the paper Strength-based decomposition of the property Büchi automaton for faster model checking (TACAS'13). This page uses the Python bindings, but the same decompositions can be performed from the shell using autfilt and its --decompose-scc option. Let's define the following strengths of accepting SCCs: The strengths strong, stricly inherently weak, and inherently terminal define a partition of all accepting SCCs. The following Büchi automaton has 4 SCCs, and its 3 accepting SCCs show an example of each strength. Note: the reason we use the word inherently is that the weak and terminal properties are usually defined syntactically: an accepting SCC would be weak if all its transitions belong to the same acceptance sets. This syntactic criterion is a sufficient condition for an accepting SCC to not have any rejecting cycle, but it is not necessary. Hence a weak SCC is inherently weak; but while an inherently weak SCC is not necessarily weak, it can be modified to be weak without alterning the langage. aut = spot.translate('(Ga -> Gb) W c') aut The decompose_strength() function takes an automaton, and a string specifying which strength to preserve. The letters used for this specification are as follows: t: (inherently) terminal w: (strictly inherently) weak s: strong For instance if we want to preserve only the strictly inherently weak part of this automaton, we should get only the SCC with the self-loop on $b$, and the SCC above it so that we can reach it. However the SCC above is not stricly weak, so it should not accept any word in the new automaton. spot.decompose_scc(aut, 'w') Similarly, we can extract all the behaviors captured by the inherently terminal part of the automaton: spot.decompose_scc(aut, 't') Here is the strong part: strong = spot.decompose_scc(aut, 's'); strong The union of these three automata recognize the same language as the original automaton. The application proposed in the aforementioned TACAS'13 paper is for parallelizing model checking. Instead of testing the emptiness of the product between aut and a system, one could test the emptiness 3 products in parallel: each with a sub-automaton of different strength. Model checking using weak and terminal automata can be done with much more simpler emptiness check procedures than needed for the general case. So in effect, we have isolated the "hard" (i.e. strong) part of the original automaton in a smaller automaton, and we only need to use a full-fledged emptiness check for this case. An additional bonus is that it is possible that the simplification algorithms will do a better job at simplifying the sub-automata than at simplifying the original aut. For instance here the strong automaton can be further simplified: strong.postprocess('small') for opt in ('sw', 'st', 'wt'): a = spot.decompose_scc(aut, opt) a.set_name("option: " + opt) display(a) There is nothing that prevents the above decomposition to work with other types of acceptance. The following Rabin automaton was generated with ltldo -f '(Ga -> Gb) W c' 'ltl2dstar --ltl2nba=spin:ltl2tgba@-Ds' -H | autfilt -H --merge-transitions (The autfilt -H --merge-transitions pass is just here to reduce the size of the file and make the automaton more readable.) aut = spot.automaton(""" HOA: v1 States: 9 Start: 2 AP: 3 "a" "b" "c" acc-name: Rabin 2 Acceptance: 4 (Fin(0) & Inf(1)) | (Fin(2) & Inf(3)) properties: trans-labels explicit-labels state-acc complete properties: deterministic --BODY-- State: 0 {2} [0&!2] 0 [0&2] 1 [!0&!2] 5 [!0&2] 6 State: 1 {2} [0] 1 [!0] 6 State: 2 {2} [0&!1&!2] 3 [0&1&!2] 4 [!0&!2] 5 [2] 6 State: 3 {1 2} [0&!2] 0 [0&2] 1 [!0&!2] 5 [!0&2] 6 State: 4 {1 2} [0&!1&!2] 0 [0&!1&2] 1 [!0&!2] 5 [!0&2] 6 [0&1&!2] 7 [0&1&2] 8 State: 5 {1 2} [0&!1&!2] 0 [!0&!2] 5 [2] 6 [0&1&!2] 7 State: 6 {1 2} [t] 6 State: 7 {3} [0&!1&!2] 0 [0&!1&2] 1 [!0&!2] 5 [!0&2] 6 [0&1&!2] 7 [0&1&2] 8 State: 8 {3} [0&!1] 1 [!0] 6 [0&1] 8 --END-- """) aut Let's decompose it into three strengths: for (name, opt) in (('terminal', 't'), ('strictly weak', 'w'), ('strong', 's')): a = spot.decompose_scc(aut, opt) a.set_name(name) display(a) Note how the two weak automata (i.e., stricly weak and terminal) are now using a Büchi acceptance condition (because that is sufficient for weak automata) while the strong automaton inherited the original acceptance condition. When extracting multiple strengths and one of the strength is strong, we preserve the original acceptance. For instance extracting strong and inherently terminal gives the following automaton, where only stricly inherently weak SCCs have become rejecting. spot.decompose_scc(aut, "st") The weak automata seem to be good candidates for further simplification. Let's add a call to postprocess() to our decomposition loop, trying to preserve the determinism and state-based acceptance of the original automaton. for (name, opt) in (('inherently terminal', 't'), ('strictly inherently weak', 'w'), ('strong', 's')): a = spot.decompose_scc(aut, opt).postprocess('deterministic', 'SBAcc') a.set_name(name) display(a) aut = spot.automaton(""" HOA: v1 States: 8 Start: 7 AP: 3 "a" "b" "c" acc-name: Streett 2 Acceptance: 4 (Fin(0) | Inf(1)) & (Fin(2) | Inf(3)) properties: trans-labels explicit-labels state-acc complete properties: deterministic --BODY-- State: 0 {2} [0&1] 0 [0&!1] 3 [!0] 4 State: 1 {2} [0&1&2] 0 [0&1&!2] 1 [0&!1&!2] 2 [0&!1&2] 3 [!0&2] 4 [!0&!2] 7 State: 2 {2} [0&1&!2] 1 [0&!1&!2] 2 [0&2] 3 [!0&2] 4 [!0&!2] 7 State: 3 {0 3} [0] 3 [!0] 4 State: 4 {1 3} [t] 4 State: 5 {3} [0&!1] 3 [!0] 4 [0&1] 5 State: 6 {3} [0&!1&!2] 2 [0&!1&2] 3 [!0&2] 4 [0&1&2] 5 [0&1&!2] 6 [!0&!2] 7 State: 7 {3} [0&!1&!2] 2 [2] 4 [0&1&!2] 6 [!0&!2] 7 --END-- """) aut for (name, opt) in (('inherently terminal', 't'), ('strictly inherently weak', 'w'), ('strong', 's')): a = spot.decompose_strength(aut, opt) a.set_name(name) display(a) The subtlety of Streett acceptance is that if a path that does not visit any accepting set infinitely often is accepting. So when disabling SCCs, we must be careful to label them with a combination of rejecting acceptance sets. This is easy to understand using an example. In the following extraction of the strong and inherently terminal parts, the rejecting SCCs (that were either rejecting or strictly inherently weak originally) have been labeled by the same acceptance sets, to ensure that they are rejected. spot.decompose_scc(aut, 'st') When the acceptance condition is always satisfiable, all non-trivial SCCs are accepting, and inherently weak. This include acceptances like Acceptance: 0 t, but also trickier ones like Acceptance: 1 Inf(0) | Fin(0) that you can make as complex as you fancy. Acceptance: 0 t¶ This occur frequently whant translating LTL formulas that are safety properties: aut = spot.translate('(Gb|c) R a', 'any'); aut # There is no strong part for this automaton assert spot.decompose_scc(aut, 's') is None for opt in ('w', 't'): display(spot.decompose_scc(aut, opt)) If we try to extract multiple strengths and include the (empty) strong part, this request will simply be ignored: spot.decompose_scc(aut, 'st') Note that the above is exactly the output of decompose_strength(aut, 't'). The 's' flag was actively ignored. If 's' had not been ignored an the automaton processed as if its strong part had to be preserved, the original acceptance conditions would have been used, and this would have prevented the disabling of the initial SCC. aut = spot.automaton(""" HOA: v1 States: 4 Start: 0 AP: 1 "a" Acceptance: 1 Inf(0) | Fin(0) --BODY-- State: 0 [0] 0 [!0] 1 State: 1 [0] 1 [!0] 2 {0} State: 2 [0] 1 [!0] 3 State: 3 [t] 3 {0} --END-- """) aut By our definitions, SCC $\{0\}$ and $\{1,2\}$ are inherently weak, and SCC $\{3\}$ is terminal. for (name, opt) in (('terminal', 't'), ('strictly weak', 'w'), ('strong', 's'), ('all strengths', 'swt')): a = spot.decompose_scc(aut, opt) if a: a.set_name(name) display(a) else: print("no output for " + name) no output for strong decompose_scc()by SCC number¶ Decompose SCC can also be called by SCC numbers. The example below show the different SCC numbers and the state they contains, before extracting the sub-automaton containing SCC 0 and 2 (i.e., anything leading to states 1 and 4 of the original automaton). This example also shows that when an scc_info is available for to automaton to decompose, it can be passed to decompose_scc() in lieu of the automaton: doing so is faster because decompose_scc() does not need to rebuild this object. aut = spot.translate('(Ga -> Gb) W c') si = spot.scc_info(aut) for scc in range(si.scc_count()): print("SCC #{} contains states {}".format(scc, list(si.states_of(scc)))) display(aut) spot.decompose_scc(si, '0,2') SCC #0 contains states [1] SCC #1 contains states [2] SCC #2 contains states [4] SCC #3 contains states [0, 3] If an SCC number N is prefixed by a, it signifies that we want to extract the Nth accepting SCC. In the above example SCC 2 is rejecting so SCC a2 denotes SCC 3. spot.decompose_scc(si, 'a2')
https://spot.lrde.epita.fr/ipynb/decompose.html
CC-MAIN-2020-24
refinedweb
1,635
56.55
The QServiceChecker class allows client applications to check to see if a service is valid to use. More... #include <QServiceChecker> Inherits QCommInterface. Inherited by QServiceCheckerServer. The QServiceChecker class allows client applications to check to see if a service is valid to use. Some services (e.g. GSM modems) may be available, but unusable because of hardware failure. This class allows the failure to be advertised to client applications. All telephony services that inherit from QTelephonyService will have a default QServiceChecker instance with isValid() set to true. This can be overridden in subclasses to set isValid() to false if a hardware failure is detected during start up. See also QTelephonyService. Construct a new service checker object for service and attach it to parent. The object will be created in client mode if mode is Client, or server mode otherwise. If service is empty, this class will use the first available service that supports service checking. If there is more than one service that supports service checking, the caller should enumerate them with QCommServiceManager::supports() and create separate QServiceChecker objects for each. See also QCommServiceManager::supports(). Destroy this service checker object. Returns true if the service is valid; otherwise returns false. See also setValid(). Sets the isValid() state to value. This is used by server-side implementations. See also isValid().
https://doc.qt.io/archives/qtopia4.3/qservicechecker.html
CC-MAIN-2021-43
refinedweb
218
61.12
In this article I will explain how to send email by embedding images using Gmail credentials in asp.net Description: Generally we will send mails using SMTP server suppose if we don’t have smtp server in that situation we can send mails by using gmail smtp server in asp.net. I will explain how to implement mail sending concept using Gmail credentials using asp.net. To implement this concept first you need to enable POP enable in your Gmail account for this Settings-->Forwarding and POP/IMAP To implement this mail concept in your asp.net application first we need to add this reference to our application System.Net.Mail namespace What is System.Net.Mail ? The System.Net.Mail is a namespace which contains classes to send electronic mail through Simple Mail Transfer Protocol (SMTP) server for delivery. How we can get this reference (System.Net.Mail) for that first add System.Net.dll reference to our application. for that first add System.Net.dll reference to our application. a a) On the Project menu, click Add Reference. b b) On the .NET tab, locate System.Net.dll, and then click Select. c c) Click OK in the Add References. After that design your aspx page like this After that add following namcespace in your codebehind Now write following code in button click Demo our output mail is like this Other related posts are 14 comments : Article is Very Helpful and cool. I got an error in uploadind the image, hence unale to send image really all examples are very usefull and very very helpfull..thank u soooo much i used your post for how to send mail with images using Gmail credentials in asp.net or how to send mail with images using asp.net but there is come some error Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\mahesh.JPG'. hi, how to set img src=cid:companylogo Hi g user following to linkResource LinkedResource myimage = new LinkedResource(Server.MapPath("~//" +FileName), "image/jpg"); you will not get above error. but there is another issue at smtp.Send(Msg) line, it throws an exception ("Failure sending mail.") i am not understanding why this error comes. while my gmail credentials are right. Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\image_name.jpg this error is thrown by the program. give some solution regarding this.. i can' able to attach the image while sednig mail.can u do a favour me? Before using LinkedResource save the file in some folder the code will work !!!! i run the above code without attachment in .net framework 4.5,vs 2012.It's working fine but showing error superb, thank you friend Nice article it's really helpful ................................... superb, thank you error in this code.. plz. corrent then...
http://www.aspdotnet-suresh.com/2010/12/how-to-send-mail-with-images-using.html?showComment=1333718585919
CC-MAIN-2016-26
refinedweb
478
68.57
>> well – code. A few years later, FitMeal was born, and featured on Vice. FitMeal lets you record what you eat via SMS, and texts you back nutritional information about your meal – calories, grams of fat etc. Vice puts what FitMeal does quite simply in their headline “Text This Number To See How Unhealthy Your Lunch Was”. When Georges noticed a massive uptick in registrations he thought it was from the article. But when he checked his Twilio SMS logs, he realized that wasn’t the case. In his logs Georges saw a text along the lines of “saw you on Vice’s snapchat!” He replied to the user directly. But that process wasn’t scalable as users kept rolling in. Eventually he had to build a waitlist for FitMeal. The validation felt like it was a long time coming for Georges. Here’s what the Vice-induced traffic spike looked like in Georges’ Twilio logs. FitMeal was built using Python, deployed on Heroku and uses a Django Database. But, it started on pen and paper. When Georges was looking for a good way to track his eating habits he struggled to find something that was both easy to use, and private. He tried posting his meals to a private blog, but he had to remember to do that after each meal, and often missed a few. Texting seemed like the easiest and most reasonable medium for Georges. “I can do it in 30 seconds, with no hands. I just tell Siri what to text my Twilio number,” says Georges. “Naturally, I ended up with SMS because it’s the simplest entry method.” For Georges, the initial success of FitMeal pays off in double. He lost the weight, and he found success with a product he built himself. The sensation of personal and professional success is not lost upon him, but he prefers to keep it professional. “After a few experiments, I found something that resonates with people. That feels good.” Here’s a little portion of George’s code that shows how FitMeal replies with the calorie count of your meal. def reply(request): """ Reply to a text message with nutrition facts (edited snippet) """ args = {} if request.method == 'POST': # Get the text message text = request.POST.get('text') # Find the food features = app_process.extract_features(text) # Find the nutrition facts nutrients = app_process.compute_nutrients(features) # Write the response response = app_process.compose_response(nutrients) if response: args.update({'response': response}) else: logger.error(text) return render_to_response('reply.xml', args, context_instance=RequestContext(request), content_type='application/xml')
https://www.twilio.com/blog/2015/11/fitmeal-twilio-sms-georges-duverger.html
CC-MAIN-2020-05
refinedweb
421
68.26
--- Wu Yongwei <adah@...> wrote: > Sorry if I am ignorant here, but > > 1) Why quotes? (Ignore it if it is a foolish question.) The code in gcc sources wants a string literal. > > 2) Does "unsigned short" suffice? Maybe. I haven't tried. I just copied the string from this define: #define WCHAR_TYPE "short unsigned int" Danny - SOLD.com.au Auctions - 1,000s of Bargains! Sorry if I am ignorant here, but 1) Why quotes? (Ignore it if it is a foolish question.) 2) Does "unsigned short" suffice? Best regards, Wu Yongwei --- Original Message from Danny Smith --- > /* Define as unsigned short for compatability with MS runtime. */ > #undef WINT_TYPE > #define WINT_TYPE "short unsigned int" > Currently mingw runtime includes stdarg.h, varargs.h stddef.h. These are not really necessary since the ones provided by GCC could do the job, but are masked by the mingw ones. They also create maintenance woes. If we want the mingw runtime versions of these files to be compatable with GCC's internal builtins (which changes from version to version), we have to do this kind of thing in, eg, stdio.h: #if defined __GNUC__ && __GNUC__ >= 3 typedef __builtin_va_list va_list; #else typedef char* va_list; #endif What happens in GCC 3.2? This is especially bothersome because the ANSI standard says that va_list should be defined in stdarg.h, not in stdio.h (see the comments in GCC's stdarg.h). Why not just let GCC's version-specific fixincludes take care of that kind of maintenance, as do other platforms. I propose that we get rid of the mingw runtime versions of stdarg.h, vararg.h and stddef.h and use GCC's. The only modification necessary for the GCC ones is to guard everything with ndef RC_INVOKED. That is easy. The other modification necessary is in stdio.h. Rather than putting va_list typedef in stdio.h as mingw does, do what cygwin and other platforms do: #define __need___va_list #include <stdarg.h> then #ifdef __GNUC__ #define __VALIST __gnuc_va_list #else #define __VALIST char* #endif then replace all va_list parms in function prototypes with __VALIST. Yes, it works with MS versions of vprintf, vsprintf, _vsnprintf and wide counterparts. No I haven't run into the varargs/stdarg conflicts that Colin Peters notes in mingw stdio.h comments. Danny - SOLD.com.au Auctions - 1,000s of Bargains! I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/mingw/mailman/mingw-dvlpr/?viewmonth=200203&style=flat&viewday=25
CC-MAIN-2017-26
refinedweb
429
68.97
- Source code( ChainDesk.CN )Content editing - Wish code slogan | connects each programmer’s story - Website| - Willing code vision | to create a free course of IT system for the whole discipline, help Xiaobai users and junior engineers to learn free system at zero cost and advance at low cost, help bat senior engineers grow and use their own advantages to create post sleep income. - Official account number, code of wishes, service code, block chain, tribe - Free join the code of thinking community of engineers, any official account reply “wish code” two characters to get into the group two-dimensional code. Reading time: 13min Before using the create react app, you didn’t actually have many options to clean up visually. Often at randomCascading style sheets (CSS)Project maintainers come up with a new idea and try to make other libraries, frameworks or preprocessors involved in project compilation a nightmare. The preprocessor in the context of create react app is basically a step in the build process. In this case, we’re talking about something that takes some style code (CSS or other format), compiles it into basic CSS, and adds it to the output of the build process. In this article, we’ll cover a variety of materials covering style related features and highlight one of the best new features in the create react app in my opinion: support for CSS modules and sass. Introduce CSS module CSS modules can modularize any CSS code you import in a way that prevents the introduction of global overlapping namespaces, although the end result is still a huge CSS file. Better project organization Let’s clean up the directory structure in our project first. All we have to do is separate each component with CSS and JavaScript code into its own folder. First, create the new todo, todo, app, todolist, and provider folders, and put all their related code in each of them. We also need to create a new file in each called directory, which index.js Only import and export the corresponding components. For example, an app index file (SRC / APP/ index.js )It will be as follows: import App from "./App"; export default App; Todo (src/Todo/ index.js )The new index file for is as follows: import Todo from "./Todo"; export default Todo; Based on this pattern, you can guess the contents of index files, such as newtodo, todolist and their dividers. Next, we need to change each location that references these files to make it easier to import all of them. Unfortunately, it’s going to be tedious work, but we need to do the same thing to make sure we don’t break anything in the process. First, src/App in/ App.js , change the todolist import component to the following: import TodoList from "../TodoList"; We don’t need to do anything, divider because it’s a component that hasn’t been imported. New todo and todo are similar types, so we can skip them as well. src/TodoList/ TodoList.js On the other hand, we need to deal with many things, because it is one of our highest level components and imports a lot: import Todo from "../Todo"; import NewTodo from "../NewTodo"; import Divider from "../Divider"; But that’s not all. Our test file Src / todolist/ TodoList.test.js We also need to modify these new paths to include files, otherwise our test will fail! We need almost the same import list as before: import TodoList from "./TodoList"; import NewTodo from "../NewTodo"; import Todo from "../Todo"; When you reload your application, your code should still work, the tests should all pass, and everything should be clean! Our complete ... Bringing CSS modules into our applications If we want to use CSS modules, we need to follow some simple guidelines. First, we need to name our file [whatever] module.css , instead of [whatever]. CSS. The next thing we need to do is make sure our style is simple to name and easy to reference. Let’s first follow these conventions and rename our CSS file to todoas Src / todo/ Todo.module.css , and then we’ll change a little bit: .todo { border: 2px solid black; text-align: center; background: #f5f5f5; color: #333; margin: 20px; padding: 20px; } .done { background: #f5a5a5; } Next, we will open Src / todo/ Todo.js To take advantage of CSS modules. We created a helper function in our todo component, cssclass (), which returns the style we should use in the component, and we don’t need to make changes to make everything exactly the same as before. We also need import to change our statement at the top because we renamed the file and are changing the way our CSS is loaded into the code! Look at the following: import styles from "./Todo.module.css"; This allows our code to Todo.module.css Use any of the defined class names styles. [classname] by referencing them. For example, in the previous file, we defined two CSS class names: todo and done, so we can now use the styles.Todo And reference them in components styles.done 。 We need to change the cssclass() function to use it, so let’s make those exact changes now. In Src / todo/ Todo.js , our cssclass() function should now look like this: cssClasses() { let classes = [styles.todo]; if (this.state.done) { classes = [...classes, styles.done]; } return classes.join(' '); } Save and reload, our application should return to normal! Next, let’s change the label todo inside component HR to have its own style and effect. Return to Src / todo/ Todo.module.css Add the following blocks to our HR tag, and we will give a new class reddivider: .redDivider { border: 2px solid red; } Finally, return our render() function Src / todo/ Todo.js , and save and reload the HR tag of the render() function with changes. Now we should fully partition the CSS code without worrying about conflicts and global namespaces! This is what the output looks like: Composability with CSS module This is not all the CSS module gives us, although it is certainly an important part of the CSS module, we get it immediately and effortlessly. We also get CSS composability, which can inherit CSS classes from other classes, whether they are in the main file or not. This can be useful when you set up more complex nested components that all need to work with slightly different stylesheets, but not much different from each other. Suppose we want to be able to mark some components as critical rather than just regular todos. We don’t want to make too many changes to the component; we want it to inherit the same basic rules as all other todos. We need to set up some code to achieve this. Back to Src / todo/ Todo.js , we will make some changes to allow a new state attribute named critical. We will start with the constructor component, and we will add the new state property and bind function tag: constructor(props) { super(props); this.state = { done: false, critical: false }; this.markAsDone = this.markAsDone.bind(this); this.removeTodo = this.removeTodo.bind(this); this.markCritical = this.markCritical.bind(this); } We add a new attribute to the critical attribute, state, and set it to the default value of false. Then we also referenced a function (we haven’t written yet) markcritical, and we bound this because we’ll use it later in the event handler. Next, we will solve the problem markcritical(): markCritical() { this.setState({ critical: true }); } We also need to modify our CSS classes () function so that it can react to this new state property. To demonstrate the composability of CSS modules, we set the classes as an empty array, and then the first item becomes critical or todo, depending on whether the item is marked critical or not cssClasses() { let classes = []; if (this.state.critical) { classes = [styles.critical]; } else { classes = [styles.todo]; } if (this.state.done) { classes = [...classes, styles.done]; } return classes.join(' '); } Finally, in our render function, we will create a button tag to mark the item critical: render() { return ( {this.props.description} Mark as Done Remove Me Mark as Critical ); } We haven’t finished yet, although we have at least 90% of the way. We also want to go back to Src / todo/ Todo.module.css And add a new block for the critical class name. We will also use our composable attributes: .critical { composes: todo; border: 4px dashed red; } To use composition, all you need to do is add a new CSS property, compose and specify a class name (or multiple class names) for it. In this case, writing is a strange way of saying that it inherits the behavior of other class names and allows you to override other class names. In the previous example, we said critical is a CSS module class, which is based on a todo model and added a large red dotted component of border, because we just said that it means it is critical. Save and reload as usual, you should be able to mark items as complete, critical or both, or delete them by clicking delete me, as shown in the following screenshot: This is our brief introduction to CSS module! Before proceeding, you also need to quickly update the test snapshot yarn test by clicking u on the screen. Introduce sass into our project Sass is essentially CSS with extended function support. When I say extended feature support here, I mean it! Sass supports the following feature sets, which are missing from CSS: ·Variables ·Nesting ·Some CSS files ·Import Support ·Mix in ·Extension and inheritance ·Operators and calculations Installing and configuring sass The good news is that it’s easy to get sass support in the create react app project. We first need to install it through yarn or NPM. $ yarn add node-sass We will see a lot of its output, but assuming there are no errors and everything goes well, we should be able to restart our development server and start using some sass. Let’s create a more general utility sass file that will be responsible for storing the standardized colors we want to use throughout the application, as well as storing things in a neat gradient HR mode, in case we want to use it elsewhere. We will also change some of the colors we are using to have some red, green and blue, depending on whether the project is critical, complete or neither. In addition, we need to slightly change our project and add a new file to get some idea of shared styles and colors. So let’s start: - src/ shared.scss Create a new file in our project and provide it with the following principals: , go to Src / divider/ Divider.css And rename the file Src / divider/ Divider.scss 。 Next, we will change the Divider.cssin References to Src / dividers for/ Divider.js , as follows: import "./Divider.scss"; - Now we need to change the code Divider.scss To import and use variables as part of our shared variable file: @import "../shared"; hr { border: 0; height: 1px; background-image: $fancy-gradient; } So, we import Src / into the new shared sass file, and then the background image value only references the variable we created $family grade, which means that we can now recreate that fancy gradient when we need it without having to rewrite it repeatedly. - Save and reload, and you should see no significant changes. Mixed sass and CSS modules The good news is that introducing sass into the CSS module in the create react app is basically not complicated. In fact, these steps are the same! So if we want to start mixing the two, all we need to do is rename some files and change our import processing. Let’s take a look at this action: - First, return to our Src / todo/ Todo.module.css File and make a very small change. Specifically, let’s rename it Src / todo/ Todo.module.scss 。 Next, we need to change our import statement Src / todo/ Todo.js Otherwise the whole thing will collapse: import styles from "./Todo.module.scss"; - Now, we should let our sass use the CSS module of todo component, so let’s start using it. Thirdly, we need to import our shared file to this file sass. Please note the following Src / todo/ Todo.module.scss : @import '../shared'; - Next, we need to start changing references to various background colors. We changed the background of the regular todos to $todo normal. Then, we change the completed todo background to $todo complete. Finally, we will change the critical project, let’s make sure the new color scheme is respected: Now, we have a good integration of CSS module and sass in the create react app project without installing a single new dependency. We let them play well together, which is a greater achievement!
https://developpaper.com/create-react-app-project-with-modern-css/
CC-MAIN-2020-24
refinedweb
2,143
63.7
Which of the following operators cannot be used in conjunction with a String object? Select the two correct answers. + - += . & Which expression will extract the substring "kap" from a string defined by String str = "kakapo"? Select the one correct answer. str.substring(2, 2) str.substring(2, 3) str.substring(2, 4) str.substring(2, 5) str.substring(3, 3) What will be the result of attempting to compile and run the following code? class MyClass { public static void main(String[] args) { String str1 = "str1"; String str2 = "str2"; String str3 = "str3"; str1.concat(str2); System.out.println(str3.concat(str1)); } } The code will fail to compile since the expression str3.concat(str1) will not result in a valid argument for the println() method. The program will print str3str1str2 when run. The program will print str3 when run. The program will print str3str1 when run. The program will print str3str2 when run. What function does the trim() method of the String class perform? It returns a string where the leading white space of the original string has been removed. It returns a string where the trailing white space of the original string has been removed. It returns a string where both the leading and trailing white space of the original string has been removed. It returns a string where all the white space of the original string has been removed. None of the above. Which statements are true? String objects are immutable. Subclasses of the String class can be mutable. All wrapper classes are declared final. All objects have a public method named clone(). The expression ((new StringBuffer()) instanceof String) is always true. Which of these expressions are legal? Select the four correct answers. "co".concat("ol") ("co" + "ol") ('c' + 'o' + 'o' + 'l') ("co" + new String('o' + 'l')) ("co" + new String("co")) public class RefEq { public static void main(String[] args) { String s = "ab" + "12"; String t = "ab" + 12; String u = new String("ab12"); System.out.println((s==t) + " " + (s==u)); } } The code will fail to compile. The program will print false false when run. The program will print false true when run. The program will print true false when run. The program will print true true when run. Which of these parameter lists have a corresponding constructor in the String class? Select the three correct answers. () (int capacity) (char[] data) (String str) Which method is not defined in the String class? trim() length() concat(String) hashCode() reverse() Which statement concerning the charAt() method of the String class is true? The charAt() method takes a char value as an argument. The charAt() method returns a Character object. The expression ("abcdef").charAt(3) is illegal. The expression "abcdef".charAt(3) evaluates to the character 'd'. The index of the first character is 1. Which expression will evaluate to true? "hello: there!".equals("hello there") "HELLO THERE".equals("hello there") ("hello".concat("there")).equals("hello there") "Hello There".compareTo("hello there") == 0 "Hello there".toLowerCase().equals("hello there") What will the following program print when run? public class Search { public static void main(String[] args) { String s = "Contentment!"; int middle = s.length()/2; String nt = s.substring(middle-1, middle+1); System.out.println(s.lastIndexOf(nt, middle)); } }; 2 4 5 7 9 11
http://etutorials.org/cert/java+certification/Chapter+10.+Fundamental+Classes/Review+Questions_3pxo4/
CC-MAIN-2019-09
refinedweb
540
71.51
Flutter H5Pay A Flutter plugin for h5pay(Support WeChat and Alipay) Usage Add flutter_h5pay as a dependency in your pubspec.yaml file. dependencies: flutter_h5pay: ^0.1.0 import 'package:flutter_h5pay/h5pay.dart'; //wrap you widget with H5PayWidget //call the pay method to invoke the payment app H5PayWidget( refererScheme: "", builder: (ctx, controller) { return FlatButton( onPressed: () { controller.pay(getPayUrl(), jumpPayResultCallback: (p) { print("jump pay app result ->$p"); }); }, child: Text("pay")); }, ) iOS Opt-in to the embedded views preview by adding a boolean property to the app's Info.plist file with the key io.flutter.embedded_views_preview and the value YES. Notice When payment completed or cancelled,on IOS, if need to return to the App,you must add target URL Types into the Info.plist file。 For Exmalpe. If you referer(申请H5支付时的授权域名) is In Android you can set this referer. In iOS you should set like this:\\,and add a URL Schemes of into the Info.plist file.Please refer to this article for more details.
https://pub.dev/documentation/flutter_h5pay/latest/
CC-MAIN-2019-51
refinedweb
164
51.04
to1” under “UWMadison744-F21” project for you to start your experiment. The profile is a simple 3-node cluster with Ubuntu installed on each machine. While launching the experiment make sure to choose the right group name. You get full control of the machines once the experiment is created, so feel free to download any missing packages you need in the assignment. As the first step, you should run following commands on every VM: sudo apt update sudo apt install openjdk-8-jdk ssh-keygen -t rsaon the master node. You should designate a VM to act as a master/follower (say node-0) while the others are assigned as followers followers -O StrictHostKeyChecking=no hostname Your home directory in the CloudLab machine is relatively small and can only hold 16GB of data. We have also enabled another mount point to contain around 96 TA744@node2:~$ df -h | grep "data" /dev/xvda4 95G 60M 90 follower.2.2.tar.gz There are a few configuration files we need to edit. They are originally empty so users have to manually set them. Add the following contents in the <property> field in hadoop-3. NOTE: Make sure to use internal IPs in your config files as specified in the FAQ below. Also you need to add the following in hadoop-3.2.2/etc/hadoop/hdfs-site.xml. Make sure you specify the path by yourself (You should create folders by yourself if needed. For example, create hadoop-3 follower.2.2/etc/hadoop/workers to add the IP address of all the datanodes. Once again remember to use the internal IP address! In our case, we need to add the IP addresses for all the nodes in the cluster, so every node can store data. Now, we start to format the namenode and start the namenode daemon. Firstly, add hadoop-3.2.2/bin and hadoop-3-3.1.2-bin-hadoop3.2.tgz Similar to HDFS you will need to modify spark-3.1.2-bin-hadoop3.2/conf/workers to include the IP address of all the follower machines. Recall that we should be using internal IP addresses! To start the Spark standalone cluster you can then run the following command on the master node: spark-3.1.2-bin-hadoop3.2 follower VMs. To stop all nodes in the cluster, do spark-3.1.2-bin-hadoop3.2/sbin/stop-all.sh Next, setup the properties for the memory and CPU used by Spark applications. Set Spark driver memory to 30GB and executor memory to 30GB. Set executor cores to be 5 Spark SQL Guide and the APIs. Spark DataFrame is a distributed collection of data organized into named columns. It is conceptually equal to a table in relational database. In our case you will create DataFrames from the data that you load into HDFS. Users may also ask Spark to persist a DataFrame in memory, allowing it to be reused efficiently in subsequent actions (not necessary to do for this par of the assignment, but will need to do it in part 3). An example of couple commands if you are using PySpark (Python API that supports Spark) that should be handy. from pyspark.sql import SparkSession # The entry point into all functionality in Spark is the SparkSession class. spark = (SparkSession .builder .appName(appName) .config("some.config.option", "some-value") .master(master) .getOrCreate()) # You can read the data from file into DataFrames df = spark.read.json("/path/to/a/json/file") After loading data you can apply DataFrame operations on it. Read more about them here. df.select("name").show() df.filter(df['age'] > 21).show()21. In order to achieve high parallelism, Spark will split the data into smaller chunks called partitions which are distributed across different nodes in the cluster. Partitions can be changed in several ways. For example, any shuffle operation on a DataFrame (e.g., join()) will result in a change in partitions (customizable via user’s configuration). In addition, one can also decide how to partition data when writing DataFrames back to disk. For this task, add appropriate custom DataFrame partitioning and see what changes. Task 3. Persist the appropriate DataFrame as in-memory objects and see what changes.). run.shscript for each part of the assignment that can re-execute your code on a similar CloudLab cluster assuming that Hadoop and Spark are present in the same location. These are based on the questions which students who previously took the course asked. Regarding Experiments on Cloudlab The default length of experiments on cloudlab is 16hrs. You can extend a running experiment by another 16hrs if you need more time. Extensions longer than that require approval by cloudlab staff are not recommended. Make sure you create one experiment per group so all groups have access to compute clusters. Permission denied(Public Keys) Make sure you have copied the SSH keys correctly. Oftentimes copying end up adding a new line, which leads to this failure. Be careful about this. Network setup on cloudlab All cloudlab nodes in Wisconsin are connected to switches, a switch for control network and faster switch for experiment network. For all your experiments you should use the experiment network. To use the experiment network use the IP-Addresses which start with 10.*.*.* instead of IP addresses that start with 172.*.*.* or 128.*.*.*. More information about cloudlab network can be found here. You can find the ip-address using ifconfig command. To force HDFS to use these, you need to configure them in the worker files. For Spark modify SPARK_LOCAL_IP in conf/spark-env.sh with the IP’s to take this is effect. Also note configs passed via command line are overridden by spark-default configs. So make sure to make changes in the spark configs. Using Non-Routable IP’s The profile “cs744-fa21-assignmet1” creates non-routable IP’s. To access instances via internet you will need to use SOCK proxy or ssh tunneling to access the health pages. Detailed steps can be found here. The main things to do are ssh -D 8123 -C -N -p 29610 myhost This assignment uses insights from Professor Aditya Akella’s assignment 1 of CS744 Fall 2017 fall and Professor Mosharaf Chowdhury’s assignment 1 of ECE598 Fall 2017.
https://pages.cs.wisc.edu/~shivaram/cs744-fa21/assignment1.html
CC-MAIN-2021-49
refinedweb
1,049
66.13
Previous posts can be found here: In part two we set up our domain model. Now, before we can test nhibernate’s ability to work with and persist objects, we need to ensure that we’ve defined our schema well enough that NHibernate can create the Schema for us (since that was kind of the point). Now is where NUnit starts to become very useful. First step we’re going to take to set up NUnit is to add another project to our solution. I named this project the very creative RecipeTracker.Tests. When setting up this project, it is important to add all the same references as we used in the main project. In addition we need to add a reference to the main project itself and a reference to nunit.framework. For the main project, we’ll need to again set the “CopyLocal” option to true. Finally, we also need a copy of our Sql Compact database in this project. Our first unit test will just be to see that we can export the schema. Here it is: using System; using System.Collections.Generic; using System.Linq; using System.Text; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; using NUnit.Framework; using RecipeTrackerPartOne; namespace RecipeTrackerPartOne.Tests { [TestFixture] public class GenerateSchema_Fixture { [Test] public void Can_generate_schema() { var cfg = new Configuration(); cfg.Configure(); cfg.AddAssembly(typeof(Model.Recipe).Assembly); new SchemaExport(cfg).Execute(false, true, false, false); } } } There’s a lot of new stuff going on here. Most noticeable is the directive to use nunit.framework, and the attributes added to our class and our methods. These attributes are used when we load the project into NUnit, so that the NUnit application knows which code to execute as a test. We need to identify our class as a TestFixture, then our method within the class as a Test (this setup allows us to include supporting code that is not necessarily a test). Also notable is the directive to use NHibernate.Tool.hbm2ddl. This is what allows NHibernate to create the schema for us (by converting Hibernate mappings to Data Definition Language). The most interesting line, as far as I am concerned, is the “AddAssembly” line. This is what associates our Configuration with a given assembly, and therefore that assembly’s hibernate.cfg.xml file. So, what we are really testing here is really the schema we have defined in the xml file. If everything is set up right, when you fire up the NUnit GUI, load the RecipeTracker.Tests assembly, and run the test, you should see a nice green bar. Unfortunately, we broke the first rule of Unit Testing, that the first time we run a test it should fail. Well, I didn’t, but I wanted to spare you gentle readers some of the pain of wrestling with the mapping file. But fear not, because now it is time to experience the joy that is the red, “you screwed up” bar. Remember, we want to confirm that NUnit will in fact tell us when we do screw up! For this part we’ll need to start setting up our repositories to move the objects to and from the database. This gets pretty involved, so this will have to be continued in Part 4. Here is the sample project (so far). Next one will be where it gets interesting! Sample Project – Part 1
http://blogs.lessthandot.com/index.php/DesktopDev/MSTech/my-path-to-the-dark-side-part-3-testing-/
CC-MAIN-2017-04
refinedweb
562
75
Implementing SURF using iplimage in opencv and c++ unresolved externals 'm facing a problem with implementing SURf using Mat because of heap, so I tried to use iplimage. I used the code of this guy SURF using iplimage I've got errors: unresolved external symbol _cvExtractSURF unresolved external symbol _cvSURFParams I added these #include "opencv2/nonfree/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/nonfree/nonfree.hpp" #include <opencv2/legacy/legacy.hpp> with cv::initModule_nonfree(); in main but it didnt work. does anyone know what is the problem ? You are trying to execute C-API code using the C++ include headers. That will never work. I suggest leaving those IplImages and C-API. Show us your non working C++ and Mat code and we will help you out there with problems. The C-API is depricated and will disappear soon! this link contains a code for real time surf using mat it gives me heap corruption exception or memory location exception it gives me heap exception or memory location exception did you check that csv ? is it working fine with the code ? and did you check the path of your images ?
https://answers.opencv.org/question/33141/implementing-surf-using-iplimage-in-opencv-and-c-unresolved-externals/
CC-MAIN-2021-21
refinedweb
192
59.6
using System; public class MultiplicationTable { public static void Main() { int i = 1; while (i <= 10) { int j = 1; string line = ""; while (j <= 10) { line += (i * j).ToString() + " "; j++; } Console.WriteLine(line); i++; } } } C# Multiplication table Page 1 of 1 10x10 multiplication table using C# 1 Replies - 21302 Views - Last Post: 20 October 2009 - 06:03 PM #1 C# Multiplication table Posted 20 October 2009 - 05:55 PM Okay, you guys have helped me with one of the problems i was having creating another program. Now I am trying to create a 10x10 multiplication table using C#. I have the code done and when i execute it comes up briefly and then disappears. Normally I add Console.ReadLine() to the end and that solves the problem, but with this code when i add ReadLine to the code it just comes up with an empty window. Can anyone tell me why it wont accept the command? Replies To: C# Multiplication table #2 Re: C# Multiplication table Posted 20 October 2009 - 06:03 PM try using Console.Read() as opposed to ReadLine()... I can't think of anything that would cause it to do that. Page 1 of 1
http://www.dreamincode.net/forums/topic/133331-c%23-multiplication-table/
CC-MAIN-2018-13
refinedweb
196
72.56
In the high jump event, you must soar to new heights as you read a database containing high jumpers training data in order to predict who will win on gameday.dim objConnectiondim subsub subsub checkForError(msg) if err.number <> 0 then wscript.echo "Error encountered for " & msg & ", Error = " & err.description end ifend sub When we run the BeginnerEvent4Solution.vbs script, in CScript, we see the following information displayed. Richard Siddaway is an Infrastructure Technical Architect, and Windows PowerShell MVP. He is the founder and leader of the UK Windows PowerShell User Group. He maintains the Of PowerShell and Other Things blog, and is the author PowerShell in Practice.. Field Data Type ID AutoNumber Name Text Country Personal Best Number Season Best:\Scripts\High:\Scripts\HighizeWrite: The high jump event is an event in which participants jump over a horizontal bar that is placed at different heights. For this event, you will be given the results of a series of jumps and be asked to draw a graph that indicates the trend of the jumps. ' Hide the application till the graph is plotted.xlApp.workbooks.add ' Add a workbook to work upon. xlapp.Worksheets(1).Name = "High Jump Data" ' Name the first sheet The next step is to read the data and populate this worksheet. To open the file, we create an instance of Scripting.FileSystemObject and invoke its OpenTextFile method. Here we specify the open mode to be ReadOnly, as we only need to read the data in the file. This is seen here. Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.OpenTextFile (".\High Jump Stats_Adv4.txt", FileOpenMode) Once we have a handle to the file, we read it line by line. This is the same as reading each participant’s record one at a time. The process is repeated until you read to the the end of file for all the participants. We use the Readline method as seen here. strNextLine = objFile.Readline As previously stated, each string is a comma-separated list of values. This list is obtained by splitting the string on a comma. This is shown here. arrScores = Split(strNextLine, ",") The participant’s name is constructed from the first two entries of the arrScores array. These elements represent the first and last name respectively. The rest of the entries in the array represent the person’s scores for the event. Here we build the participant’s name. strName = arrScores(0) & arrScores(1) There are two variables, rowNumber and colNumber, that are used to maintain the location of the current row and column to be updated. In the activesheet (the first worksheet), we set the first column to the name of the participant. The particpant’s scores are entered in subsequent cells, one entry per cell and for every read record. The colNumber variable is set to 1, to refer to the first column. This is seen here. colNumber = 1 xlApp.activesheet.cells(rowNumber, colNumber) = strName For i = LBound(arrScores) + 2 To UBound(arrScores) colNumber = colNumber + 1 xlApp.activesheet.cells(rowNumber, colNumber) = arrScores(i) Next Now that the data has been ported to Office Excel, our final task is to draw the chart with the data. From the different charts that one can choose from, for a scenario such as this, the Line Chart would be a good choice. To know what the chart depicts and what are its axes represents, we must label them appropriately. Coming back to the scripting part, once the file read is complete, the row and column counters point to the last row and the last column. Because the rowNumber is always updated in advance, the actual last cell is one less than the current value of the rowNumber variable (rownumber - 1). The data range in our case goes from the first cell 1, 1 to the last cell (rowNumber-1, colNumber). The confusing issue is that Excel refers to cells by a combination of letters and numbers. But when using Excel automation, you only use numbers. We add a chart with the chart type set to Line Chart (value = 4), assign titles for the chart and axes, provide the data range and specify the chart to be created in new sheet. This newly added chart is an ActiveChart. This is seen here. Once the chart configuration is completed, the application is visible. xlApp.Visible = True The complete AdvancedEvent4Solution.vbs script is shown here. AdvancedEvent4Solution.vbs ' 2009 Scripting Games - Event 4 - Rajesh B RConst FileOpenMode = 1 ' Opening mode of the file, read-only hereConst xlChartType = 4 ' Line Chart IDConst xlXAxisID = 1 ' X-Axis IDConst xlYAxisID = 2 ' Y-Axis IDConst xlPrimaryAxis = 1 ' Primary axis group IDConst xlNewSheet = 1 ' Create chart in new sheetSet xlApp = CreateObject("Excel.Application")xlApp.Visible = False ' Hide the application till the graph is plotted.xlApp.workbooks.add ' Add a workbook to work upon. xlapp.Worksheets(1).Name = "High Jump Data" ' Name the first sheet rowNumber = 1 ' Initialize counters to track cell to be updatedcolNumber = 1' Open the statistics file in read-only modeSet objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.OpenTextFile (".\High Jump Stats_Adv4.txt", FileOpenMode)Do Until objFile.AtEndOfStream ' Read all records, till the end is reached strNextLine = objFile.Readline ' Read a record If strNextLine <> "" Then arrScores = Split(strNextLine, ",") ' split the record string on comma strName = arrScores(0) & arrScores(1) ' participant name: irst 2 entries of the list colNumber = 1 ' foreach new record, re-initialize counter to 1 xlApp.activesheet.cells(rowNumber, colNumber) = strName ' first column is name For i = LBound(arrScores) + 2 To UBound(arrScores) ' add scores to cells colNumber = colNumber + 1 xlApp.activesheet.cells(rowNumber, colNumber) = arrScores(i) Next rowNumber = rowNumber + 1 ' once record is processed, update row counter End IfLoopobjFile.Close ' close the file' Get the range in Excel Row and Column format. Range here is from first cell (1, 1) to last cell (rowNumber - 1, colNumber)rangeString = "A1:" & xlApp.activesheet.cells(rowNumber - 1, colNumber).Address(RowAbsolute = True, ColumnAbsolute = TruexlApp.Visible = True ' make the app visible Once the AdvancedEvent4Solution.vbs script is run, this output is displayed: Richard has worked in programming and Web development for 25 years. Currently, he works for Microsoft as a Development/Debugging engineer primarily specializing in SharePoint technologies. In addition to this work, he has been involved with DBA application integration tools such as Tibco and Biztalk. Recently, he began branching out to ISA server and CardSpace security technologies. For the advanced high jump event, I had to produce a chart or graph of a series of jumps. LogParser is one tool that I could use; however the script is dependent that tool is available on the system. Another tool that could be useful would be Office Excel through COM Automation. But once again, we must ensure that Excel is installed on the system, and the installation of Microsoft Office products is not supported on server operating systems except in very specific circumstances. For this script, I decided to use the new Charting Controls for .NET 3.5 SP1 (examples). With these charting controls, I have some flexibility of data imported and an advanced way to manipulate the charts that are produced. The data file is a CSV file so Import-CSV is an option, but because the file does not have headers, Import-CSV will not work without cleaning up the CSV file first. The Import-CSV cmdlet assumes that in the first line of the file is the headers associated with the columns. Since this is not the case, I used string parsing with the Split”method to get a list of rows and columns from the file. This is shown here. $resultlst = get-content "$($Env:USERPROFILE)\Documents\High Jump Stats_Adv4.txt"$results=@(); $resultlst | foreach-object {$results+=,($_.split(","))} After this step, the rest of the script then takes the data and adds it to the chart control. The chart control is used to finally export the chart to a Portable NetworkGraphics (PNG) file. The first thing we need to do is to load the DataVisualization namespace into Windows PowerShell because it is not loaded by default. In Windows PowerShell 2.0, we can use the Add-Type cmdlet, but in Windows PowerShell 1.0, we must use Reflection. I am using the strong name to load the class, because it is the recommended way to ensure you get the exact version of the assembly. This is seen here (note it is a single line of code). [Reflection.Assembly]::load("System.Windows.Forms.DataVisualization, Version=3.5.0.0,Culture=Neutral, PublicKeyToken=31bf3856ad364e35") Now we must create an instance of the charting object, and set the width and height. This is seen here. $Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart$Chart.Width = 500$Chart.Height = 400 Once the chart object has been created, we create the chart area, the legend objects. We then add them to the chart object. This is seen here. $ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea$Legend = New-Object System.Windows.Forms.DataVisualization.Charting.Legend$Chart.ChartAreas.Add($ChartArea)$chart.Legends.add($Legend) Now it is time to add the data to the data series, and to set up the legend. This is seen here. foreach ($result in $results){ $Chart.Series.Add("$($result[1].trim()) $($result[0].trim())") $Chart.Series["$($result[1].trim()) $($result[0].trim())"].Points.DataBindXY(1..$([int]$result.length-2), $result[2..[int]$result.length]) $Chart.Series["$($result[1].trim()) $($result[0].trim())"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Line $Chart.Series["$($result[1].trim()) $($result[0].trim())"].LegendText ="$($result[1].trim()) $($result[0].trim())" } We now must save the chart. To do this, we use the SaveImage method, and specify both the name of the script and the type. For this event, we are saving it as a PNG file. After we have saved the chart, we release the objects by calling the Dispose method. This is shown here. $Chart.SaveImage($Env:USERPROFILE + "\Documents\demo\Total High Jump Chart.png", "PNG")$ChartArea.Dispose()$Legend.Dispose()$Chart.Dispose() The second half of the script creates an individual chart for each person in the file by using the same process above. We will not cover that portion of the script here because it is a similar process. The completed AdvancedEvent4Solution.ps1 script is seen here. AdvancedEvent4Solution.ps1 #============================================================# Load the data into PowerShell for analysis# The data file is a CSV file with last name, First name, # and the rest are the results.$resultlst = get-content "$($Env:USERPROFILE)\Documents\High Jump Stats_Adv4.txt"#============================================================# Parse each column so that the values are in their own "cells"$results=@(); $resultlst | foreach-object {$results+=,($_.split(","))}#============================================================# load the charting assembly into PowerShell# in V2 I could have used Add-Type with the type name below[Reflection.Assembly]::load("System.Windows.Forms.DataVisualization, Version=3.5.0.0,Culture=Neutral, PublicKeyToken=31bf3856ad364e)#============================================================# For each result, add the data to the data series # and set up the legend informationforeach ($result in $results){ #============================================================ #, documented on MSDN \Total High Jump Chart.png", "PNG")#============================================================# Dispose of objects now that I am done.$ChartArea.Dispose()$Legend.dispose()$Chart.dispose()#============================================================# In this area, I am going to create a chart using the # same set of results instead of a single chart.# Each chart will be an individual chart for each person. # In this case I don't need to reload the data again since # I have already done the parsing.foreach ($result in , but I can set this for # each series I want \$($result[1].trim()) $($result[0].trim()) High Jump Chart.png", "PNG") #============================================================ # Dispose of objects now that I am done. $ChartArea.Dispose() $Legend.dispose() $Chart.dispose()} #end script When the AdvancedEvent4Solution.ps1 script runs, it creates a chart that looks like the following: Very cool, everyone. Thank you, Bruno, Richard, Rajesh, and Richard for your hard work on the shot put events. We have picked up some new techniques that we just cannot wait to try out. Join us tomorrow as we unveil the details for Event 9, the javelin throw. Make sure you check out the 2009 Summer Scripting Games forum for discussion of the events and for answers to questions if they arise while you are working on the Scripting Games. Follow us on Twitter for all the latest Scripting Games information. Ed Wilson and Craig Liebendorfer, Scripting Guys All the Scripting Games links in one location! Let the learning begin. (We will update this page every I did the expert commentary for this one – it can be read here
http://blogs.technet.com/b/heyscriptingguy/archive/2009/06/17/hey-scripting-guy-event-4-solutions-from-expert-commentators-beginner-and-advanced-the-high-jump.aspx
CC-MAIN-2014-23
refinedweb
2,075
57.98
For the past week I have been trying to track this bug in which is causing my Qt application to crash and have been unsuccessful in finding the source of the corruption. What I have done is created 2 global QVectors<double> using "extern", as well as 3 Qwt plots that are plotting what ever is in those vectors every 20 mS on a timer. Meanwhile, a QThread is running at the same time looping at 20 mS as well, populating, resizing, and appending values to the arrays to update the plot on the main thread so it updates realtime. I am only allowing 30 seconds worth of data to be displayed at all times on all three plots, and once the 30 seconds has been met, I clear the arrays and start appending again in a loop... 30 seconds, with 20 mS refresh, the counter will have to reach 1500 when it needs to refresh...so my counter is from 0 to 1500 Here is the code in the thread that handles the resizing and clearing ect.. ect. ect. @ // check if the packet counter is maxed for the graph if (p_counter >= 1500){ // check packet counter // clear the data xDataGlobal.clear(); xAxisGlobal.clear(); // resize arrays xDataGlobal.resize(0); xAxisGlobal.resize(0); p_counter = 1; // clear packet counter } // check values if (typeid(xVal) == typeid(double)){ // append data to packets xDataGlobal.resize(p_counter + 1); xAxisGlobal.resize(p_counter + 1); xDataGlobal[p_counter] = xVal; xAxisGlobal[p_counter] = (double)p_counter; // increment the packet counter p_counter++; // increment packet counter } else { qDebug() << "type id error"; } @ This code is in a loop every 20 mS... Now on the main thread, the 3 graphs are being updated using the QwtPlot::timerEvent in which is triggering every 20 mS and setting the data to a QwtPlotCurves as shown below @ void Plot::timerEvent(QTimerEvent *event) { if (event->timerId() == d_timerId){ setCurveData(xDataGlobal, xAxisGlobal); replot(); return; } QwtPlot::timerEvent(event); } /* // set the curve data */ void Plot::setCurveData(QVector<double> xData, QVector<double> xAxisData) { d_curveX->setSamples(xAxisData, xData); } @ At random times, if I have this application running in debug mode, or release, within an hour or two it crashes (in consistant on the timing though...) and I am unable to figure out why. The crash is difficult to pin point in the crash log and the debugger but it always seems to point to a bad alloc or a QVector on the last couple arguments in the stack. The most recent crash, I opened the application up in the MSVC2008 debugger when it gave me the option and it showed the free.c file for deleting allocated memory. This is the crash line @ #endif /* CRTDLL / else // __active_heap == __SYSTEM_HEAP #endif / _WIN64 */ { retval = HeapFree(_crtheap, 0, pBlock); if (retval == 0) // says it crashes right here and that retval is invalid { errno = _get_errno_from_oserr(GetLastError()); } } } @ From the Qt documentation, clear() frees all of the allocated memory, and resize also removes any extra allocated memory not being used...Am I pushing the QVector to hard? or does anyone have any tips on helping solve this crash? I feel its a memory error... My system is running Windows 7 using msvc2008 in the QtCreator envoirnment
http://forum.qt.io/topic/16404/crash-with-qvector-and-freeing-memory
CC-MAIN-2015-14
refinedweb
521
56.39
Let. Integer i = new Integer(5)?or String s = new String("hello");? We're still repeating ourselves, and the repetition adds nothing to making the program more understandable. I would agree that generics make the repetition even more ugly (and pointless) but that perhaps including James' option as well we can implement DRY more thoroughly. So I'd be in favor of: s := new String("hello");and Map<String,List<Integer>> map = HashMap.new();Also, what about factories that (reasonably) take parameters, like the starting size of the HashMap? Regards, Patrick Posted by Patrick Wright on January 18, 2007 at 01:24 AM PST # Posted by Stefan Schulz on January 18, 2007 at 03:10 AM PST # I believe that a key part of the 'look and feel' of Java code is the type declaration being on the left. Thats why I *really* dislike the suggestions from James and Christian (although I understand the motivation). Neal's suggestion comes originally from me (AFAIK) via the Javapolis whiteboards. I won't pretend its beautiful, but it is effective. As to your static factory idea, I think it might work OK. You won't be able to block <code>Integer i = new Integer(5)</code> if I understand it correctly (due to backwards compatability). As a result, you won't be able to use it to fix old code where you later realise that you should have had a factory, for caching, not a public constructor. And finally, one more possibility to throw in the mix: SomeVeryLongClassName someEvenLongerVariablename = new(args); which I think is within the Java 'look and feel'. Posted by Stephen Colebourne on January 18, 2007 at 03:34 AM PST # HashMap<String,String> hmap = new(10, 0.75); Map<String,String> map = new HashMap(10, 0.75); Other point, about concerns about existing #new(...) methods. How could this be an issue ? 'new' is a keyword, and thus cannot appear as an identifier anywhere in the code. Thus 'new' methods would be purely synthetics, and no user code could ever refer to them without using the proposed syntax. The only problematic point, is that you couldn't let a user write custom ones, and purely rely on synthetic ones. If so, then why even need a generated method ? The compiler could simply macroexpand the call into a constructor call for free. Also if instantiating the lhs type, then no explicit type would be required. HashMap<String,String> hmap = new(10, 0.75); Map<String,String> map = HashMap.new(10, 0.75); Posted by Philippe Mulet on January 18, 2007 at 04:48 AM PST # public class Test { class A { } public static void main(String[] args) { Test Test=new Test(); Test.new A(); } } And i don't understand why javac needs to automatically generates static factories ? The compiler could try to call a static factory first and if it doesn't find an applicable one try to call a constructor. Rémi Posted by Rémi Forax on January 18, 2007 at 04:58 AM PST # MyClass.new({somearguments});could be compiled similar to new MyClass<{inferredtypes}>({somearguments}); Posted by Stefan Schulz on January 18, 2007 at 05:29 AM PST # @ Philippe I'm not sure I get the reference to "array initializer simplification for variable declarations". @ Philippe and Rémi The syntax could be used without the static factory methods. However, then it would be a different proposal ;-) I think it is more powerful, yet simple, to add factory methods that can be provided by the user. Posted by Peter von der Ahé on January 18, 2007 at 06:25 AM PST # Posted by Peter von der Ahé on January 18, 2007 at 06:33 AM PST # Posted by Peter von der Ahé on January 18, 2007 at 06:41 AM PST # As you've shown, we already have type inference on method calls, just not on constructor calls (why?). It's possible to write a generic method 'hashMap()' that returns the right kind of Map, used like so: Map<String,Integer> aMap=hashMap(); Rather than a language change, this could be a simple API change to add hashMap(), hashSet(), etc., to the APIs. If ArrayList et al had been designed from the start to be instantiated via a static method, then I doubt we'd even be discussing this. Ok, discounting my uninteresting solution, onto your idea: If the compiler had to generate code to do this, then the language feature would be incompatible with existing bytecode, unless it could generate it at call-sites. A problem with allowing programmers to write methods called 'new' is that they might not actually generate a 'new' object, whereas as far as I know, in Java 'new' always creates a new object. Is there a reason why HashMap.new() could not use the existing constructor and apply type inference? Further, is there a reason why 'new HashMap()' could not have type inference applied, then there's no new syntax? Currently, assigning a raw type to a parameterised type is a compile warning. I don't see how allowing inference on this will adversely affect any existing code; other than removing the warning. Is there a test case that shows this problem? The older idea, using 'final' to mean 'infer local variable type', has an interesting repercussion. The type could actually be an anonymous type, e.g.: final o=new Object(){int a=5,b=6;}; o.a=6; o.b=5; If that looks odd, note that this already works. System.out.println(new Object(){int a=5;}.a); If I had to choose between your proposal and the 'final' proposal, I'd go with yours for readability and security (I treat variables defined in anonymous classes as private, regardless of their actual visibility). Another idea is, when you have a concrete type, simply HashMap<whatever> map=new(); without having to statically import 'new' from somewhere. Getting closer to C++'s stack-allocation syntax there.. Posted by Ricky Clarkson on January 18, 2007 at 07:45 AM PST # (1) DRY is good (2) boilerplate repeated type definitions obscure rather than enlighten so (3) this seems like a generally good idea. However, aren't there problems with completeness and O() of runtime when you try to infer types from right to left? I can't remember whether SML/ML allowed it for example. And wasn't it one of the hurdles in front of covariant Java method return types? I'm still deciding if I like the auto boxing/unboxing in JSE5, having just started using it to save considerable keystrokes, just because I now have to start wondering again (very C++ like) if something as apparently benign as "final long l = <simpleexpr>;" can cause an NPE. Before, I knew that it could not unless I could see a function call. Now it might if simplexpr involves Long rather than long by design or accident. Are there any such slight-anxiety-raising features lurking in your suggestion(s)? Rgds Damon Posted by Damon Hart-Davis on January 18, 2007 at 08:24 AM PST # HashMap<String, List<Integer>> map = new({parameters}); HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>({parameters}); Posted by Stefan Schulz on January 18, 2007 at 08:26 AM PST # Posted by Morten on January 18, 2007 at 08:28 AM PST # Posted by Ricky Clarkson on January 18, 2007 at 08:53 AM PST # Posted by zproxy on January 18, 2007 at 09:50 AM PST # I will apologize in advance for putting 4 things into one post, but I wanted to make 4 separate points! If you get bored reading such a long post :) stick to item 1 - its the most important! You could add new keywords without pain. If you added the keyword source that accepted the Java version number. The source declaration would go before the package declaration. No code broken because no statement could go before package previously. Then if a package or import statement included something that was a keyword in the language version, e.g. source 7, then this keyword could be name mangled. So for example in the proposal C3S the keyword declare is proposed, as in declare map = HashMap.new( collection ), but if the name declare was included from elsewhere it could be mangled to _declare_ say. Note this suggestion will work well now that other languages are on the JVM. These languages don't have the same keywords as Java and might well have a method called final, say, in one of their libraries. Removing the type declaration in a local/field declaration from the left hand side of = has more use cases than removing it from the right. There are a lot of examples of a method returning a value that you assign to a local/field. EG final x = someMethod( ... ) as opposed to final SomeType = someMethod( ... ). None of the ideas you are presenting for Java 7 are that new, you will find very similar proposals from many people on the web, some going back years, e.g. from myself: RFE 6389769, SSCO, and C3S. The later of the proposal referenced above, C3S, includes an alternative treatment for new defining a constructor instead of defining a static factory but retaining the type inference that the static factory has. This addresses the issue raised by others in this forum of why generate a static factory - just call the constructor. Just to re-iterate the most important point raised above, item 1, is a suggestion as to how new keywords can be added painlessly that is compatible with other languages. Posted by Howard Lovatt on January 18, 2007 at 05:56 PM PST # Although it solves the most common use case, I still would be disappointed about not getting type inference for local variables. Avoiding clutter in a method body seems well worth the minor inconvenience of using class types rather than instance types. In well-written code, most methods should be short, so this is a minor issue. I also agree with the previous poster that we shouldn't accept keywords being hard to add as an immutable rule. Adding keywords makes the code for new language features more readable, so we should figure out how to do it. Posted by Brian Slesinsky on January 18, 2007 at 08:22 PM PST # Following on from Brian Slesinsky post and his comment re. keywords. I started off trying to think of syntax without new keywords in RFE 6389769 and SSCO, but I kept hetting feedback that keywords are the essence of Java and hence version 3 of my proposal, C3S, I put in keywords and this has recieved largely positive comments. Posted by Howard Lovatt on January 18, 2007 at 09:01 PM PST # Posted by Stephen Colebourne on January 19, 2007 at 02:48 AM PST # Looking at this proposal, I can't help but think it's a special case for something more general - being able to define 'static interfaces' which is to say being able to require a class implement certain static methods. Doing that would move Java towards SmallTalk and other languages where classes are extendable. Sketching it out would look something like this: <code> package java.lang; static interface Creatable<C> { static C create(Object...); } class Foo implements Bar, static Creatable<Foo> { //how would you enforce creatable<Foo> though? public static Foo create(Object...) { //required by interface return new Foo(); } } //now use it for(Creatable<?> c : listOfFactories) { instances.add(c.create()); //what's the type of 'c' here? some kind of generated subclass of java.lang.Class? } </code> Of course, what's above isn't very coherent. Introducing extendable classes into Java might well be impossible, but what you're proposing does make me think there's a more general feature hiding in there somewhere. Posted by Andrew Thompson on January 20, 2007 at 08:33 AM PST # public interface Metaclass<I, C<I> extends Metaclass<I, C<I>> { <U> C<? extends U> asSubclass(C<U> clazz); C<? super I> getSuperclass(); I cast(Object obj); I newInstance(); ... } public class Class<T> implements Metaclass<T, Class<T>> { <U> Class<? extends U> asSubclass(Class<U> clazz) {...} Class<? super T> getSuperclass(); T cast(Object obj) {...} T newInstance() {...} ... } public interface Stringable<T> { force static T valueOf(String string); String toString(); } public interface Clonable<T> { force T clone(); } public interface Factory<T> { force this(); } Posted by Stefan Schulz on January 20, 2007 at 12:20 PM PST # import static java.util.HashMap.new; For the majority of cases, we know which implementation will by required. Defaults are a smart move. If I say I want a new Maplt;K,V>, you know 95% it's a new java.util.HashMap<K, V> I want (even if some PuTTY author calls it a cowboy algorithm). new Listlt;E> will be a new ArrayListlt;E>. new Font will be a new Font (ignoring PL&Fs). So why not just allow interfaces and classes to nominate a default implementation: interface Map<K,V> default new HashMap<K,V> { ... } ... Map<MyKey, MyValue> map = new(); I still haven't worked out what the problem is with inferring types in the currently legal syntax: Map<MyKey, MyValue> map = new HashMap(); Posted by Tom Hawtin on January 21, 2007 at 01:36 PM PST # Posted by Ricky Clarkson on January 21, 2007 at 05:30 PM PST # one of the examples you've given already compiles in Java 5, albeit with "unchecked warning": Map<String,List<Integer>> map = new HashMap(); Note, that you don't need any type inference to make it work, you just need some "smart rule" which tells that this assignment of freshly constructed raw type to a concrete instantiation of Map interface is actually _safe_, since pointer to this instance of raw type did not leak anywhere else and could not possibly become polluted with something else. So, unchecked warning should not have been emitted for this code in the first place. I admit, that this linear property of this particular constructor cannot be checked without additional changes in the language, however we could recruit some new annotation to do the trick. Posted by Roman Elizarov on January 22, 2007 at 01:45 AM PST # Posted by Michael Mangeng on January 23, 2007 at 01:20 AM PST # import java.util.Collections; import java.util.List; public abstract class NewClass<T> { public static final NewClass<List<String>> STATIC_INSTANCE = new NewClass<List<String>>(Collections.emptyList()) { }; private NewClass(final T t) {} } Posted by Steven Coco on January 23, 2007 at 07:13 PM PST # Posted by Steven Coco on January 23, 2007 at 07:20 PM PST # Posted by Stephen Colebourne on January 24, 2007 at 03:17 PM PST # Anyone still reading this entry?! @Stephen C.: Thanks a lot for responding with that help. I already did implement something just like that. I thought it might be a bug though. I will actually go look at the JLS and see how that type is inferred. Thanks again for the help. On this exact topic: in fact, on the exact method .emptyList(): I had previously filed a bug against javac about the implementation that's used by that method. I was writing a utility class of my own, and I wanted to do something just like .emptyList(); and I got stuck realizing it didn't seem possible. I peeked at that code and found a bug -- javac has a bug, and that method seems to rely on it. For those interested, that bug id is 6467183. Thanks. - Steev Coco. Posted by Ste on January 26, 2007 at 09:16 AM PST # Hi Peter, You write: "we need more static factories throughout the JDK". This is very true, but on the other hand, there are very serious problems with static factories in their current form. For example, if class A has a static factory called getInstance(), and we wish to mandate using that method, then the class's constructor must be private. Which means A can't be subclassed! Or, if the constructor isn't private (e.g., package-level access) and some other class B extends it, then --- if you forget to re-define getInstance() for B --- the expression B.getInstance() will return an instance of A! Another problem is that static factory methods are not "transparent", in the sense that you cannot introduce a new such method and have every existing clients immediately use it. Let's say we have an old class S and we wish to make it a singleton (or manage an instance pool, or whatever). We can add a new factory method getInstance(), but existing clients are now broken, since they still use the old constructor... The solution is to allow classes to control how instances are generated, by default; i.e., every call to new S() is always a factory call. By default, a factory is generated for each constructor; but developers can choose to specify their own factories (in which case no default factories are generated). The syntax I suggest is: class S { public static S instance = null; public static new() { if (instance == null) s = this(); return instance; } public S() { ... constructor code ... } } A few things to note: the keyword new is used as the name of factories. The keyword this is used for invoking the constructor from within the factory; constructors can only be invoked from within factories -- external clients never have direct access to constructors. However, existing code is not broken since the syntax used so far ("new S") now implies a factory invocation. We use "this" rather than "new S" to invoke the constructor in order to prevent a recursive call. Factories are generated by default only for regular classes, but can be manually added to abstract classes or even to interfaces. Think of adding a factory method to an interface like List: interface List { public static new(boolean synch, boolean randomAccess) { ... } ... } Which will return an instance of Vector, ArrayList, LinkedList or a synchronized LinkedList, depending on the arguments provided by the user. The user is now completely shielded from explicitly naming any specific implementation of List in his code. And if a future version of the JDK includes a new SuperDuperList class, any code using "new List(...)" with relevant parameters will immediately benefit from this new class. Factories can be viewed as an overriding of the "new" operator. However this is different than "new" overriding in C++, since there, you only get to control memory allocation; you cannot, for example, return an existing instance (or an instance of a subclass, etc.). In fact, this mechanism cannot be easily introduced into C++, since in C++ objects can be stored on the stack -- but here, we cannot know in advance what specific type will be returned by the factory, so the exact memory requirement is not known in advance. Additional details and discussion can be found in Better Construction with Factories. Posted by Tal Cohen on March 02, 2007 at 05:04 AM PST # var map = new HashMap<String,List<Integer>>();is the best syntax. It is the most beautiful and most obvious, and it could be used in for loops as well: for (var e : someEnum)I don't think that other suggestions could be used inside for loops. And what is the problem with adding a new "var" keyword (when compiled into JDK7)? Posted by Harri Pesonen on March 16, 2007 at 05:50 AM PDT # If introducing a new keyword is really a problem (breaks existing code), how about using "*" instead of "var"? After all, "*" is the universal "wildcard" symbol. So we'll have: * map = new HashMap<String,List<Integer>>(); or: for (* e : someEnum) Posted by Tal Cohen on March 16, 2007 at 09:44 AM PDT #
http://blogs.sun.com/ahe/entry/factory_methods
crawl-002
refinedweb
3,291
61.36
This post is second in a series of six. Need to go back to the beginning? Rewriting the automated test code we use at work to test against Dave Haeffner's mock site, The-Internet: Login Page. Please note: I have been an automated tester only since March 2015. This is only my best guess on how to translate what we use at work. I am writing this blog to deepen my own understanding of automated testing. If there are any glaring errors about Java, OO, WebDriver, or anything else please let me know in the Comments section! The-Internet: Common Utilities: methods, exceptions and logging Part Two: Drafting the Common Utilities Library The Selenium WebDriver API provides the basic methods to manipulate a brower to perform actions, such as navigating to a web page, but it doesn't have all the functionality we would need. What if we wanted to add in exception handling, such as if the web page was not found? What if we wanted to throw a customized error to a log file when the page was not found? What if, even upon a success, we wanted to write a message to the log? A Common Utilities library, such as one they are using at the moment at my workplace, can be developed to handle these cases. Each Selenium API method is wrapped in try / catch / throw blocks for exception handling, built-in with logging functionality. When things go wrong, clear and concise error messages will save a lot of time debugging if the issue was with the server, with the code of the site, or the tests themselves. If you want to skip ahead to see an example of a CommonUtils library, you can view one at: test/java/utils/CommonUtils.java, which closely resembles the one drafted by the automation test team at work. For this project, we will test against The-Internet. About The-Internet Dave Haeffner wrote a test site called The-Internet ( ) that entry level automated testers could use to test against. For this blog post, I will be examining his Login Page example. If you want more information about Dave, you can view my blog entry about him. Automated Test Suite code to test The-Internet To deepen my understanding of automation test suites, over the next month or so I will be examining and rewriting code to test against The-Internet. Feel free to follow along, make suggestions, and ask questions about the code I am writing in the Comments section of this blog! I have only been writing code on-the-job since March, so there are bound to be errors of interpretation. All code I develop will be uploaded to my GitHub account at - WebDriver_TheInternet_Basics: Quick-and-dirty code to test the basics of The-Internet login page with SimpleManipulationWebElements.java - WebDriver_TheInternet_Advanced: The beginnings of the test suite for The-Internet. Creating Methods to Navigate to a Web PageNavigating to The-Internet's Login page is pretty simple with WebDriver. All it takes is one driver.get statement in order to navigate to the login page: driver.get(" But what if you wanted to add functionality to write to the log console every time you use WebDriver to navigate to a web page? This means you would have to enter two lines of code per driver.get statement. System.out.println("Navigating to: driver.get(" Let's say you also wanted to add even more: - Logging functionality when an action is performed - Catch any errors if the action failed - Throw an error to the logs detailing if an error ever happened - Document the Thread ID, useful when dealing with multithreaded systems that are running many Selenium WebDriver tests in parallel. - Include any wait statements, if a page is known to be slow loading. To satisfy all these new requirements, at work they came up with the following method for their CommonUtils library, navigateToURL: public void navigateToURL(String URL) { System.out.println("Navigating to: " + URL); System.out.println("Thread id = " + Thread.currentThread().getId()); try { _driver.navigate().to(URL); } catch (Exception e) { System.out.println("URL did not load: " + URL); throw new TestException("URL did not load"); } } To use this method, we can use this method in a test, passing in the URL as a String: navigateToURL(" Now imagine if you had a whole library where all the Selenium WebDriver functions are wrapped in try / catch / throw blocks, logging functionality is added, threads have identification numbers listed, and any optional wait statements are included. Methods in the CommonUtils Library These are the methods in the CommonUtility we can use: - navigateToURL(String URL) - getPageTitle() - getElement(By selector) - sendKeys(By selector, String value) - clearField(WebElement element) - click(By selector) - waitForElementToBeClickable(By selector ) - waitForElementToBeVisible(By selector) How to use the Methods: Selectors can be found By Id or By CSS Selector. If we wanted to grab the Username textbox, the Password textbox, or the Login button, we could: - Username: getElement(By.cssSelector("[name='username']") - Password: getElement(By.cssSelector("[name='password']") - Login Button: getElement(By.cssSelector(""[type='submit'][class='radius']"") ... And wherever these CommonUtils methods are used, we need to make sure to: import utils.CommonUtils;NEXT: Storing Constanst: public final vs [ 3 ] month and counting! Please note: 'Adventures in Automation' is a personal blog about automated testing. It is not an official blog of Fitbit.com.
https://www.tjmaher.com/2015/06/creating-common-utilities-for-webdriver.html
CC-MAIN-2022-21
refinedweb
894
53.71
Add optional 'format' argument to pygame.image.save == Arnau Sanchez, 2010-05-19 11:22:25 -0700 {{{ Sometimes we need to store a surface image into a string instead of a filename. I tested with StringIO and it worked: import StringIO fd = StringIO.StringIO() pygame.image.save(surface, fd) print len(fd.getvalue()) 1334 However, since we have no real filename, we cannot set the file format. That's why I propose to add a third optional argument that forces the function to use a given format: pygame.image.save(Surface, filename, format="TGA"): return None }}} This is a good idea. I've marked this as something for pygame 1.9.2. Thanks! Removing version: unspecified (automated comment)
https://bitbucket.org/pygame/pygame/issues/48/add-optional-format-argument-to
CC-MAIN-2018-26
refinedweb
118
60.41
| Join Last post 03-27-2008 2:42 PM by Zenuke. 6 replies. Sort Posts: Oldest to newest Newest to oldest I have successfully launched a sliverlight 1.0 app and now I am up to the task of trying to create a silverlight webpart. It's nothing fancy and it follows the ideas of the helloworld webpart i've seen. Everything seems ok except the project will not recognize the XAML files. Everything with in the XAML file is blue as if VS2008 has no idea what it is. The project will not build because of this. I've built other webparts usingthe VB CLass library and adding a bunch of Imports. this is the error Error 1 The tag 'Canvas' does not exist in XML namespace ''. Line 3 Position 13. C:\Documents and Settings\cacarey\My Documents\Visual Studio 2008\Projects\ClassLibrary1\ClassLibrary1\ClientBin\sl\HelloSilverlight10.xaml 3 13 ClassLibrary1 Now I was able to fix the above error by change the XMLNS= line to be 2006/xaml/presentation which completely breaks other XAML things I have done when it said /2007/ on it. I get erros like "All objects added to an IDictionary must have a key attribute or some other type of associated with them." I have no idea what this means or how to fix it other than adding an x:key="" to everything (which I have no idea what that will do) What am I doing wrong? Completely silly if you can't do this in webparts without using some old code version or something. HI It seems that you are using a non existing key ... Did you read this : I understand what I'm missing, I don't undertand why i Need that now, I did not in the past. what is strange in the application I wrote before using silverlight, this was never an issue. With this I can't even use things like onMouseDown="function" it doesn't allow me. I have to make all the hadlers in the javascript. So many things I did in Silverlight I can no longer do or I need to use a roundabout way to do it and this is the only thing that changed xmlns="" There must be way to do this, I don't feel I should need to hand code everything when I didn't need to before. Hi did you installed Microsoft Silverlight Tools Beta 1 for Visual Studio 2008 ? As far as i know , you can add onMouseDown to the elements , (as in the silverlight 1.0 SDK) I want to mention here is that there is a community for silverlight and you can login with the same ID that used in this site.. check : I really didn't worked much with silverlight , but i used silverlight 1.0 in a project ( before 1 month ). I found a work around is to just build the SL and the webpart that adds the SL in different projects and just make them meet on the MOSS 07 server. Now I need to find out how to get SL to interact with MOSS07 I did install the Beta 1 tools. Still working mainly with SL+JS but attempting to learn the VB side now. I loved SL+JS :( I found that you need to use Silverlight Blueprint for SharePoint. you can see this blog post from the sharepoint team : Regards, Eek, this looks beyond me at the moment. Does anyone have a much more basic example of a silverlight webpart that at least accesses something simple from MOSS07?? Advertise on ASP.NET About this Site © 2008 Microsoft Corporation. All Rights Reserved. | Terms of Use | Trademarks | Privacy Statement
http://forums.asp.net/p/1238926/2259524.aspx
crawl-001
refinedweb
614
80.51
Mapping memory Memory-mapped I/O is something you can do reasonably well in standard C and C++. Device drivers communicate with peripheral devices through device registers. A driver sends commands or data to a device by storing into its device register, or retrieves status or data from a device by reading from its device register.. Some processors use port-mapped I/O, which maps device registers to locations in a separate address space, typically smaller than the conventional memory space. On these processors, programs must use special machine instructions, such as the in and out instructions of the Intel x86 processors, to move data to or from device registers. To a C programmer, port-mapped device registers don't look quite like ordinary data. The C and C++ standards are silent about port-mapped I/O. Programs that perform port-mapped I/O must use some nonstandard, platform-specific language or library extensions, or worse, assembly code. On the other hand, memory-mapped I/O is something you can do reasonably well within the standard language dialects. This month, I'll look at different approaches you can use to refer to memory-mapped device registers. Device register types Some device registers might occupy just a byte; others may occupy a word or more. In C or C++, the simplest representation for a single device register is as an object of an appropriately sized and signed integer type. For example, you might declare a one-byte register as a char or a two-byte register as an unsigned short. For example, the ARM Evaluator-7T is a single-board computer with a small assortment of memory-mapped peripheral devices. The board's documentation refers to the device registers as special registers. The special registers span 64KB starting at address 0x03FF0000. The memory is byte-addressable, but each register is a four-byte word aligned to an address that's a multiple of four. You could manipulate each special register as if it were an int or unsigned int. Some programmers prefer to use a type that specifies the physical size of the register more overtly, such as int32_t or uint32_t. (Types such as int32_t and uint32_t are defined in the C99 header <stdint.h>.)1 I prefer to use a symbolic type whose name conveys the meaning of the type rather than its physical extent, such as: typedef unsigned int special_register; Special registers are actually volatile entities — they may change state in ways that the compiler can't detect. Therefore, the typedef should be an alias for a volatile-qualified type, as in: typedef unsigned int volatile special_register; Many devices interact through a small collection of device registers, rather than just one. For example, the Evaluator-7T uses five special registers to control the two integrated timers: - TMOD: timer mode register - TDATA0: timer 0 data register - TDATA1: timer 1 data register - TCNT0: timer 0 count register - TCNT1: timer 1 count register You can represent the timer registers as a struct defined as: typedef struct dual_timers dual_timers; struct dual_timers { special_register TMOD; special_register TDATA0; special_register TDATA1; special_register TCNT0; special_register TCNT1; }; The typedef before the struct definition elevates the name dual_timers from a mere tag to a full-fledged type name.2 I'd rather spell TCNT0 as count0, but TCNT0 is the name used throughout the product documentation, so it's probably best not to change it. In C++, I'd define this struct as a class with appropriate member functions. Whether dual_timers is a C struct or a C++ class doesn't affect the following discussion. Positioning device registers Some compilers provide language extensions that will let you position an object at a specified memory address. For example, using the TASKING C166/ST10 C Cross-Compiler's _at attribute you can write a global declaration such as: unsigned short count _at(0xFF08); to declare count as a memory-mapped device register residing at address 0xFF08. Other compilers offer #pragma directives to do something similar. However, the _at attribute and #pragma directives are nonstandard. Each compiler with such extensions is likely to support something different. Standard C and C++ don't let you declare a variable so that it resides at a specified address. The common idiom for accessing a device register is to use a pointer whose value contains the register's address. For example, the timer registers on the Evaluator-7T reside at address 0x03FF6000. A program can access these registers via a pointer that points to that address. You can define that pointer as a macro, as in: #define timers ((dual_timers *)0x03FF6000) or as a constant pointer, as in: dual_timers *const timers     = (dual_timers *)0x03FF6000; Either way you define timers, you can use it to reach the timer registers. For example,); Weighing the alternatives These two pointer definitions—the macro and the constant object—are largely interchangeable. However, they produce slightly different behavior and, on some platforms, generate slightly different machine code. As I explained in an earlier column, the macro preprocessor is a distinct compilation phase.3 The preprocessor does macro substitution before the compiler does any other symbol processing. For example, given the macro definition for timers, the preprocessor transforms: timers->TMOD &= ~(TE0 | TE1); into: ((dual_timers *)0x03FF6000)->TMOD     &= ~(TE0 | TE1); Later compilation phases never see the macro symbol timers; they see only the source text after macro substitution. Many compilers don't pass macro names on to their debuggers, in which case macro names are invisible to the debugger. Macros have an even more serious problem: macro names don't observe the scope rules that apply to other names. For example, you can't restrict a macro to a local scope. Defining a macro within a function, as in: void timer_handler()     {     #define timers ((dual_timers *)0x03FF6000)     ...     } doesn't make the macro local to the function. The macro is still effectively global. Similarly, you can't declare a macro as a member of a C++ class or namespace. Actually, macro names are worse than global names. Names declared in inner scopes can temporarily hide names from outer scopes, but they can't hide macro names. Consequently, macros might substitute in places where you don't expect them to. Declaring timers as a constant pointer avoids both of these problems. The name should be visible in your debugger, and if you declare it in a nonglobal scope, it should stay there. On the other hand, with some compilers on some platforms, declaring timers as a constant pointer might—I emphasize might—produce slightly slower and larger code. The compiler might produce different code if you define the pointer globally or locally. It might produce different code if you compile the definition in C as opposed to C++. I'll explain what the differences are and why they occur in my next column. Dan Saks Saks is president of Saks & Associates, a C/C++ training and consulting company. You can write to him at dsaks@wittenberg.edu. - Barr, Michael, "Introduction to fixed-width integers, Embedded.com. January 2004. - Saks, Dan, "Tag Names vs. Type Names," Embedded Systems Programming, September 2002, p. 7. - Saks, Dan, "Symbolic Constants," Embedded Systems Programming, November 2001, p. 55. Please confirm the information below before signing in.{* #socialRegistrationForm *} {* firstName *} {* lastName *} {* displayName *} {* emailAddress *} {* addressCountry *} {* companyName *} {* ednembJobfunction *} {* jobFunctionOther *} {* ednembIndustry *} {* industryOther *}
https://www.embedded.com/electronics-blogs/programming-pointers/4025002/Mapping-memory
CC-MAIN-2019-09
refinedweb
1,210
53.61
README ¶ Bigslice Bigslice is a serverless cluster data processing system for Go. Bigslice exposes composable API that lets the user express data processing tasks in terms of a series of data transformations that invoke user code. The Bigslice runtime then transparently parallelizes and distributes the work, using the Bigmachine library to create an ad hoc cluster on a cloud provider. - website: bigslice.io - API documentation: godoc.org/github.com/grailbio/bigslice - issue tracker: github.com/grailbio/bigslice/issues Developing Bigslice Bigslice uses Go modules to capture its dependencies; no tooling other than the base Go install is required. $ git clone $ cd bigslice $ GO111MODULE=on go test If tests fail with socket: too many open files errors, try increasing the maximum number of open files. $ ulimit -n 2000 Documentation ¶ Overview ¶ Package bigslice implements a distributed data processing system. Users compose computations by operating over large collections ("big slices") of data, transforming them with a handful of combinators. While users express computations using collections-style operations, bigslice takes care of the details of parallel execution and distribution across multiple machines. Bigslice jobs can run locally, but uses bigmachine for distribution among a cluster of compute nodes. In either case, user code does not change; the details of distribution are handled by the combination of bigmachine and bigslice. Because Go cannot easily serialize code to be sent over the wire and executed remotely, bigslice programs have to be written with a few constraints: 1. All slices must be constructed by bigslice funcs (bigslice.Func), and all such functions must be instantiated before bigslice.Start is called. This rule is easy to follow: if funcs are global variables, and bigslice.Start is called from a program's main, then the program is compliant. 2. The driver program must be compiled on the same GOOS and GOARCH as the target architecture. When running locally, this is not a concern, but programs that require distribution must be run from a linux/amd64 binary. Bigslice also supports the fat binary format implemented by github.com/grailbio/base/fatbin. The bigslice tool (github.com/grailbio/bigslice/cmd/bigslice) uses this package to compile portable fat binaries. Some Bigslice operations may be annotated with runtime pragmas: directives for the Bigslice runtime. See Pragma for details. User provided functions in Bigslice ¶ Functions provided to the various bigslice combinators (e.g., bigslice.Map) may take an additional argument of type context.Context. If specified, then the lifetime of the context is tied to that of the underlying bigslice task. Additionally, the context carries a metrics scope (github.com/grailbio/base/bigslice/metrics.Scope) which can be used to update metric values during data processing. Index ¶ - func FuncLocations() []string - func FuncLocationsDiff(lhs, rhs []string) []string - func Helper() - func String(slice Slice) string - type Accumulator - type Dep - type FuncValue - - - type Invocation - - type Name - - - type Partitioner - type Pragma - - type Pragmas - - type ShardType - type Slice - func Cache(ctx context.Context, slice Slice, prefix string) Slice - func CachePartial(ctx context.Context, slice Slice, prefix string) Slice - func Cogroup(slices ...Slice) Slice - func Const(nshard int, columns ...interface{}) Slice - func Filter(slice Slice, pred interface{}, prags ...Pragma) Slice - func Flatmap(slice Slice, fn interface{}, prags ...Pragma) Slice - func Fold(slice Slice, fold interface{}) Slice - func Head(slice Slice, n int) Slice - func Map(slice Slice, fn interface{}, prags ...Pragma) Slice - func Prefixed(slice Slice, prefix int) Slice - func ReadCache(ctx context.Context, typ slicetype.Type, numShard int, prefix string) Slice - func ReaderFunc(nshard int, read interface{}, prags ...Pragma) Slice - func Reduce(slice Slice, reduce interface{}) Slice - func Repartition(slice Slice, partition interface{}) Slice - func Reshard(slice Slice, nshard int) Slice - func Reshuffle(slice Slice) Slice - func Scan(slice Slice, scan func(shard int, scanner *sliceio.Scanner) error) Slice - func ScanReader(nshard int, reader func() (io.ReadCloser, error)) Slice - func Unwrap(slice Slice) Slice - func WriterFunc(slice Slice, write interface{}) Slice - Bugs Examples ¶ Constants ¶ Variables ¶ Functions ¶ func FuncLocations ¶ FuncLocations returns a slice of strings that describe the locations of Func creation, in the same order as the Funcs registry. We use this to verify that worker processes have the same Funcs. Note that this is not a precisely correct verification, as it's possible to define multiple Funcs on the same line. However, it's good enough for the scenarios we have encountered or anticipate. func FuncLocationsDiff ¶ FuncLocationsDiff returns a slice of strings that describes the differences between lhs and rhs locations slices as returned by FuncLocations. The slice is a unified diff between the slices, so if you print each element on a line, you'll get interpretable output. For example: for _, edit := FuncLocationsDiff([]string{"a", "b", "c"}, []string{"a", "c"}) { fmt.Println(edit) } will produce: a - b c If the slices are identical, it returns nil. func Helper ¶ func Helper() Helper is used to mark a function as a helper function: names for newly created slices will be attributed to the caller of the function instead of the function itself. Types ¶ type Accumulator ¶ type Accumulator interface { // Accumulate the provided columns of length n. Accumulate(in frame.Frame, n int) // Read a batch of accumulated values into keys and values. These // are slices of the key type and accumulator type respectively. Read(keys, values reflect.Value) (int, error) } An Accumulator represents a stateful accumulation of values of a certain type. Accumulators maintain their state in memory. Accumulators should be read only after accumulation is complete. type Dep ¶ type Dep struct { Slice Shuffle bool Partitioner Partitioner // Expand indicates that each shard of a shuffle dependency (i.e., // all the shards of a given partition) should be expanded (i.e., // not merged) when handed to the slice implementation. This is to // support merge-sorting of shards of the same partition. Expand bool } A Dep is a Slice dependency. Deps comprise a slice and a boolean flag determining whether this is represents a shuffle dependency. Shuffle dependencies must perform a data shuffle step: the dependency must partition its output according to the Slice's partitioner, and, when the dependent Slice is computed, the evaluator must pass in Readers that read a single partition from all dependent shards. If Shuffle is true, then the provided partitioner determines how the output is partitioned. If it is nil, the default (hash by first column) partitioner is used. type FuncValue ¶ type FuncValue struct { // contains filtered or unexported fields } A FuncValue represents a Bigslice function, as returned by Func. func Func ¶ Func creates a bigslice function from the provided function value. Bigslice funcs must return a single Slice value. Funcs provide bigslice with a means of dynamic abstraction: since Funcs can be invoked remotely, dynamically created slices may be named across process boundaries. func (*FuncValue) Apply ¶ Apply invokes the function f with the provided arguments, returning the computed Slice. Apply panics with a type error if argument type or arity do not match. func (*FuncValue) Exclusive ¶ Exclusive marks this func to require mutually exclusive machine allocation. NOTE: This is an experimental API that may change. func (*FuncValue) In ¶ In returns the i'th argument type of function f. func (*FuncValue) Invocation ¶ func (f *FuncValue) Invocation(location string, args ...interface{}) Invocation Invocation creates an invocation representing the function f applied to the provided arguments. Invocation panics with a type error if the provided arguments do not match in type or arity. type Invocation ¶ type Invocation struct { Index uint64 Func uint64 Args []interface{} Exclusive bool Location string } Invocation represents an invocation of a Bigslice func of the same binary. Invocations can be transmitted across process boundaries and thus may be invoked by remote executors. Each invocation carries an invocation index, which is a unique index for invocations within a process namespace. It can thus be used to represent a particular function invocation from a driver process. Invocations must be created by newInvocation. func (Invocation) Invoke ¶ func (i Invocation) Invoke() Slice Invoke performs the Func invocation represented by this Invocation instance, returning the resulting slice. func (Invocation) String ¶ func (inv Invocation) String() string type Name ¶ type Name struct { // Op is the operation that the slice performs (e.g. "reduce", "map") Op string // File is the file in which the slice was defined. File string // Line is the line in File at which the slice was defined. Line int // Index disambiguates slices created on the same File and Line. Index int } Name is a unique name for a slice, constructed with useful context for diagnostic or status display. type Partitioner ¶ A Partitioner is used to assign partitions to rows in a frame. type Pragma ¶ type Pragma interface { // Procs returns the number of procs a slice task needs to run. It is // superceded by Exclusive and clamped to the maximum number of procs per // machine. Procs() int // Exclusive indicates that a slice task should be given // exclusive access to the underlying machine. Exclusive() bool // Materialize indicates that the result of the slice task should be // materialized, i.e. break pipelining. Materialize() bool } Pragma comprises runtime directives used during bigslice execution. Exclusive is a Pragma that indicates the slice task should be given exclusive access to the machine that runs it. Exclusive takes precedence over Procs. ExperimentalMaterialize is a Pragma that indicates the slice task results should be materialized, i.e. not pipelined. You may want to use this to materialize and reuse results of tasks that would normally have been pipelined. It is tagged "experimental" because we are considering other ways of achieving this. TODO(jcharumilind): Consider doing this automatically for slices on which multiple slices depend. type Pragmas ¶ Pragmas composes multiple underlying Pragmas. func (Pragmas) Materialize ¶ Materialize implements Pragma. type ShardType ¶ ShardType indicates the type of sharding used by a Slice. const ( // HashShard Slices are partitioned by an (unspecified) // hash of an record. That is, the same record should // be assigned a stable shard number. HashShard ShardType = iota // RangeShard Slices are partitioned by the range of a key. The key // is always the first column of the slice. RangeShard ) type Slice ¶ type Slice interface { slicetype.Type // Name returns a unique (composite) name for this Slice that also has // useful context for diagnostic or status display. Name() Name // NumShard returns the number of shards in this Slice. NumShard() int // ShardType returns the sharding type of this Slice. ShardType() ShardType // NumDep returns the number of dependencies of this Slice. NumDep() int // Dep returns the i'th dependency for this Slice. Dep(i int) Dep // Combiner is an optional function that is used to combine multiple values // with the same key from the slice's output. No combination is performed // if Nil. Combiner() slicefunc.Func // Reader returns a Reader for a shard of this Slice. The reader itself // computes the shard's values on demand. The caller must provide Readers // for all of this shard's dependencies, constructed according to the // dependency type (see Dep). Reader(shard int, deps []sliceio.Reader) sliceio.Reader } A Slice is a shardable, ordered dataset. Each slice consists of zero or more columns of data distributed over one or more shards. Slices may declare dependencies on other slices from which it is computed. In order to compute a slice, its dependencies must first be computed, and their resulting Readers are passed to a Slice's Reader method. Since Go does not support generic typing, Slice combinators perform their own dynamic type checking. Schematically we write the n-ary slice with types t1, t2, ..., tn as Slice<t1, t2, ..., tn>. Types that implement the Slice interface must be comparable. func Cache ¶ Cache caches the output of a slice to the given file prefix. Cached data are stored as "prefix-nnnn-of-mmmm" for shards nnnn of mmmm. When the slice is computed, each shard is encoded and written to a separate file with this prefix. If all shards exist, then Cache shortcuts computation and instead reads directly from the previously computed output. The user must guarantee cache consistency: if the cache could be invalid (e.g., because of code changes), the user is responsible for removing existing cached files, or picking a different prefix that correctly represents the operation to be cached. Cache uses GRAIL's file library, so prefix may refer to URLs to a distributed object store such as S3. func CachePartial ¶ CachePartial caches the output of the slice to the given file prefix (it uses the same file naming scheme as Cache). However, unlike Cache, if CachePartial finds incomplete cached results (from an earlier failed or interrupted run), it will use them and recompute only the missing data. WARNING: The user is responsible for ensuring slice's contents are deterministic between bigslice runs. If keys are non-deterministic, for example due to pseudorandom seeding based on time, or reading the state of a modifiable file in S3, CachePartial produces corrupt results. As with Cache, the user must guarantee cache consistency. func Cogroup ¶ Cogroup returns a slice that, for each key in any slice, contains the group of values for that key, in each slice. Schematically: Cogroup(Slice<tk1, ..., tkp, t11, ..., t1n>, Slice<tk1, ..., tkp, t21, ..., t2n>, ..., Slice<tk1, ..., tkp, tm1, ..., tmn>) Slice<tk1, ..., tkp, []t11, ..., []t1n, []t21, ..., []tmn> It thus implements a form of generalized JOIN and GROUP. Cogroup uses the prefix columns of each slice as its key; keys must be partitionable. TODO(marius): don't require spilling to disk when the input data set is small enough. TODO(marius): consider providing a version that returns scanners in the returned slice, so that we can stream through. This would require some changes downstream, however, so that buffering and encoding functionality also know how to read scanner values. Example ¶ Output: 0 [cero zero] [0] 1 [one uno] [1] 2 [two] [4] 3 [three] [9] 4 [] [16] 5 [] [25] 6 [] [36] func Const ¶ Const returns a Slice representing the provided value. Each column of the Slice should be provided as a Go slice of the column's type. The value is split into nshard shards. func Filter ¶ Filter returns a slice where the provided predicate is applied to each element in the given slice. The output slice contains only those entries for which the predicate is true. The predicate function should receive each column of slice and return a single boolean value. Schematically: Filter(Slice<t1, t2, ..., tn>, func(t1, t2, ..., tn) bool) Slice<t1, t2, ..., tn> func Flatmap ¶ Flatmap returns a Slice that applies the function fn to each record in the slice, flattening the returned slice. That is, the function fn should be of the form: func(in1 inType1, in2 inType2, ...) (out1 []outType1, out2 []outType2) Schematically: Flatmap(Slice<t1, t2, ..., tn>, func(v1 t1, v2 t2, ..., vn tn) ([]r1, []r2, ..., []rn)) Slice<r1, r2, ..., rn> func Fold ¶ Fold returns a slice that aggregates values by the first column using a custom aggregation function. For an input slice Slice<t1, t2, ..., tn>, Fold requires that the provided accumulator function follow the form: func(accum acctype, v2 t2, ..., vn tn) acctype The function is invoked once for each slice element with the same value for column 1 (t1). On the first invocation, the accumulator is passed the zero value of its accumulator type. Fold requires that the first column of the slice is partitionable. See the documentation for Keyer for more details. Schematically: Fold(Slice<t1, t2, ..., tn>, func(accum acctype, v2 t2, ..., vn tn) acctype) Slice<t1, acctype> BUG(marius): Fold does not yet support slice grouping func Head ¶ Head returns a slice that returns at most the first n items from each shard of the underlying slice. Its type is the same as the provided slice. func Map ¶ Map transforms a slice by invoking a function for each record. The type of slice must match the arguments of the function fn. The type of the returned slice is the set of columns returned by fn. The returned slice matches the input slice's sharding, but is always hash partitioned. Schematically: Map(Slice<t1, t2, ..., tn>, func(v1 t1, v2 t2, ..., vn tn) (r1, r2, ..., rn)) Slice<r1, r2, ..., rn> func Prefixed ¶ Prefixed returns a slice with the provided prefix. A prefix determines the number of columns (starting at 0) in the slice that compose the key values for that slice for operations like reduce. func ReadCache ¶ ReadCache reads from an existing cache but does not write any cache itself. This may be useful if you want to reuse a cache from a previous computation and fail if it does not exist. typ is the type of the cached and returned slice. You may construct typ using slicetype.New or pass a Slice, which embeds slicetype.Type. func ReaderFunc ¶ ReaderFunc returns a Slice that uses the provided function to read data. The function read must be of the form: func(shard int, state stateType, col1 []col1Type, col2 []col2Type, ..., colN []colNType) (int, error) This returns a slice of the form: Slice<col1Type, col2Type, ..., colNType> The function is invoked to fill a vector of elements. col1, ..., colN are preallocated slices that should be filled by the reader function. The function should return the number of elements that were filled. The error EOF should be returned when no more data are available. ReaderFunc provides the function with a zero-value state upon the first invocation of the function for a given shard. (If the state argument is a pointer, it is allocated.) Subsequent invocations of the function receive the same state value, thus permitting the reader to maintain local state across the read of a whole shard. func Reduce ¶ Reduce returns a slice that reduces elements pairwise. Reduce operations must be commutative and associative. Schematically: Reduce(Slice<k, v>, func(v1, v2 v) v) Slice<k, v> The provided reducer function is invoked to aggregate values of type v. Reduce can perform map-side "combining", so that data are reduced to their aggregated value aggressively. This can often speed up computations significantly. The slice to be reduced must have exactly 1 residual column: that is, its prefix must leave just one column as the value column to be aggregated. TODO(marius): Reduce currently maintains the working set of keys in memory, and is thus appropriate only where the working set can fit in memory. For situations where this is not the case, Cogroup should be used instead (at an overhead). Reduce should spill to disk when necessary. TODO(marius): consider pushing combiners into task dependency definitions so that we can combine-read all partitions on one machine simultaneously. func Repartition ¶ Repartition (re-)partitions the slice according to the provided function fn, which is invoked for each record in the slice to assign that record's shard. The function is supplied with the number of shards to partition over as well as the column values; the assigned shard is returned. Schematically: Repartition(Slice<t1, t2, ..., tn> func(nshard int, v1 t1, ..., vn tn) int) Slice<t1, t2, ..., tn> func Reshard ¶ Reshard returns a slice that is resharded to the given number of shards; this is done by re-shuffling to the provided number of shards. func Reshuffle ¶ Reshuffle returns a slice that shuffles rows by prefix so that all rows with equal prefix values end up in the same shard. Rows are not sorted within a shard. The output slice has the same type as the input. TODO: Add ReshuffleSort, which also sorts keys within each shard. func Scan ¶ Scan invokes a function for each shard of the input Slice. It returns a unit Slice: Scan is inteded to be used for its side effects. func ScanReader ¶ func ScanReader(nshard int, reader func() (io.ReadCloser, error)) Slice ScanReader returns a slice of strings that are scanned from the provided reader. ScanReader shards the file by lines. Note that since ScanReader is unaware of the underlying data layout, it may be inefficient for highly parallel access: each shard must read the full file, skipping over data not belonging to the shard. func Unwrap ¶ Unwrap returns the underlying slice if the provided slice is used only to amend the type of the slice it composes. TODO(marius): this is required to properly compile slices that use the prefix combinator; we should have a more general and robust solution to this. func WriterFunc ¶ WriterFunc returns a Slice that is functionally equivalent to the input Slice, allowing for computation with side effects by the provided write function. The write function must be of the form: func(shard int, state stateType, err error, col1 []col1Type, col2 []col2Type, ..., colN []colNType) error where the input slice is of the form: Slice<col1Type, col2Type, ..., colNType> The write function is invoked with every read of the input Slice. Each column slice will be of the same length and will be populated with the data from the read. For performance, the passed column slices share memory with the internal frame of the read. Do not modify the data in them, and assume that they will be modified once write returns. The write function should return a non-nil error if there is a problem writing, e.g. the write function encounters and error while writing to a file. It should otherwise return nil. Any error from the read, including EOF, will be passed as err to the write function. Note that err may be EOF when column lengths are >0, similar to the semantics of sliceio.Reader.Read. If the write function performs I/O, it is recommended that the I/O be buffered to allow downstream computations to progress. WriterFunc provides the function with a zero-value state upon the first invocation of the function for a given shard. (If the state argument is a pointer, it is allocated.) Subsequent invocations of the function receive the same state value, thus permitting the writer to maintain local state across the write of the whole shard.
https://pkg.go.dev/github.com/grailbio/bigslice?utm_source=godoc
CC-MAIN-2021-21
refinedweb
3,617
56.96
import "os/exec". Code: path, err := exec.LookPath("fortune") if err != nil { log.Fatal("installing fortune is in your future") } fmt.Printf("fortune is available at %s\n", path). A Cmd cannot be reused after calling its Run, Output or CombinedOutput methods.. Code: cmd := exec.Command("tr", "a-z", "A-Z") cmd.Stdin = strings.NewReader("some input") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { log.Fatal(err) } fmt.Printf("in all caps: %q\n", out.String()) Code: cmd := exec.Command("prog") cmd.Env = append(os.Environ(), "FOO=duplicate_value", // ignored "FOO=actual_value", // this value is used ) if err := cmd.Run(); err != nil { log.Fatal(err) } func CommandContext(ctx context.Context, name string, arg ...string) *Cmd CommandContext is like Command but includes a context. The provided context is used to kill the process (by calling os.Process.Kill) if the context becomes done before the command completes on its own. Code: ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil { // This will fail after 100 milliseconds. The 5 second sleep // will be interrupted. } func (c *Cmd) CombinedOutput() ([]byte, error) CombinedOutput runs the command and returns its combined standard output and standard error. Code: cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr") stdoutStderr, err := cmd.CombinedOutput() if err != nil { log.Fatal(err) } fmt.Printf("%s\n", stdoutStderr) func (c *Cmd) Output() ([]byte, error) Output runs the command and returns its standard output. Any returned error will usually be of type *ExitError. If c.Stderr was nil, Output populates ExitError.Stderr. Code: out, err := exec.Command("date").Output() if err != nil { log.Fatal(err) } fmt.Printf("The date is %s\n", out). Code: cmd := exec.Command("sleep", "1") log.Printf("Running command and waiting for it to finish...") err := cmd.Run() log.Printf("Command finished with error: %v", err) func (c *Cmd) Start() error Start starts the specified command but does not wait for it to complete. The Wait method will return the exit code and release associated resources once the command exits. Code: cmd := exec.Command("sleep", "5") err := cmd.Start() if err != nil { log.Fatal(err) } log.Printf("Waiting for command to finish...") err = cmd.Wait() log.Printf("Command finished with error: %v", err). Code: cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr") stderr, err := cmd.StderrPipe() if err != nil { log.Fatal(err) } if err := cmd.Start(); err != nil { log.Fatal(err) } slurp, _ := ioutil.ReadAll(stderr) fmt.Printf("%s\n", slurp) if err := cmd.Wait(); err != nil { log.Fatal(err) }. Code:. Code: c.Stdin is not an *os.File, Wait also waits for the I/O loop copying from c.Stdin into the process's standard input to complete. Wait releases any resources associated with the Cmd. type Error struct { Name string Err error } Error records the name of a binary that failed to be executed and the reason it failed. func (e *Error) Error() string } An ExitError reports an unsuccessful exit by a command. func (e *ExitError) Error() string
https://static-hotlinks.digitalstatic.net/os/exec/
CC-MAIN-2018-51
refinedweb
513
55.61
Hi everyone, i’m new to coding, i think it’s a silly question but i don’t know what’s the error here, please helppp I need help please! Hi everyone, You need to be careful about tabs because python uses them to put code in the proper block. Your code says that the “for” is part of an import block. It is not. so if the “for” aligned with the import, the code runs properly: import random for i in range(5): print(random.random()) This is what the error message is actually saying, though often error messages can be hard to interpret. This question might be better in a python forum, as it is a language question, not an editor question
https://discuss.atom.io/t/i-need-help-please/43321
CC-MAIN-2018-30
refinedweb
124
71.44
Introduction We have done lots of IL grammar so far. As I warned you earlier, Reverse engineering could be exercising both offensive and defensive motives. Now, it is time to crack some real things with the association of IL opcode grammar knowledge. Ideally, this article taught us how to reveal sensitive information from the source code in order to bypass security constraints such as user credentials validation, extending software trial evaluation period and bypassing serial keys limitation without actually having the access of real source code. We are not going to perform sort of binary or byte code patching in the context reversing the code as we have typically, employed hex editor, IDA Pro or ollydb software tools in respective of playing with real bytes but in this article, we would be confronted only with IL opcodes instead in order to divert the actual program logic flows as per out requirement to achieve the aforesaid objective. Cracking Serial Keys Software are usually developed by means of financial points of view in this commercial world. That is, the vendor who developed the software won’t be giving out the software free of cost. Aside from that, they won’t expose the source code to the client because that is their intellectual property. However, they can launch a beta version or be flexible when running the software until a special trial duration regarding the deployment of their product to the market. So, it is obligatory to buy the license key of that particular software, otherwise it will stop working after the completion of its specific evaluation duration. Some skillful professionals though can devise a way to use the software without actually purchasing software license key. They actually diagnose the whole software’s working life cycle and eventually find some vulnerability in the mechanism. They ultimately exploit such loopholes in order to bypass the serial key security obstacle. In this context, they can recover the actually serial key, divert the serial key checking program flow, or inject custom serial keys. Suppose a renowned company developed an application which requires a 7 digit license key (hard-coded 1111111) in order to unlock the software and proceed. Fortunately, some individuals somehow got this software executable (maybe the beta version) through some means. However they don’t have the license key to unlock it. using System; namespace CILComplexTest { static class LicenseKeyAuthentication { private static int Authentic_Key = 1111111; public static bool VerifyKey(int key) { return key == Authentic_Key; } } class Program { static void Main(string[] args) { Console.Write("Enter License key to unlock Software (7 digit):"); var Keys = Int32.Parse(Console.ReadLine()); if (LicenseKeyAuthentication.VerifyKey(Keys)) { Console.WriteLine("Thank you!"); } else { Console.WriteLine("Invalid license key; Continue evaluation."); } Console.ReadKey(); } } } After executing this software. It prompts the user to enter a seven digit license key. Otherwise it will not let you go further in case of futile hit and trial as follows. Ok, don’t bother yourself; we can still get through this application without having the real license keys. First, decompile the shipped executable file using ILDASM, which will produce the following IL opcode: .module SerialCrack .class private abstract auto ansi sealed beforefieldinit LicenseKeyAuthentication extends [mscorlib]System.Object { .field private static int32 Authentic_Key .method public hidebysig static bool VerifyKey(int32 key) cil managed { .maxstack 2 .locals init ([0] bool CS$1$0000) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld int32 LicenseKeyAuthentication::Authentic_Key IL_0007: ceq IL_0009: stloc.0 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ret } .method private hidebysig specialname rtspecialname static void .cctor() cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldc.i4 0x10f447 IL_0005: stsfld int32 LicenseKeyAuthentication::Authentic_Key IL_000a: ret } } .class private auto ansi beforefieldinit Program extends [mscorlib]System.Object { .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 2 .locals init ([0] int32 Keys,[1] bool CS$4$0000) IL_0000: nop IL_0001: ldstr "Enter License key to unlock Software (7 digit):" IL_0006: call void [mscorlib]System.Console::Write(string) IL_000b: nop IL_000c: call string [mscorlib]System.Console::ReadLine() IL_0011: call int32 [mscorlib]System.Int32::Parse(string) IL_0016: stloc.0 IL_0017: ldloc.0 IL_0018: call bool LicenseKeyAuthentication::VerifyKey(int32) IL_001d: ldc.i4.0 IL_001e: ceq IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: brtrue.s IL_0033 IL_0024: nop IL_0025: ldstr "Thank you!" IL_002a: call void [mscorlib]System.Console::WriteLine(string) IL_002f: nop IL_0030: nop IL_0031: br.s IL_0040 IL_0033: nop IL_0034: ldstr "Invalid license key; Continue evaluation." IL_0039: call void [mscorlib]System.Console::WriteLine(string) IL_003e: nop IL_003f: nop IL_0040: call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey() IL_0045: pop IL_0046: ret } } We can bypass or reveal such security constraints multiple ways. In the Main() method declaration, if you look over the following opcode instructions, you’ll notice IL_0022, which implies that if the proper serial key is not entered, jump to the error message instruction. So, we change this jump code instruction to IL_0025 instead of IL_0033 so that the code execution will always jump to the correct code block, no matter what key values we enter. IL_0021: ldloc.1 IL_0022: brtrue.s IL_0033 // put IL_0025 IL_0024: nop IL_0025: ldstr "Thank you!" The second trick resides again in the Main() method near to the key verify method. What this code does is it compares the entered key values to the actual key value. If the values match then we can continue; otherwise it throws us to the invalid message section using stloc.1. So if you change it to stloc.0, then our execution will always go in the right block: IL_0018: call bool LicenseKeyAuthentication::VerifyKey(int32) IL_001d: ldc.i4.0 IL_001e: ceq IL_0020: stloc.1 //put stloc.0 IL_0021: ldloc.1 IL_0022: brtrue.s IL_0033 Now, if you don’t possess the right key values then you can still get into the software without having the exact key values: For the final trick, if you examine the class constructor block, you can easily find the hard-coded key values. Here, in this instruction, we can guess that the key value is as 0x10f447, so just change it to decimal format and you’ll get the exact key to validate. After finally employing one of these above methods, you can bypass the serial key limitation despite not having the key: .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 8 IL_0000: ldc.i4 0x10f447 IL_0005: stsfld int32 LicenseKeyAuthentication::Authentic_Key IL_000a: ret } Cracking Passwords Cracking passwords of software or bypassing login screens is one of the most sophisticated tasks. Sometimes a password is easily obtained, but sometimes it could be very time consuming. This all depends on how exactly the password mechanism is manipulated in the system. The following Dummy Software requires a user name and password to proceed but we have no idea about correct user credentials. So how do we breach this security restriction? By God’s grace, we have at least the executable of this software. If we decompile it into its corresponding *.il file, and diagnose the corresponding method responsible for validating user credentials, then we might breach this security restriction. Here’s the UserAuth() method IL code: .method private hidebysig instance bool UserAuth(string usr,string pwd) cil managed { .maxstack 2 .locals init ([0] string USR, [1] string PWD, [2] bool status, [3] bool CS$1$0000, [4] bool CS$4$0001) IL_0000: nop IL_0001: ldstr "ajay" IL_0006: stloc.0 IL_0007: ldstr "1234" IL_000c: stloc.1 IL_000d: ldc.i4.0 IL_000e: stloc.2 IL_000f: ldarg.1 IL_0010: ldloc.0 IL_0011: call bool [mscorlib]System.String::op_Equality(string, string) IL_0016: brfalse.s IL_0024 IL_0018: ldarg.2 IL_0019: ldloc.1 IL_001a: call bool [mscorlib]System.String::op_Equality(string, string) IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: br.s IL_0025 IL_0024: ldc.i4.1 IL_0025: stloc.s CS$4$0001 IL_0027: ldloc.s CS$4$0001 IL_0029: brtrue.s IL_002f IL_002b: nop IL_002c: ldc.i4.1 IL_002d: stloc.2 IL_002e: nop IL_002f: ldloc.2 IL_0030: stloc.3 IL_0031: br.s IL_0033 IL_0033: ldloc.3 IL_0034: ret } If we rigorously scrutinize that code, we can reach some conclusive result by obtaining some significant information. We can easily judge here that instructions IL_0001 and IL_0007 store actual user name and password information as “ajay” and “1234”: IL_0000: nop IL_0001: ldstr "ajay" IL_0006: stloc.0 IL_0007: ldstr "1234" IL_000c: stloc.1 The second important thing we can conclude from these opcodes is that IL_000d is responsible for setting a Boolean value to true or false. As per the UserAuth() method, if the user entered the correct user name and password then this Boolean value is set to true, otherwise it would always be false. IL_000d: ldc.i4.0 So here is the trick: if we change it to True right here, then it won’t matter what the user would input since the Boolean value would always be true. IL_000d: ldc.i4.1 In another observation, we can imply some substantial information from the btnLog_Click() method. In fact, this method takes the user name and password from the user and validates them against predefined parameters. .method private hidebysig instance void btnLog_Click(object sender,class [mscorlib]System.EventArgs e) cil managed { .maxstack 3 .locals init ([0] bool CS$4$0000) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.0 IL_0003: ldfld class [System.Windows.Forms]System.Windows.Forms.TextBox DummySoftware.Login::txtUser IL_0008: callvirt instance string [System.Windows.Forms]System.Windows.Forms.Control::get_Text() IL_000d: ldarg.0 IL_000e: ldfld class [System.Windows.Forms]System.Windows.Forms.TextBox DummySoftware.Login::Password IL_0013: callvirt instance string [System.Windows.Forms]System.Windows.Forms.Control::get_Text() // ---------- Modification Required here-------------------- //---------------------------------------------------------------- IL_0024: nop IL_0025: ldarg.0 IL_0026: ldfld class [System.Windows.Forms]System.Windows.Forms.Label DummySoftware.Login::label3 IL_002b: ldstr "Login Successful" IL_0030: callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Text(string) IL_0035: nop IL_0036: nop IL_0037: br.s IL_004c IL_0039: nop IL_003a: ldarg.0 IL_003b: ldfld class [System.Windows.Forms]System.Windows.Forms.Label DummySoftware.Login::label3 IL_0040: ldstr "Login Failed" IL_0045: callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Text(string) IL_004a: nop IL_004b: nop IL_004c: ret } Now look at these instructions. These are actually checking the input credentials against the predefined. If the user enters correct information then OK; otherwise it throws the execution to IL_0039 which shows some invalid message. So here is the loophole: if we throw the execution to instruction IL0024 rather than IL_0039, then our program always runs perfectly, and it doesn’t matter what credentials we are entering. IL_0022: brtrue.s IL_0024 In another tactic, if we bypass the equal condition where the credentials are validated, then we can breach the software easily. These instructions are responsible for equating the condition: L_0018: call instance bool DummySoftware.Login::UserAuth(string,string) // ---------- Modification Required here-------------------- IL_001d: ldc.i4.0 //------------------------------------------------------------------ IL_001e: ceq IL_0020: stloc.0 IL_0021: ldloc.0 IL_0022: brtrue.s IL_0039 So if we change the IL_001d instruction to ldc.i4.1 then the equal would never be checked and we can breach the login screen easily: Extending Trial Duration Sometimes we install some beta version software just for testing point of view but they expire after the completion of their evaluation period and we can no longer use them. As an analogy, the following software calculates some math functions but it is expired now. We can resume our operation until we don’t buy the license key. But by applying round-trip reverse engineering we can extend its expiry date and make it usable without investing money on a license key. First, decompile its exe file in the IL file and rigorously study it to detect vulnerability. .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { .maxstack 8 IL_0000: ldarg.0 // ---------- Modification Required here-------------------- IL_0001: ldc.i4 0x7dd IL_0006: ldc.i4.7 IL_0007: ldc.i4.s 30 //------------------------------------------------------------------- IL_0009: newobj instance void [mscorlib]System.DateTime::.ctor(int32,int32,int32) IL_000e: stfld valuetype [mscorlib]System.DateTime TrailSoftware.Form1::expDate IL_0013: ldarg.0 IL_0014: ldnull IL_0015: stfld class [System]System.ComponentModel.IContainer TrailSoftware.Form1::components IL_001a: ldarg.0 IL_001b: call instance void [System.Windows.Forms]System.Windows.Forms.Form::.ctor() IL_0020: nop IL_0021: nop IL_0022: ldarg.0 IL_0023: call instance void TrailSoftware.Form1::InitializeComponent() IL_0028: nop IL_0029: nop IL_002a: ret } After doing some R&D, we found some instructions which show the expiry date of this software as 30/7/2013: IL_0001: ldc.i4 0x7dd IL_0006: ldc.i4.7 IL_0007: ldc.i4.s 30 So if we modify the instruction IL_0007 to some other value and recompile it using ILASM then we can still use this software. In another code review, which checks the current date to expiry date whether it’s less or not: .method private hidebysig instance void Form1_Load(object sender, class [mscorlib]System.EventArgs e) cil managed { .maxstack 2 .locals init ([0] bool CS$4$0000) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldfld valuetype [mscorlib]System.DateTime TrailSoftware.Form1::expDate IL_0007: call valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now() IL_000c: call bool [mscorlib]System.DateTime::op_GreaterThan(valuetype [mscorlib]System.DateTime, valuetype [mscorlib]System.DateTime) // ---------- Modification Required here-------------------- IL_0011: ldc.i4.0 IL_0012: ceq IL_0014: stloc.0 IL_0015: ldloc.0 //--------------------Till Here--------------------------------------- IL_0016: brtrue.s IL_0052 ------ } If we delete some code instructions which show the expiry date message then we can bypass this restriction: IL_0012: ceq IL_0014: stloc.0 IL_0015: ldloc.0 Wipe out these aforementioned instructions from the code file, save and recompile it, and finally run it. Here’s the modified code: IL_0011: ldc.i4.0 IL_0016: brtrue.s IL_0052 The software now works indefinitely. Summary In this article, we saw how to obtain sensitive information in order to crack user names, passwords, and serials keys, and to extend trial duration without using IDA Pro or OllyDbg software. We have come to an understanding how to manipulate IL codes with respect to achieving our objective. In the forthcoming article of this series, we will address advance reverse engineering subjects such as byte patching using Hex editor, CFF explorer and IDA Pro.
http://resources.infosecinstitute.com/extreme-net-reverse-engineering-5/
CC-MAIN-2015-22
refinedweb
2,327
52.05
I am to to write a program that generates a number from 1-9 & allow the user to guess the number. I have two questions. 1) Why am I getting the same number every game? 2) Why when the guess isnt correct does all my cout's re appear? I had this happen b4 in a C program & trapped the menu from showing again. This is why I created a char c. Not working this time. If anyone can point me in the right direction, I appreciate it. Code:#include<ctime> //rand() uses same number; srand uses different number for new game #include<iostream> #include<cstdlib> //required to use rand() function using namespace std; int main() { srand((unsigned)time(NULL)); int number; number = rand()%10; int guess; char c; //used to trap extra menu do { cout<<"Let's play a game!"<<endl; cout<<"I'm thinking of a number from 1 to 9"<<endl; cout<<"Let's see if you can guess my number!"<<endl; cout<<"What number am I thinking? "<<endl; cin>>guess; cout<<c<<endl; if (guess == number) { cout<<"Lucky guess!!"<<endl; } else if ((guess-2 == number) || (guess+2 == number)) { cout<<"Oh, so close! You are within two of the number."<<endl; cout<<"Try again! "<<endl; cout<<c<<endl; } else { cout<<"Not even close! Your are more than two off the number."<<endl; cout<<"Try again! "<<endl; cout<<c<<endl; } }while(guess != number); system("PAUSE"); //prevents console window from closing return 0; }
http://cboard.cprogramming.com/cplusplus-programming/129989-question.html
CC-MAIN-2015-18
refinedweb
244
77.94
Publishers UPKAR PRAKASHAN 2/11A, Swadeshi Bima Nagar, AGRA–282 002 Phone : 2530966, 2531101, 2602653, 2602930; Fax : (0562) 2531940 Website : Branch Office 4840/24, Govind Lane, Ansari Road, Daryaganj, New Delhi–110 002 Phone : 23251844, 23251866 • This book or any part thereof may not be reproduced in any form by Photographic, Mechanical, or any other method, for any use, without written permission from the Publishers. • The publishers have taken all possible precautions in publishing the book, yet if any mistake has crept in, the publishers shall not be responsible for the same. • Only Agra shall be the jurisdiction for any legal dispute. Things to Remember The characteristics of following consonants : 1. G always remains silent if followed by ‘N’. For example, Gnat (nat), Gnaw (no), Gnocchi (noke), Gnosis (nosis) etc. 2. K always remains silent if followed by ‘N’. For example, Knack (nak), Knight (nit), Know (no), Knuckle (nukl) etc. 3. P always remains silent if followed by ‘S’ or ‘T’. For example, Psalm (sam), Psycho (siko), Ptomaine (tomain), ptosis (tosis) etc. 4. Q always followed by ‘U’ (except Q–boat, the war-ship also used as merchantship), and gives the sound of k w . For example, Quality (kwoliti), Quantum e (kwont m) , Queen (kwen), Quote (kwot) etc. 5. W followed by ‘r’ loses its sound. For example, Wran- gler (ranglr), Wreath (reth), Wring (ring), write (rit) etc.. | 7 Understand the English Alphabet Properlya- tions like ‘ ’ or ‘ : ’. ‘ ’ is a semi–vowel sound frequently e e e used in English. This semi-vowel sounds like a semi–‘a’ or a semi–‘e’ or a semi–‘o’ sound. To know how ‘ ’ sounds e like, clench your teeth, stretch the lips sideways towards the cheek, but don’t round your lips. And say ‘a’. You have not to say letter ‘a’, but sound ‘a’. This sound comes e from your throat. It is the sound of semi-vowel ‘ ’. It is a very short sound. ‘ : ’ is the long form of ‘ ’, but its length e e is also very short in comparison to length of other vowels. Now let’s forward towards the pronunciation chart. PRONUNCIATION CHART Alpha- Examples Pronunciations bet Vowels a bat, glad, has, sad bat, glad, haz, sad a air, raid, same, tame - ar, rad, sam, tam a glass, heart, mass, glas, hart, mas, sam psalm e den, eld, mend, red den, eld, mend, red e chief, clean, seize, team chef, klen, sez, tem i busy, chin, hymn, tin bizi, chin, him, tin i might, side, shy, write mit, sid, shi, rit o cot, lot, mop, shop kot, lot, mop, shop o dough, low, toe, tone do, lo, to, ton 8 | S. E. F. Chapter in Nutshell • Always remember that the practice material should be read ALOUD and that too again and again to train your Tongue, your Lips, your Throat and other organs of speech. • It is the Spoken language that comes first, and Written language only afterwards. • The Spoken part of language is not the same as the Written part. Don’t try to speak in written style of language. •. • You are not required to consciously stop to think about how to string the words together. Speak out spontaneously. expres- ses extra- ordinary Shortened Pronunciatio Form n I am I’m a’im I have I’ve a’iv I had/I would I’d a’id I shall/I will I’ll a’il We are We’re ve’ea(r)* We have We’ve ve’ev We had/We would We’d ve’ed We shall/We will We’ll ve’el You are You’re yooa’(r)* You have You’ve yoov You had/You would You’d yood You will You’ll yool They are They’re the’a(r)* They have They’ve the’iv They had/ They would They’d the’id They will They’ll the’il He is/He has He’s heez He had/He would He’d heed He will He’ll heel She is/She has She’s sheez She had/She would She’d sheed 14 | S. E.- contained idea-units. Read each idea-unit as a single word. For example, utter “I am afraid of cockroaches”, as if the word–group is a single word “Iamafraidofcock- ro Chapter in Nutshell • To avoid the Fear of Grammatical Mistakes, don’t try to use the Long Forms of starters at this stage. •- meanings segrega- ted, – owl, own, ox. ore, ought, our, ours, out, owe (o),- syll- syllabic words with a special effect.* Since poly-syllabic words contain both stressed and unstressed syllable, hence note down the following points while say these syllables : Chapter in Nutshell • Build up your own Vocabulary Bank. • Have better acquaintance with words, i.e. Mono– syllabic words, and Poly–syllabic words. Mono– syllabic words contain only one syllable. On the other hand, Poly–syllabic words contain more than one syllable. • Mono–syllabic words generally need not any stress or extra effort to speak them out, while Poly–syllabic words require stress as the situation demands. • Read out the given Mono–syllabic, and Poly–syllabic words ALOUD. • Practic e Material requires frequent and several readings ALOUD. * efficien- tly. What should What’s not speak I I don’t I doesn’t × We We don’t We doesn’t × You You don’t You doesn’t × They They don’t They doesn’t × He He doesn’t He don’t × She She doesn’t She don’t × It It doesn’t It don’t × I I didn’t — We We didn’t — You You didn’t — They They didn’t — He He didn’t — She She didn’t — It It didn’t — I I have/haven’t I has/hasn’t × We We have/haven’t We has/hasn’t × You You have/haven’t You has/hasn’t × They They have/haven’t They has/hasn’t × He He has/hasn’t He have/haven’t × She She has/hasn’t She have/haven’t × It It has/hasn’t It have/haven’t × I I had/hadn’t — We We had/hadn’t — You You had/hadn’t — They They had/hadn’t — He He had/hadn’t — She She had/hadn’t — It It had/hadn’t — comp- lained. * ‘that’ is not an essential part of spoken English, hence you can omit it. Chapter in Nutshell • Grasp the Principles of Description, i.e. Important Combinations of Speech. • Pay due attention towards ‘Things to Remember’. • Understand the Action words and their three forms carefully. •, Conjunc- tion, Interjection and Articles. There is no necessity to go in details for all these parts of speech. As we are concerned with speech–fluency part of English, there- fore, we shall look at the structures from different angle. Generally, whenever we speak, we speak about a person, or a place or a thing. It means a part of idea- unit- time inspira- tional scatte- red,, un- derstood some- thing,- ment, rubbed his hand, gripped my shoulder, planted a tree, shook his head, missed the train, shown the com- position, some- thing, style. • Understand the Parts of Speech, viz. Naming Part, Descriptive Part, and Action Part. • Read the list of ‘Naming Frames’ and ‘Action Frames’ ALOUD. • Pick a Naming frame and conjugate it with different Action frames ; and generate numerous idea-units. • indispens- able abused, they opened, they urged, they aimed, they added, they easily, they asked, may organise, may offer, say everything lay each, convey confirmation, delay in, justify each, buy everything. buy ornaments, buy eggs, buy oil, buy aeroplane, try out, try it, why object, cry aloud, I only, shy and, occupy our, my uncle, my age, my arguments, my eyes, my active. enjoy it, enjoy all, empty oil–can, employ every, employ army, boy eagerly, boy actually, boy urged, employ ideal, employ old–one, boy obviously, boy inherited, annoy others, destroy our, destroy old, lay among. very angry, very often, very urgent, very ideal, bury it, carry out, copy everything, many other, many old, many advantages, many awful, many aircrafts, many objectives, many offer only argued,, draw each, new actor, new artist, new engine, new officer, renew it, grew anxious, grew up, threw out, threw all, knew urban, knew about, knew only, new items, new aim, new ideas, throw it, throw each, screw it, slow effect, now outside, now active, now earns, now actor, now it, now over, how artificial, how amazing, how often, how awkward, how astonishing, how about, grow up grow idle, low opinion. no idea, no objections, no oil, no enemies, no aim, so also, so each, so ugly, so urgent, so only, two of, to all, to any–one to even, to added, to ask, to offer, to overcome, to illustrate, into its, do an, two ears, go out, go across, go inside, who organised, you upset, you acted, you overheard, you imagined, you ordered, you isolated, you ate, you objected, you aimed, you answered, you abondoned, you oiled, you urged, you expressed. (c) Words ending with the sound of ‘a’—This cate- gory * Chapter in Nutshell • Divide your speech in chunks, wherever it is necessary. • A chunk is a piece of specific information. • A standard chunk shouldn’t contain more than eight words. • Grasp the Seven Tips given in the chapter for effective division of utterable structure of word–group. • idea- unit which was to be uttered by him. Whenever the speaker faces any of such problems, he finds him in a crucial fix and he automati- cally compul- sor Things to Remember You should have— • Pause whenever you feel any hesitation during utterance of your idea–unit. Pause at every point of hesitation. • Pause at every junction of chunks, use Standard (*) or Lengthy (≠) pause at every momentous junction. • Pause while you feel any short of breath. Pause and take breath before continuation of utterance. • Use the hesitaion sounds or hesitation fillers with the pauses as per the demand of context. • overpo- wering with- out any preparation. [The speaker wanted to say the word ‘spontaneou- sly’, funda- mentals- period. mono- syll atten- tion towards the meaning conveyed by that particular monosyllabic word. Further you have the liberty to put stress on a mono- syll repre- sentation. - period. Chapter in Nutshell • Rhythm of Fluency depends upon the Rhythtech, i.e., a predetermined order, and distinct up and down movements in your speech. • Rhythtech works primarily with the help of some spare parts like syllables—the word or the part of word uttered by a single effort. • Rhythtech needs the proper arrangement of stressed and unstressed syllables as well as the amount of time- period invested in utterance thereof. •- unit; conver- sation.- group- group,- question, idea- units is correct : “She has been singing for the whole day, isn’t it ?” “She has been singing for the whole day, hasn’t she ?” Yes, you are correct that the correct idea–unit is ‘She has been singing for the whole day, hasn’t she ?’ There- fore, you should avoid the mistake of using only ‘isn’t it ?’ or ‘is it ?’ with every idea–unit, but use an appropriate tag-question as per the requirement of statement. (d) Also remember that ‘no’ has no place in tag- questions.- questions idea- units.- questions opportu- nities- improvis differen- tiate from written language. If there is no vagueness, tentativeness and lack of exactness in your spoken language, it may not be a true spoken language. So of the spoken English. Unique Order of Word-groups The style in which a sizeable proportion of word- groups’. Accor- ding- correction idea- unit some- thing. under- standing :- groups- man. I don’t like her—too talkative. FW 2 : They like her—obedient †# disciplined † dedica- ted. Have you seen Sushmita—beautiful, sharp fea- tures- composition uncer- tainty emo- tional atten- tion- mind state- ment.i-- availability pres- sure cooker. I came over here to buy some—things—cheeze. Chapter in Nutshell • Spontaneous speech making is an impromptu action, i.e., speech without planning, preparation and organi- sation in advance, thus having uniqueness of make- shift improvisation—composition and speech of your idea-units simultaneously. • Spontaneous speech confers you the freedom of arranging your speech in various styles like (a) Topic– comment order, (b) Comment–topic order, (c) Repetition of References, etc. • It’s the spontaneous speech that provides you better chances for (a) Self–correction, (b) Fronting, (c) Appendages, (d) Addition of Afterthoughts, (e) Use of fragments, etc., thus, you’ve the appreciable freedom of speech. • Comment clauses play the commendable role in composition as well as correction in spontaneous speech. • The Hallmark of spoken English is imprecision and vagueness. 13 Beautify Your Speech with Drops Now it must be clear to you that there’s an apparent distinction between spoken English and written English. And you know that during conversation, context plays an important role, and the listener grasps the subject- matter approa- ched some- where. some- thing.-to- day ? Chapter in Nutshell • Though adding something makes your English effective, but you can beautify your spoken English even by some drops too. • I-We-You-They-He-She-It; Am-Is-Are-Was-Were; Has- Have Dri- ving- sessions.- groups.) ? Things to Remember • To Speak English Fluently, don’t try hard to use very new or extra-ordinary word-groups at this stage. • Never try to go after colourful expressions and structures you see in the news papers, books or you hear over the radio or TV, to convey your message effectively to the listener. • Always speak in spoken English and avoid speaking in written English. • Always speak in small structures or in chunks; and try to avoid very lengthy word-groups or idea-units. Things to Do • Think of the contexts or situations in which you can frame the questions and can use them in your day-to- day conversation. • Select about 20 questions from this chapter or frame your own questions every day. And create or look for contexts or situations to use them. • Speak English Fluently the Rhythtech way to ensure your success. * For detailed study of phrases, please refer to ‘The world of Idioms and Phrases’, published by Upkar Prakashan. † To read aloud. S. E. F. | 203 Act up = to behave badly Answer back = to reply arrogantly Answer for = to be responsible for Ask after = to enquire about health Ask for = to invite trouble Back away = to reverse away Back down = to abandon one’s opinion or position Back out = to move out backwards Back up = to give support to Bargain for = to expect Bear out = to corroborate Bear up = to keep up one’s spirits Bear with = to make allowance for Blow down = to knock down Blow out = to extinguish by blowing Blow over = to pass away, as a storm Blow up = to lose one’s temper Boil over = to spill-over after boiling Break away = to go away, escape Break down = to collapse, in tears; to fail completely Break in = to enter violently, to interrupt Break off = to detach by breaking, end suddenly Break off with = to have no further relation with Break out = to get out by breaking; to burst into speech Break through = to overcome an obstacle Break up = to disintegrate, destroy or upset completely Bring about = to cause to happen Bring back = to return something Bring in = to introduce something Bring off = to achieve Bring out = to make clear; to put before the public Bring over = to convert Bring round = to win over; to restore from ill- ness 204 | S. E. F. Bring together = to bring into contact Bring up = to rear or educate; to vomit Brush off = to ignore, dismiss Brush up = to clean and tidy; to renew one’s knowledge of Build up = to create, acquire, consolidate Burst in = to enter suddenly into a room or into conversation Burst out = to start violently into, e.g., scolding etc. Burst up = to quarrel or disrupt But in = to interrupt Button up = to fix or close by doing up buttons; to ready for action Buy off = to get rid of by paying Buy over = to bribe Call away = to summon to carry on another activity Call back = to visit again; to telephone again Call by = to visit in passing Call down = to invoke; to rebuke Call for = to ask loudly for; to demand; to require Call in = to visit; to demand repayment of Call of = to abandon; to cancel Call on = to make a short visit; to appeal to Call out = to challenge to fight a duel Call over = to read aloud (a list) Call round = to visit casually Call up = to summon; to mobilise Care about = to be concerned Care for = to attend; to look after Carry away = to deprive of self-control by exciting the feelings; to transport Carry it = to behave, demean oneself; Carry off = to cause the death of; to gain, to win Carry on = to continue; to have an affair S. E. F. | 205 Carry out = to accomplish; to complete a task Carry over = to postpone to next occassion Carry up = to continue a building upward Cart off = to remove Carve up = to divide; to injure a person esp. by slashing with a razor. Cash in on = to turn to one’s advantage Cast about = to look about; to search for Cast away = to waste; to wreck Cast back = to revert Cast down = to deject; to turn downward Cast off = to reject Cast out = to quarrel Cast up = to throw up; to turn up Catch on = to comprehend; to become popular Catch out = to detect in error or deceit Catch up = to draw level and sometime over-take Chase up = to pursue for a purpose Check in = to arrive at a hotel a hotel Check over = to inspect carefully Check up = to examine or verify Clear off = to get rid of, dispose of Clear out = to empty, a drawer etc. Clear up = to explain; to make or to become clear Close down = to give up business; to come to stoppage of work Close with = to accede to; to accept ; to grapple with Clutter up = to make untidy by cluttering or crowding with many things Colour up = to blush, flush Come about = to happen Come across = to be understood; to meet or find by chance Come across with = to provide 206 | S. E. F. Come at = to attack; to reach Come by = S. E. F. | 207 Crack up = to praise; to fail suddenly; to go to pieces Cross out = to delete from a list etc. Cry down = to decry Cry off = to withdraw from an agreement Cry on = to call upon Cry out for = to be in urgent or obvious need of Cry up = to praise Cut across = to take shorter way Cut back = to reduce, e.g., expenses etc. Cut down = to curtail; to reduce, e.g., expen- ses etc. Cut in = to interpose; to interrupt Cut off = to disconnect; to stop flow of supplies, communication etc. Cut out = to shape; to debar; to give up a habit Cut short = to abridge; to silence by interru- ption Cut up = to cut into pieces; to criticise severally Dab on = to apply in small quantities Deal in = to do business or trade Deal with = to have to do with, to take action in regard to Dig in = to work hard Dip in = to take a share Dispose of = to settle what is to be done with; to make an end of; to part with; to sell Do away with = to abolish; to destroy Do by = to act towards Do down = to put down; to cheat Do for = to suit; to provide for; to ruin; to kill Do in = to murder; to exhaust; to deceive Do out of = to deprive Do over = to do again; to beat up 208 | S. E. F. Do up = to fasten up; to redecorate Do well = to prosper; to be justified Do with = to make use of; to meddle with Do without = to dispense with, not to be dependent on Draw in = to reduce, contract; to become shorter; to slow down and stop, e.g., car etc. Draw on = to approach; to pull on Draw out = to leave the place; to take money out of Bank account Draw up = to prepare a written statement; to stop Dream up = to plan in the mind, often unrealistically Drop across = to come across to visit Drop away = to depart, disappear Drop back = to fall behind in performance Drop by = to visit casually Drop down = to sail, move or row down a coast Drop in = to come, fall, set etc. in casually Drop off = to fall asleep; to diminish Drop out = to disappear from one’s place; to withdraw esp. from an academic course Dry up = to stop talking; to lose inspira- tion Eat away = to destroy gradually Eat in = to corrode; to consume, use up Eat out = to eat in a restaurant Egg on = to encourage End up = to finish (with, by); to come to an end, usually unsatisfactory Face out = to carry off by bold looks Face upto = to face, to accept the challenge Fall about = to laugh hysterically Fall across = to meet by chance S. E. F. | 209 Fall away = to decline gradually, to dwindle, to grow lean, to waste away Fall back = to retreat, give way Fall back on = to depend on for support Fall behind = to lag behind; to get in arrears Fall flat = to fail completely Fall for = to be taken in by (a trick etc.); to be duped by Fall in with = to concur or agree with; to comply with Fall off = to deteriorate; to perish; to die away Fall on = to begin eagerly; to make an attempt, to meet Fall out = to quarrel Fall over = to go to sleep; to go over to the enemy Fall through = to fail, come to nothing Fall to = to begin hastily; to begin to eat Fed up = to be tired, bored, depressed Feel like = to be in the mood for Feel up to = to feel equal to, or capable of Fight down = to supress or restrain, e.g., an emotion Fight off = to resist, repel Fill in = to act as a temporary substitute; to add what is necessary to complete Fill up = to fill to the full, by addition of more Finish off = to conclude; to kill Fish for = to seek Fix on = to single out, decide for Fix up = to arrange; to settle; to put to rights, attend to Flesh out = to give substance to; to elaborate on (an idea etc.) Fling away = to waste Fly high = to aim high, be ambitious Fly open = to open suddenly or violently 210 | S. E. F. Fold ver- bally circum- vent S. E. F. | 211 Get up = to rise from bed; to arrange; to prepare Give away = to give for nothing; to betray Give back = to return; to restore Give ear = to listen (to) Give forth = to emit; to publish; to expatiate Give in = to yield, surrender; to hand in something Give off = to emit, e.g., a smell Give out = to report; to emit; to distribute to individuals Give over = to transfer; to cease Give up = to abandon; to surrender; to stop doing Go about = to pass from place to place; to seek Go ahead = to proceed at once, to continue Go along with = to agree with, support Go aside = to err; to withdraw; to retire Go at = to attack vigorously Go back on = to betray, fail to keep (promise, etc.) Go by = to pass by, base judgement on Go down = to sink; to decline; to be swallowed, believed or accepted (with pleasure); to fail to fulfil one’s contract Go down with = to contract (an illness) Go far = to go long way; to achieve success Go for = to assail; to set out to secure; to fetch Go hang = to forgotten, neglected Go in = to enter; to assemble regularly Go in for = to make a practice of; to take part in Go it = to act in a striking or dashing manner Go off = to leave, depart, go bad, e.g., milk etc. Go on = to continue; to proceed; to behave; to fare 212 | S. E. F. Go on for = to approach Go out = in- crease; ham- mering posses- sion S. E. F. | 213 Hang over = to project over or lean out from Hang tough = to stay resolute or determined Hang up = to delay, to suspend; to replace a telephone receiver; to break of communication Have in = to have people in one’s home, e.g., visitors Have it = to prevail, to exceed in any way, to get punishment Have on = to wear; to take in; to have as an appointment; to deceive; to tease; to mislead Have out = to have extracted or removed Have up = to call to account before a court of justice etc. Hear of = to listen to Hear out = to listen (to some one) until he has said all he wishes to say Hit back = to resist actively, strike in again Hit it = to find, often by chance, the right answer Hit on = to come upon, discover, devise; to single out Hit out = to strike out, esp. with the fist Hold back = to withhold; to restrain; to hesi- tate Hold by = to believe in Hold forth = to put forward; to show; to speak in public Hold in = to restrain, check, supress Hold off = to keep at a distance Hold on = to persist in something Hold out = to endure, last; to continue resistance; to offer Hold over = to postpone; to keep possession of (land or house beyond the term of agreement) Hold up = to raise; to keep back; to endure; to bring to expose; to ehxibit; to stop 214 | S. E. F. Hunt out = to seek out Hush up = to be silent; to suppress Idle away = to waste (time) Join in = to take part; to participate Join issue = to begin to dispute Join up = to link together; to connect; to unite Jumble together = to mix, compound Jump at = to accept with enthusiasm, eagerness Jump off = to complete in another, more difficult round Keep at = to persist in anything Keep back = to cause to stay at a distance, to withhold Keep down = to restrain; to repress; to remain low Keep from = to abstain from; to remain away from Keep in = to prevent from escaping, to conceal, to restrain Keep off = to stay away or refrain from Keep on = to continue Keep to = to stick closely; to confine oneself to Keep up = to retain one’s strength or spirit; to support, prevent from falling, to maintain in good condition Knock about = to mistreat physically; to saunter, loaf about Knock back = to drink, eat; to cost Knock down = to demolish; to fell with a blow, to reduce in price Knock off = to stop (work), to deduct, to steal, to kill Knock out = to dislodge by a blow, to over- come, demolish, to overwhelm with amazement, admiration etc. Knock up = to rouse by knocking, to weary out, to be worn out, to construct or arrange hastly S. E. F. | 215 Knuckle down = to set oneself to hardwork Knuckle under = to yield to authority, pressure etc. Laugh at = to mock, get amused about, to dismiss one as unimportant Laugh off = to treat as of no importance Lay aside = to discard; to put apart for future use Lay at = to endeavour to strike Lay by = to save; to keep for future use; to dismiss Lay down = to give up; to deposit, as a pledge; to formulate Lay on = to install a supply of; to provide Lay out = to display; to expend; to plan; to fall Lay up = to store up; to preserve; to con- fine to bad or one’s room Lead off = to begin or take the start in anything Lead on = to persuade to go on; to draw on Lead up to = to prepare for by steps or stages; to play in challenge to, or with Leave in = to allow to remain Leave off = to desist; to terminate; to give up using Leave on = to allow to stay in place or position Leave out = to omit, exclude Let down = to allow to fall, to lower Let fall = to drop Let in = to allow to enter Let off = to allow to go free or without exacting all Let on = to allow to be believed, to pretend, to reveal Let out = to allow to get free or to become known Let up = to become less, to abate Light up = to light one’s lamp, pipe, cigarette etc. 216 | S. E. F. Live down = to survive, to manage to forget Live for = to attach great importance to Live S. E. F. | 217 Make out = to descry; to comprehend, understand; to prove; to seek to make it appear; to draw up; to achieve; to fill up; to succeed Make out of = to interpret (a situation or statement) Make over = to remake, reconstruct; to transfer Make up = to fabricate, to feign; to collect; to put together; to parcel; to arrange; to become friends again; to repair; to complete, supplement; to compensate Meet up = to meet, by chance or with an arrangement Meet with = to come to or upon, esp. unex- pectedly; to encounter Mess about = to potter about; to behave in a foolish or annoying way; to upset, disturb Mess up = to make a mess of; to spoil; to confuse Miss out = to lose; to miss completely; to omit; to fail to take part Mix it = to fight forcefully Mix up = to involve; to be confused; to prepare by mixing thoroughly Muster in = to enroll, receive as recruits Muster out = to discharge from service Nod off = to fall asleap Nod through = to allow to vote by proxy (in Parliament) Open fire = to begin to shoot Open out = to make or become more widely unpack; to develop Open up = to open completely; speak frankly; to unfasten Pass away = to come to an end, go off; to die; to elapse 218 | S. E. F. Pass by = to move, go beyond or past; to ignore or overlook Pass for = to be mistaken for or accepted as Pass off = to disappear gradually, e.g., pain; to palm off; to impose fraudulently Pass on = to go forward; to proceed; to die, to go off; to complete military training, to faint Pass through = to undergo, experience Pass up = to renounce, to have nothing to do with Pay back = to pay in return (a debt); to give tit for tat Pay for = to make amends for, to suffer for; to bear the expense Pay in = to contribute to a fund; to deposit money in a bank account Pay off = to pay in full and discharge; to take revenge upon, to yield good results, justify itself Pay out = to cause to run out, as rope; to disburse Pay round = to turn the ship’s head Pay up = to pay in full; to pay arrears Pick at = to find fault with Pick off = to select from a number and shoot; to detach and remove Pick on = to single out; to carp at; to nag at Pick out = to make out, distinguish; to pluck out Pick over = to go over and select Pick up = to lift from the ground, floor etc; to recover after an illness; to learn or acquire without difficulty Pile up = to run ashore; to accumulate Pin down = to secure with a pin, to locate, limit, restrict; to confine, trap in a position S. E. F. | 219 Pin up = to fix up with a pin Play about = opportuni- ties to; to flatter Puff up = to swollen with pride, presump- tion or the like Pull about = to treat roughly Pull back = to retreat, withdraw Pull down = to take down or apart; to demo- l im- prison; to set aside Put back = to push backward; to delay; to repulse Put down = to crush, quell; to kill; to degrade; to enter, write down on paper; to attribute; to give up Put for = to make an attempt to gain 220 | S. E. F. Put forth = to extend; to propose; to display; to produce Put forward = to propose; to advance Put in = to introduce; to insert; to lodge; to appoint Put in for = to request; to apply for Put off = to lay aside; to take off; to palm off; to dismiss; to divert; to postpone; to disconcert Put on = to don, clothe with; to assume; to mislead, deceive; to affix, attach, apply; to set to work Put out = to expel; to dismiss; to expand; to extinguish; to put to in-conve- nience; to offend Put over = to refer; to impress an audience Put through = to bring to an end; to accom- plish; to process Put to = to apply; to add to; to set to; to shut Put up = to compound; to parcel up; to put aside; to erect; to raise, e.g., price Put up with = to endure; to tolerate Rake up = to collect together; to discover Rattle on = to talk continuously Read out = to read aloud Read up = to amass knowledge of by reading Reel off = to utter rapidly and fluently Rig out = to dress up or equip quickly with whatever available Ring back = to call again over phone Ring off = to close a conversation over phone Ring up = to call on the telephone Rip off = to steal; to exploit; to cheat, overcharge Roll along = to arrive by chance, or with a casual air Roll up = to assemble, arrive S. E. F. | 221 Root out = to remove by roots, to destroy totally, to extirpate Rot away = to rot or decay slowly and completely Rough it = to take whatever hardships come Rub along = to get along; to manage somehow Rub down = to rub from head to foot; to search by passing the hands over the body Rub out = to erase; to murder Rub up = to polish; to freshen one’s memory of Run across = to come upon by accident Run after = to pursue Run away with = to take away; to win easily Run down = to knock down on road; to disparage Run dry = to come to an end; to cease to flow Run for it = to attempt to escape, run away from Run into = to meet by chance; to extend into Run off = to cause to flow out; to repeat, recount Run on = to talk on and on; to continue in the same line Run out = to run short; to terminate, expire, determine; to leak, let out liquid Run over = to overflow; to overthrow, to knock down Run through = to exhaust, to transfix; to read or perform quickly but completely Run up = to make or mend hastily; to build hurriedly; to incur increasingly; to string up, hang Scrub round = to cancel; to ignore intentionally Seal off = to make it impossible for any- thing, person, to leave or enter (an area etc.) See about = to consider, to attend to 222 | S. E. F. See off = to accompany (someone) at his departure, to get rid of, to reprimand See out = to see to the end See round = to be conducted all through See through = to help through a difficult time See to = to look after; to make sure about Seek out = to look for and find Send down = to rusticate or expel Send for = to summon or order, e.g., by messenger or post Send in = to submit (an entry) for compe- tition etc. Send off = to despatch; to see off Send on = to redirect, forward to a new address Send out = to make persons to leave the room; to emit, to give out; to circulate Send up = to make fun of; to sentence to imprisonment Serve out = to deal or distribute; to punish Serve up = to bring to table Set aside = to put aside; to reject; to lay by Set back = to check, reverse; to cost Set by = to lay up, to value or esteem; to care Set down = to lay on the ground; to put in writing; to judge, esteem; to attribute, charge Set forth = to exhibit; to display; to praise, recommend; to start for a journey; to publish Set in = to begin, e.g., season etc., to become prevalent Set off = to mark off, lay off; to start off; to send off Set on = to move on; to instigate; to incite to attack Set out = to start, go forth; to adorn, to expound, to display S. E. F. | 223 Set to = to affix; to apply oneself Set up = to erect; to put up; to exalt Settle down = to calm down; to establish a home; to become reasonable Settle for = to agree to accept (as a compro- mise) Settle in = to adapt to a new environment Settle with = to come to an agreement Shake down = to cheat of one’s money at one stroke; to go to be (esp. in a temporary bed) Shake off = to get rid of, often by shaking Shake up = to rouse, mix, disturb, loosen by shaking Shape up = to make progress; to develop Show away = to let out a secret Show forth = to manifest, proclaim Show off = to display or behave ostenta- tiously Show up = to expose; to appear to advantage or disadvantage; to be present; to appear, arrive Sign away = to transfer by signing Sign off = to record departure from work; to stop work etc. signature Single out = to distinguish or pick out for special treatment Sink in = to be absorbed; to be understood Sit at = to live at the rate of expense of Sit back = to take no active part Sit by = to look on without taking any action Sit down = to take a seat; to pause, rest; to begin a siege Sit for = to take examination Sit in = to be present as visitor at confe- rence etc. 224 | S. E. F. Sit on = to hold an official enquiry regar- ding; to repress Sit out = to sit apart without participating; to sit to the end of Sit up = to become alert or started; to keep watch during the night, to sit upsight Size up = to take mental measure of; to assess Slack away = to ease off freely Slack up = to slow Sort out = to classify, separate, arrange etc; to deal with, punish etc. Sound about = to speak loudly and freely (in complaint); to boast Soup up = to increase the power of Spark off = to cause to begin, kindle, animate Speak for = to be a proof of; to witness to Speak out = to speak boldly, freely, unreser- vedly Speak up = to speak so as to be easily heard Speed up = to quicken the rate of working Spin out = to prolong, protract Split on = to betray, give (a person) away Square up = to settle (a bill, account etc.) Square up to = to face up to and tackle Stand against = to resist Stand back = to stand to the rear, to keep clear Stand by = to support; to adhere to, abide by; to be at hand; to prepare to work at Stand down = to leave the witness box; to go off duty Stand for = to be a candidate for; to be a sponsor for; to represent; to put up with, endure Stand in = to cost; to become a party; to deputise, act as a substitute (for) S. E. F. | 225 Stand off = to keep at a distance; to direct the course from Stand on = to continue on the same track or course; to insist on Stand out = to project; to be prominent; to refuse to yield Stand over = to keep (someone who is working) under close supervision; to postpone Stand to = to fall to, set to work; to back up; to upheld Stand up to = to meet face–to–face; to show resistance Stand with = to be consistent Start in = to begin Start out = to begin a journey Start up = to rise suddenly; to set in motion Step down = to withdraw, retire, resign; to decrease the voltage of; to reduce the rate of Step in = to enter easily or unexpectely; to intervene Step out = to go out a little way; to have a gay social life Step up = to come forward; to raise by steps; to increase the rate of, as production etc. Stick around = to remain in the vicinity Stick at = to hesitate or scruple at; to persist at Stick out = to project; to continue to resist; to be obvious Stick to = to persevere in holding to Stick up = to remain attached; to stay with; to remain loyal to Stick up for = to speak or act in defence of Stink out = to drive out by a bad smell Stir forth = to go out of doors Stir up = to excite; to incite; to arouse; to mix by stirring 226 | S. E. F. Stop behind = to remain while group goes on Stop over = to break one’s journey Stop up = to seal up or close completely, e.g., a car Straighten out = to disentangle, resolve Strike down = to fell; to make ill or cause to die Strike in = to enter suddenly; to agree Strike off = to erase from an account; to deduct, to remove Strike out = to efface; to bring into light; to swim away Strike up = to begin to beat, sing, or play String up = to hang Strip down = to dismantle, remove parts from Strip off = to take one’s clothes off Stump up = to pay up, fork out Swan arround = to move about aimlessly Swan up = to arrive, either aimlessly or gracefully Swim against = to go against Swim with = to conform to Tail off = to become gradually less or fewer Take after = to follow in resemblance Take against = to oppose; to take a dislike to Take back = to retract; to withdraw Take down = to reduce; to lower; to demolish, pull down; to escort to the dining room; to report or write down to dictation Take effect = to come off, succeed; to come into force Take heed = to be careful Take off = to remove; to swallow; to mimic Take on = to receive aboard; to undertake; to assume Take out = to remove from within; to extract; to go out with; to copy; to receive an equivalent for Take over = to receive by transfer; to assume control of S. E. F. | 227 Take up = to lift, to raise; to pick up for use; to absorb; to accept; to interrupt sharply; to arrest Talk at = to address remarks indirectly; to talk to incessantly, without wait- ing for a response Talk back = to reply impudently Talk big = to talk boastfully Talk down = to argue down; to talk as to inferiors in intellect or education Talk into = to persuade Talk out = to defeat Talk over = to convince; to discuss, consider together Talk round = to talk of all sorts of related matters without coming to the point Talk tall = to boast Talk to = to address; to rebuke Talk up = to speak boldly; to praise or boost; to make much of Tell off = to count off; to rate, chide Tell on = to betray, give away secrets about Think aloud = to utter one’s thoughts uninten- tionally Think back to = to bring to one’s mind the memory of Think for = to expect Think long = to yearn; to weary (from deferred hopes or broedom) Think out = to devise, project completely Think over = to reconsider at leisure Think through = to solve by a process of thought Think up = to find by thinking, devise, concoct Throw away = to reject, toss aside; to squander; to bestow unworthily Throw back = to retort; to refuse Throw down = to demolish 228 | S. E. F. Throw in = to interject; to add as an extra Throw off = to divest oneself of; to utter or compose off-hand Throw on = to put on hastily Throw open = to make freely accessible Throw out = to cast out; to reject; to expel; to emit, to utter Throw over = to discard or desert Throw up = to erect hastily; to give up; to resign; to vomit Tide over = to carry over, or surmount, difficulties for the time at least Tie in = to agree with; to be closely associated with Tie up = to parcel up; to tether; to tie so as to remain up Tie with = to be linked with (as e.g., a book containing the story of) Tone down = to give a lower tone; to moderate; to soften Tone up = to heighten; to intesify; to make healthier Top out = to finish (a building) by putting on the top or highest course Top up = to fill up, e.g., with fuel oil Toss off = to perform, produce quickly; to drink off Toss out = to dress smartly, fancily Toss up = to throw a coin in order to decide; to cook and serve up hastily Touch off = to trigger Touch up = to lash lightly; stimulate Track down = to find after intensive search Trade down = to deal in lower grade, cheaper goods Trade in = to give in part payment Trade off = to give one thing in return of another Trade up = To deal in higher grade, dearer goods S. E. F. | 229 Trot out = to bring forward, adduce, pro- duce for show; to walk out with Tumble in = to go to bed Tumble over = to toss about carelessly, to upset; to fall over Tumble up = to get out of bed; to throw into confusion Turn about = to spin, rotate; to face round to the opposite quarter Turn aside = to avert; to deviate Turn away = to dismiss from service; to discharge; to refuse admittance; to depart Turn back = to cause to retreat; to return Turn down = to bend, double, or fold down; to invert Turn forth = to expel Turn in = to bend inward; to enter; to surrender Turn off = to deviate; to dismiss; to comp- lete; to switch off Turn on = to set running (as water); to depend on Turn out = to bend outwards; to drive out; to expel; to dress groom, take care of the appearance of; to muster Turn over = to roll over; to change sides; to hand over, pass on; to ponder; to rob Turn up = to fold upwards; to come, or bring, to light; to appear by chance; to invert; to disturb; to refer to Use up = to consume; to exhaust; to tire out View away = to see by breaking the cover Visit with = to visit; to be guest with; to chat with Vote down = to defeat or supress by vote, or otherwise 230 | S. E. F. Vote in = to elect Wade in = to make a very vigorous attack Wait on = to wait for Wait up = to stay out of bed waiting for Wait upon = to call upon, visit formally; to attend and serve Wake up to = to become conscious of, alive to Walk away with = to win with ease Walk into = to beat; to storm at; to eat hear- tily of Walk off = to leave; to depart; to get rid of by walking Walk on = to walk ahead; to continue to walk Walk out = to leave, esp. as a gesture of disapproval Walk over = to cross, or traverse; to win an uncontested game Walk tall = to be proud, have self-respect Wall up = to block with a wall, to entomb in a wall Warm up = to make or become warm; to become animated, interested or eager Wash out = to remove by washing; to cancel; to exhaust Wash up = to wash one’s hands and face; to spoil; to finish Watch in = to keep awake to welcome (the New Year) Watch out = to look out, be careful Watch over = to guard, take care of Watch up = to sit up at night Water down = to make less strong Wave aside = to dismiss (a suggestion etc.) as irrelevant or unimportant Wave down = to signal to stop by waving Wear down = to diminish, or overcome, gra- dually by persistence Wear off = to rub off by friction; to pass away by degrees S. E. F. | 231 Wear out = to impair by use; to render useless by decay Weather along = to make headway against adverse weather Weather out = to hold out against till the end Weigh down = to force down; to depress Weigh up = to force up; to consider carefully and assess the quality of Weigh with = to appear important to; to in- fluence Win of = to get the better of Win on = to gain on; to obtain favour with, influence over Win out = to get out, to be successful Win over = to bring over to one’s opinion or party Wind down = to relax; to lose strength Wind up = to bring, or come, to a conclusion; to excite very much Wipe out = to obliterate, annihilate or abolish Wire away = to act or work with vigour Work at = to apply oneself to Work into = to make way gradually into; to change, alter into Work off = to separate and throw off Work on = to influence, or try to do so Work out = to effect by continued labour, to exhaust; to train, exercise (of an athlete) Work over = to examine in detail; to beat up, thrash Work up = to excite, rouse, to expand, elaborate Wrap up = to settle completely; to have completely in hand Wring off = to force off by wringing Wring out = to squeeze out by twisting Write down = to write; to reduce the book value of an asset 232 | S. E. F. Write for = to apply for; to send away for Write off = acquain- tances of the same age group. It is not used for elderly persons. For example : S. E. F. | 233 Hallo Raju ! How do you do ? Hello Ria ! Come here. Besides so many things, the knack of conversation, i.e., framing up of questions, plays an important role to gain speech-fluency. • The Secret of Success in any sphere is a single worded Mantra—REPETITION, so of the spoken English. Keep it up. • Practice, yes Perfect Practice is the “SUPREME SUTRA” to get skill in any art, so for the art of Spoken English. Keep it up.
https://fr.scribd.com/doc/16618492/13723947-Speak-English-Fluently
CC-MAIN-2019-26
refinedweb
8,309
56.86
Ted Honderich's narrative of the academic philosopher's perilous progress in and out of classrooms, including the thinking -- here are the first six sections of it. There are 60 or so sections in the book published in the United States, Canada and England for 2001 -- Philosopher: A Kind of Life. The first five sections make up a tour of a university philosopher's green summer. They raise a question of how he got there, and of the explanation of a life. The sixth section -- the very last free one, declares Routledge, my good but reasonably self-interested publisher -- begins on the answers to those questions. Have a look too, if you want, at first eight reviews of the book, these being lovely, good, bad, and curiously deceptive, and the author's reviews of the reviews. 1 This now a place where I am alone, a small room of recesses and bays, bright at the window. It is made calm by the green palisade of trees against the sky at the bottom of the gardens, a backdrop waiting for the rest of the play. The room is freshly painted in its old colours, two light and just different blues on the walls, with the whiter one above the picture rail under the white ceiling. In the room there are now the things of only my own life, and only one kind of life. It is an orderly study again. A table in the window without clutter, a brass clock on it that gets attention. Watercolours and paintings, two of them large and emotional impressions of trees, framed by me. In place of women’s radio programmes, there is quiet Bach and Mozart, or silence except for the birds. In a recess, a framed announcement recalling my inaugural lecture, ‘The Mind, Neuroscience, and Life-Hopes,’ not certain to escape the eye of a visitor rightly seated. Up the few steps from the study and along the hallway, past the undetaining watercolours, past the empty space from which the too detaining still-life departed with Jane, is the drawing room. I learned to call it by that name, a little resolutely. It is large enough to have held a few dozen friends and acquaintances who trooped in once more to the Christmas drinks, perhaps some of them a little resolutely too. Through three good windows, their slender glazing bars as well preserved as those of the study, the drawing room also looks out to the palisade of trees. This room is still brighter than the study, being somewhat higher in the house. It has six sides, in two light and just different greens, the nearly white one above. Wainscot rail reinstated in very living memory. Older urns and swales in relief on the fireplace. Odd pillars of books on the tables and on the carpet, next to the wicker settee and chairs and the brown Victorian sofa. Flowers and candles, and some small brass vessels, nicely worked frowa caskets, brought back from visits as external examiner to the university in Ghana. Eleven small portraits in a line around the room, some of 18th Century gents in ruffs, several of Russian lads, the latter in memory of the Soviet Union I was too sensible or respectable or timid to support. I see again that the room is a little contrived, perhaps a little comic. Even worse in the report of a guest of sceptical sensibility or with an eye for social aspiration? This does not much touch my simple pleasure in it. In particular, I do not follow persons of more rigorous taste who would exchange its decorous ease for, say, one of those white cells of the Palais Wittgenstein, those stern products of functional necessity and geometry, dutifully visited in Vienna the other week. The philosopher-architect, after arriving at the dimensions for his white shoeboxes, took more aesthetic thought only to conceal the central heating and to determine the right height for the door handles. They look pretty high to me. The third of my more easeful rooms is through two facing doors from the drawing room. It too is in accord with the principle of decoration already noticed, owed to departed Janet: two just different yellows here. A good table and ten chairs. This dining room is heavy with more pictures, some above others, a motley but all in accord with another principle, my own. It is that the main value of art must surely have to do with its being true of something, and so it is better when we are not left wondering what that thing might be. Hence the reproduction of a portrait of Hume, patron saint of philosophers of my inclination, and also, Victorian or later, the still-lifes, studies of women and landscapes, etchings on wood of lion, tiger and fox, profile of the Spanish lieutenant and so on, and portrait of the host. There are French doors to a pretty balcony. Some later Juliet could lean against that white balustrade. An older and wiser one might be best. What remains to be noted in Flat B, this first-floor setting of my life, is a bedroom. One large window of sixteen panes, looking into the boughs of a great tree at the front of the house. A smaller room, two pinks, more pictures. In a section of the bookcase are the books I have written. Those once brave hopes, still not extinguished. They are somewhat revived now by the growing company of their translations. There is space left for another two or three vols, including the one that will do the trick, at last guarantee me a future. I made the solid bed too. It is in a new position now, against a different wall. For a time I avert my eyes from it. Out of the window and down below, in the garden between the house and the street, in the shadow of the chestnut boughs, connected to the house by stained-glass porch and perambulator store, is something else. It is The Studio, as it says on its door, and as it is named, its definite article intact, in five hundred letters about rent arrears and damp and keys. An artist’s studio of good size, added to the property, like the porch and pram store, by some Victorian. Good-enough brickwork, chimney, slate roof, broad skylight over a good working space and two galleries. In it is an adversary, the socialist landlord’s problem, the occupant who seized her moment and would succeed the tenant. Does my life have an adversary in it more often than others? Do I just make more of my ordinary allotment of adversaries than others do? Let me look away from that for a time too. The narrow street takes its short way down from St. John’s Church at the top, cream and upstanding, to the shops and Hampstead Heath at the bottom. The street is still quiet enough, save for the morning cars. Its cited charm has not been too much touched by garden designers and by the determination of new residents to floodlight their Regency stucco, for purposes of night security as they say. Once Albion Grove, it now has a name not writ in water, Keats’s. In it, when it was a village path, he wrote and lived a part of his brief life, the best part and some of the rest. The nightingale in the garden, other odes, beauty and truth, love of Fanny, the drop of blood on the pillow, and the parting. I pedal past his house each morning to the other place of my life. Down the hill through Belsize Park, Chalk Farm, Primrose Hill, Camden Town and Euston, to Bloomsbury and my other room. It too can seem closer to being my life than just a setting of it, closer to being the stuff of my life than just a principal location of it. Can there be some sense in this, some plain truth? Some actual philosophy, some English philosophy, not only fancy and feeling or French performance? The room is one of pride and success, history, work, many lectures and papers, fewer pleasures, argument in good temper and bad, strategies and alliances, beginnings and endings of careers, hurt and sad drama. The main hurt and sad drama was also a stabbing, some say. It is of a size owed to the good opinion that was had, by himself and others, of an earlier and larger Grote Professor of the Philosophy of Mind and Logic at University College London. A. J. Ayer, Professor Sir Alfred, Freddie, known to me in all those roles, all attacked with practised panache. In the first, he wrote the book Language, Truth and Logic. It inspired my retorts to teachers of my late boyhood who tried to lead me into deep thinking. Along with the decency of the Welfare State, which lingers on far less well, and placenames, and the lure of a past, and not much susceptibility to the American way of life, the book brought me to England. University College London, as resistant to the inclusion of a comma in its name as The Studio is to the loss of its definite article, stands as firmly and as godlessly in Gower St. as it did in 1828, when it first set out to awaken Oxford and Cambridge from their dogmatic slumbers. It was the original University of London. Its Corinthian portico and measured dome, partly paid for by the worthy Grote, welcomed atheists, Dissenters, Catholics, Utilitarians, Jews, women, and other lower orders. It was a breath of fresh air. It still is, despite being effectively a university itself, with some thousands of students and with a good sense of its achievements and of the worth of respectability. Such a breath was Jeremy Bentham himself, its presiding spirit and household god. The great Utilitarian also had self-regard, presumably even more than Freddie. His auto-icon, which is to say his mummified skeleton, remains with us in a college cloister, according to his instructions. The beadles unlock his box to tourists with moderate gravity. My room is away from the portico and dome, on the other side of the college, in Gordon Square, where blue plaques recall the Bloomsbury past. In particular those Stracheys, Bells, Carringtons, Morrells and Woolfs, not quite immortal, officially committed to the pleasures of human intercourse and the enjoyment of beautiful objects. The room is large, L-shaped and suited to a worthy Victorian. It is all of the first floor of the house of the philosophers of the college, my colleagues, the Department of Philosophy. Six floors of Lecturers, Senior Lecturers and Readers, working their way down from the attic or up from the basement by patience and publications. In the settled scheme of things, the room is both the Grote’s own study and teaching room and also a place for other lectures, seminars and meetings. Thus it welcomes visiting philosophers, up from Oxford to do a turn on this metropolitan stage, or in from Berkeley to bring confident news of California and the future. The ring of soft armchairs and sofa, now green, has behind it rows of upright and serviceable chairs, 45 of them. Undergraduates or postgraduates hear about and may find themselves in only the company of only a philosophical subject-matter. Time and space, causation, possible worlds, the Redundancy Theory of Truth, modal logic, mind and brain, or Functionalism. Scepticism, Moral Realism, the values of art, the rationality of the free market, what it is like to be a bat, or, once in a long while, the proprietary doctrines of Aristotle, Kant and other greats of the past. No longer, I am pleased to say, Freud’s theory of sexuality, which, after an extended appearance, slipped off the curriculum. The rest of life just comes to a stop for a while as various propositions are laid out and turned over by me or by the visitors, or by my departmental colleagues when they book my room in the hope that their own smaller rooms will be insufficient for their audience. But the room has long had another part to play in our lives as well. Here we have had our departmental meetings. Occasions for the sharing out of labours, the gathering of opinions on undergraduates, and the massed interviewing of candidates for lectureships. Who is to join us and who not? Very serious matter. Here too the Headship of the department has been our unofficial or official subject. That was the hurt and the sad drama, maybe a stabbing. In a distant corner, a personal computer and a steamer trunk. The computer delivers my thoughts of yesterday back to me for further revision, and also the e-mail, often from my daughter in Princeton. My son, not having an ocean between us, preserves his independence more sternly. The steamer trunk has past in it. A thousand dated notes, many of self-mortification or self-justification, an official complaint or two of injustice, histories of academic struggles and transactions, and also very many letters, some of them sweet letters of love, desire and marriage. Safer here than in Hampstead. A small archive of the struggle. I admit to the usual amount of interest in myself and my thinking, but am reassured that this self-interest may issue in something more general. My aim, of course, middle-sized. I do not have the satisfaction and misfotunate of being a real individual, so impressively and uselessly different that to learn of me is to learn only of me. The kind of life in question is that of a working, academic or university philosopher. Not real life, they say. Still, carried on quite as fully elsewhere as in studies, lecture rooms, common rooms and committee rooms. We do not leave our natures behind in leaving our places of work. Of course this example of the full-time professional philosopher will be different from other examples of the kind, even greatly different, perhaps to their relief. But will it not be more enlightening as to the kind, nevertheless, than any general distillation, composite, constructed average member, survey, or group photo? Particularly if I really make use of my unique knowledge of the example from the inside, really try to tell the truth? Roussea left a lot out in his confessions, and not just the bit about baring his bum in the street in the hope of a spanking. May I, in this more confessional age, be different from him not only in being middle-sized but by leaving out less? My second aim is explanation. How do I and my kind get to places like this? What explains the rest of what else needs saying of me in this green summer -- about my philosophical commitments and tendencies, my daily round, and my inner life? They say philosophy doesn't come from nowhere, summoned into being by pure reason and reading good books. Also, why did those non-philosophical things in the recent past happen as they did? Could it be that the philosophy and the habits in it explain more of the rest of my life than the rest of life explains them? Out of what prehistory did the philosophy and its habits and the rest of life come? But perhaps this aim of explanation is too brave -- even before it turns to trying to explain itself. I see from the philosophical quotations book of Jane and Freddie that it was Kierkegaard, gloomy sod that he was, who said that life must be understood backwards, but has to be lived forwards, and so it can never be understood at all. No moment can have the complete stillness needed for a real view backwards. But is that true? Or, before we get to that, there is that old reflex question. What does it actually mean that might be true? And if we have to be content with an answer about the reach of explanation, the extent to which a life and a kind of life can be explained, that in itself will be to find out something. 2 The philosophical furniture of my mind consists in fewer pieces than are in my rooms, heavier ones. Whatever their history, and whether they stand to love, beds, rent and adversaries as effects or causes or neither, they do not seem external to me, but internal. They are not goods for sale, for example, or means of getting on in the world, helpful though they have been. Do these pieces hang together themselves? They are certainly no three-piece suite. I have had a thought or two of adding and rearranging things, if not of getting rid of any. Well, maybe even getting rid of something. One large item of my inner furniture is determinism, or rather one kind of thing that goes under that heavy name. I expound it to the first-year undergraduates who drift into my college room for their General Introduction to Philosophy, Mondays at 11, the more incredulous taking themselves to deserve the soft armchairs. We use the heavy name `determinism' in a certain way, for theories that say nothing about freedom or responsibility or hopes, but leave all that to later. What the theories do say, very roughly, is that each of the actions in our lives and also the choosing and willing of it is an effect. It is the effect of a sequence of events or states or properties, each of these also being an effect. The sequence starts further back than any first thought or feeling about the action, let alone the choosing or willing of it. Indeed the sequence goes back to events that are not thoughts or feelings at all. Each effect is what it sounds like, something that had to happen. There was no other possibility. It wasn’t just probable, to any degree. If a story of this kind is clear enough to be true or false, and if it is true, then there is a sense in which everything is fixed or settled in advance, all choices and decisions and all actions, and thus a sense in which everything could have been predicted. All of it, if you subtract the mythology from the word, was fated. I am the somewhat reluctant owner of such a theory, a philosophy of mind in itself, worked out in more detail than some of my fellow workers have valued. 644 pages of detail. Some people say it is clear enough, and many say that any such thing is false -- falsified by the physics of Einstein et al. They say Quantum Theory settles the matter. Determinism is now history, quite a good piece of history since it has Spinoza, Hume, Newton and indeed Einstein himself and most of science in it, but still history. The fact of the matter is that we now know there are things that happen that are not effects. Ask any physicist. This has been hard for me to believe, partly because the interpretation of Quantum Theory, the understanding of what it comes to in terms of the world, is allowed by most of its users to be a mess. Certainly it is a mess, and has remained so for too long. Sometimes verbiage and enthusiasm conceals this, but not very much. What is the mathematics or formalism of the theory about? Certainly not particles or waves of matter in any ordinary or plain senses of the words, as is readily admitted, even celebrated. The fundamental question of what the theory is about goes without a decent answer. So another question arises. Are the things in the theory that are said not to be effects in fact things which we determinists say are effects? We only say events are effects. There are certainly things that are irrelevant to determinism, these being non-events in general, starting with numbers, propositions and locations. We don’t say 7 is an effect. There is also some other trouble for the disprovers of determinism. Suppose, despite my sensible doubt, that we take up the common interpretation of Quantum Theory. Suppose there really are real events that are uncaused or random, truly unpredictable events, down where they are supposed to be, at the physicist’s micro-level of reality. They are so small as to be way below the level of ordinary things and events, including the electrochemical events in a brain that seem to go with choices and decisions. There is a troublesome question. Do any random events at the micro-level translate upwards into events at the level with which determinism is concerned, the level of the brain events, choices, actions and so on? It is good sense to doubt it, for an excellent reason. It is that we encounter no random events at all in the world we experience. No planet leaves its orbit without explanation. No bicycle tire goes flat for no reason. No spoon ever levitates at breakfast. But then it seems that determinism may be unaffected by Quantum Theory even if the theory is interpreted in the common way. The small events of Quantum Theory are irrelevant. Still, I am somewhat happier in having a view about something separate from the determinism problem. This is the problem of the consequences of determinism. If determinism is clear enough and true, what follows from it? What is its consequence or import for our lives. In my view not the heavy proposition that we are unfree. A regiment of philosophers has said that -- or rather that if determinism were true, which it isn't, we would be unfree. They have thought so on account of being convinced that freedom by definition consists in Free Will, daily miracles of true origination, mental events somehow under our control but uncaused. The regiment is wrong. But it doesn’t seem to me either that if determinism is true, we nevertheless can still be fully free -- because determinism and freedom are wholly compatible propositions. Another regiment of philosophers has cheerily said that, being convinced that freedom consists just in being able to do what you want, which you can be even if everything is caused. It is a touch discomfiting that the blessed Hume is among them. My own view is at least new. Professor Daniel Dennett of Tufts University, agreeably doughty though he is, did not endear himself to me when he let the readers of his review in The Times Literary Supplement suppose he had thought of it too. It is in part that freedom is not so simple as either regiment supposes, a matter of a right definition, but is about attitudes and feelings. If determinism is true, we lose some of what we want, but not everything. This, as you will hear later, is where the real problem of determinism starts. It is coming to terms with things, making the right response. Affirmation of a kind. My second piece of philosophical furniture is a conviction about minds, which is to say mainly about consciousness. The two problems here are the nature of consciousness itself and the relation of this consciousness to the brain. My conviction is that conscious events, states or properties involve what it is easier to name than analyse, a fundamental subjectivity. That is their essential nature. They are not anything less. This conviction about subjectivity, much more so than determinism, has a fortifying history. It also has a majority of sympathizers among contemporary philosophers generally—albeit that some have been frightened into hiding by the brash public relations and clutter of technicalities on the other side. The ideas on that other side derive partly from two things I share. One of these is a kind of naturalism. It is the outlook that the natural world, in some sense the physical world, is all that there is. Hence all there is can be studied by unmysterious methods, the main ones being science, cool philosophy, good sense, and an empirical kind of literature and art. The mind, then, whatever it is, must be natural or physical and open to such study. The second and more particular thing I share is our new realization of the closeness of mind and brain, of conscious and neural events. A demonstrated fact of psychoneural intimacy, as I was pleased to name it, is the gift of neuroscience to philosophy. A better gift, as it seems to me, than anything from muddled physics. From such sources has come the brash idea, of no great history, that the mind is the brain, that they are one thing -- where this ambiguity is not taken to mean something innocuous, but that the mind has only the properties of the brain. Or rather, that our human minds have only the properties of our brains, which is to say electrochemical properties. Putting aside computers and other unlikely possessors of consciousness, consciousness is cells, those particular cells that are neurons. This idea gives a solution to the problem of the nature of consciousness that is also a quick solution of the problem of the mind-brain relation. The idea is in accord with naturalism all right. And it could not be more in accord with the fact of psychoneural intimacy. Nothing could make mind and brain more intimate than this particular way of making them identical. It is also an idea for those who are too averse to mystery, too frightened of it, too hooked on the sweet drug of simple clarity. This identity idea takes a number of forms. The simplest version is indeed that consciousness is cells -- Eliminative Materialism. Except in Australia and Southern California, those places of strong sunlight where powers of belief are evidently greater, the pill is always sweetened. One sweetener is that despite what has just been reported, that our conscious events are just brain events, what they really are in their essences are something else. They are functional events, so-called. They are events that function in a certain way. That is to say nothing mysterious, indeed nothing more than that they are certain causes and certain effects. They come from input and they issue in output. This thought could have begun in, but gets out of sight of, certain truisms. One is that a good definition of a particular desire will include, but of course not only include, something about a thing perceived, say a glass of wine, and some resulting behaviour, say an arm-movement -- input and output. The thought also owes a lot to computers, those mesmerizing converters of input into output. This imperfectly consistent story of the mind, then, is that the essential nature of our conscious events is not that they are just neural or material, although they are, but that they are things in the right causal relations. This is Functionalism boiled down or rather decluttered, which it cries out to be. Or, as you can also say, computerized philosophy of mind or cognitive science with philosophical ambition. As it has seemed to me, the coating doesn’t make the pill swallowable. I think of what I had a moment ago, an uneasy feeling about my past. The idea that it had only neural properties isn’t made better by the addition that it had causes and effects, and these were of the essence. There was a lot more essence to the feeling, which was its fundamental subjectivity. That is something easy to say, but a lot harder to say something clear about. To admit the great difficulty is not to give up the truth that consciousness is other than neural properties in bare causal relations. As surely all must know? Nor is it to give up the conviction that conscious events are in intimate relation with neural events. Psychoneural intimacy. My own ultimate working out of that is that they are in a kind of union, as a matter of necessity or law. Or, rather, two different kinds of properties of ourselves go together in this way. And I haven’t given up naturalism. Conscious properties in their real subjectivity must also somehow be physical properties, despite not being neural ones. What else could they be? There aren’t ghosts, and there aren’t ghostly properties in the head either. 3 My daily round starts early. It begins almost every morning at five or six, not by alarm clock but by a habit of awakening and a little determination. There is always something in particular to be done. But the determination is also a general one, to make use of my time. I have sometimes half-wondered if it is owed to what also happens at some stage almost every day, including almost every cheerful day. That is the thought that my time will come to an end. On reflection, though, my onward marching could be a lot more fundamental to my life than my anticipation of its dark end. It may well be that my active determination in the early morning and in the rest of my life is not owed to the thought of death at all. Isn’t it relevant that this determination is often happy, or anyway contented enough? It may not have roots in any thought at all, but be in a way primitive. And it may do some explaining itself, be more of a cause than an effect. Maybe a cause of my thinking about death? At five or six, after coffee and the first dose of nicotine from the chewing gum I should have given up some years back, what happens has very much to do with what happened the evening before. If resolution did not fail and thus I did not exceed my daily ration of three quarters of a bottle of white wine, the early morning passes in happy work. The rest of life can just stop for philosophy. Philosophy can be time out, time away from the rest of life that is happening, and seemingly unconnected with it. This morning was that way. With a bit of luck, I will satisfy the anonymous cavillers who advise the editor of The American Philosophical Quarterly what articles to admit to its pages. With a bit of luck they will take ‘Consciousness, Neural Functionalism, Real Subjectivity’ as fit to print. I thought on looking it over that it was better than that, say measured but magnificent. It is a feeling I and my kind have had before. Writing on these summer days of good hope, now that the college teaching terms are over for the year and the students are gone, can go on to lunchtime. Writing makes my life better. What a blessing to have a life in which the necessary work is engrossing. Piling up truths in solitude, or anyway goodish guesses, or at least things not obviously false. Doing the thing, making a future, rising over the past, escaping the problem of The Studio, getting my due. Nicotine is good, but work is wonderful. I have read hardly a word of Marx, having shared the orthodox condescension of my analytical colleagues for his lumbering metaphysics of history. All that stuff about the dominion of matter over spirit through the several historical eras, got by reversing the unspeakable Hegel. Not to mention the economics. But lately a core of moral perception and feeling in Marx, owing nothing to Hegel, has seemed so true. I have been tempted towards his sinking ship, now abandoned not only by the rats but also by the theoreticians who used to be on the bridge. All market-Marxists now. One part of the moral core of Marx has to do with work. It is his proper accusation against the arrangers of bad lives for others, bad because these others are estranged from their work. Lunch at University College comes in several varieties and places. All the world’s in the Lower Refectory, all colours feeding at close quarters on fish and cannelloni. The Senior Common Room, with good pictures from our Slade School of Fine Art, brings together my college colleagues with an inclination to the genteel, or a desire to get away from students. Or an ongoing interest in the college committees and an ear for the Provost’s new thinking on top-up fees, senior promotions, the decline of the library, and the outrageous idea of selling Bentham’s manuscripts in order to finance the project of editing them. I had an interest in the committees for a while. This college is no cut-throat place, but it is a good idea for a Head of Department to keep in touch. Once an insane Bursar had a look over the Grote’s room, and ventured thoughts about the fuller utilization of space by partitioning, so to have two or three philosophers thinking where one thought before. My lunch, whether in Lower Refectory or Senior Common Room, is usually solitary, partly because we philosophers of University College do not usually congregate. Maybe we are less in need of reassuring company than the physicists stuck with their Quantum Theory. There are other reasons for my solitude. One is shyness. I have had practice in breaking out of it, often into badinage and knock-about, but practice hasn’t made perfect. My daily round in the college teaching terms, most of the year, cannot be just the writing. Monday has an hour given over to devising a decent sequence of propositions for the lecture at ll, the week’s instalment of the General Introduction to Philosophy for undergraduates just come up from their schools. The lecture is not new-minted, not thought up just before or in the hour. Why quarrel with success, even moderate success? The subjects are mainly my main interests of the past, determinism and the mind and so on. They are new to my listeners, even provocations to them. I do not have to try hard to get audience-participation, to prompt the philosophizing from the soft armchairs. My two other regular classes of the week are post-graduate seminars, also in my room. When I became Grote Professor, the Senior Seminar at 5 on Mondays was the focus of my teaching ambitions. I remembered it from my own postgraduate years, as Freddie used to give it, a weekly colloseum in which mortal challenge was offered. The Thesis Seminar, at 5 on Thursdays, is for postgraduates not only from University College but also from those other colleges of the University of London in which philosophy flourishes. The seminar is conducted by me and another professor or two, our dignity not wholly concealed by our bonhomie. They come from King’s College down in the Strand, founded as a reproach to the godless college in Gower Street, where the philosophy of religion has since succumbed to the logical paradoxes and the philosophy of psychology, or from the London School of Economics, whose philosophers breathe easier now that they have escaped the long shadow of Karl Popper. He who had no doubt that he had solved the problem of induction and discovered the nature of science, and appointed lecturers inclined to propagate these two truths, the first being, if you will let me to speak with my customary force of conviction, such that nothing is falser. The problem of induction, you can say, is the problem of explaining how a limited amount of evidence somehow does give rational support to the unlimited conclusion that all ordinary hen’s eggs break when hit by heavy hammers, without the evidence logically entailing the conclusion. Plainly there isn't such an entailment between the two things as between `Kant was a bachelor' and `Kant was unmarried' or `2+2 =' and `4'. The problem is not solved by some bumble including the idea that we do not really believe the unlimited conclusion. Half-believing it, saying it's tentatively corroborated, conjecturing it, even just guessing it, which science is supposed to do, is enough to make for the very same problem. The Thesis Seminar is for a postgraduate’s reading out of a part of his or her thesis, or, more often, work in the direction of a thesis. My professorial colleagues and I do not join battle among ourselves in the discussion, in order to preserve decorum and out of an apprehensive sense that knowledge is diversely distributed among us. I have no love for Formal Logic, and enjoy the certainty that it has not solved or advanced any philosophical problem, and so I have not learned a lot. I am not always restrained by my ignorance, but mostly take care to sit back when others depend on their knowledge. Students discover that a thesis chapter is not impregnable, and provide me with materials, noted down, for the letters of reference to be written to try to get them jobs. In these I am generous, rather than given to severe standards of assessment. That is the story too at those annual gatherings of the philosophers of the University of London, the meetings to settle the classes of B.A. degrees to be awarded to undergraduates. There was one the other day. I argue that our massed judgement is not so acute that that it is clear that this borderline candidate or that can confidently be sent down into the Upper Seconds or the Lower Seconds or the Thirds. The fact of the matter, not congenial to me in every way, is that I identify with those being judged. Certainly I am known for my want of academic principle, as others are known for the opposite. It is my university colleagues whose politics are Rightward who consistently are able to discern muddle and failure. I speculate that they themselves were disappointed, and do not want too many Firsts around, but I do not check up. To the Monday lecture and the two seminars are added other teaching duties more time-consuming but as tolerable. Unlike my philosophical colleagues at University College, and not in perfect accord with each of their senses of justice, I as Grote escape the weekly grind of giving undergraduate tutorials, on subjects fixed by curriculum. That is the repetitive labour, rightly named the tutorial load, which is also familiar to the Fellows of colleges in Oxford, and leads them to say in passing, but more than once, that they might think about moving to a London chair. On the evidence of recent migrations, they must also have thought, in passing, of Chapel Hill in North Carolina, Geneva, and Pittsburgh. In place of undergraduate tutorials, I give postgraduate supervisions. These higher things have their name because, officially, they are more a matter of talking about and advising on work being carried forward independently. They are fortnightly meetings with my own students, aspiring to the M.A., the M.Phil or the Ph.D. They are encouraged to come with some philosophy got down on paper, since it seems to me that one learns most by the discipline of writing. Sections of thesis are better than thoughts on the wing. Not all graduate students have been well prepared for our local ways by their undergraduate years in Athens, Toronto, or literary Cambridge. I work hard with them, but better on some days than others. I am compensated by being instructed, the receiver of goods rather than the imparter, by others of my fortnightly visitors, those who have done more reading than me. On the whole they are amiable about this reversal of roles. For my part, I own up easily. I am not so open or so perfectly composed when they are cleverer than I. We all get on pretty well, or all of us who have a proper sense of our intellectual line of life. That is required for good temper. Philosophy is not any of linguistics, psychology, cognitive science or any other science. To its credit or discredit, there is hardly any Philosophy of Life in it, not much on the meaning of life, hardly any consolation. It is not the history of ideas, morality, religion, politics or political theory. It is not wisdom, the deep, classical scholarship, dead languages, literature, literary theory or feminism. If it is not logic in any narrow sense, certainly not formal logic, you can't read the stuff like a novel, drift through it. You have to think on the way. As for ongoing philosophy’s relation to its own past, to the history of philosophy well and charmingly laid out in the best-seller Sophie's World, that is complicated. There is complication, anyway, with respect to ongoing philosophy in the English language. It does not quite slough off its past as science does, become new in more than its skin. But, except in the piety of historically-minded practitioners and of classicists, our ongoing philosophy does not take its past to be a proper part of itself either. The philosophical past, for almost all of us, is a source of strong expressions of inevitable and inevitably contested views that interest us. That in seeing a cup or any other perceiving, each of us is aware of only private data, not a public thing, or that society somehow rests on a contract that saves us from a state of nature, and so on. For most philosophers, these strong expressions of views are in fact teaching aids. The philosophers of the past are rarely discussed for themselves in the foremost journals. My students and I do not reflect a lot on this or on what our line of life actually is. Rather, having seemed to wake up in it, we get on with it. It is, some others say, the line of life owed to a certain impulse. That is the impulse to reduce to clarity and thereby get a systematic and comprehensive hold on the nature of one or two of the fundamental parts of reality, including human reality. The various fundamental parts, of which you have already heard something, include physical objects, effects, time, propositions, minds, the sources of action, sense perception, reasoning, responsibility, justice, and art. Such parts, some say, some together into three broad categories, having to do with what things exist, knowing about them, and what things are good. It is added that given this impulse of philosophy, getting a clarified hold on a fundamental part or two of reality, it must necessarily ask general questions. There is no alternative to this if you are to be true to the impulse. Nothing large comes into focus close up. But pause a bit. All of that raises a question or two. It seems to make philosophy in its first broad category of concerns, about what exists, more or less indistinguishable from science generally. And does not the second category, about the acquisition of knowledge, make philosophy at least something like part of psychology and a good deal else in mathematics and science? And the third, about value, much the same as morality, religion, and politics? It would be too arrogant to suppose that these various disciplines do not aspire to systematic and comprehensive holds on their subject-matters, and it would be mistaken to suppose they do not ask general questions in addition to particular ones. In any case, there is no want of particularity in philosophy, for all its generality. You can’t see the wood for the trees in a lot of philosophy, some of it about determinism and subjectivity. I suspect the truth is that our line of life is different in that it concentrates more on something. It concentrates more on good thinking about the facts as against getting or using the facts, and good thinking about methods of knowing as against getting or using the methods, and good thinking about convictions as to what is good rather than embracing them. Good thinking in getting a clear hold. That is the real impulse in philosophy. As I say, you can wake up in it one day. To put the main point again, as the diligent lecturer will, there is a kind of division of labour between philosophy and its rivals. Philosophy’s initial and its subsequent questions are peculiarly well-formed, only formed after presuppositions have been examined, and its answers aspire more to clarity, completeness, and above all consistency and other logical relations. In a very general sense of the word, logic is the core of it. Philosophy in comparison with morality, religion and politics is more committed to independence from desire and hope. Philosophy in comparison with science certainly does less grubbing of particular facts, but that is far from saying that it is unempirical if that means it rides over facts or is not about the world. It doesn't aways ride over subjectivity. These generalities may make you forgetful of something already implied in passing. Hardly any philosopher has as his line of life a concern with all of present philosophy, or even just one of the three broad categories, let alone this and all of its past. We're not in Sophie's world. The panoramic historians among working philosophers are odd exceptions, maybe even suspect. Are they bunking off? What we try to do in our kind of life is the good thinking about just one or two or a few of the fundamental parts of reality. The strength of our ambition restricts our fields of operation. Seminar over or postgraduate despatched, I cycle off from Gordon Square, usually up the hill to Hampstead for the television news at 7 in the study and my daily wine. So begins, often enough, a solitary evening. That is now the story two or three evenings out of seven in this summer. If I am inclined to reduce the number to zero, and will do so if I run true to past form, this solitude is no pain to me, but near enough a pleasure. Company and talk, save for the intimate kind which seems nearly half of life itself, has always had two sides for me. One is everything good about it. The other is the obligation to perform, at least to measure up. I try to keep the goods in mind. The happy flare of talk or the rollick, amiability or instruction of it. Also the consolation of it and the credit of being trusted. In anticipation of one or another of these, I am diligent about arranging dinners. Down the street to South End Green and the Tandoori Paradise with someone of my present or past. Almost always with a woman, sometimes Pauline, the mother of my children. The Tandoori Paradise is half-price, since it faces hard competition, and they treat me well there. I do not mind saving a pound or two, whatever the real need. On other evenings I go elsewhere. To parties of friends and acquaintances, once recently to Cheyne Walk where Ken Follett of the novels flourishes, as sagely cocky now as in those past tutorials in the attic at 19 Gordon Square. Or I take myself to the Garrick Club, from which fortuitously I did not resign the other year when the membership rose up to deny the passage of time and affirm that women will not be admitted to membership. The club was founded to be a resort of actors and writers, and remains something of that, despite the influx of judges and politicians and titled persons looking for better company. The membership committee at the Garrick does not look so kindly on applicants as I look on candidates for the B.A. Why, if I am a member at all, am I not sharp and superior with the reactionary and misogynist novelist or the pushy peer? Instead I try to hold up my end companionably and amiably. In fact I have not looked too closely into the question of whether being in this exclusive and self-approving crew is consistent with my principles. I do remember a line from my undergraduate days. It was that the argument for revolution is in part not the superiority of common culture, the moral grandeur of the working class, but the awfulness of that culture and class. True or false, I would not deliver the line now. On yet other evenings, a few, I give a dinner in Hampstead. A little Boswell-like, and hardened against the charge of snob, I have in admiration sought out several who come. One is Michael Foot from up the hill. He knows how to sing for his supper. Would that the working class had risen over its unspeakable newspapers and elected him Prime Minister. Our local beggar Alan Cook might not be on the bench outside the church, but have a job, and our library might be open oftener. My dinners in Keats Grove are not short on drink, and those who come are organized into general conversation. I am in practice from the seminars, and, comic or not, do not plan to give up. I would do otherwise to suit my son if he would come, but usually he won’t. 4 Some of that brings to mind a third philosophical conviction of mine, the Principle of Equality. It is not one of your lawyer’s or sensible philosopher’s or closet Conservative’s principles of justice. It is not hung with weights of respect for the world as it is. It is not a petty principle of no more than equal respect for persons, which comes to nothing much until turned into something else. Nor is it the famous principle about the distribution of primary goods owed to the goodly if doctrinally-burdened liberal of Harvard, Professor Rawls, a principle whose upshot is uncertain, and leaves politicians of any party able to add it to their talk. The Principle of Equality, in brief, is that we should not be distracted or detained in any way from trying to make well-off in a certain sense all those who are badly-off. That is the solution to the problem of justice. This third philosophical conviction of mine is also a moral conviction, and so cannot have the kind of support of the first two, about determinism and subjectivity—the support of fact. Perhaps that is why I have held on to it tenaciously. It has needed allies. It would be fine, of course, to be able to agree with a handful of philosophers who have lately become bored with the orthodoxy about the nature of moral judgements -- that all moral convictions are personal feelings. They have revived the earlier piety that moral convictions can be true . True, they say, in roughly the same way that it is now true that the trees I am looking at are green. We human perceivers contribute something in both cases, by way of our particular perceptual or other personal equipment, but value is as much a fact of the world as colour. They call this Moral Realism. How estimable and how merely audacious the idea is. Too good to be true. So much stands in its way, beginning with the intractable fact that we agree about what is green but not about what is right. The Principle of Equality, when spelled out, stipulates what it is to be well-off or badly-off -- in terms of the satisfaction or frustration of fundamental human desires. These six desires are for a decent length of life, material goods that give a quality to life, freedom and power, respect and self-respect, closer and wider relationships with others, and the goods of culture. The ways in which we are not to be distracted or detained from making people well-off are many. We are not to be unnecessarily concerned with incentive-rewards for those who contribute something to economic progress. We are not to be unnecessarily concerned either with improving the lot of those who are already well-off, or with any of deserts, special liberties, rights and privileges, duties to be done despite bad consequences, truth to oneself, or ties of loyalty and blood. You will notice, close reader, that according to the principle there is to be no unnecessary concern with those things, which is not to say no concern at all. You may suspect, suspicious reader, that the principle is really not so brave. Not so brave in intent as that deceptive but in fact pregnant sentence of the English Revolution uttered by Col. Rainborowe in the Army Debates at Putney. ‘The poorest he that is in England hath a life to live as the greatest he.’ Well, it is certainly true that the principle is not out of sight of all other morality. It does not require overturning the world to the extent that might be supposed. There is the point too that it has not yet reduced me myself to penury, that I remain in the class not of champagne socialists but certainly prosecco. On the braveness of the the principle, one thing to be said is that it would be irrational not to adopt the various means to its end when they are really necessary, including the means of certain incentive-rewards and the resulting inequality. But note also that these will be means to its end, the reduction of the number of the badly-off, rather than the end of some self-serving economic progress, say an increase in total economic goods in a society. Further, and very importantly, the principle is to be so understood as enjoining us to work at reducing the incentive-demands of contributors to the goal. I have not been so alarmed as the amiable Lord Quinton, reviewer of a book of mine in The Times , by the idea of the need for re-education of the profiting classes. With respect to the prosecco socialism, I do confess that in the disposition of my salary, I have not been very true to the Principle of Equality. What follows about me from this failure? Quite a lot. I may turn out to have no justification for myself, but only a thing or two to say in mitigation. Is it not better to be a self-preserving or even self-advertising advocate of a human principle than a more consistent advocate of an inhuman one? Something else is more important. What follows about the worth of the principle from my failure to act on it as I ought? Not much, as it still seems to me easy to say. Is a principle put into question by a failure to live up to it? This would be embarrassing not for one morality, but for many, maybe for all things that can claim the name of moralities. ‘Do as I say, not as I have done’, whatever it tells you of the sayer, may be exactly the right instruction. Another conviction in this particular philosopher's bundle, a fifth if you do not count the one against Moral Realism, is about the problem of political means-to-ends and in particular political violence. It is that there is something rightly called democratic violence, something that has enough of the recommendation of democracy itself to deserve the name. Does it have a moral justification? Well, certainly no more automatically than the result of a democratic election is automatically right. But let me put aside for a while this item and some others related to it. They need slower handling. Another conviction has not been put on paper before now, and is less worked out. It is yet more relevant to what follows in this book. The question of personal identity as philosophers ordinarily understand it is the question of what makes a person at a later time numerically identical with a person at an earlier time. What makes you today one and the same person as some boy or girl of the past? One bad answer now put aside by philosophers is an enduring inner self of an extraordinary kind, a voyaging thing in a person, different from both a flow of experiences and the continuation of a body. One better answer is that the later and earlier persons involve one body, one continuing organism. Another better answer, in essence, is that you today remember experiences of the boy or girl. My own philosophical conviction is not that one of those two better answers is right. It is that we are missing what is most important in this neighbourhood if we ask the ordinary question of what makes a later person identical with an earlier. What do we have personal and moral attitudes to? In the ordinary course of life, what is it that we admire or hold responsible when we admire a woman or hold her responsible for something? The answer appears to be the person she is. That is not something which is the same as or includes the girl she was. We admire or morally disapprove of something to which certain facts are integral, say style or intolerance, which facts may have been no part of the girl she was. To express the point in a philosopher’s way, our fundamental attitudes to others are to person-stages. Our attitudes are to a stage in the existence of a person, this being importantly a matter of two connected things, dispositions and conduct. We may also have lesser and more passive attitudes to a past person-stage, of course, a person someone was. The thought has to do not only with our attitudes to others, but our attitudes to ourselves. I, in being concerned with myself, am concerned with a person-stage, the person I am or a person I was. Suppose the two are different, and in particular that I have become more honourable. There is a sense, obviously, in which I cannot hold myself responsible for the dishonourable past or be shamed by it. The person I am is not dishonourable. Certainly we sometimes feel this way about other people. To be convinced that a man is reformed, which is not easy, is necessarily not to hold responsible the person he is for what happened in the past. This thought in the direction of exculpation is not the only thought there is in this neighbourhood. If it were, then if I really did know I was reformed, everything would be rosy. I could contemplate my past not only in a passive but in a detached or dispassionate way. But could I? Even if I knew I was reformed, surely I might remain troubled or even tormented about my past. How can this be? If I were to believe in an inner self sailing through all my person-stages, that would seem like the beginning of an explanation. But I don’t believe in an inner self. Thus my fifth philosophical conviction, to describe it again, is that the crucial questions of personal identity do not have to do with identity over time but with the persons we are, the persons we have been, and the connections between them. This survey of my convictions might now turn in the direction of the question of the nature of truth. It seems to me a real question. It did not go up in smoke when the Cambridge philosopher Ramsey noticed in the 1920’s that ‘It’s true that it’s raining’ seems to come to no more than ‘It’s raining’, and thereby had the idea that philosophical talk of truth is redundant. Despite rediscovery of Ramsey’s discovery by my new and esteemed colleague Professor Horwich, there is a question of the nature of truth, of the general condition under which a factual statement is true, and the answer, somehow or other, still seems to be some kind of correspondence to things in the world. Or the survey might turn to the problem of the nature of sense perception -- seeing and the like, mentioned in passing some way back. Here there is now more allegiance to the reassuring proposition that the objects of our experience, the things each of us is aware of, are not private to the person in question and fleeting, but public and more or less enduring. Not sense-data of trees, but trees. Or we might turn to the analysis of desert, or of what it is to argue that someone deserves punishment in particular. Take the second. My persistent proposal has been that it is really to argue that punishing him will give satisfaction to people, satisfaction in exactly the distress or suffering of others. That is what talk of desert comes to with the institution of punishment. Many have disagreed. They think better of it, and of us. They want more moral tone in their solution to the problem of the justification of punishment. Or, something might be said of the nature of time. Does it amount only to relations? To things being before other things, simultaneous with them, and after them? If so, what of the facts of past, present, and future? Can it be that saying something is present is just saying it is simultaneous with the saying? And that saying something is past is saying it is before the saying? And that saying it is future is saying that it is after the saying? Many who like neatness have thought so. But let me leave all of that, and end this tour with more political philosophy, near to politics. More of my political convictions, like the Principle of Equality, have in them a feeling that issues in rant and insult and sometimes seems what it never turns out to be, ungovernable. It is the feeling, certainly not unique to me, of the awfulness of the conditions of existence of so many people. For a start, so many are deprived of what almost all of us want above all, a living-time of decent length. With the 21st Century begun, what is to be said of any political tradition or party that does not embarrass itself by shame or rage about societies where humans exist as if they were a lower species? I have in mind societies of half-lives, where an average life-expectancy is not about 72 years, as in the societies we know better, but about 40. This grisly fact about lifetimes in other places has smaller replicas at home, still awful enough, about the bottom socio-economic classes in Britain, America, and the like. The feeling of shame and rage, in so far as it issues in political convictions, issues first in convictions about our democracies – those systems about which some of us are so morally reassured by the fall of Communism. These democracies, which we now propose to teach to all the world, make a signal contribution to deprivations in living-time at home and abroad, and to other deprivations as terrible. Given this fact and some others, how are we to understand our democracies? The annual Conway Memorial Lecture had been given 68 times before I got my turn some months ago. I was mightily pleased to get it, not least because Bertrand Russell was among the figures in the list of my predecessors. My title told all in advance. ‘Hierarchic Democracy and the Necessity of Mass Civil Disobedience’. Given the kind of democracy we have, mass civil disobedience is a rational and necessary supplement to it. This advice, you may say, is utopian. Well, utopianism is a right of philosophy, a right which has served us all very well. And I am not sure the advice is utopian. It was easier to be sure about that before the fall of Communism, before the civil disobedience that precipitated that once-impossible thing. Still, was my confidence in laying out the two convictions of my lecture reduced by something other than the fact that Conway Hall was less than full? That the audience, true to the venue, seemed to consist mainly in the good autodidactic atheists of London? I think so. The prospect of laying out my footnotes to Rainborowe, Rousseau, Tom Paine, R. H. Tawney, Russell, and I suppose Marx, was less than a happy one. And still I believe my footnotes, or so it seems. 5 My inner life, as you will have gathered from my daily round, is in one large part exertion. It is my trying to do some of that good thinking and arrive at some of those high-quality questions and answers, the stuff of philosophy. But in my case, as with many of my fellows, this is not so elevated an activity as might be supposed from an abstract description. Even if philosophy alternates with the rest of life, switches it off for a while, it is not what might be called the project of pure inquiry. The activity is directed towards truth, but also towards truth got down on paper or anyway into the external world. Would I understand more if I were higher-minded, less concerned with output? More Cambridge, as Cambridge once prissily conceived itself? I doubt it. I suspect I would understand less without the pressure of my own and other people’s deadlines. As a result of them, I may go out of this fallen world knowing more., prudence or principle, it may have more truth in it. It may not conceal hurts or try to talk up a reputation. But there is another side to the coin. Since this reflection and feeling is also not constrained by the scrutiny and judgement of others, by public tests, it may have less truth in it. So if inner lives can have less hypocrisy and calculation, they can also have less sense and realism. I have reason to remind myself of both points. Inner lives of this second kind can have various concerns. There is the long spiritual but more intellectual than religious tradition, to me glowing in its aspiration, of those taken up with what they take to be true reality. Something better behind the appearances. Ingrid, lately sent by Plato to remind me that naturalism is not the only possible human condition, and that atheism is not identical with rationality, contemplates the Form of the Good and related matters. She presses on me a sentence from Iris Murdoch -- ‘Good represents the reality of which God is the dream.’ Attracted as I am, partly because of that fact of being a little death-minded, I feel the impulse at moments to try to join the glowing tradition. I resist cavilling about whether Iris’s sentence should not have ‘is’ in places of ‘represents’. I wonder again if there could be a kind of hope that in some way is true. It would still be hope, since it could not possibly be ordinarily-supported belief. But it would be hope somehow partaking of truth. My last mother-in-law liked me more for the idea. It doesn’t really come into focus. So I do not succeed in the impulse to join the glowing tradition. There is too much metaphysical mist. Some take the line, of course, that despite the mist, you can have some sense of something. Although it is disputed by his less damp admirers, Wittgenstein seems to have been inclined this way. ‘Whereof one cannot speak, thereof one must be silent.’ It was Ramsey who in this case made what has seemed the right reply. ‘What you can’t say, you can’t say, and you can’t whistle it either.’ It is right, isn't it? As for religion itself, or more literal religion, including plain immortality, that is unthinkable. Surely the autodidacts in Conway Hall are right about that. For me to turn to religion would be cowardice. It would be to hide from truth. Sad or terrible truth, but truth. I go to concerts in churches, and not only for the music, but I do not believe or, really, want to believe. You can only want what there is some chance of having. The little I have been able to do along these lines is to affirm to myself that despite my failings I have a vicarious membership card in a moral struggle, a great struggle in politics that will certainly outlast me. It seems at moments to have outlasted the Labour Party that we used to have. It will last as long as there is desire and there is reason. Reason will always see through pomp and sham and nonsense to the need for real fairness in the satisfaction of desire. I can identify with the struggle sometimes, be reassured by the thought of it going on after me. I have once or twice succeeded in thinking of it as holy. To those several feelings are to be added some that can flow from a theory of determinism. The theory is hard to believe, and what has seemed the right response to it is hard to sustain, since our culture runs against it. Mothers, those first agents of culture, set us against this response. Rae Laura Armstrong Honderich was good at that, in no need of support from John William Honderich. From time to time, I have the consolation of personal success, the kind that matters most. That is personal success by one’s own present test. I wanted to be a professor and then the Grote. It has sometimes been my story that academic ambition was at first pressed upon me, that the asp was put into my breast by others. In whatever way it happened, and that is something to look into, I came to have the desire. On some days its being fulfilled is still worth something. I see from the phone book that some of my fellow professors announce their standing in their entry and some do not. Professor Wiggins of course does, and Professor Papineau does not. I do. Maybe I should take it out, but I think I won’t. My life has something in it I like, and am willing to advertise. But perhaps I should fill out the entry. ‘No sage, not so clever as could be, too quick to declaim truth rather than argue for it, shrewd, sticks to subject, has got one or two things right, more than most competitors, does not always make enough distinctions to satisfy former teachers, has a good sense of unnecessary distinctions.’ Another of my consolations is the happy contemplation of other minds when they are on view, and other bodies. I am never long in that bleak mood where all humankind are a bore. Seeing a happy couple swinging along downhill is a fine thing that can cure the mood. So is seeing a kiss. Hampstead High Street does very nicely for the purposes of this respectable voyeurism. I recommend it, and am pleased on occasion to be part of the cure for others. The pleasure of seeing happy couples has to do with something larger in both the contemplative part a bit more than middle-sized. I have been a libertine too, if one of those goes on being free from convention, and does not go in for much concealment of his freedom. Not often a womanizer, if one of those is deceitfully unfaithful in his relations. My relationships, certainly, have not been with bodies -- with someone in terms of more than their bodily attributes strictly speaking, presumably, but not enough of the rest. My relationships have been more ordinary. They have been with persons, and, to the extent that the distinction can be made, have had more to do with qualities that give rise to affection or love or maybe admiration than with qualities that give rise directly to desire. At the very least my connections have been friendships. Our lives have been connected. It is a perhaps prim to say so, and suggestive of more restraint with women than has been the case, but I have been with a prostitute only once. She knocked on the door of my room one afternoon, and was pretty and drunk. That was Regent Square, not far from college. I was not in my quiet state, thinking of truth and ambition. We bargained a bit, and I, not wanting to be lost, which I would have been by giving her money, said I had only cigarettes. She performed a lesser act, only later dignified by the American presidency. Sometimes I have drifted into thinking that it was only on that occasion that my activity was not made respectable to myself by at least an illusion of something else, some future. That is not true. But it is not far from true. I have not been among those who have seen, no doubt truly, that sex can be a thing that is good in itself. The fact that I have been a man of many women sits in my mind as something about which I am a little rueful but it is not a large fact or a stigma. I care about it, and keep quiet about the number of my lovers, and how far I am ahead of Russell and lag behind Freddie and some energetic lesser lights in our way of life. But I care less than about having not taken the philosophical world by storm. I would not subtract one connection from my past, and I feel or can summon a fondness at the very least for each of them. I feel some of that traditional pride, the pride of having done what many other men have wanted to do but not done. I have on a few occasions, encouraged by another’s curiosity or prurience, in a way boasted of it. For the most part in my relationships, or so it has seemed, I have never strayed far from truth for long. I have with an exception or two been faithful until near the ending of each settled relationship in which faithfulness was the policy. Almost all my relationships have indeed begun with a hope of futurity in them. I intended not to be one of Donne’s dull, sublunary lovers.. Defending myself in passing against the charge of having been with too many women brings me to a last large part of my inner life. I remain more uncertain about my general moral standing than my defence in connection with women suggests. That defence is not confident, but argumentative or speculative, and it is put in partly for the reason that nobody ever found his way to truth about himself by collapsing. I need to hear both sides, one of which is mine. I have heard something of the other side before now. Jane took up that brief on behalf of the sisterhood. But hearing from myself and remembering my critics has not answered the question of my human standing. The uncertainty does not have to do only with women, but also with my son and daughter, and maybe my academic progress down from the attic in Gorden Square, and my politics seeming to be inconsistent with other things. The nature of morality is no easy matter, but clearly one’s standing is not in itself the question of whether a particular action or a kind of action or a habit was right. That is the question of whether it ought to have been done or engaged in, given the best judgement and knowledge at the time, maybe not one's own. Many have done right things by mistake or in ignorance or out of bad motives, and hence got no credit. Many have done wrong things out of innocent ignorance or misjudgement, and earned no condemnation. Nor is the question of standing just about the judgements, beliefs, feelings and motives of a person with respect to a particular action, kind of action or maybe habit -- about the person’s moral credit or moral responsibility for that particular thing. The question of general human standing, rather, is about a person’s general decency in a whole stage of a lifetime or maybe all of it. This general decency or want of it is something like the the sum of one’s good and bad records in the particular cases of this action and that -- the pluses and minuses of moral credit and moral responsibility. This general standing is one thing to worry about, as I do. Another, to revert to actions, is about whether mine were right. Whatever my beliefs and motives and the rest, and however things turned out, did I act rightly? It is very possible to think differently later. That the matter is not merely historical or theoretical, but troubling, suggests some doubt about my separating right actions from the matter of standing. But it can hardly be that one counts as bad just because one did the wrong thing -- there are honest mistakes and there is ignorance. Whatever the truth of all that, the questions of my standing and of whether I did the right things seem always in the offing. They are so hard. Partly they are hard because of the problems mentioned earlier, having to do with the person I am and the persons I was. There is also the problem of self-deception in one’s struggles to see one’s standing and whether one did right. Nietzsche, one hopes, was not yet mad, but merely being provocative, in writing his lines to the effect that in such struggles self-deception will always carry the day. `"I have done that" says my memory. "I cannot have done that" says my pride. At last—memory yields.' It doesn’t always. It doesn’t with me. Memory may see to it that self-deception does not put a happy end to the struggle. Conscious self-deception. to introduce some useful detail, presumably does not consist in what people often suppose -- the paradoxical feat of consciously believing opposite things at the same time. It isn’t one’s ordinary self or consciousness being two, the first believing X but successfully deceiving the second into believing Y. By my lights conscious self-deception consists in one single self maintaining itself in uncertainty, keeping a question open, taking care not to look closely at what might turn out to be evidence against what it wants to believe. That is something we can do. Self-deception is essentially having the desire to look away from possible evidence, and this desire’s resisting the pull to truth. If we think this way about self-deception, Nietzsche’s thought turns into the somewhat different thought that we will always succeed in not looking at what might be unhappy evidence. Surely it isn’t true. Evidence can raise its head, arm the inclination to truth, unsettle the strategy. I fear there is some in the archive of my steamer trunk. Person-stages and self-deception are not the only problems. Do I bring a general and distorting guilt to my reflections, a predisposition to judge against myself? There are some thoughts that give me reason to wonder. They have to do with the effect on me of the gentle rightousness or anyway virtuousness of Rae Laura Armstrong Honderich. Or, on the other hand, do I take a necessary arrogance too far? If I will not find my way to truth about myself or anything else by collapsing, there is also the real danger of being too tough-minded. To remember my critics, of whom I have a sufficient number, what is to be said about something else, the fact of mixed motivation? It has not been paid much attention by moral philosophers, who have mainly been content to think of purer cases. Much of my life has come out of both respectable and not so respectable thoughts and feelings. Judgement cannot be quick in this neighbourhood. Sometimes it seems that it can’t be slow either. An ex-colleague of whom you will hear comes to mind, and the alleged stabbing in the Grote's room, and the thought that true rage can have calculation in it or going with it. Coming towards the end of this tour of the interior, I see that I have left out so large a fact, my moods. Like my feelings focussed on or directed at persons and other things, which include rage, my moods are strong. My good ones are close to exuberance, my darker ones on the way to despair. These all-encompassing things have sometimes seemed to me in a way not prompted by events in my outer life at all, not to successes or failures, good luck or bad, or the contributions of others. That cannot be right. But it does seem true that my state of body, that large inner fact, ordinarily has more to do with the cast of my world. Depression is tiredness, I used to say, and I still find some sense in that false proposition. So much, so little, for my inner life as I think about it, but one thing remains. Some doctrinalists of the self and personality say my inner life as I am aware of it is only part of the story, the smaller part. In a way they are absolutely right. I have an unconscious mind. Being human, I must have. It has been said about all of us so often. ‘...the absence of a conscious perception is no proof of the absence of mental activity.’ There are ‘processes in the soul of which we are unaware....’ ‘Our human souls are not always conscious of whatever they have in them....’ ‘consciousness and unconsciousness are like warp and weft.’ ‘...ideas and matters of fact...lie by for use, till some fortuitous circumstance makes the information dart into the mind....’ ‘Consciousness only touches the surface.... The great basic activity is unconscious.’ The six sentences are not Sigmund Freud’s, of course, but come from a small selection of his predecessors. Plotinus in the 3rd Century A.D., Aquinas in the 13th, Cudworth in the 19th, and then Goethe, Wollstonecraft, and Nietzsche. The total number of Freud’s predecessors, I suppose, were all the reflective members of the human race before him. It is no surprise to me that through known history the truism has been recorded that our lives have in them ongoing mental facts of which we are conscious only sometimes. One of mine, although not breathtaking, is my belief that my name on my birth certificate is Edgar Dawn Ross Honderich. Philosophers have long given these ongoing mental facts the name of being dispositions. Dispositional beliefs and dispositional desires mainly. They are, as I sensibly see it, not items that are conscious in a second sense, items in a dimly-lit or even pitch-black level or part of the mind separate from the ordinary conscious mind. What they are is neural facts, standing causes that may or may not issue in the only consciousness there is. It is convenient to use the language of ordinary consciousness on them, to speak of them as beliefs and the like, as it is convenient to talk about the rest of the natural world and machines in terms of goals and the like. Missiles seek targets. But let us not turn convenience into mystery. We have enough levels of reality already. Freudians are inclined to let the innocent suppose that the large fact of the unconscious was discovered a while ago in Vienna. They are inclined, too, to let the truism that it exists do some work in recommending something entirely different from it. I have an attitude to that different thing and to the stratagems used in its defence. My attitude, I confess, is such that while there was time in my itinerary in Vienna, after the Palais Wittgenstein, to see the university staircase where the student shot the Logical Positivist, there was not quite enough time to get to the house where Freud lived. The thing different from the fact of the unconscious is a special theory of it, a theory of what is in it. At bottom this is the colourful if now somewhat faded story that what each of us mainly has in our unconscious is sexual desires somehow left over from earlier on. Mine, in the theory, were for Rae Laura, tired and other-worldly as she was. Here my powers of belief are weak. Test the idea, if you want, or astrology, with the narrative that now begins. 6 Village The Anabaptists were the Left Wing of the Protestant Reformation. They shared the view, too reasonable for the 16th Century and indeed for Luther, that true baptism into the church cannot be of infants, but needs to be a commitment by adults who know what they are doing. ‘The Christian life is not child’s play.’ They added to this view a strong distinction between the unworldly and the worldly, an avowal of the necessity of separating church from state, an aversion to hierarchy, and a refusal to bear arms or swear oaths. Some were burned and others drowned for their heresy—at bottom, as seems to me likely, for standing up a little against the world’s injustice by way of their religion. Among the Anabaptists were the Mennonites. They were still unpopular and migratory at the beginning of the 19th Century. Unlike some of their earlier brethren, they were not looking for a place in which to practice community of goods and women, but only for a less radical religious freedom and quiet lives in good farming country. Among them were Christian and Margaret Honderich, who emigrated from South Germany to Canada in 1825. They cleared virgin forest near what would afterward be the villages of Baden and New Hamburg in a Germanic township of the province of Ontario. Their son, to be the Rev. John Honderich, was, as his tombstone says, ‘the first male white child born in Wilmot Township’. My ancestors in Canada on my mother’s side of the family tree also came as pioneers. Those on her mother’s side came in 1831, to what subsequently were predominantly English and Scottish townships. Here the villages were to be Kincardine, Kinloss, and Lucknow. The original ancestral pair were Richard William Haldenby and his wife Hannah, he of an unprosperous generation of an old and well-connected Yorkshire and East Anglia family. Thus our family geneologists have been happy to prove that we share a past with Lady Diana Spencer as she was, she who was to have been Queen of England. To the Haldenby or English line, there was subsequently an admixture of Irish, no doubt useful. County Armagh. I have not yet informed myself about our first Canadian ancestors on my mother’s father’s side, the Scottish side, or their ancestors in the border country, although research by others is well forward. Still, I have been pleased enough to count myself as not only coming from German, English, and Irish stock, but also of the Armstrong clan. True to my Anabaptist forebears, I left it until coming to my maturity to elect a nationality. Born a sixth-generation Canadian, British I became, at any rate by passport. The church of the Reformed Mennonites were more liberal than some, the women not being confined to bonnets nor the men to hooks and eyes in place of the ornament of buttons. They were not paradigms of toleration, however. Their doctrine did not allow them to hear other religion. My grandfather and father on an occasion took themselves to hear False Gospel in another church, although, as will transpire, the verb ‘to hear’ is not quite right. They would not recant their visit, and were formally excommunicated from the Reformed Mennonites. Thereafter, other members of their own family, on meeting them, could not shake hands, but were permitted a grasp of the shoulder as a sign of affection. A lesser martyrdom. Rae Laura Armstrong was a school teacher, her father being an officer of the court in Bruce County, and her mother, so it was afterward said, being a reader of books rather than a keeper of a house in punctilious good order. Rae Laura was finding Anglicanism and the like insufficient to her soul’s impulses, and was yet more engaged in the spiritual search than my father. They met on a train to a religious gathering. Perhaps it was early on that my father undertook with her, as at some stage he did, to devote their lives to being missionaries. In any case it was a spiritual side to him which overcame what he also possessed, a distinct shortcoming. He was profoundly deaf, the victim of a childhood sickness. He had learned to lip-read, but, because he was not expert in this, she was to learn sign-language. They married within a year, he 29 and she 25. It was she, it seems, who brought character and invention to the naming of several of their six children: Ruth Laura, Loine Christian, Beland Hugh, Robert Wayne, Mary Jean Kathleen, and Edgar Dawn Ross. I, last of the six, was born on 30 January 1933 in my grandfather’s house, to which we had succeeded. My mother was several weeks short of being 45. Much later, in England, my accent having been worn down and also somewhat improved, ‘going to mass on Sundays’ having been made indistinguishable from ‘going to moss on Sundays,’ the curious sometimes touched delicately on the matter of my antecedents. I sometimes responded with a weak jocularity. It was that I was born in a filthy peasant village. One aim of the jocularity, which I have given up, was to get in first with some superiority. It also conveyed another fact, a vestige of resentment. Do I feel it still? Is there something to be said for my unkind description of this place that seemed to be my life? Baden in 1933 and into the 1940’s had a population of about 700, very many of them bearing German names. Basts, Gingerichs, Naumanns, Schwartzentrubers, Webers, and Zehrs. They supplemented the English language with a German dialect. The village looked beyond itself, in so far as it looked anywhere, only to the county town, ten miles away. This had been named Berlin until the First World War. Then soldiers of English descent made trouble, throwing the Kaiser’s statue into a lake, and it was thought wise to rename the town. It became Kitchener, which it still is. Baden, having no soldiery and no statue, saved its name. In its twelve unnamed streets were about 165 houses, township hall, churches for Mennonites, Lutherans and Presbyterians, two hotels, school, bank, butcher, baker, cobbler, post office and four other shops. Also two declining blacksmiths, three garages, a foundry, mills for flour, linseed oil, wood and cider, places for the waxing of turnips and the making of Limburger cheese and electric fences for cattle. Railway station, volunteer fire hall, undertaker cum seed-merchant, softball diamond and two tennis courts, a stream, two dams. And, remembered in fullest detail, a telephone exchange. I enumerate these partly to indicate that the village of 700 was sufficient unto itself. Partly because of this, it was a community, something with a membership. From the start, I seemed to myself not a full member. There was not only the reason of my family’s excommunication from a respectable and conscientious local tradition of religion. That was a first cause of another fact. An unspoken breach eventually opened between us and the farming Honderichs, who would otherwise have been my allies of blood. My cousins, to my mind, were on that other side. We did not speak much at the softball games. There were also larger things that stood in the way of my being a full member of my village. My father was odd, first on account of his deafness. When I became aware of him, he had already gone into his private world of silence. Certainly he made affectionate excursions from it, which I loved, and occasionally raging ones, but mostly he was in that other place, in which he was not unhappy. It would be wrong to say that the village was such that many in it made mock of him for his affliction and his departure from local space and time. But a few did, or at any rate included it in the roster of his shortcomings. Chief among these was his lack of the principal virtue. He was not a good provider for his family. He had inherited a large house on the death of my grandfather, but also a decent amount of capital, and had founded a number of newspapers, one being The Baden Sun. It is difficult to see these and similar endeavours as manifesting a commercial realism. Nor was there great evidence of such an attribute when, as you might say, we met our Waterloo, more particularly the Waterloo Trust Co. It threatened to foreclose on a mortgage he had taken out on the house. His response was to circulate a petition on our behalf among the villagers, against the iniquity of the Waterloo Trust. This did not greatly detain it. He took his family to lodgings and then to a lesser habitation at the edge of the village. He did not learn to make ends meet. Rae Laura no doubt rejoiced, as certainly she did on other occasions later, when the Almighty worked in a mysterious way. The post of village telephone operator fell vacant. With it went a proper house, the telephone exchange. Thereafter there were considerable hours of paid work at home. It was she who was the principal and steady provider for those of the family who had not taken wing, quite soon only I. I did most of my growing up in the telephone house, aware that we had come down in the world. The eight rooms behind its front verandah included one for the telephone switchboard and an adjacent bedroom for my mother, to whose operating of the switchboard for much of the day was added night-duty. My father paid visits from his bedroom upstairs. These were never explicitly connected by me with a side of life about which neither he nor Mother ever uttered a word to me, save for a later and inexplicit aspiration, by Mother, that I would come as a Christian to my wife. The house was not inferior to some others, and neat in seven of its eight rooms, but various reflections were to reduce its desirability for me as a residence. We did not own it, and our having it was dependent on my mother’s labours. There was the further fact of the hand pump in the kitchen, which drew water from a well. This did not compare with the gleaming taps in the kitchen of our neighbours the Kuhns, financed by the making of electric fences. There was also the outhouse or privy, attached to the nearer of the two small wooden barns in the long back garden. The eighth room of the house, the one that was not neat, was the inner domain of my father, a sweet place of my early memories. It contained, above all, his printing press. Out of its slow breathing when the flywheel was sustained by the foot treadle, breathing unheard by him but listened to by me, came his pamphlets. Several of them, as I was to know later, were arguments for religious toleration. They were, to say the least, not widely circulated, but no doubt copies found their way to the Reformed Mennonites. That Father was a pamphleteer in a small way may suggest that the household was at a high level of reflective and cultural activity. Well, he was concerned with ideas and, as it seemed, turned them over in a somewhat leisurely fashion in the silent world, but he was not burdened with learning. Nor did the printing press produce only pamphlets. From it came labels for his products, the last of these being VIM, a patent soap of some fierceness. Mother and Father discussed religion, and argued peacefully about it, sometimes a little enlivened by the strongest drink in the house, which was Pepsi-Cola. But she was not of a persistent intellectual bent. Although she never lacked her school teacher’s resolution that I be educated, she did not take on the task herself. I think she was worn down, not only by the switchboard but also by life’s not having gone according to its high plan. They were, as I have said, to be missionaries. On many days she glorified God to me, but she never visited a foreign field to do so to those less familiar with the experience. My parents could not now divert dollars to enlarging the household library. It was meagre, containing such items as a volume of Byron, Robert Louis Stevenson’s Kidnapped, and The Boy’s Own Annual, insufficient antidotes to the Bibles, hymnals and tracts. Still, the little collection existed, and was read through by me several times. Thus the uncertainty of my membership in my village, and the part the village played in this, were owed not only to the old fact of excommunication, the casting-off by cousins, the deafness, Father’s lack of the principal virtue, and the telephone house. We were also unique in the reflective and cultural activity, such as it was, undramatic and mainly religious. The meaning of life was not much considered elsewhere in the village, or the difficulty of justifying God’s ways to man. Moreover, this activity and in fact the whole of our family life were rightly perceived as English and Scottish in timbre rather than Germanic. Father had in a way defected to Mother’s side, perhaps in a way been overcome by her. If I did not do so then, it is hard to resist assigning a philistinism to my village. Baden was unprepared for us. You will find no public library in my list of its utilities. Still, you may wonder if there is room for a question. My brother Bee may wonder. Was the uncertainty of my membership only in my own small head? Herb Miller lounged against the window of his corner shop, within range of a five-year-old and his tricycle. When I passed, I and he alone at that bare corner, or I and he with his crony, a foot of his would find its way under one of my rear wheels. My five-year-old falls to the pavement must have pleased him. Perhaps as much as his name for the Edgar I was. It was Ga-Ga, whose mockery served him well until I went to school and was discovered to need spectacles, after which time Four Eyes served him well. He was not deranged or defective. While not the most highly estimated of the 700, he was not excluded by them or notorious. Others took up his usages, but it is he who would come to mind first now if I were to try to excuse my later epithet for my birthplace. At least once after having been deemed to have attained that first level of personal responsibility to which all are called, I did not hold to it by making my way to the privy behind the first small barn. Rather, I produced a small brown pile, still nicely formed in my mind’s eye today, behind the stove in the shadowy kitchen. The result was remonstration, and guilt. The guilt was deep. In that way of families, a place had been prepared for it. I was not punished, nor, so far as I can remember, ever punished thereafter by my parents, for anything whatever. It would be agreeable to say that the pain of guilt was really the pain of withdrawal of love. That, I think, was not so. It was not the felt nature of the thing. As philosophers say, that was not the phenomenology of the feeling. I did consistently have, as it seemed to me, what affection Mother could muster, and more from my untroubled father. But guilt was a weight in itself, not to be avoided on account of something else, not made greatly heavier by what accompanied it by way of the feelings of others. No doubt it was sin. School began when I was six, in 1939, the year of the Royal Train. I began my education more impressively than it went on thereafter. My E’s for Excellence from the Misses Martinson and Taylor perhaps owed something to a want of academic principle like my own as an examiner later on, or to a comparison with the unbookishness of the Mennonites. In fact I did not shine. Nor have I often shone since. Clever I have wanted to be, but not often been. If I am sometimes quick enough in thought, often ahead of others, I have not regularly been adroit or dexterous. I am no nimble inventor of speculations, and am not often good at retorts or quick escapes. My intellectual virtues, fully awakened only later, have from the beginning been more in the way of an involuntary interest in the very facts of things, scepticism, some judgement, orderliness, and an unwillingness to give up a campaign towards truth because of a little local difficulty. I value these duller virtues, and can say, if slightly morosely, that I might have chosen them. Florence Ferguson, I fancy, had some of the same virtues. She had arrived in the first class before me, and was deputed to teach me my numbers. Subsequently she sharply put me right about words I had read but not mastered. ‘Antique’ was not to be pronounced, she said, so as to rhyme with something that might have been part of billards, the anti-cue. She did well in her instruction of me, and has my gratitude, but is remembered for herself. She was the first of the girls. Tall, fair, and of a proud family. Scots among the Mennonites. A year or two later, she was succeeded in my contemplations by Marjorie Miller, dark ringlets and composure, whose books I carried silently out of the village and up the Baden Hill to her door. Her family always seemed to be calling her away. They were not, so far as I know, related to the impediment to my tricycle. But I was adding a walk of two or three miles to the obligatory mile or two to follow, these later ones being my round of delivering the village’s copies of The Kitchener Daily Record, and so they may have deemed me ardent. I had no words for this attachment, any more than for its predecessor, and would need to struggle to find some now. I thought first of Marjorie Miller some decades later, on first hearing a line from Goethe, no doubt mistranslated or misunderstood: Stay with me awhile, you are so beautiful. My contemplations of girls, whatever desire may have been under them in my nature, in fact had nothing much explicit in them that would have dismayed Rae Laura. In this, perhaps, they were ordinary. Their explicit content was pure enough, and had to do with good looks and with respectable events. Still, and rightly, the very existence of these contemplations would not have reassured my mother. She may have had intimations. To school, and to religious homilies at home, having to do exclusively with the spirit rather than the loins, she added Presbyterian Sunday School. Then Mennonite Bible School during several weeks of my summer vacations. I went unwillingly. That I came early to my resistance to the promise of Eternal Life presumably had to do with Father. His amicable discussions of religion with Mother continued, but in my time he never darkened a church door. He had for a time a postal relationship with the Church of Unity, presumably an institution not stiff with doctrine. He was, I suspect, following that line of personal religious development familiar in the 19th Century and indeed since. Its culmination, while having piety and eloquence in it, is very little religious belief indeed. Conway Hall might have suited him for his final inquiries. By the time I was about seven, all my siblings had departed. Ruth in the direction of good causes, and in particular the publicizing of them. Loine to learn to preach, as he never after failed to do. Bee was beginning his ascent from reporter for the Kitchener Daily Record. Lovely handsome Bob, best of black sheep, was incomprehensibly a chef in a restaurant in Kitchener. Mary was following her mother in the religious quest, wife to another preacher. All would reappear for short visits, bearing their new credentials as knowers of a wider world. Bob returned smoking Sweet Caporal cigarettes, and, in the back garden, he painted metal signs in the shape of shields, and told me something about them. He proposed to go round inspecting the kitchens of restaurants and their menus. If they were up to scratch, the restaurants would be enrolled in his association, and get a shield to hang outside. It is an old idea now, but was not then, in Baden in 1940. Loine came back too, as from the dead. En route to the Bible College in Springfield, Missouri, there had been an awful car crash. News came that of the four young men in the car, three were dead, Loine among them. Was there some uncertainty in the message? Mother would not believe it, had faith, and prayed. In a day or two another message came, followed in due course by my brother, scarred and without some fingers, but in no way deterred from his mission. On one of his returns, Bee took a first and maybe a reasonable step in exerting a worldly authority over me. He was, later, to succeed my father. I had wheedled the purchase of a toy truck out of Mother. Very likely the money came from Bee’s subsidy to us. The truck had to be returned to the shop, the money got back. More guilt, whatever its efficacy, and some beginning of insubordination. There followed two other larger events of my earlier boyhood. I gathered the reality of the first when I was eight, in 1941. Loine, Bee and I made a car journey through snow to a reformatory. Bob was in it, aged 20, found guilty on account of the restaurant shields. I did not see him, as my brothers did, but helped to hide a roast chicken for him in a farm building attached to the institution. Was he a victim of a judicial system not ready for the age of guides to restaurants and their certification? Did some of the restaurants pay their fee for their inspection, and pass, and then not get their shields? Was it worse? The matter has not been researched. It has to be said for my peasant village that no one ever spoke to me of it. Somehow subject to morality, I did not defend my brother to myself, but loved him more, and thought of his audacity, and perhaps of following him in a safer audacity. Nor has the matter of his release from the reformatory been researched. I wonder if it came early, on the understanding that he fight for the King and his Dominions, which he did. He was in the RCAF by February of 1942. I read of the war in the Record before delivering it, and studied the few letters that came back from his flying school in Quebec, and then from a base in England. He was rapidly promoted. I study now his log book. ‘1943, Aug 19, convoy escort west.’ ‘1944, Jan 5, Cairo-Wadi.’ ‘1944, Mar 13, Scram. Investigate A/O.’ He was killed on active service in April of 1944, at age 22. I cannot say I was devastated, as was my mother. It was not like losing a son. His death, despite my love, had not enough reality. Children, as evolution has ordained, are saved from being destroyed by some bad things. I marched around my paper round, and first looked at myself from outside, a boy with lowered eyes, and doubted myself for this show. So far, I have not much gilded my boyhood, recalled it as an idyll. This too is necessary. Certainly I was not wholly taken up with not being a full member of my village, or with any other discomfort or darkness. I was a boy among boys, sometimes leader, never far behind. I learned the possibility of happiness, even the expectation of it, conceivably too great an expectation. Together with James Nesbit, Douglas Kuhn, Glen Schwartzentruber, the older Kenneth and Robert Knoll, I climbed by stages towards 14, not always primly. Some, it seems, awaken in philosophy early. Such, it seems, was the good fortune of my later acquaintance in another world, Bryan Magee, Member of Parliament and of the Garrick, veteran of broadcasting. Author not only of such diverse works as Go West Young Man, The Television Interviewer, To Live in Danger, Towards 2000 and Aspects of Wagner, but also of Confessions of a Philosopher. We learn from the latter work that each night as a boy of 5 he approached a thought about falling asleep that Wittgenstein himself had about dying, that by definition we cannot experience it. At 7 or 8 he was entranced by how willing such an action as bending a finger is possible, and well on his way to the falsehood of determinism and the truth of Free Will. Between 9 and 12 he came on his own to contemplate Zeno's paradox of the arrow -- at any instant of its flight, it is moving or at rest? If you try to say the first, how can it possibly move at an instant? If you say the second, how can it ever be moving? The young Bryan went further, to reflect on the problem of fatalism that whatever is going to happen tomorrow is of course true now, and therefore is settled already. He was also upset to realize, without the help of Hume, that he was aware only of his own sense impressions of the world, not the world in itself. Sense-data of trees, not trees. Since he also reflected on the antinomy that space must surely have an end but that there must also be space on the other side, he grew up no less than a natural Kantian, as he reports. I was not so fully conscious, but I and my comrades did other things. We brought back wild flowers from the black loam in the woods, played Run Sheep Run on summer evenings, reflected again on the heat which had bent the iron stanchions in the two barns burned down on two nights by the jealous brother who left his footprints in the snow. We carved flat arrows from pine shingles and slung them for distance with stick and string, and bravely came within a few yards of Depression hoboes camping beside the railway track. We set booby traps for my deaf father in his small barn in the long back garden, frustrated the invisible trapper by springing his muskrat traps in the stream, and fished for carp in the dam where once Jews had been seen. I was not always cowed by ‘Take off your glasses’, but fought, except with the Knolls. We rafted on Brubacher’s dam, shot at one another with BB guns from the willows and the crow’s nest in the tree, hoped to unsettle householders at 10 p.m. by the moaning that comes from the end of a long thread tacked to an outside window when the other end is rubbed with resin. We ate from the watermelon patch on the Baden Hill and then, two of us, stamped on a dozen or two, leaving in me the shame of having been a complicit witness. We got a better idea of death when Glen Schwartzentruber was not careful in driving a tractor over the railway track. Alone enough too, I had a full if lethargic sense of myself and my world, this place of existence. I was king of the apple tree beside the first barn, got matches and lit small wooden pyres in the outhouse, wrote the initials EDRH in wet concrete, ruminated during the paper round from which Mother would never release me, lay in the grass having a half-idea about the reality of it. I was alone too in the crime of turning off the school’s electricity by the outside switch on a winter Sunday, thereby cancelling Monday morning’s classes, and in exploding a .22 cartridge with the lead removed at the last Halloween party, making an impression on the party and also the impression that remains on my knuckle. If being out of school was better, I took a little pride in being left by a teacher to read by myself in some classes, and got more entangled with language. In one way I was precocious. Paragraphs of mine, news of Baden, were appearing in The Kitchener Record when I was 13. Mother had had this commission, and also Bee. I sang of car crashes and the burning down of the flour mill, and clipped out these unsigned threnodies. I was most impressed by my manner of bringing the news of a victory of our grown-up village softball team over another village. The Baden Pirates, I wrote, had won the trophy emblematic of championship of the league. It was the ‘emblematic’ that made me wonderfully proud. It was Homeric. The Record supplied scorecards for softball games, and I became scorekeeper to the village team, as official a scorekeeper as it ever had, with a seat on the players’ bench, and, necessarily, a place in the truck that transported the team to its games in other villages. The departure from outside Stiffelmeyer’s Hotel was itself a ritual which drew an audience. If Glen Honderich of my farming cousins was a third baseman whose hand was quicker than the eye, my humbler role was a satisfaction to me, no doubt an evident satisfaction. In a late inning of one of our home games, an uncertainty arose about the score. A Pirate or two took one view, favouring the Pirates. The adult scorekeeper on the visitors’ side took another, favouring the visitors. I agreed with the other scorekeeper. Was I subject to truth rather than overawed? A fortnight passed without forewarning, and I presented myself outside Stiffelmeyer’s Hotel. The great Lloyd Miller, first base and manager, barred my way onto the truck, wordlessly dismissing me from my humble role and summoning a more loyal scorekeeper. I am uncertain if he was a Miller related to the impediment to my tricycle, but I am certain the hurt was greater. At 13 one knows disgrace. I cried at home. Mother said I should not be bothered by the ignorant. I was not bothered, but bleeding. In the summer of the year when I was 13, I went to join Father, who, having found VIM no money-spinner, and bee-keeping no better, would take himself off in the summers to pick peaches and cherries in what was called the fruit belt of our Province of Ontario. We lived contentedly in a hut, and laboured together in the trees happily, our peace ruffled only by the effect on the farmer of my remarking to him that I would pick cherries faster if I were getting the profit on them. In another summer Father lived in a tent in the fruit belt, and may have offered a pamphlet of his to someone. It is my recollection, as I have remarked, that his works were not limited to the subject of religious toleration, and that at least one was of a more seditious character. More particularly, as I seem to recollect, it was devoted to the propositions that Christianity is true Communism, and Communism true Christianity. Both propositions are needed, as logic will tell you, to secure a perfect equivalence. My recollection has some support from an undoubted fact, that Father and his tent were visited by the Royal Canadian Mounted Police for the purpose of looking over the literature. These Mounties were vigilant early, since the miasma of McCarthyism south of the border was still to come. They thought Father no immediate danger to the security of the State. Perhaps they discerned he had probably read no word of Marx. In March of 1947, when I was 14, winter brought life to a halt. There was a great blizzard. After it, we gathered in the schoolyard at the railway fence to wait for the two engines and the immense plough, They had backed up two miles in order to gain momentum to clear snow 15 feet deep from the cutting. They succeeded mightily, and threw up a deluge over the fence. Finding myself under three feet of snow, with time left before losing consciousness, I prayed in earnest, for the first and last time. We were dug out and I set to work. It was gratifying to read the next day’s Record. BOY TELLS HIS OWN STORY OF BEING BURIED IN SNOW. By EDGAR HONDERICH. Nor did I much mind the little interview with Mother about this first piece of writing identified as mine. ‘Mrs. Honderich said this morning it took him three hours to write it—he was that sincere about doing a good job.’ Count on Rae Laura to find in this early breast-baring some moral responsibility. She was much concerned with a religious form of it, and is somehow to be credited with what she would have taken to be a particular achievement in this connection. My first contemplations of girls, as I have reported, were restricted to a kind of respectable content, perhaps with some slight addition no more definable today than then. Subsequently, more content was made available to me. The two destroyers of the watermelons on the Baden Hill were the informants of me and my comrades as to another side of life, and its intransitive and transitive verbs. They also went beyond language, to the very demonstration of reality. They spoke of jerking off, thereby providing me both with a new verb and, so to speak, with my first piece of carnal knowledge. For our instruction, they had competitions in jerking off, in the sunlight at the edge of Brubacher’s Dam. The white spurts out into the water were mesmerizing. They did more, with amazingly compliant girls, proud to help. As we watched closely, they felt them up, in the course of a kind of dancing in front of the ice-cream counter in Roth’s Garage, and while lying down with them in snow-houses. My second verb and piece of carnal knowledge. Look and learn is what we did, but in my case the knowledge remained inert. It remained so despite my audacity in other respects, and despite the warm and inspiriting feeling produced in me when the rim of the drinking fountain at school pressed against my flies. I appreciated the feeling, but I never put my first piece of carnal knowledge into action until university, and then only experimentally, and after I had acquired a third. That I should act on the second, touch a girl there, was beyond all conception, not something in any possible world. This paralysis on my part was that particular achievement of Rae Laura of which I spoke a moment ago. It presumably had to do with her expressed aspiration that I would come as a Christian to my wife. I seemed to myself unimpressed by it, as by her other yet more general exhortations to virtue. As it seems, their efficacy did not depend on my seeming impressed. I seemed still less impressed by the last of my religious experiences, and in this case it had none of its intended effect. Rae Laura, having exhausted the resources of the Anglicans and the Presbyterians, had found her way not to something more mystical but to something more substantial. Not for her the Church of Unity. In what I think were her sorrows, she became a fundamentalist, a Pentecostal, and was able to take with her two of my siblings, Loine and Mary. She succeeded in taking me to the Pentecostal Tabernacle in Kitchener a time or two. There, on one Sunday, I was saved. This enrolment in the army of the Lord was worked on my 15-year-old soul by emotion and ululation, and perhaps by speaking in tongues, and by my being led from the tabernacle to a side room for the coup de grace. I gave in to some urgent adult, and loathed myself and him for it on the way back to Baden. My conversion did not take, and was the late stimulus to my atheism. It was soon to find its plainer tongue, and to separate me from my religious brother and sister for too long thereafter. My formal and other education in Baden completed, I became a pupil of the Kitchener-Waterloo Collegiate Institute, the high school of Kitchener and the adjacent town of Waterloo. Very few if any of my village classmates ascended to a secondary school. I had no great inclination. Although my boyhood had contained no exhortations to success, but only to goodness, and would not change in this respect, my parents arranged that Grey Coach Lines would take me the ten miles to Kitchener each morning. I was less a scholar than earlier, and more attracted to urban life than to Latin. I doubt whether my want of commitment had much to do with another fact of membership. Again I was not a full member. I was a village boy in Kitchener. Its boys had English names, doctors for mothers, fathers with Buicks, shoes and haircuts of an ordained mode, and played hardball. They went to summer cottages on islands, presumably were not told by a dentist that another filling was needed but they should not come back except with money in hand, and they could dance. This second experience of being outside a world, not owed to any intention of those inside, was no distress. Perhaps, sometimes after coming to know disgrace, one starts on the way to learning that always and for ever there is something of which one is not a member. Would that I had learned the lesson better. In fact, I was in a way beckoned inside Kitchener. Girls liked me, perhaps for some independence, pride, and lazy intelligence. Helen Geiger was one, as comely as she was serious. It was not rejection that kept me from the Christmas Prom, but, despite those mentioned strengths of mine, a temporary lack of nerve. My boyhood moved towards a certain ending in tranquillity, owed in part to something’s being kept from me. School went on uneventfully and I achieved no great distinction and did not kiss girls. Nor did I distinguish myself in jobs each summer. I learned the dreariness of the life of a factory labourer, in a Kitchener textile mill, and did not learn to do well at minding the machines. Another job, at 16, was working on the railway, with men of Baden. Having learned to drive in spikes, I tired of the labour, but had not the face to show myself and announce my resignation in advance of the agreed time, at the beginning of the school term. Mother saw the foreman at my suggestion, and to my disgrace. If I censured her in my mind for not minding her appearance enough, and more particularly for not arranging to support her bosom, and resented her for these failures, I did not hesitate to make use of her unfailing resolution on my behalf. It had to be told me in the end, when I was approaching 17, that she was not only tired and disappointed. Something else was wrong. She would go to Toronto, where Ruth and Bee now lived, to a nursing home. Father, for reasons not wholly clear to me, would go to friends in Kitchener. The telephone house was at a sudden end, as was Baden. I would go to Toronto too, to live first with my sister and then with my brother. +++++++++++++++ It is too early for me, and may be too early for you, really to set about explaining me. There seems to me insufficient reason for a certain orthodoxy. It is the giving of greatest weight, in understanding the later or mature part of a life, to what came first. As it seems to me, what forms the later part and the person in it may be more recent. Certainly the middle, the time of youth, cannot simply be left out. Life does not consist in (1) childhood followed by (2) nothing much followed by (3) what is to be explained. Later life is not a large and remarkable case of action at a distance. So I shall wait a bit to think about any serious explaining. With an eye on that, though, a summary of my boyhood is worth trying. My sense of membership and standing was small, which fact, to add a further thought, may have made me in some ways less rule-governed. The rules were the rules of others. My tendency to self-doubt was large, and, if it now seems I was not fully awake, I was not lacking in some pride and boldness. Places were much to me. I had the affection of my parents, and in different ways returned it, but with insufficient generosity to the parent to whom I was closer, in fact my mother. I was aware of their taking a moral view of things before any other, and of their morality’s being decent. It was not selfishness. But, affected in my feelings as I was, this morality did not paralyze me. Perhaps it only kept me from acting on my inclination to girls, by whom I was always taken. As against all this, I was often sweetly happy out of school, and at least content in school. I was no cradle philosopher. I never fell easily into belief, without great effort took things in, was never touched by religion, was kept at work so far as that was possible, and did not fail to learn to fight sometimes.
http://www.homepages.ucl.ac.uk/~uctytho/ted11.html
CC-MAIN-2018-05
refinedweb
21,146
70.13
Subject: Re: Type 1 postscript font support questions... From: Mike Meyer (mwm@mired.org) Date: Sat Jun 03 2000 - 04:49:46 CDT sam th writes: > On Fri, 2 Jun 2000, Mike Meyer wrote: > >. > Well, my isspace() man page says that it's in ANSI C, so there shouldn't > be much of a problems. And I suspect that all the systems that we build > the Unix build on will have it available. So, unless other people object, > I think we would be happy to take your patch. Just remember to add to the > changelog at the top of the file (since it's adobe code). Ok, the patch for this is at the end of this message. I've also included a simple patch to prevent fonts that have a slant other than "r" or "i" from clobbering the normal font style for that font. It would be nice if slant "o" (oblique) fonts could be detected and used if there wasn't an italic slant, but that's a bit more painful. Since these are simple one-file patches in the same directory, apply them in the abi/src/af/xap/unix directory. The next thing on my list is adding the pfb->pfa conversion code to the print facility. Both the "church secretary" rule and my instincts say to just do this conversion, as anything that can handle pfb should handle pfa. Before starting on it, I just wanted to check to see if the fix should go some place other than xap_UnixPSGraphics.cpp for the Windows build. Thanx, <mike --- xap_UnixPSParseAFM.c-orig Thu Dec 2 19:22:01 1999 +++ xap_UnixPSParseAFM.c Sat Jun 3 03:53:49 2000 @@ -58,6 +58,8 @@ * - if 0'd initializeArray() * modified: AbiSource, Inc. Jun 14 1999 * - introduced initializeArray() back to metric parsing + * modified: mwm@mired.org Jun 01, 2000 + * - Changed whitespace tests to use isspace */ #ifdef WIN32 #pragma warning (disable : 4244) /* conversion from 'double' to 'float', possible loss of data */ @@ -70,6 +72,7 @@ #include <malloc.h> #include <stdlib.h> #include <math.h> +#include <ctype.h> #include "xap_UnixPSParseAFM.h" #define lineterm EOL /* line terminating character */ @@ -157,12 +160,10 @@ int ch, idx; /* skip over white space */ - while ((ch = fgetc(stream)) == ' ' || ch == lineterm || - ch == ',' || ch == '\t' || ch == ';'); + while (isspace((ch = fgetc(stream))) || ch == ',' || ch == ';'); idx = 0; - while (ch != EOF && ch != ' ' && ch != lineterm - && ch != '\t' && ch != ':' && ch != ';') + while (ch != EOF && !isspace(ch) && ch != ':' && ch != ';') { ident[idx++] = ch; ch = fgetc(stream); @@ -190,7 +191,7 @@ { int ch, idx; - while ((ch = fgetc(stream)) == ' ' || ch == '\t' ); + while (isspace(ch = fgetc(stream))); idx = 0; while (ch != EOF && ch != lineterm) --- xap_UnixFontManager.cpp-orig Thu Apr 20 15:36:32 2000 +++ xap_UnixFontManager.cpp Sat Jun 3 04:28:18 2000 @@ -386,7 +386,14 @@ { s = XAP_UnixFont::STYLE_BOLD_ITALIC; } - + else + { + UT_DEBUGMSG(("XAP_UnixFontManager::_allocateThisFont() - can't guess " + "font style from XLFD.\n")); + FREEP(linedup); + return; + } + // do some voodoo to get the AFM file from the file name char * dot = strrchr(fontfile, '.'); if (!dot) This archive was generated by hypermail 2b25 : Sat Jun 03 2000 - 04:50:26 CDT
http://www.abisource.com/mailinglists/abiword-dev/00/June/0059.html
CC-MAIN-2016-26
refinedweb
507
73.47
Linear Regression, also called Ordinary Least-Squares (OLS) Regression, is probably the most commonly used technique in Statistical Learning. It is also the oldest, dating back to the eighteenth century and the work of Carl Friedrich Gauss and Adrien-Marie Legendre. It is also one of the easier and more intuitive techniques to understand, and it provides a good basis for learning more advanced concepts and techniques. This posting explains how to perform linear regression using the statsmodels Python package, we will discuss the single variable case and defer multiple regression to a future post. This is part of a series of blog posts to show how to do common statistical learning techniques in Python. We provide only a small amount of background on the concepts and techniques we cover, so if you’d like a more thorough explanation check out Introduction to Statistical Learning or sign up for the free online course by the authors here. If you are just here to learn how to do it in Python skip directly to the examples below. Statsmodels Statsmodel is a Python library designed for more statistically-oriented approaches to data analysis, with an emphasis on econometric analyses. It integrates well with the pandas and numpy libraries we covered in a previous post. It also has built in support for many of the statistical tests to check the quality of the fit and a dedicated set of plotting functions to visualize and diagnose the fit. Scikit-learn also has support for linear regression, including many forms of regularized regression lacking in statsmodels, but it lacks the rich set of statistical tests and diagnostics that have been developed for linear models. Linear Regression and Ordinary Least Squares Linear regression is one of the simplest and most commonly used modeling techniques. It makes very strong assumptions about the relationship between the predictor variables (the X) and the response (the Y). It assumes that this relationship takes the form: \(y = \beta_0 + \beta_1 * x\) Ordinary Least Squares is the simplest and most common estimator in which the two \(\beta\)s are chosen to minimize the square of the distance between the predicted values and the actual values. Even though this model is quite rigid and often does not reflect the true relationship, this still remains a popular approach for several reasons. For one, it is computationally cheap to calculate the coefficients. It is also easier to interpret than more sophisticated models, and in situations where the goal is understanding a simple model in detail, rather than estimating the response well, they can provide insight into what the model captures. Finally, in situations where there is a lot of noise, it may be hard to find the true functional form, so a constrained model can perform quite well compared to a complex model which is more affected by noise. The resulting model is represented as follows: \(\hat{y} = \hat{\beta}_0 + \hat{\beta}_1 * x\) Here the hats on the variables represent the fact that they are estimated from the data we have available. The \(\beta\)s are termed the parameters of the model or the coefficients. \(\beta_0\) is called the constant term or the intercept. Ordinary Least Squares Using Statsmodels The statsmodels package provides several different classes that provide different options for linear regression. Getting started with linear regression is quite straightforward with the OLS module. To start with we load the Longley dataset of US macroeconomic data from the Rdatasets website. # load numpy and pandas for data manipulation import numpy as np import pandas as pd # load statsmodels as alias ``sm`` import statsmodels.api as sm # load the longley dataset into a pandas data frame - first column (year) used as row labels df = pd.read_csv('', index_col=0) df.head() We will use the variable Total Derived Employment ( 'Employed') as our response y and Gross National Product ( 'GNP') as our predictor X. We take the single response variable and store it separately. We also add a constant term so that we fit the intercept of our linear model. y = df.Employed # response X = df.GNP # predictor X = sm.add_constant(X) # Adds a constant term to the predictor X.head() Now we perform the regression of the predictor on the response, using the sm.OLS class and and its initialization OLS(y, X) method. This method takes as an input two array-like objects: X and y. In general, X will either be a numpy array or a pandas data frame with shape (n, p) where n is the number of data points and p is the number of predictors. y is either a one-dimensional numpy array or a pandas series of length n. est = sm.OLS(y, X) We then need to fit the model by calling the OLS object’s fit() method. Ignore the warning about the kurtosis test if it appears, we have only 16 examples in our dataset and the test of the kurtosis is valid only if there are more than 20 examples. est = est.fit() est.summary() /usr/local/lib/python2.7/dist-packages/scipy/stats/stats.py:1276: UserWarning: kurtosistest only valid for n>=20 ... continuing anyway, n=16 int(n)) After visualizing the relationship we will explain the summary. First, we need the coefficients of the fit. est.params const 51.843590 GNP 0.034752 dtype: float64 # Make sure that graphics appear inline in the iPython notebook %pylab inline # We pick 100 hundred points equally spaced from the min to the max X_prime = np.linspace(X.GNP.min(), X.GNP.max(), 100)[:, np.newaxis] X_prime = sm.add_constant(X_prime) # add constant as we did before # Now we calculate the predicted values y_hat = est.predict(X_prime) plt.scatter(X.GNP, y, alpha=0.3) # Plot the raw data plt.xlabel("Gross National Product") plt.ylabel("Total Employment") plt.plot(X_prime[:, 1], y_hat, 'r', alpha=0.9) # Add the regression line, colored in red Populating the interactive namespace from numpy and matplotlib [<matplotlib.lines.Line2D at 0x4444350>] Statsmodels also provides a formulaic interface that will be familiar to users of R. Note that this requires the use of a different api to statsmodels, and the class is now called ols rather than OLS. The argument formula allows you to specify the response and the predictors using the column names of the input data frame data. # import formula api as alias smf import statsmodels.formula.api as smf # formula: response ~ predictors est = smf.ols(formula='Employed ~ GNP', data=df).fit() est.summary() This summary provides quite a lot of information about the fit. The parts of the table we think are the most important are bolded in the description below. The left part of the first table provides basic information about the model fit: The right part of the first table shows the goodness of fit The second table reports for each of the coefficients Finally, there are several statistical tests to assess the distribution of the residuals As a final note, if you don’t want to include a constant term in your model, you can exclude it using the minus operator. # Fit the no-intercept model est_no_int = smf.ols(formula='Employed ~ GNP - 1', data=df).fit() # We pick 100 hundred points equally spaced from the min to the max X_prime_1 = pd.DataFrame({'GNP': np.linspace(X.GNP.min(), X.GNP.max(), 100)}) X_prime_1 = sm.add_constant(X_prime_1) # add constant as we did before y_hat_int = est.predict(X_prime_1) y_hat_no_int = est_no_int.predict(X_prime_1) fig = plt.figure(figsize=(8,4)) splt = plt.subplot(121) splt.scatter(X.GNP, y, alpha=0.3) # Plot the raw data plt.ylim(30, 100) # Set the y-axis to be the same plt.xlabel("Gross National Product") plt.ylabel("Total Employment") plt.title("With intercept") splt.plot(X_prime[:, 1], y_hat_int, 'r', alpha=0.9) # Add the regression line, colored in red splt = plt.subplot(122) splt.scatter(X.GNP, y, alpha=0.3) # Plot the raw data plt.xlabel("Gross National Product") plt.title("Without intercept") splt.plot(X_prime[:, 1], y_hat_no_int, 'r', alpha=0.9) # Add the regression line, colored in red [<matplotlib.lines.Line2D at 0x47eab50>] But notice that this may not be the best idea… 🙂 Correlation and Causation Clearly there is a relationship or correlation between GNP and total employment. So does that mean a change in GNP cause a change in total employment? Or does a change in total employment cause a change in GNP? This is a subject we will explore in the next post. Download Notebook View on NBViewer
https://www.datarobot.com/blog/ordinary-least-squares-in-python/
CC-MAIN-2017-51
refinedweb
1,417
57.27
Sharing code between native and web: React and Relay choose to bring it on board. At YLD, we use React on quite a few of our projects, and we started to wonder what was the best way to share code between native and web apps. Problem and Solution Reusing 100% of the codebase would be impossible at this stage, as React Native is oblivious to HTML elements like <div> and <p>, and uses its own native components instead - <View>, <Text>, and so on. If conflicts arise within the render() function, we can overcome the problem by exporting into separate files; in short, sharing logic between "dumb" components is achieved by swapping the views. To showcase our approach, we made a simple app that shows the latest articles from our blog as a list view. This has been a great exercise to see the "learn once write everywhere" mantra at work, as we maintained separate entry points to our app, but shared the same GraphQL server, (mock) database and most of the logic for our components. The repository is online here and we would love some feedback! Project Structure The main entry points for the app are: app.jsfor native; client.jsfor the client; server.jsfor the server; We chose Relay and GraphQL, and the web app is rendered both on the client and the server thanks to isomorphic-relay. The main src/ directory structure is very similar to a standard Relay isomorphic app, the only anomaly being the presence of two separate containers; this makes sense as we expect two different user experiences (native vs. web): src/ components/ containers/ AppContainer.native.js AppContainer.web.js data/ routes/ app.js client.js renderOnServer.js server.js Hooking up React Native React Native uses index.ios.js and index.android.js as entry points to compile the respective bundles. We import src/app.js in both of these, which look identical: import { AppRegistry } from 'react-native'; import NewsfeedApp from './src/app.js'; AppRegistry.registerComponent('nativeRelay', () => NewsfeedApp); Keep views separate The main challenge with this was adopting a flexible structure, allowing iOS and Android to share the same view (if needed), while keeping everything reasonably tidy. This is the structure of a simple Toolbar component that showcases different views for Android and iOS: src/components/Toolbar/ |-- Component.js |-- Render.android.js |-- Render.ios.js |-- Render.js Every component lives in its own directory and exports a Component.js file, which in turns delegates the responsibility of displaying the view to a render() function. Props (including styles) are passed along from the main container down to the Render files. import React from 'react'; import Render from './Render'; class Toolbar extends React.Component { static propTypes = { onClick: React.PropTypes.func, styles: React.PropTypes.shape({}).isRequired, }; constructor(props, context) { super(props, context); } onClick() { this.props.onClick(); } render() { const options = { styles: this.props.styles, onClick: this.props.onClick, } return Render.bind(this)(options); } } export default Toolbar; React Native has this neat feature that allows you include iOS and Android specific files, without specifying the full path while importing. We can take advantage of this by importing a "neutral" ./Render file; React Native will only see Render.android.js and Render.ios.js, which in turn will not be included in webpack's bundle for the web. React Native can also work with the .native.js extension, which we are using when iOS and Android share the same view: src/components/Article/ |-- Component.js |-- Render.js |-- Render.native.js Server-side rendering with Relay Relay has a full working example in React Native as a TodoMVC app here. Our implementation is not far off, except we are using the isomorphic-relay library to help with server-side rendering. This is only a proof of concept and the aesthetics leave a lot to be desired; however, we are relatively happy with what we have achieved given only a little experience of Android and iOS native development. A few other projects aim to bridge the gap between native and web, and you can read more about it here. Among these, React Native Web has been mentioned by Eric Vicenti at React Europe, while showcasing a fully isomorphic app. As libraries like these become less experimental, hopefully this will become the way forward.
https://blog.yld.io/2016/06/13/sharing-code-between-native-and-web-in-react-and-relay/
CC-MAIN-2018-09
refinedweb
711
56.86
For a given array of integers, find the maximum distance between 2 points (i and j) that have higher values than any element between them. Example: values: 0 10 8 9 6 7 4 10 0 index : 0 1 2 3 4 5 6 7 8 for the values above the solution is i=1, j=7, but - if the value of index 7 is 9 instead of 10 the solution is i=3, j=7 - if the value of index 7 is 7 instead of 10 the solution is i=5, j=7 I can’t see a solution in O(n) … anyone ? A simple stack based solution. Iterate over the array left to right, with the stack holding elements (technically, indexes, but use values for comparisons) that are either: - The largest from the left (i.e. no larger or equal element between the start of the array and the element) - The largest since the previous element on the stack. When processing the next element x, pop elements smaller than x as long as they are from the category 2. above, then push x on the stack. Obviously you need to keep the current max to be able to discern between category 2 and 1 in constant time. The processing above is O(n) – each element can be pushed at most once and popped at most once. Having the final stack, just check neighboring pairs (on the stack) – one of the pairs is the solution. This too is O(n). Here’s a picture with what should stay on the stack (the fat rectangles) after the whole scan of the array: (There’s a small mistake in the above picture: fourth bar from the left should either be thick or drawn shorter than the first one, sorry) Why this works: the final stack contains all elements of the input array that are not between any two larger elements (I’ve skipped the case of an element between two equal elements) . The solution is obviously a neighboring pair of such elements. Here’s an implementation in Python: from collections import namedtuple E = namedtuple('E', 'i x') def maxrange(iterable): stack = [E(0, None)]*2 # push sentinel values maxsofar = None top = lambda: stack[-1] # peek at the top element on the stack for i, x in enumerate(iterable): while top().x < x and top().x < maxsofar: stack.pop() stack.append(E(i, x)) # push maxsofar = max(maxsofar, x) return max(b.i-a.i for a,b in zip(stack, stack[1:])) Example: >>> maxrange([2,1,3]) 2
https://coded3.com/given-an-array-can-i-find-in-on-the-longest-range-whose-endpoints-are-the-greatest-values-in-the-range/
CC-MAIN-2022-40
refinedweb
427
66.47
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. Undan, Here you Go! import datetime t_date = datetime.datetime.today() num_of_day = 10 # This is different between two date range, you just find difference and use as numb_of_day date_list = [base - datetime.timedelta(days=x) for x in range(0, num_of_day)] print "Day List in Datetime Format:",date_list This might help you, Regards, Anil. use the following function, it is based on using the 'timedelta' from datetime import datetime, timedelta #show dates between two dates def get_date_list(date1, date2): date_list = [] loop_dt = date1 print loop_dt while loop_dt < date2: loop_dt = loop_dt + timedelta(days=1) print loop_dt get_date_list( datetime(2016,1,5), datetime(2016,03,5)) you can change it to return a list of dates fmt = '%Y-%m-%d' d1 = datetime.strptime(from_date, fmt) d2 = datetime.strptime(to_date, fmt) dates_btwn = d1 while dates_btwn <= d2: print "dates_between=========>>>",dates_btwn.date() dates_btwn = dates_btwn + relativedelta.relativedelta(days=1) This will display the dates between two dates..Hope this will help You.. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-to-display-all-dates-between-two-dates-102174
CC-MAIN-2017-26
refinedweb
208
67.35
This article discusses how to create and use a TabControl available in Silverlight 2.0. This article discusses how to create and use the TabControl available in Silverlight 2.0. Creating a Silverlight Application Create a Silverlight application using Visual Studio 2008 by selecting New Project >> Silverlight Application from the Templates list. See Figure 1. Figure 1. Creating a Silverlight Application. After the application is created, you land on Page.xaml page in the designer. The XAML of Page.xaml looks like following: <UserControl x:Class="MyFirstSilverlightApplication.Page" xmlns="" xmlns: <Grid x: </Grid> </UserControl> In the left side bar, you will see a Toolbox that lists Silverlight controls available to you. Now simply drag a TabControl from the Toolbox to your XAML file inside the Grid tag. This action will add System.Controls.Extended namespace reference to your XAML file that looks like this: xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Extended" You will also see the following tag is added for the tab control. <my:TabControl /> Now, similar to any other XAML controls, you can set tab control properties using XAML attributes. For example, the following code sets the height, font, font size, and background color of the tab control. <my:TabControl </my:TabControl> You may also add some properties outside of the tab control. For example, the following code sets the background property of the tab control using TabControl.Background. <my:TabControl <my:TabControl.Background> <SolidColorBrush Color="Green" Opacity="0.30"/> </my:TabControl.Background> </my:TabControl> Adding Tab Items You will hardly recognize a tab control without tab items. The <TabItem \> tag represents a tab item. The Header property of TabItem represents the header text of the header. The following code creates a tab item with header text "Circle". <my:TabItem </my:TabItem> A tab item can host other XAML controls similar to a panel or grid control. For example, the following code adds a StackPanel to the tab item and on that StackPanel, it creates a circle with height and width 100. <my:TabItem <StackPanel> <Ellipse Height="100" Width="100" StrokeThickness="5" Stroke="black" Fill="gold"/> </StackPanel> Using the same above approach, I add three tab items to the tab control called Circle, Rectangle, and Polygon. See the code listed in Listing 1. <my:TabControl <my:TabItem <StackPanel> <Ellipse Height="100" Width="100" StrokeThickness="5" Stroke="black" </StackPanel> </my:TabItem> <my:TabItem <Rectangle Fill="Yellow" Width="100" Height="100" Stroke="Blue" StrokeThickness="5"> </Rectangle> <my:TabItem <Polygon Points="100,50 50,100 150,100 100,50 100,30" Stroke="green" StrokeThickness="3" Fill="Yellow"/> Listing 1. Adding three tab items to a tab control. If I run the application, the Circle tab shows me a circle looks like Figure 2. Figure 2. If I click on Rectangle and Polygon, the output looks like Figure 3 and Figure 4 respectively. Figure 3. Figure 4. Formatting Tab Items Let's get some creative. We will display the images on the tab items as the part of tab item headers. The final tab control would look like Figure 5. Figure 5. Tab item header with drawings To achieve this, I separated tab item header and put a stack panel within it. The stack panel then hosts a text and a drawing depending on what tab item it is. <my:TabItem.Header> <StackPanel Orientation="Horizontal"> <Polygon Points="20,10 20,10 15,15 20,10 20,15" Stroke="green" StrokeThickness="3" Fill="Yellow"/> <TextBlock Text="Polygon" Margin="1,1,1,1" VerticalAlignment="Center" /> </StackPanel> </my:TabItem.Header> Note: If you would like to load images at the top of text of the header, simply remove Orientation="Horizontal" from the stack panel in the above code. The default orientation is vertical. Using the same approach, you may load an image in the header of a tab item. Simply, replace tab header code above that is creating a polygon with the following code. Make sure your image is available in your project. <Image Height="20" Source="MyImage.jpg" /> Summary In this article, we saw how to create and use a TabControl in a Silverlight application. We also saw, how to make a tab item header and its contents more interactive by simply adding a few lines of code to our XAML file. Thanks for the support on SilverLight.I would be thankful to you if you provide me good tab control within ASP.NET and C#.My email is shuq@rediffmail.com
http://www.c-sharpcorner.com/UploadFile/mahesh/SilverlightTabControl07022008170702PM/SilverlightTabControl.aspx
crawl-002
refinedweb
743
58.08
Use this Class to define application metrics for SYS.History. User classes inherit from this class and can then define %Numeric properties to create user-defined metrics, which get collected and summarized like the other SYS.History system metrics. The Sample() method must be coded to collect all user-defined properties. Classes defined using this as a parent class will get included as an embedded object in the SYS.History.User (or UserPerf or UserSys), and the UserHourly and UserDaily persistent classes. User written classes must be in the %SYS namespace, and begin with "Z" or "z" to prevent naming conflicts with system classes. All properties of the user-defined class must be %Numeric. This is because the same classes get embedded in the Hourly/Daily summaries and the summary functions may create decimal digits. All of the options for the user-defined classes are defined in the Parameters of this class. WARNING: User-defined metics classes become embedded objects in persistent data, and some care must be taken by the user if definitions change after data has been collected. The 'schema evolution' feature of Cache Objects allows you to safely add new objects and properties. But deleting objects can result in 'orphaned' data, and re-defining existing objects can cause data to be misinterpretted. Set this parameter to "1" to indicate that the user-defined class will be collected as a %ArrayOfObjects. This allows for multiple instances of the class for each sample. The user-written Sample() method is responsible for creating the %ArrayOfObjects and the keys which identify the instances of the class. If the class is collected as a %ArrayOfObjects, then there are two choices for the Hourly and Daily summaries of the interval data. The default (ARRAYSUM=1) is to calculate a single value of all instances for each summary function (Avg, Max, etc). If ARRAYSUM=0, then each instance will be calculated separately, and the name of the function will be concatenated to the user-defined key to generate a key for the summary instance (see the summaries for SYS.History.Database for an example of how this option looks). A comma-delimited list of functions used to calculate Daily summaries for this class. This may be any of "Avg", "Max", "Min", StDev", Med", or "Tot". Or, it may be "None". This parameter is used to indicate that the properties in this user-defined class should be collected as delta values. This is generally used when the metrics are "counters", where the values keep increasing and you want to capture the difference between each sample rather than the actual value of each sample. A comma-delimited list of functions used to calculate Hourly summaries for this class. This may be any of "Avg", "Max", "Min", StDev", Med", or "Tot". Or, it may be "None". Parameter used to select which SYS.History.User* class is used to collect the interval data for this class. Choices are "User", "UserPerf" or "UserSys. This user class will be added as an embedded object to the selected class. These classes correspond to the classes %Monitor.System.HistoryUser, %Monitor.System.HistoryPerf and %Monitor.System.HistorySys. "UserPerf" and "UserSys" will collect user-defined metrics at the same intervals and with the same identifying timestamp as the PerfData and SysData classes, so that results may be correlated to those metrics. "User" is only for user-defined data and %Monitor.System.HistoryUser can be set to a different (and non-related) timer interval. This parameter provides a string which is used as the Property name for the embedded objects in the persistent classes. It's recommended that this name be fairly short, since it appears as a prefix for SQL projected tables and properties. It must also be unique for each user-defined class. The class name (without the Package name) will be used if nothing is specified. ** USER MUST IMPLEMENT THIS METHOD ** This method is called to instantiate the user-defined class and provide values for all properties. If the application namespace must be accessed to fetch the values, then the code may switch namespaces to collect the data, and then MUST switch back to %SYS. The application may return either a single instance of their class or a %ArrayOfObjects of that class, depending on how the ARRAY parameter is defined.
https://docs.intersystems.com/latest/csp/documatic/%25CSP.Documatic.cls?PAGE=CLASS&LIBRARY=%25SYS&CLASSNAME=SYS.History.Adaptor
CC-MAIN-2019-13
refinedweb
718
55.74
You have learned that a classpath points to one or more directories. Each of these directories can contain class (.as) files. In addition to containing class files, a classpath directory can contain subdirectories. A subdirectory in a classpath directory is known as a package, and can contain class files and more directories, called subpackages. Keeping classes in packages is a good way to keep them organized. You might have hundreds of class files after just a few months of programming with Flash. Saving these classes in a logical directory structure makes them easier to locate, and can help you avoid class-name conflicts with multiple projects. When you use packages, the class file syntax changes slightly, and can complicate instantiating an instance of that class. As shown earlier, this is the basic syntax used to create a class called TestClass: class TestClass { function TestClass() { //Constructor } } The rule that we didn't mention earlier is that the name declaration of the class must contain the path to the class file from the root classpath directory in which the class resides. The TestClass class above assumes that the class file is not in any package, but is sitting directly in a classpath directory. However, if we decided to create the TestClass class in a package called TestPackage, the class definition would look like this: class TestPackage.TestClass { function TestClass() { //Constructor } } The text after the class keyword contains not only the name of the class (TestClass) but the overall path where it exists. In this case, TestClass exists inside the TestPackage directory, which itself exists in a classpath directory. Suppose you created an address book class for Macromedia. Because you're a very organized person, you created a logical package (directory) structure for your class file. The class definition might look like this: class Clients.Macromedia.AddressBook { function AddressBook() { //Constructor } } This class is contained in the Macromedia directory, which is in the Clients directory, which is in a classpath directory. To create an instance of a class that's in a package, you must use the full package path. For example: var myInstance:TestPackage.TestClass = new TestPackage.TestClass(); Notice that the data type and the constructor are referenced using the full path. As you can imagine, working with long class names such as this can make for a lot of typing if you're creating many instances. But there's a way to use the abbreviated name of your class (the class name without package path)by importing the class. You can import a class by using the import statement followed by the path to the class. For example: import TestPackage.TestClass; After the import statement, you can work with the class by using the abbreviated name. For example: import TestPackage.TestClass; var myInstance:TestClass = new TestClass(); You can import all class files in a package by using an asterisk (*) in place of a class name. For example: import TestPackage.* This line of ActionScript imports all classes found in the TestPackage package. It doesn't import any classes from subpackages. The import statement allows you to use the abbreviated class name only within the frame on which the statement appeared. If you import TestPackage on Frame 1, you cannot use the abbreviated name on Frame 2 unless Frame 2 also imports TestPackage. You've been introduced to a lot of new concepts up to this point, and now it's time to get your hands dirty. In this exercise, you will create a simple custom class and use it in a Flash document. Open Flash. Select File > New. Select ActionScript File from the list. Save the file as CurrencyConverter.as. You have just created an empty ActionScript file that will contain a class called CurrencyConverter. This class will allow you to convert an amount of currency from U.S. dollars (USD) to Great Britain pounds (GBP) or vice versa.Later in the exercise, you will add just a few lines of script to an FLA file to use the functionality of the CurrencyConverter class. NOTE When creating an ActionScript file, which in this case is a class file, Flash gives you a full-screen ActionScript window in which to type. You don't have access to the normal Flash user interface elements, such as the drawing tools or components. With the ActionScript file open, add the following line of ActionScript to start the class definition: class CurrencyConverter { The first word, class, tells Flash that what follows is a class definition. Not all ActionScript files contain a class, so this definition is necessary. The text just after the class keyword is the name of the class. Remember that the name of the class must also contain the path to the class from a root classpath directory. The FLA file that will use this class (which we'll create in a moment) will be saved in the same directory as the class file (which is considered a global classpath); therefore, using just the name of the class is acceptable. If we decided to save this class file into a subdirectory called Currency, we would name the class Currency.CurrencyConverter.The last character in the previous ActionScript is an opening curly brace ({). The last character that we will add in the class is the closing curly brace (}). Everything between these two braces defines the properties and methods of the class. Add the following variable declaration on the next line: var exchangeRate:Number; The purpose of this class is to convert USD to GBP or GBP to USD. The exchangeRate variable stores the exchange rate ratio between GBP and USD. If the value of exchangeRate were 0.634731, for example, there would be .634731 GBP for one USD. This exchange rate will be used by a method of this class to convert the currency.The value of the exchangeRate variable is set via the constructor method of the CurrencyConverter class, which we'll define next. Add the following constructor method: function CurrencyConverter(rate:Number) { exchangeRate = rate; } To use this class, you must be able to create an instance of it. A constructor method is a function that defines actions to take when creating a new instance of the class. It must have the same name as the classbut without the path to the class (if applicable). This constructor method takes one parameter, rate, which is used to set the value of exchangeRate when an instance is created.The way the constructor method is set up allows us to create a new instance of the CurrencyConverter class in the following manner: var myConverter:CurrencyConverter = new CurrencyConverter(.54321); Add the following method, which will be used to convert the currency: function convert(convertTo:String, amount:Number):Number { var result:Number; if (convertTo == "USD") { return amount / exchangeRate; } else if (convertTo == "GBP") { return amount * exchangeRate; } return result; } Add a closing curly brace (}) on the last line of the class to close the definition. Save the file. You have created a class file! The next thing that we need to do is create and use an instance of this class in a Flash movie.You have created a class file! The next thing that we need to do is create and use an instance of this class in a Flash movie. Open CurrencyConverter1.fla in the Lesson07/Assets directory.Notice that this FLA contains only one layer called Actions, and one frame. The objective of this exercise is simply to create a custom class and then learn how to use it in an FLA file. Over the next three steps you'll add the four lines of ActionScript needed to accomplish this goal. Select Frame 1, open the Actions panel, and create the following variable: var rate:Number = 0.634731; Create a new instance of the CurrencyConverter class by adding this code: var converter:CurrencyConverter = new CurrencyConverter(rate); The name of the instance that we're creating is converter. It has a data type of CurrencyConverter. By using the statement new CurrencyConverter(rate), we create a new instance of the CurrencyConverter class. The value of rate was passed in to set the exchange rate that this instance will use.When the FLA is compiled into an SWF, the compiler sees that CurrencyConverter is used as if it were a class; therefore, the compiler searches the classpath directories for a class named CurrencyConverter. If the compiler finds the class, it adds the class to the SWF. If the compiler doesn't find the class, a compile error is reported. Add the following final two lines of ActionScript to convert some currency and to show the result: var result:Number = converter.convert("USD", 130.5); trace(result);. Select Control > Test Movie to test your work.The Output window should pop up and display a number. When the SWF was compiled, the compiler detected the use of a class called CurrencyConverter, searched the classpath directories for that class, and included the class in the SWF. The ActionScript in the SWF then created a new instance of the class and used it to perform a task. Close the test movie and save your work as CurrencyConverter2.fla.In this exercise, you created a class and then used it in a Flash movie. As this lesson progresses, you'll learn much more about classes and gain more experience working with them.
http://etutorials.org/Macromedia/Flash+MX+2004.+Actionscript/Lesson+7.+Creating+Custom+Classes/Packages+and+Importing+Classes/
CC-MAIN-2021-43
refinedweb
1,554
63.29
Introduction Python closure is a technique for binding function with an environment where the function gets access to all the variables defined in the enclosing scope. Closure typically appears in the programming language with first class function, which means functions are allowed to be passed as arguments, return value or assigned to a variable. This definition sounds confusing to the python beginners, and sometimes the examples found from online also not intuitive enough in the way that most of the examples are trying to illustrate with some printing statement, so the readers may not get the whole idea of why and how the closure should be used. In this article, I will be using some real-world example to explain how to use closure in your code. Nested function in Python To understand closure, we must first know that Python has nested function where one function can be defined inside another. For instance, the below inner_func is the nested function and the outer_func returns it’s nested function as return value. def outer_func(): print("starting outer func") def inner_func(): pi = 3.1415926 print(f"pi is : {pi}") return inner_func When you invoke the outer_func, it returns the reference to the inner_func, and subsequently you can call the inner_func. Below is the output when you run in Jupyter Notebook: After you have got some feeling about the nested function, let’s continue to explore how nested function is related to closure. If we modify our previous function and move the pi variable into outer function, surprisedly it generates the same result as previously. def outer_func(): print("starting outer func") #move pi variable definition to outer function pi = 3.1415926 def inner_func(): print(f"pi is : {pi}") return inner_func You may wonder the pi variable is defined in outer function which is a local variable to outer_func, why inner_func is able access it since it’s not a global scope? This is exactly where closure happens, the inner_func has the full access to the environment (variables) in it’s enclosing scope. The inner_func refers to pi variable as nonlocal variable since there is no other local variable called pi. If you want to modify the value of the pi inside the inner_func, you will have to explicitly specify “nonlocal pi” before you modify it since it’s immutable data type. With the above understanding, now let’s walk through some real-world examples to see how we can use closure in our code. Hide data with Python closure Let’s say we want to implement a counter to record how many time the word has been repeated. The first thing you may want to do is to define a dictionary in global scope, and then create a function to add in the words as key into this dictionary and also update the number of times it repeated. Below is the sample code: counter = {} def count_word(word): global counter counter[word] = counter.get(word, 0) + 1 return counter[word] To make sure the count_word function updates the correct “counter”, we need to put the global keyword to explicitly tell Python interpreter to use the “counter” defined in global scope, not any variable we accidentally defined with the same name in the local scope (within this function). Sample output: The above code works as expected, but there are two potential issues: Firstly, the global variable is accessible to any of the other functions and you cannot guarantee your data won’t be modified by others. Secondly, the global variable exists in the memory as long as the program is still running, so you may not want to create so many global variables if not necessary. To address these two issues, let’s re-implement it with closure: def word_counter(): counter = {} def count(word): counter[word] = counter.get(word, 0) + 1 return counter[word] return count If we run it from Jupyter Notebook, you will see the below output: With this implementation, the counter dictionary is hidden from the public access and the functionality remains the same. (you may notice it works even after the word_counter function is deleted) Convert small class to function with Python closure Occasionally in your project, you may want to implement a small utility class to do some simple task. Let’s take a look at the below example: import requests class RequestMaker: def __init__(self, base_url): self.url = base_url def request(self, **kwargs): return requests.get(self.url.format_map(kwargs)) You can see the below output when you call the make_request from an instance of RequestMaker: Since you’ve already seen in the word counter example, the closure can also hold the data for your later use, the above class can be converted into a function with closure: import requests def request_maker(url): def make_request(**kwargs): return requests.get(url.format_map(kwargs)) return make_request The code becomes more concise and achieves the same result. Take note that in the above code, we are able to pass in the arguments into the nested function with **kwargs (or *args). Replace text with case matching When you use regular express to find and replace some text, you may realize if you are trying to match text in case insensitive mode, you will not able to replace the text with proper case. For instance: import re paragraph = 'To start Python programming, you need to install python and configure PYTHON env.' re.sub("python", "java", paragraph, flags=re.I) Output from above: It indeed replaced all the occurrence of the “python”, but the case does not match with the original text. To solve this problem, let’s implement the replace function with closure: def replace_case(word): def replace(m): text = m.group() if text.islower(): return word.lower() elif text.isupper(): return word.upper() elif text[0].isupper(): return word.capitalize() else: return word return replace In the above code, the replace function has the access to the original text we intend to replace with, and when we detect the case of the matched text, we can convert the case of original text and return it back. So in our original substitute function, let’s pass in a function replace_case(“java”) as the second argument. (You may refer to Python official doc in case you want to know what is the behavior when passing in function to re.sub) re.sub("python", replace_case("java"), paragraph, flags=re.IGNORECASE) If we run the above again, you should be able to see the case has been retained during the replacement as per below: Conclusion In this article, we have discussed about the general reasons why Python closure is used and also demonstrated how it can be used in your code with 3 real-world examples. In fact, Python decorator is also a use case of closure, I will be discussing this topic in the next article.
https://www.codeforests.com/category/tutorials/page/4/
CC-MAIN-2022-21
refinedweb
1,140
56.79
Copyright ©2002-2008 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply. Many people want to use XHTML to author their web pages, but are confused about the best ways to deliver those pages in such a way that they will be processed correctly by various user agents. This Note contains suggestions about how to format XHTML to ensure it is maximally portable, and how to deliver XHTML to various user agents - even those that do not yet support XHTML natively. This document is intended to be used by document authors who want to use XHTML today, but want to be confident that their XHTML content is going to work in the greatest number of. In general, . Note: While this document sometimes uses terms like "must" and "should", this document is not normative and those terms do not have the same meaning as when they are used in a normative W3C specification.. xml:lang), but an XHTML Family document type may also include elements and attributes from other namespaces,.. While XML provides the CDATA method to embed data such as this, that method will not work correctly should the document be delivered as media type text/html Note that if you really need to embed scripts or stylesheets, the following patterns can be used: Portably escaping embedded script contents: <script>//<![CDATA[ ... //]]></script> Portably escaping embedded style contents: <style>/*<![CDATA[*/ ... /*]]>*/</style> @@@ - user agents are permitted to collapse multiple whitespace characters to a single white space character.=utf-8" />). element. guidelies..
http://www.w3.org/MarkUp/2008/ED-xhtmlmime-20081024/
CC-MAIN-2017-47
refinedweb
257
54.56
Red Hat Bugzilla – Bug 373651 GCC does not generate DW_AT_object_pointer Last modified: 2016-06-07 18:46:22 EDT From Bugzilla Helper: User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.8) Gecko/20071019 Fedora/2.0.0.8-1.fc7 Firefox/2.0.0.8 Description of problem: Gcc does not generate the DW_AT_object_pointer attribute entry, which is a reference at the Subprogram level to the artificial parameter entry representing the object for which the function is called Version-Release number of selected component (if applicable): gcc version 4.1.2 20070626 (Red Hat 4.1.2-14) How reproducible: Always Steps to Reproduce: 1.compile the following program with -g: #include <stdlib.h> #include <stdio.h> class A{ public: void crash(); }; void A::crash(){ int* a = 0; a[0] = 0; } int main(){ A a = A(); a.crash(); return 0; } 2. use readelf --debug-dump a.out 3. Notice missing entry Actual Results: Expected Results:.
https://bugzilla.redhat.com/show_bug.cgi?id=373651
CC-MAIN-2017-17
refinedweb
162
52.46
FAQ - How can the performance of queries be monitored? Detail Within Aerospike there are macro-benchmarks which are written to the aerospike.log in histogram form by default. Within these macro-benchmarks there is a histogram called Query which gives performance of queries running within the cluster at a high level. In certain circumstances, it may be desirable to look at the performance of queries in more detail. What are the options for doing this? Answer There are a specific set of query-microbenchmarks that can be switched on at will. The command to do this is: asinfo -v 'set-config:context= service;query-microbenchmark=true For version 3.9 onwards, microbenchmarks can be enabled at the namespace level. The link below has the list of histograms possible. asinfo -v 'set-config:context=namespace;id=<namespaceName>;enable-benchmarks-read=true' Once these are switched on the following histograms will be written into the aerospike.log. Notes - When a query returns n records it does not process them sequentially but rather in a batch. Each batch is a unit of work with a default size of 100 (controlled by the query-batch-size parameter). Histograms that refer to batch size are measuring the time taken to prepare or wait for the batch in either queues or i/o - query-microbenchmarks is not a static parameter and cannot be included in aerospike.conf - Any histogram where the name ends _us is measuring in microseconds, not milliseconds as is more common in benchmark histograms. Keywords QUERY-MICROBENCHMARKS ANALYSE QUERY Timestamp 6/6/16
https://discuss.aerospike.com/t/faq-how-can-the-performance-of-queries-be-monitored/3197
CC-MAIN-2018-30
refinedweb
260
65.22
Stephan T. Lavavej - Core C++, 8 of n In part 10, STL explores the new features in the Visual C++ Compiler November 2013 CTP (Community Technology Preview), in addition to the features that were added between VC 2013 Preview and RTM. Features included in the November CTP ( generic lambdas!!! ): C++11, C++14, and C++/CX features: See part 8: do-while loop, casts, one definition rule See part 9: lambdas and other expressions Printing the 101 inside test2() is kind of redundant, because if zeroth didn't return a reference, the expression ++zeroth(v) would not even compile, right?) ;> I've hit a use nearly half of these features while quickly trying out 2013 RTM, so I'm really interested to give this a try soon! You mentioned constexpr has restrictions in this release (better than it ICEing!) - are those defined anywhere yet? Generic lambdas are nice, I guess, but they're pretty wordy compared to other lambda syntaxes still, it would be cool to see something like [](a, b) { a += b; } in C++17 (default to auto&&). Stroustrop's Concepts-lite paper at one point (doesn't look lite it's in there anymore?) contained a neat shorthand for templates that looks like a nice solution for the decltype(t) problem mentioned: instead of: template <typename T, typename U> auto inner(T&& t, const U& u) { ... } and [](auto&& t, const auto& u) { inner(forward<decltype(t)>(t)); } you could type (something like): typename{T,U} auto inner(T&& t, U&& u) { ... } and []typename{T,U}(T&& t, const U& u) { inner(forward<T>(t)); } though typename was supposed to be a Concept name for that. For some reason, it doesn't look like it's in the current version of the paper, though I might just be missing it..) I just have to yell... STL!!!! Another awesome installment. Thank you, man. Such a treat to have you do your thing on camera, on C9. That's rock and roll, all around. C In the video you mentioned that constexpr supports for loops, but when I tried to use one constexpr auto Give(int blah){ for (int i = 0; i < 5; ++i) { blah = blah * 2; }return blah; } It errored out on me, with this message: error C3249: illegal statement or sub-expression for 'constexpr' function warning C4649: '++': operator results in a non-constant expression Is this supposed to work in C++14, or does it just not work because the CTP is incomplete?. Great video and great job, I have been using 2013 for a while now and I'm very happy. It is allways nice to see c++ moving. Still waiting for concept support here hehe. STL: Great, thanks for your reply (and for continuing Core C++ installments)! Awesome lecture! Is incredible the amount of things I learn every time I watch your series. Very interesting, as always. And also, congratulations to the MSVC team for implementing all this new features! The non-await version of the code at the end is full of errors! Missing return (in the "next" lamdba), incorrect recursive call of the "next" lambda, and I don't think the "next" lamdba is captured correctly either. Which just demonstrates the point, but still.?" Great lecture! Great, like always! As always - great stuff STL! One question about auto return type. Is it possible to indicate somehow that you want to return a reference? Something like auto& func() {... or do you just use return std::move(...) and it knows? You would say decltype(auto) for the return type, then return an lvalue (like ptr[idx]) for X&, or an xvalue (like move(ptr[idx])) for X&&. ah, I watched again and you talked about it. sorry, somehow I missed that bit. thx. Regarding constexpr, I notice that non-member constexpr functions dealing with strings don't work: template<std::size_t N> constexpr std::size_t valid_helper(const char (&sql)[N], const std::size_t num_params, std::size_t i, std::size_t acc = 0) { return sql[i] >= '0' && sql[i] <= '9' ? valid_helper(sql, num_params, i + 1, acc * 10 + sql[i] - '0') : sql[i] == '}' ? acc < num_params ? i : ~0 : i; } template<std::size_t N> constexpr std::size_t valid(const char (&sql)[N], const std::size_t num_params, std::size_t i) { return sql[i] >= '0' && sql[i] <= '9' ? valid_helper(sql, num_params, i) : ~0; } template<std::size_t N> constexpr std::size_t next(const char (&sql)[N], const std::size_t num_params, std::size_t i = 0) { return i > N ? ~0 : sql[i] == 0 ? i : sql[i] == '{' ? next(sql, num_params, valid(sql, num_params, i + 1)) : next(sql, num_params, i + 1); } int main(int argc, char *argv[]) { static_assert(next("SELECT {2}, {1}", 2) != ~0, "Out of bounds"); return 0; } Thanks, I'll ask the compiler dev who wrote constexpr. That's emitting "warning C4425: 'const char (&)[N]' : 'constexpr' was ignored (class literal types are not yet supported)" which at the very least is an inaccurate warning. > Thanks, I'll ask the compiler dev who wrote constexpr. Thanks Stephan. I've gotten confirmation that constexpr arrays are also a CTP limitation, they just reused the warning for class literal types (which was confusing). wow. Great. Thanks Stephan. Do the reumable functions support generators as in the working paper. This will give us c# yield behavior. (Which makes linq possible etc...) With Nov CTP for Visual Studio 2013, some template alias, which used to work with RTM version no longer works. 1) template<bool B,class T1,class T2> using if_ = typename std::conditional<B, T1,T2>::type; template<unsigned N> using meow = if_<(N <= 8), char, int>; static_assert(std::is_same<meow<10>,int>::value,"error"); It seems the alias truncates N to bool before placing it in if_ 2) template<bool B, class E = void> using enable_if = typename std::enable_if<B, E>::type; template<class T> enable_if<std::is_integral<T>::value, void> meow(T x){} template<class T> enable_if<std::is_floating_point<T>::value, void> meow(T x){} This complains that function meow already defined. 3) somewhat different story to enable_if in class definition. That only causes problem, when it is inside another template. template<class T> //comment out this line to compile struct meow { template<class U,class E = void> struct purr; template<class U> struct purr < U, enable_if<std::is_integral<U>::value > > {}; template<class U> struct purr < U, enable_if<std::is_floating_point<U>::value > > {}; };. Dan Golick> Do the reumable functions support generators as in the working paper. I asked Deon, who implemented await, and he said: "Not in the current implementation. We're still working on the design for it." (naming hindsight lament) Interesting watch. Thanks for summarizing (love the non-static member initialization). @7:38 "Standardization committee really hates introducing new keywords" Instead of using "using", I'd have preferred the standards committee introduce a new type name with "typename", or even define a new type with "typedef" where the presence of an "=" indicates the sane ordering (more like typical assignment instead of backwards like it is now). They are understandably allergic to inventing new keywords, but they could have at least chosen the more natural one rather than a present progressive verb. typedef CatPtr = Cat*; // instead of "using CatPtr = Cat*;" template<typename T> typedef Cat = Animal<T, Mammal>; Why did they call it __func__ rather than __FUNC__?
https://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Core-Cpp-10
CC-MAIN-2020-34
refinedweb
1,209
62.98
So, I got an interesting spam comment on my post today: “It gets even crazier when you actually benchmark the two languages only to discover in some real-world cases, PHP outperforms C#.” I triple dare you to show code examples so we can explain why you’re wrong. Quadruple dare Jesus christ, how did you think this was trueBy: No McNoington This person couldn’t even be bothered to put in a decent pseudonym to call them by, but Mr./Mrs. McNoington, prepare to be blown away… See, there’s something very common that all developers must do, and that is read files… we need to parse things, transform file formats, or whatever. So, let’s compare the two languages. function test() { $file = fopen("/file/file.bin", 'r'); $counter = 0; $timer = microtime(true); while ( ! feof($file)) { $buffer = fgets($file, 4096); $counter += substr_count($buffer, '1'); } $timer = microtime(true) - $timer; fclose($file); printf("counted %s 1s in %s milliseconds\n", number_format($counter), number_format($timer * 1000, 4)); } test(); using System.Diagnostics; using System.Text; var test = () => { using var file = File.OpenText("/file/file.bin"); var counter = 0; var sw = Stopwatch.StartNew(); while(!file.EndOfStream) { if(file.Read() == '1') { counter++; } } sw.Stop(); Console.WriteLine($"Counted {counter:N0} 1s in {sw.Elapsed.TotalMilliseconds:N4} milliseconds"); }; test(); Personally, I feel like this is a pretty fair assessment of each language. We will synchronously read a 4Mib file, byte-by-byte, and count the 1’s in the file. There’s very little user-land code going on here, so we’re just trying to test the very fundamentals of a language: reading a file. We’re only adding the counting here to prevent clever optimizing compilers (opcache in PHP, release mode in C#) from cheating and removing the code. “But Rob,” I hear you say, “they’re not reading it byte-by-byte in the PHP version!” and I’d reply with, “but we’re not reading it byte-by-byte in the C# version either!” Let’s see how it goes: That’s pretty crazy… I mean, we just read four megs, which is about the size of a decent photo. What about something like a video clip that might be 2.5 gigs? Now, I need to process quite a bit of incoming files from banks and bills and stuff for my household budgeting system, which is how I discovered this earlier last year as I was porting things over from a hodgepodge of random stuff to Dapr and Kubernetes. PHP is actually faster than C# at reading files, who knew?! Does this mean you should drop everything and just rewrite all your file writing stuff in PHP (or better, C)? no. Not at all. A few milliseconds isn’t going to destroy your day, but if your bottleneck is i/o, maybe it’s worth considering :trollface:? Nah, don’t kid yourself. But if you’re already a PHP dev, now you know that PHP is faster than C#, at least when it comes to reading files… Feel free to peruse some experiments here (or if you want to inspect the configuration): withinboredom/racer: racing languages (github.com) Can this C# be written to be faster, sure! Do libraries implement “the faster way?” Not usually. Addendum Many people have pointed out that the C# version isn’t reading it in binary mode and the function call overhead are to blame. Really? C# is many order of magnitudes faster than PHP at function calls. I promise you that isn’t the problem. Here’s the code for binary mode on the 2.5gb file: using System.Diagnostics; using System.Text; var binTest = () => { using var file = File.OpenRead("/file/file.bin"); var counter = 0; var buffer = new byte[4096]; var numRead = 0; var sw = Stopwatch.StartNew(); while ((numRead = file.Read(buffer, 0, buffer.Length)) != 0) { counter += buffer.Take(numRead).Count((x) => x == '1'); } sw.Stop(); Console.WriteLine($"Counted {counter:N} 1s in {sw.Elapsed.TotalMilliseconds} milliseconds"); }; binTest(); If you now want to complain that it’s all Linq’s fault, we can just remove the .Take and double count things because I need to get to work and I’m not putting any more time to telling people the sky is blue. So yeah, if an incorrect implementation is the proof you need that PHP is slower, go for it. Time to go to work. Addendum 2 Since people come here wanting to optimize the C# without optimizing the PHP version, here is an implementation ONLY looking at file performance: function test() { $file = fopen("/file/file.bin", 'r'); $counter = 0; $timer = microtime(true); while (stream_get_line($file, 4096) !== false) { ++$counter; } $timer = microtime(true) - $timer; fclose($file); printf("counted %s 1s in %s milliseconds\n", number_format($counter), number_format($timer * 1000, 4)); } test(); var binTest = () => { using var file = File.OpenRead("/file/file.bin"); var counter = 0; var buffer = new byte[4096]; var sw = Stopwatch.StartNew(); while (file.Read(buffer, 0, buffer.Length) != 0) { counter += 1; } sw.Stop(); Console.WriteLine($"Counted {counter:N} 1s in {sw.Elapsed.TotalMilliseconds} milliseconds"); }; binTest(); And here are the results:
https://withinboredom.info/blog/2022/03/16/yes-php-is-faster-than-c/
CC-MAIN-2022-33
refinedweb
847
66.64
How to change the font across the whole app : Step 1. Download the font What I did, was go to Google Fonts and download a font. When I pick a font I look for one that has multiple styles. For this guide, I choose Source Code Pro, because it has a lot of styles and it looks quite different from the default app font. Once you picked your font, download it and you should have a folder with a lot of .ttf files like this: Step 2. Adding font to project The font will be added to the project like a resource so we should rename the fonts we want to match the android naming requirements. For this demo I picked just two fonts and renamed them: - SourceCodePro-Regular to source_code_pro_regular - SourceCodePro-Italic to source_code_pro_italic Now we will go in Android Studio to the res folder, right-click on it, and create a new Android Resource Directory And when the Dialog pops up we will choose to create a font directory Now we take our fonts and copy them in the newly created font directory. The result should look like this. Step 3. Creating the font family resource After we’ve done this we need to create a font family resource that we will use to set the font across the whole app and to tell it how to use different types of fonts. For that, we right-click on the font directory in Android Studio and create a new resource file, that will have the root as font-family. Something like this: I named it default_font, because it will be a default everywhere in the app, and know we should tell them what font to use, so we change the content of the XML file to this: <?xml version="1.0" encoding="utf-8"?> <font-family xmlns: <font android: <font android: </font-family> Basically we set the font and pick the style for each font. There is also a font-weight attribute in case you need that. Now you might notice a warning in the XML file and if you hover over it you will see that it says: Attribute font is only used in API level 26 and higher So this will only work for API level 26 or higher. To fix that we can click on the warning suggestion and choose to override Resource in font-v26. This will create a folder with two default_font.xml files. One for API level 26 and higher and the other one for below API level 26. Now the one with the (v26) we will leave it as it is and on the other one we will replace android: namespace with the app: namespace in order to take advantage of the Support Library that can set the font below API level 26. More details you can find here. <?xml version="1.0" encoding="utf-8"?> <font-family xmlns: <font app: <font app: </font-family> Step 4. Setting the font in the app Now to set the font in the app all we have to do is go to styles.xml file and set the font family in our app theme like this: <item name="android:fontFamily">@font/default_font</item> Now if you run the app the result will look like this: Conclusion This is how you change the font across the whole app, even below API level 26, in 4 simple steps. Hope this helped you and if you are interested in more guides you can find here.
https://ganduraci.medium.com/how-to-change-the-font-across-the-whole-app-d843b8711815?responsesOpen=true&source=user_profile---------4----------------------------
CC-MAIN-2021-39
refinedweb
587
73.21
Posted 2009-07-02 15:14 by Joe Script Installers A Virtualmin script installer is a small program that contains the information needed to install a web application into a virtual server's home directory, and configure it to run with that server's permissions and using its database. Most script installers are for PHP programs like phpMyAdmin, Drupal and SugarCRM, but it is possible to write an installer for Perl, Python or Ruby or Rails applications too. Virtualmin Pro ships with a large number of built-in installers, which domain owners can add to their websites using the Install Scripts link on the left menu. However, there are many applications that are not covered yet, simply because we don't have time to implement installers for them or they are judged too rarely used or too specific. For this reason, Virtualmin provides an API for adding your own script installers. Script Installer Files and Directories Each script installer is a single file containing a set of Perl functions. Those that ship with Virtualmin Pro can be found in the virtual-server/scripts directory under the Webmin root, which is usually /usr/libexec/webmin or /usr/share/webmin . If you open up one of those files (such as phpbb.pl) in a text editor, you will see a series of funtions like : sub script_phpbb_desc { return "phpBB"; } sub script_phpbb_uses { return ( "php" ); } sub script_phpbb_longdesc { return "A high powered, fully scalable, and highly customizable Open Source bulletin board package."; } Your own script installers will be in files if a similar format - the major difference will be the script ID, which appears in each function name after the word script_ . Script installers that are local to your Virtualmin installation are stored in the /etc/webmin/virtual-server/scripts directory. In most cases, each script is just a single .pl file, but it is possible for other source or support files to be part of the script too. In general though, most script installers download the files they need from the website of the application that they are installing. Script Installer IDs Every script installer has a unique ID, which must consist of only letters, numbers and the underscore character. The ID determines both the installer filename (which must be scriptid .pl), and the names of functions within the script (which must be like script_scriptid _desc). The same ID cannot be used by two different installers on the same system, even if one is built-in to Virtualmin and one is custom. For this reason, when writing an installer you should select an ID that is unlikely to clash with any that might be included in Virtualmin in the future. Starting it with the first part of your company's domain name (like foocorp_billingapp) would be a good way to ensure this. The Lifetime of a Script Virtualmin allows multiple instances of a single script to be installed, either on different domains or in different directories of the same domain. The installer defines the steps that must be taken to setup a script in some directory - in object-oriented coding parlance, it is like a class, while installed scripts are objects. When a script is installed via the web interface, Virtualmin performs the following steps : - Checks if all required dependencies are satisfied, such as required commands, a database and a website. - If the script uses PHP, checks that the versions it supports are available on the system. - Displays a form asking for installation options, such as the destination directory and database. - Parses inputs from the form. - Checks if the same script is already installed in the selected directory. - Configures the domain's website to use the correct PHP version. - Downloads files needed by the script, such as its source code. - Installs any needed PHP modules, Pear modules, Perl modules or Ruby Gems. - Calls the script's install function. This typically does the following : - Creates a database for the script, if needed and if requested. - Creates the destination directory. - Extracts the downloaded source into a temporary directory. - Copies the source to the destination directory. - Updates any config files used by the application being installed, so that it knows how to connect to the database and which directory it runs in. - Records the fact that the script has been installed. - Configures PHP for the domain, to set any options that the script has requested. - Restarts Apache. Script Installer Implementation In this section, the functions that each script installer must implement will be covered. Not all functions are mandatory - some deal with PHP dependencies that make no sense if your script does not use PHP, or if it has no non-core module or Pear dependencies. The example code for each function is taken from the Wordpress Blog installer, in wordpress.pl. This is a PHP application whose installation process is relatively simple, yet common to many other PHP programs. In your own script, you would of course replace scriptname with the script ID you have selected. script_scriptname_desc This function must return a short name for the script, usually a couple of words at most. sub script_wordpress_desc { return "WordPress"; } script_scriptname_uses This must return a list of the languages the script uses. Supported language codes are php, perl and ruby. Most scripts will return only one. sub script_wordpress_uses { return ( "php" ); } script_scriptname_versions Must return a list of versions of the script that the installer supports. Most can only install one, but in some cases you may want to offer the user the ability to install development and stable versions of some application. The version the user chooses will be passed to many other functions as a parameter. sub script_wordpress_versions { return ( "2.2.1" ); } script_scriptname_category (optional) This function should return a category for the script, which controls how it is categorized in Virtualmin's list of those available to install. At the time of writing, available categories were Blog, Calendar, Commerce, Community, Content Management System, Database, Development, Email, Guestbook, Helpdesk, Horde, Photos, Project Management, Survey, Tracker and Wiki. sub script_wordpress_category { return "Blog"; } script_scriptname_php_vers (PHP scripts only) Scripts that use PHP must implement this function, which should return a list of versions the installed application can run under. At the time of writing, Virtualmin only supports PHP versions 4 and 5. On systems that have more than one version of PHP installed, Virtualmin will configure the website to use the correct version for the path the script is installed to. sub script_wordpress_php_vers { return ( 4, 5 ); } script_scriptname_php_modules (PHP scripts only) If the application being installed is written in PHP and requires any non-core PHP modules, this function should return them as a list. Any script that talks to a MySQL database will need the mysql module, or pgsql if it uses PostgreSQL. Virtualmin will attempt to install the required modules if they are missing from the system. sub script_wordpress_php_modules { return ("mysql"); } script_scriptname_pear_modules (PHP scripts only) Pear is a repository of additional modules for PHP, which some Virtualmin scripts make use of. If the application you are installing requires some Pear modules, this function can be implemented to return a list of module names. At installation time, Virtualmin will check for and try to automatically install the needed modules. sub script_horde_pear_modules { return ("Log", "Mail", "Mail_Mime", "DB"); } script_scriptname_perl_modules (Perl scripts only) For scripts written in Perl that require modules that are not part of the standard Perl distribution, you should implement this function to return a list of additional modules required. Virtualmin will try to automatically install them from YUM, APT or CPAN where possible, and will prevent the script from being installed if they are missing. sub script_twiki_perl_modules { return ( "CGI::Session", "Net::SMTP" ); } script_scriptname_python_modules (Python scripts only) For scripts written in Python that require modules that are not part of the standard distribution, you should implement this function to return a list of additional modules required. Virtualmin will try to automatically install them from YUM or APT where possible, and will prevent the script from being installed if they are missing. sub script_django_python_modules { return ( "setuptools", "MySQLdb" ); } script_scriptname_depends(&domain, version) This function must check for any dependencies the script has before it can be installed, such as a MySQL database or virtual server features. It is given two parameters - the domain hash containing details of the virtual server being installed into, and the version number selected. sub script_wordpress_depends { local ($d, $ver) = @_; &has_domain_databases($d, [ "mysql" ]) || return "WordPress requires a MySQL database" if (!@dbs); &require_mysql(); if (&mysql::get_mysql_version() < 4) { return "WordPress requires MySQL version 4 or higher"; } return undef; } As of Virtualmin 3.57, this function can return a list of missing dependency error messages instead of a single string, which is more user-friendly as they are all reported to users at once. script_scriptname_dbs(&domain, version) If defined, this function should return a list of database types that the script can use. At least one of these types must be enabled in the virtual server the script is being installed into. sub script_wordpress_dbs local ($d, $ver) = @_; return ("mysql"); } Only Virtualmin 3.57 and above make use of this function. script_scriptname_params(&domain, version, &upgrade) This function is responsible for generating the installation form inputs, such as the destination directory and target database. When upgrading (indicated by the upgrade hash being non-null) these are fixed and should just be displayed to the user. Otherwise, it must return inputs for selecting them. The functions return value must be HTML for form fields, generated using the ui_table_row and other ui_ functions. The example below from Wordpress is a good source to copy from, as most PHP scripts that you would want to install will need a target directory and a database. The ui_database_select function can be used to generate a menu of databases in the domain, with an option to have a new one created automatically just for this script. sub script_wordpress_params { local ($d, $ver, $upgrade) = @_; local $rv; local $hdir = &public_html_dir($d, 1); if ($upgrade) { # Options are fixed when upgrading local ($dbtype, $dbname) = split(/_/, $upgrade->{'opts'}->{'db'}, 2); $rv .= &ui_table_row("Database for WordPress tables", $dbname); local $dir = $upgrade->{'opts'}->{'dir'}; $dir =~ s/^$d->{'home'}\///; $rv .= &ui_table_row("Install directory", $dir); } else { # Show editable install options local @dbs = &domain_databases($d, [ "mysql" ]); $rv .= &ui_table_row("Database for WordPress tables", &ui_database_select("db", undef, \@dbs, $d, "wordpress")); $rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>", &ui_opt_textbox("dir", "wordpress", 30, "At top level")); } return $rv; } script_scriptname_parse(&domain, version, &in, &upgrade) This function takes the inputs from the form generated by script_scriptname_params, parses them an returns an object containing options that will be used when the installation actually happens. If it detects any errors in the input, it should return an error message string instead. As in the example below, when upgrading the options are almost never changed, so it should return just $upgrade→{'opts'}, which are the options it was originally installed with. Otherwise, it should look at the hash reference in which will contain all CGI form variables, and use that to construct a hash of options. The most important keys in the hash are dir (the installation target directory) and path (the URL path under the domain's root). sub script_wordpress_parse { local ($d, $ver, $in, $upgrade) = @_; if ($upgrade) { # Options are always the same return $upgrade->{'opts'}; } else { local $hdir = &public_html_dir($d, 0); $in{'dir_def'} || $in{'dir'} =~ /\S/ && $in{'dir'} !~ /\.\./ || return "Missing or invalid installation directory"; local $dir = $in{'dir_def'} ? $hdir : "$hdir/$in{'dir'}"; local ($newdb) = ($in->{'db'} =~ s/^\*//); return { 'db' => $in->{'db'}, 'newdb' => $newdb, 'multi' => $in->{'multi'}, 'dir' => $dir, 'path' => $in{'dir_def'} ? "/" : "/$in{'dir'}", }; } } script_scriptname_check(&domain, version, &opts, &upgrade) This function must verify the installation options in the opts hash, and return an error message if any are invalid (or undef if they all look OK). Possible problems include a missing or invalid install directory, a clash with an existing install of the same script in the directory, or a clash of tables in the selected database. As the example below shows, the find_database_table function provides a convenient way to search for tables by name or regular expression - for most applications, all tables used will be prefixed by a short code, like wp_ in the case of WordPress. If you are wondering why these checks are not performed in script_scriptname_parse, the reason is that when a script is installed from the command line, that function is never called. Instead, install options are generated using a different method, and then validated by this function. sub script_wordpress_check { local ($d, $ver, $opts, $upgrade) = @_; $opts->{'dir'} =~ /^\// || return "Missing or invalid install directory"; $opts->{'db'} || return "Missing database"; if (-r "$opts->{'dir'}/wp-login.php") { return "WordPress appears to be already installed in the selected directory"; } local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2); local $clash = &find_database_table($dbtype, $dbname, "wp_.*"); $clash && return "WordPress appears to be already using the selected database (table $clash)"; return undef; } script_scriptname_files(&domain, version, &opts, &upgrade) This is the function where the script installer indicates to Virtualmin what files need to be downloaded for the installation to go ahead. Most scripts need only one, which contains the source code - but it is possible to request any number, even zero. The function must return a list of hash references, each of which should contain the following keys : nameA unique name for this file, used later by the script_scriptname_installfunction. fileA short filename for the file, to which it will be saved in /tmp/.webminafter being downloaded. urlThe URL that it can be downloaded from. nocacheOptional, but can be to 1 to force a download even if the URL is cached by Virtualmin. In most cases, the ver parameter is used in the URL and filename to get the correct source archive. WordPress (shown below) is an exception, as it has only a single download URL which always serves up the latest version. sub script_wordpress_files { local ($d, $ver, $opts, $upgrade) = @_; local @files = ( { 'name' => "source", 'file' => "latest.tar.gz", 'url' => "", 'nocache' => 1 } ); return @files; } script_scriptname_commands If your script installer requires any commands to do its job that may not be available on a typical Unix system, this function should return a list of them. In most cases, it just returns the programs needed to un-compress the tar.gz or zip file containing the source. sub script_wordpress_commands { return ("unzip"); } script_scriptname_install(&domain, version, &opts, &files, &upgrade, username, password) This function is where the real work of installing a script actually happens. It is responsible for setting up the database, un-compressing the downloaded source, copying it to the correct directory, modifying configuration files to match the domain and database, and returning a URL that can be used to login. If anything goes wrong, it must return an array whose first element is zero, and the second is an error message. Upon success, it must return an an array containing the following elements : - The number 1 (indicating success) - An HTML message to display to the user. This should include a link that can be used to access the script. - A description of where it was installed, usually formatted like Under /wordpress using mysql database yourdomain. - The URL that can be used to access the script. - The initial administration login, if any. - The initial administration password. If given, the username and password parameters should be used to set the initial administrative login for the script. If not, it should default to the domain's login and password. The code snippets below show each step of the install process, taken from the standard WordPress installer. The first part simply parses the database connection options and creates a new DB for the script, if one was requested : sub script_wordpress_install { local ($d, $version, $opts, $files, $upgrade) = @_; local ($out, $ex); if ($opts->{'newdb'} && !$upgrade) { local $err = &create_script_database($d, $opts->{'db'}); return (0, "Database creation failed : $err") if ($err); } local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2); local $dbuser = $dbtype eq "mysql" ? &mysql_user($d) : &postgres_user($d); local $dbpass = $dbtype eq "mysql" ? &mysql_pass($d) : &postgres_pass($d, 1); local $dbphptype = $dbtype eq "mysql" ? "mysql" : "psql"; local $dbhost = &get_database_host($dbtype); local $dberr = &check_script_db_connection($dbtype, $dbname, $dbuser, $dbpass); return (0, "Database connection failed : $dberr") if ($dberr); The next step is to extract the downloaded source code, and then copy it to the created destination directory. This is done by calling the unzip and cp commands as the Virtualmin domain owner, so that there is no risk of files that he is not supposed to have access to being over-written. The source code temporary file can be found from the files hash reference in the source key, which was defined by the script_scriptname_files function. Note how the code checks for expected files after extracting and copying the source, to make sure that the commands called actually succeeded. # Create target dir if (!-d $opts->{'dir'}) { $out = &run_as_domain_user($d, "mkdir -p ".quotemeta($opts->{'dir'})); -d $opts->{'dir'} || return (0, "Failed to create directory : <tt>$out</tt>."); } # Extract tar file to temp dir local $temp = &transname(); mkdir($temp, 0755); chown($d->{'uid'}, $d->{'gid'}, $temp); $out = &run_as_domain_user($d, "cd ".quotemeta($temp). " && unzip $files->{'source'}"); local $verdir = "wordpress"; -r "$temp/$verdir/wp-login.php" || return (0, "Failed to extract source : <tt>$out</tt>."); # Move html dir to target $out = &run_as_domain_user($d, "cp -rp ".quotemeta($temp)."/$verdir/* ". quotemeta($opts->{'dir'})); local $cfileorig = "$opts->{'dir'}/wp-config-sample.php"; local $cfile = "$opts->{'dir'}/wp-config.php"; -r $cfileorig || return (0, "Failed to copy source : <tt>$out</tt>."); Most scripts or applications have a configuration file of some kind that defines where to access the database, what domain they are running under, the URL path, and possibly an initial login and password. The script installers is responsible for creating or modifying this file to use the database connection details supplied by the opts paramater, as shown in the code snippet below. Be careful when upgrading, as in general the existing configuration file will be valid for the new version. This means that it doesn't need to be re-created, and should be preserved during the upgrade process if necessary. # Copy and update the config file if (!-r $cfile) { &run_as_domain_user($d, "cp ".quotemeta($cfileorig)." ". quotemeta($cfile)); local $lref = &read_file_lines($cfile); local $l; foreach $l (@$lref) { if ($l =~ /^define\('DB_NAME',/) { $l = "define('DB_NAME', '$dbname');"; } if ($l =~ /^define\('DB_USER',/) { $l = "define('DB_USER', '$dbuser');"; } if ($l =~ /^define\('DB_HOST',/) { $l = "define('DB_HOST', '$dbhost');"; } if ($l =~ /^define\('DB_PASSWORD',/) { $l = "define('DB_PASSWORD', '$dbpass');"; } if ($opts->{'multi'}) { if ($l =~ /^define\('VHOST',/) { $l = "define('VHOST', '');"; } if ($l =~ /^\$base\s*=/) { $l = "\$base = '$opts->{'path'}/';"; } } } &flush_file_lines($cfile); } In some cases, a script will come with a file of SQL statements that can be used to create and populate tables in its database. Others like WordPress do this automatically when they are first accessed. If the application you are installing needs SQL to be run as part of its setup process, you can use code like the fragment below, which was taken from the WebCalendar installer : if (!$upgrade) { # Run the SQL setup script if ($dbtype eq "mysql") { local $sqlfile = "$opts->{'dir'}/tables-mysql.sql"; &require_mysql(); ($ex, $out) = &mysql::execute_sql_file($dbname, $sqlfile, $dbuser, $dbpass); $ex && return (0, "Failed to run database setup script : <tt>$out</tt>."); } The final part of the script_scriptname_install function is returning information to Virtualmin about how to access the new script, and where it is installed. In some cases, a script will have two URLs - the one for administration (which should be references in the second element of the returned array), and the one for general use (which should be in the 4th element). local $url = &script_path_url($d, $opts). ($upgrade ? "wp-admin/upgrade.php" : "wp-admin/install.php"); local $userurl = &script_path_url($d, $opts); local $rp = $opts->{'dir'}; $rp =~ s/^$d->{'home'}\///; return (1, "WordPress installation complete. It can be accessed at <a href='$url'>$url</a>.", "Under $rp using $dbphptype database $dbname", $userurl); } script_scriptname_uninstall(&domain, version, &opts) This function is responsible for cleaning up all files and database tables created by the install code. It is only called when the user deletes a script from a domain, not when upgrading. If most cases, determining which tables to remove is simple, as they all start with some prefix (like wp_ in the case of WordPress). But if a script has created a tables that cannot be automatically identified, your installer will need to have this list hard-coded. See the oscommerce.pl installer for an example. If the installer has created any cron jobs, server processes, custom Apache configuration entries or email aliases, they must also be removed by this function. On success, it should return a two-element array whose first element is 1, and the second a message to display to the user. On failure, it should return and an error message explaining what went wrong.and an error message explaining what went wrong. sub script_wordpress_uninstall { local ($d, $version, $opts) = @_; # Remove the contents of the target directory local $derr = &delete_script_install_directory($d, $opts); return (0, $derr) if ($derr); # Remove all wp_ tables from the database local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2); if ($dbtype eq "mysql") { # Delete from MySQL &require_mysql(); foreach $t (&mysql::list_tables($dbname)) { if ($t =~ /^wp_/) { &mysql::execute_sql_logged($dbname, "drop table ".&mysql::quotestr($t)); } } } else { # Delete from PostgreSQL &require_postgres(); foreach $t (&postgresql::list_tables($dbname)) { if ($t =~ /^wp_/) { &postgresql::execute_sql_logged($dbname, "drop table $t"); } } } # Take out the DB if ($opts->{'newdb'}) { &delete_script_database($d, $opts->{'db'}); } return (1, "WordPress directory and tables deleted."); } script_scriptname_passmode(&domain, version) Most scripts that setup an initial login and password use those from the virtual server the script is being added to. However, Virtualmin can prompt the user for alternative authentication details if you implement this function. All it has to do is return one of the following numeric codes : - 1 - Script needs a username and password - 2 - Script only needs a password - 3 - Script only needs a username The custom login and password entered by the user will be passed to the script_scriptname_install function. If your script installer doesn't setup an initial login at all, you can either omit this function or have it return 0. sub script_wordpress_passmode { return 1; } Other Installation Methods The style of installation code above will work for most scripts that you want to install, but in some cases a slightly different approach is needed. This section covers two of them - scripts with their own configuration generators that cannot be easily replaced by creating the config file yourself, and installers for Ruby On Rails apps, which use a separate server process. HTTP Requests Many PHP applications come with a script that asks the user a series of questions, like the database login and name, domain name, and initial administration username and password. The script then uses this information to create a config file and perhaps populated the database. Ideally, Virtualmin script installers should create any needed config files directly - but in some cases this is too difficult due to their complexity. Similarly, it may not be possible to create and populate all the needed database tables if no SQL file is provided for doing this. In cases like this, it is simpler for a script installer to invoke the application's install code directly, by making an HTTP request to the correct URL. To figure out the installation URL and the CGI parameters it needs, you will need to install the application manually and run through its install process in a browser. The View source feature can then be used to find the names and meanings of all form fields, which can then be used to construct code to call the script the form would submit to. The following code fragment from the script_phpbb_install function of the phpbb.pl installer gives an example of this : # Make config.php writable &make_file_php_writable($d, $cfile); # Trigger the installation PHP script local @params = ( [ "lang", "english" ], [ "dbms", $dbtype eq "mysql" ? "mysql4" : "postgres" ], [ "upgrade", 0 ], [ "dbhost", $dbhost ], [ "dbname", $dbname ], [ "dbuser", $dbuser ], [ "dbpasswd", $dbpass ], [ "prefix", "phpbb_" ], [ "board_email", $d->{'emailto'} ], [ "server_name", "www.".$d->{'dom'} ], [ "server_port", $d->{'web_port'} ], [ "script_path", $opts->{'path'}."/" ], [ "admin_name", $d->{'user'} ], [ "admin_pass1", $d->{'pass'} ], [ "admin_pass2", $d->{'pass'} ], [ "install_step", 1 ], [ "current_lang", "english" ], ); local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params); local $ipage = $opts->{'path'}."/install/install.php"; # Make an HTTP post to the installer page local ($iout, $ierror); &post_http_connection("->{'dom'}", $d->{'web_port'}, $ipage, $params, \$iout, \$ierror); if ($ierror) { return (0, "phpBB post-install configuration failed : $ierror"); } elsif ($iout !~ /Finish Installation/i) { return (0, "phpBB post-install configuration failed"); } As you can see, it makes use of the post_http_connection function provided by Virtualmin which makes an HTTP POST request, which is expected by most applications. If the form is submitted using a GET, you could use Webmin's http_download function instead. In some cases, the installation process is a multi-step wizard, which means that you will need to make several POST requests with different parameters, and possibly parse the output from each. In the worst case, the application may set cookies to track the progress of the wizard - see the SugarCRM installer in sugarcrm.pl for an example of this. Ruby On Rails Installation Most Rails applications installed by Virtualmin are actually run by a separate server process, typically a Mongrel webserver. To link them up to the domain's actual website, Apache proxy directives are added that pass all requests to a path like /typo to a local webserver at a URL like <a href="" class="urlextern" title="" rel="nofollow"></a>. Starting and maintaining this server process and configuring Apache to use it requires a fair bit of work, but fortunately Virtualmin Pro version 3.44 and above include functions that make it easier. Some Ruby applications are available from the Ruby Gems package installation service, while others must be downloaded and extracted like PHP applications. For example, typo.pl does installation entirely from a Gem, and so has a script_typo_files function that returns nothing. It then makes use of the install_ruby_gem function to Install gems for Mongrel and Typo itself. The code fragment below is the first part of the script_typo_install function. As you can see, it checks for the gem command, and then calls functions to install those Gems that it needs. sub script_typo_install { local ($d, $version, $opts, $files, $upgrade) = @_; local ($out, $ex); # Check for the gem command (here instead of earlier, as it may have been # automatically installed). &has_command("gem") || return (0, "The Ruby gem command is not installed"); # Create target dir if (!-d $opts->{'dir'}) { $out = &run_as_domain_user($d, "mkdir -p ".quotemeta($opts->{'dir'})); -d $opts->{'dir'} || return (0, "Failed to create directory : <tt>$out</tt>."); } # Install mongrel first local $err = &install_ruby_gem("mongrel"); if ($err) { return (0, "Mongrel GEM install failed : <pre>$err</pre>"); } # Install typo itself local $err = &install_ruby_gem("typo"); if ($err) { return (0, "Typo GEM install failed : <pre>$err</pre>"); } if (!&has_command("typo")) { return (0, "Install appear to succeed, but the <tt>typo</tt> command ". "could not be found"); } Just installing the Gem is not enough - the code for Typo needs to be somehow copied into the virtual server's directory. Fortunately, Typo provides a command to do this, shown in the code below. Other Ruby applications are distributed in tar.gz files, and need to be extracted and copied into place. $out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ". "typo install ."); if ($?) { return (0, "Typo setup failed : <pre>$out</pre>"); } Because Rails applications use a separate server process, your installer must find a free port for it to run on, and then start it. Virtualmin provides the allocate_mongrel_port function to do the former, and the mongrel_rails_start_cmd function to build a command for the latter. Some Rails applications (like Typo) provide their own server startup scripts, so check the documentation to see which commands they recommend. $out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ". "typo start ."); if ($?) { return (0, "Failed to start Typo server : <pre>$out</pre>"); } All Rails applications will need an Apache proxy configuration to direct requests from the Apache webserver to their Mongrel server. Virtualmin provides a simple function to set this up, shown in the code below. Be aware that many Rails apps don't like being run in a sub-directory, and most don't automatically support it. Your installer may need to modify configuration files and perhaps even application code to support this. &setup_mongrel_proxy($d, $opts->{'path'}, $opts->{'port'}, $opts->{'path'} eq '/' ? undef : $opts->{'path'}); The server process that runs the Rails application must be running all the time - but what happens if the system gets rebooted? To handle this, Virtualmin makes it easy to create either an @reboot crontab entry or /etc/init.d script to start the server, as shown in the following code. The init script will only be added if the domain has the new Bootup Actions plugin installed and made available. if (!$upgrade) { # Configure server to start at boot local $typo = &has_command("typo"); local $startcmd = "cd ".quotemeta($opts->{'dir'})."; ". "$typo start . 2>&1 </dev/null"; local $stopcmd = "kill `cat ".quotemeta($pidfile)."`"; &setup_mongrel_startup($d, $startcmd, $stopcmd, $opts, 1, "typo-".$opts->{'port'}, "Typo Blog Engine"); } Ruby On Rails Un-Installation Just as special code is required to install Rails applications, your script must also implement the script_scriptname_uninstall function to clean up all server processes, boot scripts and Apache config entries. This is made easier by several convenience functions provided by Virtualmin, the use of which is show in the code below: sub script_typo_uninstall { local ($d, $version, $opts) = @_; # Shut down the server process local $pidfile = "$opts->{'dir'}/tmp/pid.txt"; local $pid = &check_pid_file($pidfile); if ($pid) { kill('KILL', $pid); } # Remove bootup script &delete_mongrel_startup($d, $opts, "typo start ."); # Remove the contents of the target directory local $derr = &delete_script_install_directory($d, $opts); return (0, $derr) if ($derr); # Remove proxy Apache config entry for /typo &delete_mongrel_proxy($d, $opts->{'path'}); ®ister_post_action(\&restart_apache); return (1, "Typo directory deleted."); } When Virtualmin deletes a domain, it does not call the uninstall functions for any installed scripts, as this would generally be a waste of time - their directories and databases are going to be removed anyway. In the case of Rails applications, this is not true - their installers start server processes and create boot scripts that must be cleaned up. To ensure that this happens, your script installer must implement the script_scriptname_stop function, which only has to shut down any server processes and prevent them from being run at boot time. This function is only called at virtual server deletion time, and is optional for installers that don't require it. sub script_typo_stop { local ($d, $sinfo) = @_; local $pidfile = "$sinfo->{'opts'}->{'dir'}/tmp/pid.txt"; local $pid = &check_pid_file($pidfile); if ($pid) { kill('KILL', $pid); } &delete_mongrel_startup($d, $sinfo->{'opts'}, "typo start ."); }
http://www.virtualmin.com/documentation/id,script_installers/
crawl-002
refinedweb
5,077
51.68
import mishandles table name (1) By Nolan (nolanw) on 2021-03-11 00:05:52 [link] [source] Currently .import file table fails to respect namespaces: sqlite3 SQLite version 3.34.1 2021-01-20 14:10:07 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite> .mode csv sqlite> .version SQLite zlib version 1.2.11 gcc-10.2.0 sqlite> .import summary_0.csv temp.summary sqlite> .schema CREATE TABLE IF NOT EXISTS "temp.summary"( "uid" TEXT, "seqid" TEXT, "accession" TEXT, "name" TEXT, "description" TEXT, "type" TEXT, "molecule_type" TEXT, "sequence_version" TEXT, "gi_number" TEXT, "cds_count" TEXT, "gene_count" TEXT, "rna_count" TEXT, "repeat_region_count" TEXT, "length" TEXT, "source" TEXT ); sqlite> select * from temp.summary; Error: no such table: temp.summary sqlite> select * from "temp.summary"; 9451451,NZ_CP071129.1,NZ_CP071129,NZ_CP071129,"Caballeronia sp. M1242 chromosome%2C complete genome",chromosome,"genomic DNA",1,"",2667,2739,72,0,2932255,"Caballeronia sp. M1242" I would expect this to create the summary table in the temp namespace. (2) By Larry Brasfield (larrybr) on 2021-03-11 00:49:23 in reply to 1 [link] [source] Because you are so fond of double-quoted identifiers in your SQL, I will tell you what effect they have. They are a way to tell the parser, "Whatever lies between these quotes is my identifier, no matter that it contains keywords, spaces, schema names, or odd punctuation (such as '.'). Because the SQLite parser does what it is told (in this case), it takes your identifier just as quoted. Your DDL creates a regular table, in the main schema, with the misleading name "temp.summary". This is not the same as if you had written "temp"."summary". (5) By Nolan (nolanw) on 2021-03-11 01:50:09 in reply to 2 [link] [source] I think you overlooked the fact that I did not create the DDL, the SQLite .import command did. (3) By Keith Medcalf (kmedcalf) on 2021-03-11 01:31:47 in reply to 1 [source] The CLI .import command can only create tables in the main schema. The tablename specifier in the command cannot be qualified with a schema name, the entire thing is taken as the table name -- including embedded dots. If the specified tablename already exists in an attached schema, then the data will be imported into that table. The ordinary search order for the tablename is used. If the tablename is not found a new table is created in the main schema. It is not possible to .import into a new table in any schema other than main using the CLI .import command. (4) By Nolan (nolanw) on 2021-03-11 01:48:32 in reply to 3 [link] [source] Thanks, I guess this is a feature request rather than a bug. I expect it is common when using import to need to import to a temporary table and then insert into another table the transformed rows of the temporary table. The schema of the imported file may not be fully known and it would be nice to be able to rely on the file header rather than pre-creating a temporary table to import into. (6.1) By Scott Robison (casaderobison) on 2021-03-11 02:59:58 edited from 6.0 in reply to 4 [link] [source] You opened an in-memory database. That database is by definition transient (aka temporary) but it is known as "main". So why not just import into a table named summary. Then if you want to do some manipulation of the data to go into a persistent file, just attach that file with a specified name: attach 'somefile.db' as nottemp; Then you can do all the data manipulation you want from the temporary database named main into the persistent database named nottemp. insert into nottemp.sometable select some-list-of-columns from main.summary where some-list-of-conditions I used that very technique for a data import project last year at work, importing awful looking CSV into a memory-based database named main, then transformed the data into a nicer format in tables in a database that I attached from a file.
https://sqlite.org/forum/info/dde5a2bfaa3df8f7
CC-MAIN-2022-21
refinedweb
698
64.51
18 June 2010 09:11 [Source: ICIS news] SINGAPORE (ICIS news)--Titan Chemicals' major shareholders – Taiwan’s Chao Group and Permodalan Nasional Berhad (PNB) – are in “informal talks” with a third party, a company source said on Friday commenting on a reported proposal of divestment. The source, however, declined to comment on whether the proposal involved the two shareholders selling their stakes in Titan Chemicals as reported by Malaysian English-language daily The Star on 17 June. Chao Group and Malaysian fund management firm PNB hold 37.4% and 30.2% stake respectively in Titan Chemicals, The Star said. Titan, in a response to the newspaper report, told domestic bourse ?xml:namespace> “There is as yet no outcome, event or other development from such discussions,” it said in the statement. “In addition, we have not received any proposal from any other person concerning our shares or business,” it said. Titan added that it would make an announcement, if warranted, by "events or developments", at an appropriate time. Titan Chemicals
http://www.icis.com/Articles/2010/06/18/9369033/titan-chemicals-shareholders-in-informal-talks-with-third-party.html
CC-MAIN-2014-15
refinedweb
169
53.21
I’m trying to upgrade an application to Rails 3 and I found a difference in the way helpers are loaded. I want to override a method based on the current controller but it now seems that all helpers are loaded. I’ve broken it down to a simple example. I have a test app with 2 controllers - books and authors. In the BooksHelper module, I have: module BooksHelper def some_helper “From books helper” end end In AuthorsHelper module, I have: module AuthorsHelper def some_helper “From authors helper” end end In my index.html.erb for Books I include <%= some_helper %> and in index.html.erb for Authors I include the same <%= some_helper %>. When I do the books index it shows as “From books helper” but when I do a authors index I get the same “From books helper” - I had hoped for “From authors helper”. I tried the same app in rails 2 and I get the helper method from the current controller used - so I get what I expected. In my real app - I have a call in the layouts - application.html.erb where I call the helper and hope to get the current controller’s helper so I can show information (like bread crumbs) for the current controller.
https://www.ruby-forum.com/t/not-able-to-override-helper/197668
CC-MAIN-2022-05
refinedweb
210
78.28
Python Programming, news on the Voidspace Python Projects and all things techie. Resolverforge: Download Modules on Demand for IronPython and Resolver One I've implemented a client-side module that allows you to specify what modules your code 'requires'. After user-confirmation, a required module that isn't available will be downloaded and on the import path. This is intended for use with Resolver One, but should work with any IronPython code where Windows Forms is available (just the message box is used currently). Modules are downloaded from whichever repository you specify, which defaults to. The code to use Resolverforge looks like: require('helloworld') import helloworld helloworld.sayhello() You can specify your own repository, so that you can make modules available on the internet or an intranet instead of having to keep dependencies with your spreadsheets. This is an early implementation (which works of course!). Resolverforge downloads modules that are individual Python files and doesn't support versioning. It will also one day gain a website counterpart that will allow users to create projects and make them available for download. For the moment you will have to make do with the modules I've put up, which are mainly aimed at Resolver One. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2008-02-11 00:28:36 | | Categories: Website, Hacking, Work, IronPython Tags: resolver, resolverhacks, resolverforge Resolver Hacks Updates Resolver One is a great program, but it can be hard to explain to people why it is radically different from existing spreadsheets. Giles Thomas recently presented Resolver One at the Lang.NET 2008 conference, and we got some great feedback as a result. They are summarised in Resolver Systems News. My favourite is this one from Laurence A. Lee. It starts "FINALLY! Someone from a Company that truly "gets it"!! YES, YES, YESSSS", and continues: we were using Excel Spreadsheets to mock up all sorts of Business Logic for the Financial Sector, and we noticed a huge gap in our development process. It took a week to mock up all that business logic in Excel, and then it took 6 MONTHS for a software development team to take that spreadsheet, play with it for a while, and try to implement that Business Logic Module in hand-written code. This is exactly the space that Resolver One fills. Anyway, I added three new pages to Resolver Hacks. The first two are snippets: - Spreadsheet Module Directory - Resolver One obeys the IRONPYTHONPATH environment variable, which can be very useful. - The Main Module - a hack that gives you access to the spreadsheet objects from inside module code. The third article is so special it deserves its own blog entry... Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2008-02-11 00:27:39 | | Categories: Work, Website Tags: resolver, resolverhacks ALT.NET UK Unconference Two weeks ago I attended a.NET conference in London. The conference was organised by "the community", and was an an open spaces conference. This means that there was no preset agenda and the point of the conference was to discuss whatever subjects were the closest to the hearts of those attending. The .NET community is in an interesting position. The community has traditionally been quiet, tending to follow wherever Microsoft leads. This has changed in recent years (even in the two years that I have been using .NET), and at the forefront of this has been the ALT.NET movement. ALT.NET is a movement amongst .NET developers who want to push beyond 'conventional development' and are interested in 'progressing the art'. A definition of the ALT.NET movement, which has a strong element of agile development, from David Laribee who first coined the phrase: -.) Many Python development have no interest in Windows development, much less .NET development, but it should come as no surprise to them that the .NET world has many intelligent developers who are interested in furthering their craft. These people have a strong interest in dynamic languages, web frameworks like Ruby on Rails and the real world application of agile development practises like pair programming, test driven development and iterative development. Folk came from quite a distance to the conference - from Newcastle, Germany and even Israel [1]. There were about sixty people there in total and it was great to see so many .NET developers who actively use agile practises in one place. I had a good time at the conference and met some great people. I learned some interesting things from the discussions on agile development, particularly aspects of agile development that we don't yet practise at Resolver. We don't yet do retrospectives. This is where you spend time as a team going over the work in the previous iteration [2]. Our velocity (actual time taken for user stories divided by estimated time) is pretty steady at 0.5, but we sometimes have stories that go wildly over-estimation and retrospectives would be helpful in diagnosing what happened. I also learned a bit about BDD, which is interesting but hasn't greatly shifted my testing mindset [3]. One of the aspects of the conference that disappointed me was the discussion on testing strategies. I'm extremely interested in different approaches to testing, but the problems faced by C# developers are often irrelevant to IronPython development! Although they do face a lot of similar problems, like how much and when to mock, they use different frameworks and have to fight the compiler in ways that Python programmers just don't. The conference was held on Conchango's premises, and one of the best parts of the conference was using their table football. Hmmm... is it a bug or a feature? From the after conference mailing list chatter, here are a couple of links on Planning Poker (the estimation game for user stories): Hmmm... looks like matplotlib is now using ConfigObj as well. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2008-02-11 00:26:24 | | Categories: General Programming Tags: conferences, .NET, altnetuk, agile New House, New Desk, New Computer I'm still settling in after moving house. We've only moved half a mile down the road (closer to the train station and the red light district), and its our first house that we've bought. It needs a fair bit of work, but along with the new house I have a new office, new internet connection, new computer and new desk. The new office and desk is great - it gives me a lot more space than my last setup. The desk comes from Office Supermarket and was surprisingly cheap (and the instructions were understandable!). Apparently L-shaped desks aren't so good for pair-programming, but I don't do much of that from home. I recently blogged about wanting a new computer, and how the new Apple Mac Pros were looking pretty good. I've just made the jump. Max recently blogged about switching from Windows to a Mac Pro (and I nicked the image from him): It really is a beautiful bit of kit. Memory is upgraded and new hard drives added by sliding out trays. I've added a raptor hard drive, and partitioned it in two. I moved Mac OS X onto one partition (using Carbon Copy Cloner) and 64-bit Vista on the other. This machine gets a 5.9 for everything under Vista Windows Experience Index except for the gaming graphics where it only scores a 5.4. With boot camp I can choose which OS to boot into. Unfortunately Parallels doesn't support 64-bit OSes (which I didn't realise), but having parallels installed does give you read-only access to any NTFS drives you have installed. I managed to migrate my 32-bit Vista install from my Macbook by exporting it with parallels transporter and then copying it across. You can network two Macs by connecting them with an Ethernet cable (it doesn't need to be a crossover cable) and enabling file sharing. You will save yourself some grief if you configure your firewall to allow this of course. I still haven't migrated my desktop environment fully onto the Mac yet. I need another graphics card to support three monitors and they are expensive for the new Mac Pros. Speaking of proprietary devices, the keyboard is amazing. It comes with a USB extender cable for the keyboard. I wanted to use the extender with another device, and it has a notch on it so that it can only be used with the Mac keyboard! The notch does make connecting the keyboard easier, but a proprietary USB extender is taking things too far... Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2008-02-11 00:25:04 | | Categories: Computers Tags: apple, office, desk, macpro Archives This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License. Counter...
http://www.voidspace.org.uk/python/weblog/arch_d7_2008_02_09.shtml
CC-MAIN-2018-05
refinedweb
1,502
64.41
PEP 382 Sprint - Silver Spring, Maryland USA 21-Jun-2011 2000UTC Attendees: - Erik Bray - Jason Coombs - Michael Droettboom - Eric Smith - Barry Warsaw - Steve Waterbury Bitbucket clone: Tasks review Martin's branch hg clone - look for reference counting issues other initialization issues (*foo = NULL) - do we have sufficient test coverage? top-level non-trivial init.py - various reload scenarios both __init__.py and .pth file exists - multiple .pth files in the same namespace package directory .pth files that contain path names: do they set __path__ correctly? is package.__path__ set correctly? must contain one *, at the beginning test that load_module_with_path() (pep 302 loader) gets called correctly test AttributeError when that's missing is importlib is covered? - pull down 3rd party pep 302 loader and see if/how it's broken - refactor import.c to yank out anything that can be written as a 302 loader? - --e.g. zip import-- Already done, but zipimport needs to support PEP-382 - load-from-file could just be a PEP 302 loader - could land independently (but need to go through python-dev) - does this really make our lives easier? - attempt a merge of mvl's branch to trunk - figure out build problems on windows (jaraco) test_imp gives one failure on fedora (make sure imp module has been updated) - fixed - stylistic cleansing of import.c - tests against 0 vs. NULL - mispellings should LBYL on AttributeError in find_path PEP Questions Clarify what happens when a directory contains both an __init__.py and a .pth file PEP should clarify what the impact of the PEP is on existing namespace packages (i.e. those with magic __init__.py files Do import statements in .pth files get ignored or does it raise an error? - Impact of PEP on setuptools/packaging/distutils* Use case for extending existing .pth file syntax (minus import support)? I.e why are non-* lines in the .pth files added to path? And should these really be called .pth files? At least clarify the PEP! Action Items "It's all so freaking big we can never make any progress on it" - ES Finish off PEP 302: Jason created a bitbucket clone for import.c refactoring - Eric to experiment zipping the stdlib and delete the Lib dir by sys.path hacking, does Python still work? - Isolate a path loader to match zip importer perhaps refactored from importlib - Add this loader to the front of path_hooks and see if stdlib can be imported - Rip out the stuff out of import.c that's not associated with calling path_hooks - Benchmarking, is the Python version good enough? If so, who needs C? - If not, make a C version of the loader In parallel: - Complete the PEP 382 tests identified above - Clarify open PEP 382 questions - Rewrite zipimport in Python? - create a sub-mailing list on python.org
https://wiki.python.org/moin/Pep382Sprint?highlight=AttributeError
CC-MAIN-2016-30
refinedweb
466
66.54
Namespaces exist in many languages, including C++ and the Java™ programming language. They came about to help with the organization of large codebases, where oftentimes, there was a concern for overlapping function or class names with the application and the problems that having that would cause. The use of namespaces can help identify what function or utility the code provides, or even help specify its origin. An example of this is the System namespace within C#, which contains all the functions and classes provided by the .NET framework. In other languages without formal namespaces (such as PHP V5.2 and earlier), people would often emulate namespaces by trying to use a specific naming convention within the class or function names. The Zend Framework does this, where each of the class names begin with Zend, and each child namespace is separated by an underscore. For example, the class definition Zend_Db_Table is a class that is part of the Zend Framework and has database functionality. One issue with this approach is that the resulting code can become verbose, especially if the class or function is several layers deep ( Zend_Cache_Backend_Apc is an example of this from the Zend Framework). Another issue is that all code must conform to this style, which can be difficult if you're integrating third-party code within an application that doesn't conform to this naming convention. The history of namespaces in PHP is quite a winding road. They were originally going to be a part of PHP V5, but they were removed in the development stages since proper implementation could not be achieved.. Namespaces in PHP PHP borrows much of the syntax and design of namespaces from other languages — most notably C++. However, it does deal with namespaces somewhat uniquely in some circumstances, which can be a stumbling block for users expecting namespaces to work exactly the same as other languages. In this section, we look at how namespaces work in PHP. Defining a namespace Defining a new namespace is fairly trivial. To do so, add the following line in Listing 1 as the first command or output in a file. Listing 1. Defining a namespace <?php namespace Foo; class Example {} ?> It's important to understand that the above declaration of namespace must be the first command or output in the file. Having anything else before it will result in a fatal error. Listing 2 shows some examples of this. Listing 2. Bad ways to define a namespace /* File1.php */ <?php echo "hello world!"; namespace Bad; class NotGood {} ?> /* File2.php */ <?php namespace Bad; class NotGood {} ?> In the first part of Listing 2, we attempted to echo out to the console before the namespace definition, which results in a fatal error. In the second part of the listing, we added an extra space before the <?php opening tag, which also causes a fatal error. It's important to watch for this situation as we write our code since it is a common mistake when working with namespaces in PHP. However, both of the above examples can be rewritten by separating out the namespace definition and the code that is to be a part of the namespace declaration into its own separate file, which can be included in the original files. Listing 3 demonstrates this. Listing 3. Fixing the bad ways to define a namespace /* Good.php */ <?php namespace Good; class IsGood() {} ?> /* File1.php */ <?php echo "hello world!"; include './good.php'; ?> /* File2.php */ <?php include './good.php'; ?> Now that we saw how to define a namespace for the code within a file, let's see how to leverage this namespaced code within an application. Using namespaced code Once we have defined a namespace and put code inside of it, we can use it very easily within an application. There are different options for calling a namespaced function, class, or constant. One way is to explicitly reference the namespace as a prefix to the call. Another option is to define an alias for the namespace and prefix the call with that, which is designed to make the namespace prefix shorter. And finally, we can simply just use the namespace within our code, which makes it the default namespace and, by default, makes all calls reference that. Listing 4 illustrates the differences between the calls. Listing 4. Calling a function within a namespace /* Foo.php */ <?php namespace Foo; function bar() { echo "calling bar...."; } ?> /* File1.php */ <?php include './Foo.php'; Foo/bar(); // outputs "calling bar...."; ?> /* File2.php */ <?php include './Foo.php'; use Foo as ns; ns/bar(); // outputs "calling bar...."; ?> /* File3.php */ <?php include './Foo.php'; use Foo; bar(); // outputs "calling bar...."; ?> Listing 4 demonstrates the different ways to call a function bar() in namespace Foo. In File1.php, we see how to make the explicit call, prefacing the call with the namespace name. File2.php uses an alias to the namespace name, so we substitute the namespace name with the alias. Finally, File3.php simply uses the namespace, which allows us to make the call to bar() without any prefix. We can also define more than one namespace within a file by adding further namespace calls in the file. Listing 5 illustrates this. Listing 5. Multiple namespaces in a file <?php namespace Foo; class Test {} namespace Bar; class Test {} $a = new Foo\Test; $b = new Bar\Test; var_dump($a, $b); Output: object(Foo\Test)#1 (0) { } object(Bar\Test)#2 (0) { } Now that we have the basics of how to make a call inside a namespace, let's see some more complicated namespace situations and how those calls work. Namespace resolution One of the hurdles to getting the hang of namespaces is learning how the scope resolution works. While simple cases like those in Listing 4 make sense, the problem comes when we begin to nest namespaces within each other, or when we are in one namespace and are looking to make calls against the global space. PHP V5.3 has rules on resolving these issue automatically in a sensible way. Let's create a few include files, with each one having the function hello() defined within it. Listing 6. Function hello() defined in different namespaces /* global.php */ <?php function hello() { echo 'hello from the global scope!'; } ?> /* Foo.php */ <?php namespace Foo; function hello() { echo 'hello from the Foo namespace!'; } ?> /* Foo_Bar.php */ <?php namespace Foo/Bar; function hello() { echo 'hello from the Foo/Bar namespace!'; } ?> Listing 6 defines the function hello() three times in three different scopes: in the global scope, in the Foo namespace, and in the Foo/Bar namespace. Depending upon the scope in which the hello() function call is made determines which hello() function is called. An example of how these calls look is shown below. Here, we'll use the Foo namespace to see how to call the hello() function in the other namespaces. Listing 7. Calling all of the hello() functions from the Foo namespace <?php include './global.php'; include './Foo.php'; include './Foo_Bar.php'; use Foo; hello(); // outputs 'hello from the Foo namespace!' Bar\hello(); // outputs 'hello from the Foo/Bar namespace!' \hello(); // outputs 'hello from the global scope!' ?> We can see that we can shorten the namespace prefix when referencing a child namespace within the current namespace (the Foo/Bar/hello() call can be shortened to Bar/hello()). And we see how to specify that we wish to call the method in the global scope by just prefacing the call with the namespace operator. Now that we have the mechanics of how namespaces work, let's see how we can use them within our code. Use cases for namespaces in PHP The overall goal for namespaces is to help us better organize our code by eliminating the amount of definitions that live within the global scope. In this section, we'll take a look at a few examples where having namespaces can help achieve these goals with minimal effort. Namespacing third-party code Many PHP applications use code from different sources, whether it be consistently designed code like what exists in the PEAR repository, code from various frameworks like CakePHP or the Zend Framework, or other code found from various places on the Internet. One of the biggest problems when integrating this code is that it may not mix very well with existing code; function or class names may clash with what we are using already in our application. One example of this is the PEAR Date package. It uses the class name Date, which is a fairly generic class name and could very well exist in other places in our code. So a good way to get around this is by adding a simple namespace command to the top of the Date.php file inside the package. Now we can be specific when we wish to use the PEAR Date class instead of our own. Listing 8. Using the PEAR Date class as defined in a namespace <?php require_once('PEAR/Date.php'); use PEAR\Date; // the name of the namespace we've specified in PEAR/Date.php // since the current namespace is PEAR\Date, we don't need to prefix the namespace name $now = new Date(); echo $now->getDate(); // outputs the ISO formatted date // this example shows the full namespace specified as part of the class name $now = new PEAR\Date\Date(); echo $now->getDate(); // outputs the ISO formatted date ?> We've defined the PEAR Date class inside namespace PEAR/Date within the PEAR/Date.php file, so all we need to do is include that code in our file and use the new namespace, or prefix the class or function names with the namespace name. With this, we can include third-party code in our application safely. Name clashing isn't just an issue with third-party code. It can also existing with large codebases that have parts never intended to get near each other. In the next section, we see how namespaces can simplify this situation. Avoid utility function name clashing Just about every PHP application has a number of utility methods. They aren't really part of any of the objects in the application, and they don't really have a fit in any one place in the application, although they do serve a role to the application as a whole. But they can cause maintenance headaches as our application grows. One place where this can be a problem is with unit testing, where we write code that tests the code that runs an application. Most unit-testing suites are designed to run every test in the entire test suite. For example, we could have two utility files that would never get included together, but in the test suite, they are, since we are testing the entire application at once. While designing an application in such a way is never a good idea for long-term maintenance, it often exists in large legacy codebases. Listing 9 shows how to avoid this. We have two files, utils_left.php and utils_right.php, which are collections of utility functions for right- and left-handed users. For each file, we define each in its own namespace. Listing 9. utils_left.php and utils_right.php /* utils_left.php */ <?php namespace Utils\Left; function whichHand() { echo "I'm using my left hand!"; } ?> /* utils_right.php */ <?php namespace Utils\Right; function whichHand() { echo "I'm using my right hand!"; } ?> We define a whichHand() function that outputs which hand we are using. In Listing 10, we see how easy it is to safely include both files and switch between the namespaces we wish to call. Listing 10. Example of using utils_left.php and utils_right.php together <?php include('./utils_left.php'); include('./utils_right.php'); Utils\Left\whichHand(); // outputs "I'm using my left hand!" Utils\Right\whichHand(); // outputs "I'm using my right hand!" use Utils\Left; whichHand(); // outputs "I'm using my left hand!" use Utils\Right; whichHand(); // outputs "I'm using my right hand!" Now both files can be included safely together, and we specify which namespace to use to handle our function call. And the impact on our existing code is minimal, since the re-factoring to support this only requires us to add the use statement at the top of the file to indicate which namespace to use. This same idea can be extended beyond our defined PHP code. In the next section, we see how we can even override internal functions in a namespace. Overriding internal function names While oftentimes, the internal functions in PHP provide great utility, sometimes they don't do exactly what we want them to. We may need to augment their behavior to match what we want the function to do, but we also want to redefine the function with another name to avoid further cluttering the scope. The filesystem functions are one area where we may want to do this. Let's say we want to make sure any file created by file_put_contents() has certain permissions set. For example, let's say we want the files created by this to be read-only; we can redefine the function in a new namespace, as shown below. Listing 11. Defining file_put_contents() inside a namespace <?php namespace Foo; function file_put_contents( $filename, $data, $flags = 0, $context = null ) { $return = \file_put_contents( $filename, $data, $flags, $context ); chmod($filename, 0444); return $return; } ?> We call the internal file_put_contents() function inside the function and prefix the function name with a backslash to indicate that it should be handled in the global scope, which means the internal function will be called. After calling the internal function, we then chmod() the file to set the appropriate permissions. These are just a few examples of how we can use namespaces to enhance our code. In each case, we avoid doing ugly hacks, such as prefixing the name of the function or class to make the name unique. We also now know how using namespaces can make it much safer to include third party code in large applications without the worry of name collisions. Summary Namespaces in PHP V5.3 are a welcome addition to the language, helping developers organize code within an application in a sensible way. They enable you to avoid using naming standards to handle namespacing, allowing you to write more efficient code. While they have been a long time coming, namespaces are a welcome addition for any large-scale PHP application suffering name clashes. Resources Learn - Start this series with "What's new in PHP V5.3, Part 1: Changes to the object interface" and "Part 2: Closures and Lambda functions." Then continue with "What's new in PHP V5.3, Part 4: Creating and using Phar archives." - Learn more about closures in Wikipedia. - See the original RFC for lambda functions and closures for more details on how closures work. - Read "A PHP V5 migration guide" to learn how to migrate code developed in PHP V4 to V5. - "Connecting PHP Applications to Apache Derby" shows you how to install and configure PHP on Windows® (some steps are applicable to Linux®). -.
http://www.ibm.com/developerworks/library/os-php-5.3new3/index.html?S_TACT=105AGY75
CC-MAIN-2014-52
refinedweb
2,498
63.09
Agenda See also: IRC log <trackbot> Date: 14 April 2009 <DaveS> dave S here <Bob> agenda: <Bob> scribenick: li <marklittle> do the dogs get a vote ;-) ? <marklittle> rofl no objection to agenda no objection to minutes bob: no new issues at this point ... please review fpwd of 5 specs in 1 week and publish comments to mailing list bob: this group is contentious and not moving toward concensus ... hope to work in more friendly fashion geoff: ok with ram's proposal <Bob> 6730 accepted with no objection <Bob> geoff: 6594 and others are joined together <Bob> ai: Geoff to prepare new proposals for 6594, 6672, and 6673 <Bob> ACTION: Geoff to prepare new proposals for 6594, 6672, and 6673 [recorded in] <trackbot> Created ACTION-57 - Prepare new proposals for 6594, 6672, and 6673 [on Geoff Bullen - due 2009-04-21]. dug: 6594 are related to others <Bob> last AI is due before next call dug: 6594, 6672, and 6673 are somewhat different daves: 6594 3rd comment links three proposal already ... dug already finish them <Bob> email at geoff: looked the joint proposal and to provide more comments by next week geoff: raised issues and katy responded them, need to look them ... request clarifications from katy katy: explain the reponses ... merge part of rt into t (only fragment feature) AI: bob to retitle the proposal to "move fragment from rt to t" wu: like to see the concrete proposal katy: the proposal is already available from the issue <Yves> fragments in T seems to not be the ideal place. (like URI fragments are not in HTTP) geoff: is this merge confusion? we need to discuss this decision: why only part of it instead of all? daves: basic fragment vs. complex fragment, take basic fragment into T, which is clear bob: difference between ws-rt fragment and ws-man fragment daves: not sure, but think ws-rt fragment addresses ws-man requirement and grid community as well dug: too much to move all rt into t, take a phase based approach ... only frag id in difference places <Yves> how about creating a ws-frag spec? (if you want to extract it from RT) geoff: still not sure if the use cases can be solved separately by two specs, instead of using the merged one ... use cases can't be solved by rt alone? katy: single spec (merged) will cover all cases, except a few, which can be addressed by extending merge t <Geoff> that would be fine by us yves: separating fragment is more reusable for ws-man and grid katy: fragment is not in the core of t, but in a appendix daves: fragment is separated in the appendix geoff: don't think appendix is a good idea ... many usages of t don't need fragment, 80% don't need, 20% may need it wu: yves's idea is good, making it its own standard is more valuable than appendix dug: if fragment not in t, it may result ad-hoc solution <asir> too much noise on the line jeffM: our goal is not just to make ws-man work, but to make ws-* work ... we need to make decision on our goal ... packaging is not that important, but operations are <Yves> fragment is relative to a resource, so it fits better alog the EPR definition, but editing ws-addr-core is close to impossible now, otherwise I agree that the content is what matters geoff: basic functions in base class, more functions in subclass, not sure why changing this design decision daves: merging frag into t is to eliminate ad-hoc solutions to frag with t ... don't want ws-man to redo frag with t <Geoff> dave's thought is worth investigation... <gpilz> +1 to daves <Katy> +1 Dave dug: frag in t is optional, what is the pain? geoff: it's not completely optional, force people to reprofile ws-t in light of frag merge <asir> Doug - your phone is noisy dug: we can make sure it's completely optional, people has to change ws-t anyway geoff: changing namespace does not justify greater changes <asir> There are such examples in W3C <asir> For instance SOAP Part 1 and Part 2 bob: daves' proposal is to make ws-t optional but normative <asir> Part 1 carries an ad for Part 2 bob: any objection to daves' direction? ashok: puting in appendix is better to avoid confusion wu: 3 specs or 2 specs bob: current proposal is 3 dug: changes to ws-t is necessary, like to see mroe detail <Katy> My phone keeps breaking up - I need to drop off an re-dial asir: frag in a separate doc means all about frag in one doc, not just appendix ... advertisement is ok but how to formulate the normative language <asir> We are okay with the precedents set by SOAP, WSDL and WS-A daves: ws-security may help us with the normative languages <Katy> Sorry - my phone breaking up again <Katy> will try to fix wu: if we can ask other standards using ws-t to make this connection, instead of link frag to ws-t daves: ws-man using ws-t may not aware frag if frag not in the appendix <gpilz> how can we tell WSMAN what do do? <DaveS> +1 <asir2> Gil - are you a member of WS-Man WG? <gpilz> yes I am wu: ws-man can specify requirement for ws-t and frag <asir2> Gil .. you are a powerful voice! wu: we should let users to decide which to use <gpilz> asir: loud doesn't help daves: worry ws-man may choose other way, creating problems katy: separate specs looses the context of frag spec, we need to make contexts for both ws-t and frag clear <Geoff> +1 to Bob bob: ws-addressing is a model we can use dug: having free choices is not good for ws-* ... we need to restrict composition choices asir: ws-addressing and soap 1.2 are good models for multiple documents of one spec ... ws-ra can influence ws-man with good values ... we should respect other bodies choice gil: ws-man may use ws-ra, but the schedule is up in the air ... ws-man is just one case that may invent its own frag yves: thers is a link from frag to ws-t, not the opposite, we need to make requirement of frag clearer bob: more time to decide direction? <gpilz> +1 to doug <gpilz> let's look at the changes to WS-T as stand-alone changes dug: taking stepwise change to ws-t leading to merge <Katy> +q asir: refine requirements for frag katy: puting appendix on hold, but do changes on the core ws-t, is asir ok with this? asir: we have issues on those changes too katy: is it ok to incorporate dialect support, for example? geoff: why dialect attribute is required? katy: it provides a simple extension point to add frag and others dug: 6712 show dialect is more than ext point asir: ambiguity can be resolved without 6712 dug: element under <create> is ambiguous asir: one->data, more->data, any particle <asir> and zero->null bob: volunteers to discuss frag issue in wiki geoff and katy volunteered bye <Bob> Li, thanks for scribing This is scribe.perl Revision: 1.135 of Date: 2009/03/02 03:52:20 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/ws-t is related to frag/thers is a link from frag to ws-t, not the opposite/ Succeeded: s/any particle/data, any particle/ Found ScribeNick: li Inferring Scribes: li WARNING: Replacing list of attendees. Old list: +20756aaaa New list: Default Agenda: WARNING: No meeting chair found! You should specify the meeting chair like this: <dbooth> Chair: dbooth Found Date: 14 Apr 2009 Guessing minutes URL: People with action items: geoff WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output]
http://www.w3.org/2009/04/14-ws-ra-minutes.html
CC-MAIN-2017-30
refinedweb
1,338
59.87
PHP Chat Systems A MySQL Driven PHP Chat Systems A MySQL Driven Chat Script Tutorial This article will show you how to create a simple chat script using PHP and MySQL database... many things just because of it is just a demo version of chat system, you can Chat Script Tutorial PHP Chat Systems A MySQL Driven Chat Script Tutorial  ... presume so many things just because of it is just a demo version of chat system... page will be look like: Full code of the chat system is provided along Open Source Chat applets. In this way, WebChat is a true Web chat system. ... to 1000 users. BRIBBLE is easy to use and contains a php based management system.... Mazen's PHP Chat This is an Open Source chat program video chat video chat Hi , how can implement video chat using jsp and servlet .but not use applet . I want to implement video chatting system in my... implement applet because this application is also run on MAC Operating System Chat server is a standlone application that is made up the combination of two... to run the MyServer.java file at any system on the network that we want chat message chat message how to create chat server which should be similar to google talk and facebook etc Chat server Chat server Please provide me complete information for making a chat server project using JMS PHP GD Get System IP <?php $image = imagecreatetruecolor(150,70); $ip = "$_SERVER[REMOTE_ADDR]"; imagestring($image, 10, 20, 36, $ip, 0x00ff00); header('Content-Type: image/png'); imagepng($image, null, 9); ?> After PHP to use the username and the password to access the system (Main Menu BEST CHaT BEST CHaT Tsuper ajax chat Read full Description Web-based system development Web-based system development I have a system written in java... it to build a gui.For server side, which 1 is better for my situation, PHP or java... PHP not script. Anyone could help me please Fleek Management System(FMS) Fleek Management System(FMS) Hi, Please anybody can reply....I wanna develop a project(FMS) in Java , which was already developed in PHP. Now what technologies should i apply for developing this project. The main aim java chat application java chat application Can u plz send me java code for Lan communicatino(chat php Include consider an example of that we have two examples of chat and mail system and we want... php Include: Include command provides the opportunity to include several php pages within a single page X-Chat X-Chat X-Chat has two good features of usability: colored nicknames and alignment by text as opposed to alignment by nicks. When you read text, it's enough for eyes to notice PHP Tutorials from RoseIndia don't want to show all of them in your pages. PHP Chat Systems... to create a simple chat script using PHP and MySQL database. The application... create a mail system using PHP and Argosoft mail server creating windo chat creating windo chat hi ... please could you help me in creating chat aprograme in java ???? with comments beside codes please System System What is System in System.out.println() method? Is it a Class or a Package Live Chat Application Live Chat Application Hello sir, I want to create "Live Chat Application" for my web site. When any person click on the Live Chat tab, it should be able to communicate with me. please help me sir, by providing Chat Ask PHP Questions the Events and calendar software in PHP. Chat - PHP based chat applications... management system can also be developed in PHP.   chat server in java - RMI chat server in java how develope a chat server in java language,not standalone application,i want to develpoe a web base application,please give me a idea,code, this application deployed in a netwok Hi Friend Tutorial college Student Admission System Tutorial college Student Admission System I want PHP Project for Student Admission System. actually i want 2 know how 2 start this...please show me my way..... please send me synopsis PEAR in php? of open-sourced code for PHP users A system for code distribution and package...PEAR in php? What is meant by PEAR in php? Hi friends, PEAR is short for "PHP Extension and Application Repository" and is pronounced how to create chat application in jsp? how to create chat application in jsp? i am developing online web portal using jsp, i need to communicate with admin, so i need integrate with the chat applicaion through the webportal PHP Development Companies PHP Development Companies When we talk about PHP development companies, we...; With the rising popularity of PHP scripting language, the demand of PHP developers have increased several times, and the numbers of PHP developers and PHP development | Input - Output String Functions | Dynamic Dropdown Menu | PHP Chat Systems A MySQL Driven Chat Script | PHP XML and PHP Backend Sharing Data | XML DOM... Questions | Site Map | Business Software Services India PHP Tutorial Operating System based Web Hosting management system (DBMS) to store, manage and data query execution, and P refers to PHP...Operating System based Web Hosting On the basis of operating system, Web Hosting system has been differentiated on four categories: Windows based Web PHP ini PHP ini PHP provides us so... customize the behavior of php. Using this file maintaining PHP will be as easy... can configure all PHP's runtime configurations. It is also better php download file browser php download file browser limiting downloading file system via browser only through my web application PHP Frameworks is a simple online chat system which uses AJAX. Ajchat also allows sharing or embedding... PHP Frameworks  .... XAJAX Library xajax is an open source PHP class library Ajax chat Application Java/PHP Developer Java/PHP Developer Hi, can u help me to embedd time on java frame and it should be independent of operating system time..if we change system time it should'nt be changed.. Thank you sir PHP Installation Process PHP Installation Process Hi, I want to install the PHP Software in My systems. So, Can any one Suggest how to installation the PHP software in My system and what configuration require to Install. So, Kindly refer any online Java/PHP Developer Java/PHP Developer Hi, I need a cloak embedded in java swing frame or panel..And it should not change when system time is changed ..please multi user chat server - Java Beginners multi user chat server write a multi chat server and client with step by step explanation? please send me this source code to my mail id with step by step explanation PHP Get Browser IP Address PHP Get Browser IP Address PHP provides us $_SERVER['REMOTE_ADDR'] function is used to display the Browser IP address PHP Get IP Address Code: <?php echo "My Browser IP is :". $_SERVER['REMOTE_ADDR']; ?> java chat using java media java chat using java media Remove the error of this code plz reply me fast on my mail ID **Deleted by Admin** package chating; //import java.applet.Applet; import java.awt.event.*; import java.awt.*; import Why PHP ? Why PHP? Reasons to use PHP are given below: 1. PHP is open source, free to download and use : PHP is free and you can download... other software etc. 2. PHP is cross platform PHP Based Chatserver - Design concepts & design patterns PHP Based Chatserver Hey i want to create a Chat server like this one : could someone plz tell me were can i get a chatserver php php what is php PHP Tutorials PHP beginning, Begin with the PHP programming language system with pre-installed php then you can also use the Linux machine for learning... The PHP beginning tutorials will first introduce you with the PHP programming language. After that we will show you how you can setup the PHP Check Date in PHP Check Date in PHP The Checkdate() The PHP Checkdate function is used for validating the system date. It validate the Gregorian date. It returns 'True... that denotes the year. Example <?php var_dump(checkdate(07,31,2009 PHP PHP Triad Tutorial PHP-Triad Tutorial  ... on the PHPTriad server. PHPTriad is a software package which installs PHP.../projects/phptriad/. To download the latest version visit the office website of the PHP Open Source content Management System Open Source content Management System The Open Source Content Management System OpenCms is a professional level Open Source Website Content Management System. OpenCms helps to create and manage complex websites easily without PHP PHP How to work in drupal with PHP php php show the constructor overloading in php Chat Server PHP Steps baby coding, lets check the developing environment of your system first. All the necessary software must be installed on your system including PHP5, MySQL... code. First of all, let’s see a snap shot of building blocks of PHP PHP Benefits - The benefits of PHP programming language. management system. In terms of advantage in running, PHP does not put strain...Benefits of PHP Whenever we think off to begin any website, we consider... will definitely zeroed on PHP, one of the most popular web development scripts PHP 5.0. Installation, Installing PHP ; But before installing, first lets us know about the system requirement, PHP installation... properly. System Requirements for PHP Install For properly running PHP... PHP and PHP itself compatible to the operating system. A different php php retrieve data from mysql in php Please visit the following links: php php plz tell me code for PHP SQL Insert,delete,update,view is used to insert the record from HTML page to Mysql database using in single PHP form PHP Cookies PHP Cookies Cookies are little packets of information that are stored locally on a computer system...;; } ?> Output: roseindia Example 2: <?php setCookie( Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/99599
CC-MAIN-2015-22
refinedweb
1,651
61.97
Example: When the user inputs 3, then in the next line, he must input only 3 numbers, too. If he exceeds or lacks, a message must prompt him. here's my code: import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class example { public static void main(String[] args) throws FileNotFoundException { File textFile = new File("newfile.txt"); try (Scanner scanner = new Scanner(textFile)) { while (scanner.hasNext()) { int firstNumber = scanner.nextInt(); int array[] = new int[firstNumber]; int compute = 1; for (int i = 0; i < array.length; i++) { array[i] = scanner.nextInt(); if (array[i] > 0) { compute *= array[i]; } } System.out.println("The maximum product is " + compute + "."); } } } } BTW, i'm using netbeans, and we are required to use textFile, that is to get user input in textFile. Please help. Thank you very much.
http://www.dreamincode.net/forums/topic/291597-how-to-limit-user-input/
CC-MAIN-2016-30
refinedweb
135
63.36
A Modular Approach to create APIs using Express.js and Node.js – Sandny Blog In this post, I would like to share a modular architecture for APIs created with express.js. The modular approach which discussed here is having a module which can perform each and every task relevant to the API. It has following features. - The functionality is well defined. - Modules are separated context wise and functionality wise. They are entities which can be treated individually which make them modular. - Every module poses similar behaviours. So each module has a similar footprint to invoke methods and provide service. If you find these kinds of features it would be appropriate to come up with a modular architecture. It would provide following advantages - All have the same footprint and therefore it would be easy to develop and introduce new features. - Can alter the underlying architecture once and provide the change to each module easily. - The module integration is easy and therefore it will save time when developing new features. But there are some cons too. - Since all the module footprints are the same, it would have a high coherence to the architecture itself. If you need a functionality that cannot be provided with the architecture, you will have to introduce it in a new definition. But if you come into a such a situation, I think there could be a solution as I didn’t find such a case when I was developing. - If you want to change some intermediate service or a middleware, it would affect all the modules. So be careful when coding the underlying architecture and look towards any unwanted repetitive function invocations. That being said let’s get our fingers working. Most of the APIs defined in express has following features, - A router with the paths and http request methods. - A schema which can validate request body before forwarding towards next middleware. - Handler functions to treat the request and generate a response. These features are well defined, modular and have similarities. So we can use this to create a module. A module would first be a folder containing module footprints. So our folder structure should contain modules. I’m going to show you a todo example in this post. -/ src -/ initializer/ -/ modules - / todo - / Handler.js - / Router.js - / Schema.js - / module2 - / module3 Each module contains three files to add defined functionalities. My application is a simple todo app and the idea is all the todo related functionalities are driven by this API. This contains GET_TODO, GET_ALL_TODOS, POST_TODO and DELETE_TODO http requests. I have named the key variables as event types which could happen in the todo app context. So I will define the path as follows in Router.js. export const API_EVENTS = { POST_TODO: 'POST_TODO', GET_TODO: 'GET_TODO', GET_ALL_TODOS: 'GET_ALL_TODOS', DELETE_TODO: 'DELETE_TODO', }; export const todoAPI = { [API_EVENTS.POST_TODO]: { method: 'POST', path: '/' }, [API_EVENTS.GET_TODO]: { method: 'GET', path: '/:id' }, [API_EVENTS.GET_ALL_TODOS]: { method: 'GET', path: '/' }, [API_EVENTS.DELETE_TODO]: { method: 'DELETE', path: '/:id' }, }; And I have a schema to validate the POST_TODO event. I have used Joi library to validate the http body attributes. Following would be the code in our Schema.js file. import Joi from 'joi'; const postTodo = Joi.object().keys({ todo: Joi.string().alphanum().min(3).max(30).required(), timestamp: Joi.number(), }); const schema = { POST_TODO: postTodo, } export default schema; Then someplace to handle the events requested from the router. I will have the handler to the API_EVENTS defined in the router. I have defined an array of todos so that I could store and delete the todos. import { API_EVENTS } from './Router'; let todos = []; export const handler = { [API_EVENTS.GET_ALL_TODOS]: (req, res, next) => { res.send(JSON.stringify(todos)); }, [API_EVENTS.POST_TODO]: (req, res, next) => { const { todo, timestamp } = req.body; todos.push({ todo, timestamp }) res.send('OK'); }, [API_EVENTS.GET_TODO]: (req, res, next) => { res.send(JSON.stringify(todos[req.params.id])); }, [API_EVENTS.DELETE_TODO]: (req, res, next) => { const deleteId = req.params.id; if (deleteId && todos[req.params.id]) { todos.splice(deleteId, 1); res.send('OK'); } else { res.send('BAD'); } }, }; export default handler; How is that? You have a full defined API with above code lines. And you can customize anything as well. Now, how did we do this? We haven’t imported fancy stuff to connect these code lines. That is what modular structure is all about. We should be able to keep what is necessary and do the connections somewhere else. I have created a package called initializer to initialize all the routes and add it into the express context. First one to go would be the app.js where all the app is created and all the others are combined. I have included the hello at the root path just to for you to do anything you want with it. import { connectRouters, express } from './initializer/framework'; import bodyParser from 'body-parser'; const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json({ type: 'application/json' })); connectRouters(app); app.get('/', function (req, res) { res.send('Hello from Todo API') }); app.listen(3000, function () { console.log('TODO API app listening on port 3000!') }); Afterwards, we need to construct this connectRouters method since it’s the place where we bind all the routers, handlers and schemas. Before going towards that, we will first try to aggregate the individual module functionalities. I have created three files called routers.js, schemas.js and handlers.js inside initializer package and I have used lodash to create the data structure I want. And a file called appModules.js so that I can define where my module is. // appModule.js export const modules = [ 'todo', ]; export default modules; import modules from './appModules'; import _ from 'lodash'; // routers.js export const routers = _(modules) .mapKeys(module => module) .mapValues((routerName) => { try { return require(`../modules/${routerName}/Router`).default; } catch (error) { console.log(error); throw 'Router names are not configured properly'; } }).value(); export default routers; import appModules from './appModules'; import _ from 'lodash'; // schemas.js export const schemas = _(appModules) .mapKeys(module => module) .mapValues((module) => { try { return require(`../modules/${module}/Schema`).default; } catch (error) { console.log(error); throw 'Schema names are not configured properly'; } }).value(); export default schemas; import appModules from './appModules'; import _ from 'lodash'; //handlers.js export const handlers = _(appModules) .mapKeys(module => module) .mapValues((module) => { try { return require(`../modules/${module}/Handler`).default; } catch (error) { console.log(error); throw 'Handler names are not configured properly'; } }).value(); export default handlers; We can see some repetition here but its better if you can keep this files separately as in future you will need to complicate these files in a different way to support the features you need. Then you will need to create the framework.js file to combine these three files. I have included the whole file I coded. And please do note that this is not complete and you will need to add more beauty to the code if you intend to use this. import express from 'express'; import Joi from 'joi'; import _ from 'lodash'; import modules from './appModules'; import schemas from './schemas'; import handlers from './handlers'; import routers from './routers'; const createRouter = () => (routingContext) => { const router = express.Router(); }; const validatorMiddleware = (schema) => (req, res, next) => { if (_.isNull(schema)) { console.log('The schema is null') next(); } else { const result = Joi.validate(req.body, schema); console.log('Req Body: ', req.body); result.error === null ? next() : res.status(422).json({ errors: result.error}); console.log(result.error); } }; const getRouterPath = (moduleName) => `/${moduleName}`; const defaulHandler = (req, res) => { res.status(404).json({ errors: ' Not Implemented'}); }; const connectRouters = (app) => { console.log('connecting Routers', JSON.stringify(routers)); _.forEach(modules, (moduleName) => { const router = express.Router(); const moduleSchema = schemas[moduleName]; const moduleHandler = handlers[moduleName]; console.log(JSON.stringify(handlers)); _.forEach(routers[moduleName], (api, apiKey ) => { const { path, method } = api; const schema = _.isNil(moduleSchema[apiKey]) ? null : moduleSchema[apiKey]; const handler = _.isNil(moduleHandler[apiKey]) ? defaulHandler : moduleHandler[apiKey]; // connection router[_.lowerCase(method)](path, validatorMiddleware(schema), handler); }); app.use(getRouterPath(moduleName), router); }); }; export { _, createRouter, express, validatorMiddleware, connectRouters, } In the connectRouters function, the modules are iterated and all the handlers, routers and schemas are connected. You can include more middlewares when you are making the connection with the router. And there are simpler ways to code this and you will have to define how to use it. And also this was coded in the way I described in the post and you could try it too. I don’t like the data structure I created for storing the modules. If you could make it flatter and 1 level deep that would be awesome. But it is a one-time initialization and there is no harm in it. The github repo for this tutorial is in Dont forget to add your feedback on this coz I want to know what could go wrong with this.
http://brianyang.com/a-modular-approach-to-create-apis-using-express-js-and-node-js-sandny-blog/
CC-MAIN-2018-43
refinedweb
1,449
53.27
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Hellow, I'm currently seeking for a neat way to add an overlay to my camera that will show me a SplitScreen version of my 16:9 camera-layout... and in the end also an option for a 1:1 version. My current code looks like the following: import c4d def draw(bd): # Various exit conditions. if (not isinstance(bd, c4d.BaseDraw) or bd.GetDrawPass() != c4d.DRAWPASS_OBJECT): return False #works only on active Camera obj = op.GetMain() scene_cam = bd.GetSceneCamera(doc) if obj != scene_cam: return False res = bd.GetFrame() x, y = res['cr'], res['cb'] # print(x, y) bd.SetPen(c4d.Vector(1,0,0)) for i in range(x/2): p1 = c4d.Vector(i,0,0) p2 = c4d.Vector(i,y,0) bd.DrawLine2D(p1, p2) def main(): pass Here's my scene-file: bddraw_safe-frame.c4d However, my questions are: BaseDraw.DrawTexture Safe Frames Thanks, Lasse Hi @lasselauch, regarding your first question, you can set the transparency of the following drawing operations with BaseDraw.SetTransparency. So you could just add bd.SetTransparency(-125) to your script for example to draw everything with an alpha of 50%. For your second question about drawing on top of the safe frame indicators (I assume that was what you meant with drawing "above" them), there is no direct answer, since there is no draw pass which lets you draw on such a high level. But you can of course just turn of the built in safe frame indicators and draw your own. Below you will find a script and a scene file which deal with both your questions and go a bit more into the details. If possible, you should use the file, since the script does rely on some user data. BaseDraw.SetTransparency bd.SetTransparency(-125) Cheers, Ferdinand draw_camera_info.c4d """ Explores the overlay and safe frame questions as discussed in Draws a semi-transparent overlay with BaseDraw.DrawPolygon() and optionally replaces the indicator bars for the safe frame area. """ import c4d def draw(bd): """Draws restriction indicators into a viewport. """ # Get out when we are not in the object draw pass or when this tag is not # sitting on the currently active camera in the document. You could also # draw in other draw passes, depending on what you want to do with this # script. node = op.GetObject() if (not isinstance(bd, c4d.BaseDraw) or bd.GetDrawPass() != c4d.DRAWPASS_OBJECT or node != bd.GetSceneCamera(doc)): return # Set the drawing coordinate system to screen space. bd.SetMatrix_Screen() # The frame and safe-frame of the viewport. frame, safe_frame = bd.GetFrame(), bd.GetSafeFrame() # Variable for up to where the overlay should reach. ratio = .5 # Set the transparency for the following drawing operations. See docs # for details on BaseDraw.SetTransparency(). transparency = int(op[c4d.ID_USERDATA, 1] * 255) bd.SetTransparency(-transparency) # Draws the main overlay. We could also use lines like you did, but # just drawing a single polygon seems to be much more straight forward. points = [c4d.Vector(frame["cl"], frame["ct"], 0), c4d.Vector(frame["cr"] * ratio, frame["ct"], 0), c4d.Vector(frame["cr"] * ratio, frame["cb"], 0), c4d.Vector(frame["cl"], frame["cb"], 0)] colors = [op[c4d.ID_USERDATA, 2]] * 4 bd.DrawPolygon(points, colors) # We cannot draw on top of Cinema's safe frame indicators, but we can # turn them off and draw our own. This comes with the disadvantage that # the tag might leave a viewport with disabled safe frame overlays when # the tag is deleted or moved. # Which could be mitigated using messages, but should be done in a full # blown TagData plugin or otherwise we would have to jump through quite # a few hoops here. # User says we should use Cinema's default safe frame indicators. if op[c4d.ID_USERDATA, 3] == False: bd[c4d.BASEDRAW_DATA_SHOWSAFEFRAME] = True # User says we should use the custom safe frame indicators. elif op[c4d.ID_USERDATA, 3] == True: bd[c4d.BASEDRAW_DATA_SHOWSAFEFRAME] = False # Based on the transparency of the default safe frame indicator of # the viewport. transparency = bd[c4d.BASEDRAW_DATA_TINTBORDER_OPACITY] * 255 # Otherwise the colors won't quite match up. transparency = min(int(transparency * 1.5), 255) bd.SetTransparency(-transparency) # First we have to figure out on which axis the viewport frame # differs from the render frame (a.k.a "safe frame"). The testing # could of course also be done on the vertical axis. frame_height = frame["cb"] - frame["ct"] safe_frame_height = safe_frame["cb"] - safe_frame["ct"] is_horizontal = frame_height > safe_frame_height # Since we draw with transparencies, we cannot just draw our overlay # area on top of the custom safe frame indicators, but have instead # to draw the safe frame indicators only there where we want them to # appear. E.g. in the horizontal case, we just draw "half a bar" # from the mid point. # We have to draw indicators on the top and bottom. if is_horizontal: mid_point = (frame["cr"] - frame["cl"]) * ratio top_bar = [c4d.Vector(mid_point, frame["ct"], 0), c4d.Vector(frame["cr"], frame["ct"], 0), c4d.Vector(frame["cr"], safe_frame["ct"], 0), c4d.Vector(mid_point, safe_frame["ct"], 0)] bottom_bar = [c4d.Vector(mid_point, frame["cb"], 0), c4d.Vector(frame["cr"], frame["cb"], 0), c4d.Vector(frame["cr"], safe_frame["cb"], 0), c4d.Vector(mid_point, safe_frame["cb"], 0)] polygons = [top_bar, bottom_bar] # We have to draw one indicator on the right (left one is covered). else: right_bar = [c4d.Vector(safe_frame["cr"], frame["ct"], 0), c4d.Vector(frame["cr"], frame["ct"], 0), c4d.Vector(frame["cr"], frame["cb"], 0), c4d.Vector(safe_frame["cr"], frame["cb"], 0)] polygons = [right_bar] # Based on the color of the default safe frame indicator of # the viewport. colors = [bd[c4d.BASEDRAW_DATA_TINTBORDER_COLOR]] * 4 for p in polygons: bd.DrawPolygon(p, colors) def main(): pass thanks for reaching out to us. We have seen and discussed your problem and I will tackle it on Monday. Have a nice weekend. Thanks for the reply, @zipit. Looking forward to it... In the meantime I created another little preset when working with takes, where I have the same problem when drawing ABOVE safe frames. Thanks for looking into this. Cheers, Lasse Hi, without further feedback, we will consider this thread as solved by tomorrow and flag it accordingly.
https://plugincafe.maxon.net/topic/12990/basedraw-drawline2d-transparency/1
CC-MAIN-2022-27
refinedweb
1,052
61.12
I introduced the concept of offline sync and discussed some of the key concepts and terminology of offline sync in my last article. However, implementation was a little lacking. I’m going to fix that today. Today, I’m going to adjust my Universal Windows Task List to use Offline Sync. You can get the starting point for this application here. You will note that I have both a backend and a frontend in the repository – they go together. You will need to configure an AAD web application to use them – you can find the instructions in an earlier post – and adjust the Client.UWP project for your backend. Once done, you should be able to deploy the backend and use the Client.UWP project to connect to your backend. Make sure you can do this before continuing. If you have problems, here are some of the blog posts you should cover again to see what is going on: Preparing the Project Azure Mobile Apps uses SQLite to store data on the client device. In order to enable Offline Sync, I need to add SQLite to my Visual Studio installation, then add the appropriate libraries to the project. The SQLite libraries themselves are available through Tools > Extensions and Updates. Just search for SQLite online: I an doing a UWP app, so SQLite for Universal Windows Platform is appropriate. I had to restart Visual Studio after installing the extension. Once that is done, I can go on to the project itself. Right-click on the Client.UWP project and select Manage NuGet Packages…, click on Browse and then enter “Azure Mobile” in the search box: Add the Microsoft.Azure.Mobile.Client.SQLiteStore v2.0.1 or later to your project. Note that the version should match the version of the Microsoft.Azure.Mobile.Client you are using. They are released in tandem, so update or install them together. Finally, add a reference to SQLite into your project. This is done by right-clicking on the References… node and selecting Add Reference…. Expand the Universal Windows node and click on Extensions. SQLite for Universal Windows Platform will be in the list: Check the box next to SQLite for Universal Windows Platform and then click on OK. Initialize the Offline Sync Store There is a SQLite store on the client device. You need to set it up. My code is in Services/AzureCloudProvider.cs and here is how I did it: /// <summary> /// Initialize the Offline Sync Store /// </summary> /// <returns>async task</returns> public async Task InitializeOfflineSync() { var store = new MobileServiceSQLiteStore("localstore.db"); store.DefineTable<TodoItem>(); syncTables.Add(typeof(TodoItem).Name); await client.SyncContext.InitializeAsync(store); } You can call your store whatever you want. It’s a local database store and there is one per app. You define the tables you want to have offline sync, and then you run the database initialization code. If the store is not defined, it will create the tables for you. If you have more than one table that you need to be offline-enabled then just add more DefineTable calls. I put this into an extra method in the AzureCloudProvider class so that I can await on it. It’s important to note here that not every table needs to be offline-enabled. Let’s say you have a table that is changed frequently, but referenced infrequently. You may consider that the overhead of maintaining the offline sync store – most notably storage, but also network bandwidth – isn’t worth it. You may just want a table that you can query for values as needed. The process I’m layout out here puts you in control – you get to decide (as the developer) which tables are available for offline sync and which ones you have to be online to access. I add my sync tables as they are set up to a list that can be queried by my table provider. Where you add the local offline sync cache initialization is up to you. I like to put it in the OnLaunched method of the App.xaml.cs file: protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } Window.Current.Content = rootFrame; } // Initialize offline-sync and wait for it to complete Debug.WriteLine($"[App.xaml.cs#OnLaunched] Initializing offline sync"); AzureCloudProvider.Instance.InitializeOfflineSync(); Debug.WriteLine($"[App.xaml.cs#OnLaunched] Finished initializing offline sync"); if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { rootFrame.Navigate(typeof(EntryPage), e.Arguments); } Window.Current.Activate(); } } However, there are other places to put it. You should definitely call it well in advance of creating a connection to the table as there is an initialization process and it takes time. Let’s stop there for a moment and take a look at the SyncContext in the debugger: Note that there is an IsInitialized property on the SyncContext that shows if the SQLite store is properly initialized. Ideally, I’d use that to ensure that initialization is done prior to creating a sync table. Talking of which, let’s take a look at the AzureDataTable class to show off how to create a sync table: public class AzureDataTable<T> where T: EntityData { private AzureCloudProvider provider; private bool isSyncTable = false; private IMobileServiceSyncTable<T> syncTable; private IMobileServiceTable<T> dataTable; private ObservableCollection<T> dataView; public AzureDataTable(AzureCloudProvider provider) { this.provider = provider; this.isSyncTable = provider.IsSyncTable(typeof(T).Name); if (isSyncTable) { this.syncTable = provider.Client.GetSyncTable<T>(); } else { this.dataTable = provider.Client.GetTable<T>(); } } Probably not the most efficient code. I have one variable for a sync table and the other for a regular table. The point is that I can use the same basic class for both offline sync and online tables with the same API. Taking a look at my new RefreshAsync() method: public async Task<ObservableCollection<T>> RefreshAsync(bool syncItems = true) { Debug.WriteLine($"[AzureDataTable$RefreshAsync] Entry"); try { if (syncItems && isSyncTable) { Debug.WriteLine($"[AzureDataTable$RefreshAsync] Updating Offline Sync Cache"); await this.SyncOfflineCacheAsync(); } Debug.WriteLine($"[AzureDataTable$RefreshAsync] Requesting Items"); if (isSyncTable) { List<T> items = await syncTable.OrderBy(item => item.UpdatedAt).ToListAsync(); dataView = new ObservableCollection<T>(items); } else { List<T> items = await dataTable.OrderBy(item => item.UpdatedAt).ToListAsync(); dataView = new ObservableCollection<T>(items); } Debug.WriteLine($"[AzureDataTable$RefreshAsync] {dataView.Count} items available"); return dataView; } catch (MobileServiceInvalidOperationException exception) { throw new CloudTableOperationFailed(exception.Message, exception); } } The only addition here is the fact that I want to synchronize the offline cache if I am synchronizing. I’ve made this optional and I’ll bind that to the “network is available” indicator. Let’s take a look at the SaveAsync() and DeleteAsync() methods: public async Task SaveAsync(T item) { try { if (item.Id == null) { if (isSyncTable) await syncTable.InsertAsync(item); else await dataTable.InsertAsync(item); dataView.Add(item); } else { if (isSyncTable) await syncTable.UpdateAsync(item); else await dataTable.UpdateAsync(item); dataView.Remove(item); dataView.Add(item); } } catch (MobileServiceInvalidOperationException exception) { throw new CloudTableOperationFailed(exception.Message, exception); } } public async Task DeleteAsync(T item) { try { if (isSyncTable) await syncTable.DeleteAsync(item); else await dataTable.DeleteAsync(item); dataView.Remove(item); } catch (MobileServiceInvalidOperationException exception) { throw new CloudTableOperationFailed(exception.Message, exception); } } Note that the only difference between the offline-sync version and the online version is the type of table I am using. The actual API is identical. Now, back to the RefreshAsync() method. I introduced a new method call there – SyncOfflineCacheAsync(). This method does the synchronization between the cloud and the offline sync store. From my prior post, I have to do a Push and then a Pull, handling conflicts during the Push section. The Client SDK does the rest. Here is the code: public async Task SyncOfflineCacheAsync() { string queryName = $"incremental_sync_{typeof(T).Name}"; try { await provider.Client.SyncContext.PushAsync(); await syncTable.PullAsync(queryName, syncTable.CreateQuery()); } catch (MobileServicePushFailedException exception) { if (exception.PushResult != null) { foreach (var error in exception.PushResult.Errors) { await ResolveConflictAsync(error); } } } } private async Task ResolveConflictAsync(MobileServiceTableOperationError error) { Debug.WriteLine($"Resolve Conflict for Item: {error.Item}"); var serverItem = error.Result.ToObject<T>(); var localItem = error.Item.ToObject<T>(); if (serverItem.Equals(localItem)) { // Items are the same, so ignore the conflict await error.CancelAndDiscardItemAsync(); } else { // Always take the client localItem.Version = serverItem.Version; await error.UpdateOperationAsync(JObject.FromObject(localItem)); } } In this case, I’m doing an implicit conflict resolution. I’m always accepting that the local item is correct and overwriting the server item. You could just as easily put a UI here that allows the end-user to select which one to use. You could also see which UpdateAt field is later and take that. There are lots of options for conflict resolution. Next Steps Offline Sync is available across all the Client SDKs, so if you have an iOS Native or Android Native mobile client, you’ll be able to take the same concepts. In the next post, I’m going to switch my attention back to the backend and look at the ASP.NET backend – why would you use it and why would you not use it. In the mean time, find the code for the server and client on my GitHub Repository. One thought on “30 Days of Zumo.v2 (Azure Mobile Apps): Day 16 – Offline Sync .NET Edition” […] 30 Days of Zumo.v2 (Azure Mobile Apps): Day 16 – Offline Sync .NET Edition (Adrian Hall) […]
https://shellmonger.com/2016/05/04/30-days-of-zumo-v2-azure-mobile-apps-day-16-offline-sync-net-edition/
CC-MAIN-2017-13
refinedweb
1,572
51.14
On Wed, 20 Nov 2002 07:11 pm, Jeff Varszegi wrote: > Is work being done on VFS right now? Yes. A little slowly, perhaps, but it is happening. > Can I help? Yes, definitely. Did you have anything particular in mind? Otherwise, If you're looking for things to do, there's a bunch of stuff in the todo list (in cvs - haven't updated the web site yet). Either way, patches are most > It seems like something > I could really sink my teeth into. Are there plans to do nice stuff like > support agglomerated file systems, so that we can support federated > namespaces? Absolutely. Have a look at the todo list. > Has VFS already been superseded by something else? Don't think so. Even if it were, a little competition never hurt. > I did poke > around a lot to find this out, but I am still not sure. > > Jeff > > P.S. I was wondering why a putFile(FileObject file) appears in the > AbstractFileSystem class, but not in the interface FileSystem. I noticed > some other stuff too. Because clients of FileSystem never need to 'put' files; The file system is responsible for creating FileObject instances, so clients only ever 'get' files. AbstractFileSystem maintains a cache of FileObjects, and the putFile() method is there for subclasses to add files to that cache. -- Adam -- To unsubscribe, e-mail: <mailto:commons-dev-unsubscribe@jakarta.apache.org> For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>
http://mail-archives.apache.org/mod_mbox/commons-dev/200211.mbox/%3C200211201950.19960.adammurdoch@apache.org%3E
CC-MAIN-2016-50
refinedweb
244
67.35
How to Play a Video in windows Application and web application Today i want to present a topic regarding about playing video files in your Windows Application and as well as Web Application.This topic covers how to add a reference Media player dll to your project,what are the propeties that we can set to the windows Media player Control in Windows Application.How to stop the video in Windows Media player.How to embed the source of Object in your webpage These are the topics i will describe in this article with snippet of code lines. Windows Application does n't have a general windows media player control (available in tool box) to play a video.So we have to add a reference from COM Component tab.You can add the reference from the Project and go to com component tab add the windows media player compnent from there. 1)Right-click within the Toolbox, and then select Choose Items. This opens the Customize Toolbox dialog box. 2)In the COM Components tab, select Windows Media Player. If Windows Media Player does not appear in the list, click Browse, and then open Wmp.dll, which should be in the Windows\System32 folder. 3)Click OK. The Windows Media Player control will be placed on the current Toolbox tab. After adding the control in the form you can set the Visible,size.hieght,size.width Add the Video Window after adding the reference than you have to import the namespace in your code using WMPLib; AxWindowsMediaPlayer AxWindowsMediaPlayer1; AxWindowsMediaPlayer1.URL = "c:\hi.wmv" To stop the Player axWindowsMediaPlayer1.Ctlcontrols.stop(); You can get Current Play List WMPLib.IWMPPlaylist firstPlaylist = player.playlistCollection.getAll().Item(0); // Make the retrieved playlist the current playlist. player.currentPlaylist = firstPlaylist; if (player.playState == WMPLib.WMPPlayState.wmppsPlaying) { player.fullScreen = true; } you can close the Windows media player player.close(); In webApplication or webpage You can embed the Windows Media Player ActiveX control in a webpage using the following four steps They start with begin tag and ends with end tag OBJECT ID="Player" height="0" width="0" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" end of the object tag /OBJECT You can set the property url as one of the attribute in the tag.The URL path define the path of Media file. OBJECT OBJECT In the Code You can define... Player.URL = "Hi.wmv"; Player.controls.stop();
http://www.dotnetspider.com/resources/44825-How-Play-Video-windows-Application-web-application.aspx
CC-MAIN-2018-47
refinedweb
401
56.45
XForms is gaining momentum rapidly, with support available for common browsers using extensions or plugins, and through things like the IBM® Workplace Forms technology (see the Resources section to find out more).. This article explains the evolution of forms from simple text searches to today's interactive masterpieces and explains the next step in Web forms, XForms. It explains what makes XForms different and gets the user ready for Part 2 by setting up his or her environment. Read on to see how a simple HTML form can be replaced with a simple XForms form, and how you can use XForms' capabilities to save (and reload later) a form's data to a local file. If you'd like to follow along with the XHTML and XForms documents discussed in this article, grab the archive linked in the Downloads section. It contains the files you're going to look at, which you can use as a starting point for your own XForms experimentation. You'll also be installing an XForms extension that lets you view XForms documents directly in current versions of Firefox, Internet Explorer, Seamonkey, or Mozilla. If you don't currently have one of these excellent, standards-compliant browsers installed, now's a good time to get one. Before jumping into XForms, let's get a little historical perspective on forms. Early in the history of the World Wide Web, simple text entry forms were used to send requests to CGI programs that ran on the server, bringing some additional interactivity to those pioneers venturing out into the unknown. As the Web matured, the data entry forms presented by Web sites grew more complex. These days, you can easily find extremely complex forms, especially on e-commerce sites or forums. These can be front ends to PHP or Java™ code running on the server, or JavaScript running in the browser, sending its results to the server using the Ajax techniques. Unfortunately, HTML's forms are created from elements that intermingle presentation and content. With the move from sloppy presentation-based HTML mixing the document structure with formatting elements, to clean XHTML styled with CSS, you need a way of separating a form's data and behavior from its presentation.. Let's take a look at a simple HTML form that submits a search string to an imaginary query engine running on your local machine (see Listing 1). Note that this is actually XHTML rather than HTML 4.01; XForms requires valid XML documents (such as XHTML) and you'll be seeing an XForms version shortly. Also note that you may need to tweak your URLs to get them to work properly in your own environment. Listing 1. A simple HTML form (simple.xhtml) Listing 1 is standard, 100% valid XHTML Strict for your viewing pleasure. The <form> section has been highlighted in bold. When rendered in a typical current Web browser, this XHTML looks quite familiar, if a bit primitive (Figure 1). Figure 1. A simple HTML form rendered by Firefox When you enter some text in the field shown in Figure 1 and click the button, the data is encoded into the URL sent to the imaginary search engine:. Listing 2 shows you the XForms version, with the differences highlighted. Listing 2. A simple XForms form There are three main changed areas here: - The " xf:" namespace adds the elements from the XForms specification. - An <xf:model>element has been added to the <head>, which declares an <xf:submission>. This binds the action (your imaginary search engine) to the get method and names it submit-search for later use. - The form's presentation elements ( <xf:input>for the text input field, and <xf:submit>for the submission button) are now just presentation elements, indicating where and how the form's fields should appear in the rendered page. They refer back to the model declared in the <xf:model>element. And here's how the XForms version looks (see Figure 2). Installation of the XForms extension for Firefox is covered later. Figure 2. A simple XForms form rendered in Firefox The forms look exactly the same! You lose absolutely nothing by using XForms instead of traditional HTML forms, and you've gained all the advantages of using an XML data model. Setting up to view XForms If you've downloaded the example archive (found in the Downloads section), you might have noticed that your browser won't display the XForms version properly (see Figure 3). Figure 3. Your simple XForms page on a browser without XForms support Until your favorite Web browser offers built-in support for XForms, you'll have to use one of the XForms implementations (see the XForms Web site listed in Resources). Let's take a quick look at installing one of the most convenient implementations, the Mozilla extension. Since this works with current versions of Mozilla, Firefox, and Seamonkey, you probably won't even have to install or switch browsers! You'll also look at installing the Internet Explorer 6 plugin. Adding the XForms extension to Firefox In Firefox, pull up the Mozilla XForms Project page (see Resources). Click the download page link you'll find under the Latest Release heading. The downloads page for the XForms Project will warn you about the plugin not being ready for end-users, and then give you a link to the actual download page. Click that, then click the Install Now link. Figure 4. Firefox's standard warning about installing extensions Firefox displays a warning dialog (see Figure 4); click the Install Now button to download and install the XForms extension. Restart Firefox to activate it (see Figure 5). Figure 5. Restart to activate your new extensions After restarting your browser, you can load the simple XForms example that was looked at earlier; this time you'll actually see the XForms elements rendered properly! Adding the XForms plugin to Internet Explorer 6 On the formsPlayer Web page (see Resources for a link), click the Download fP for free link to access the registration page. Enter your e-mail address and other data, then click the Install formsPlayer link to download and install the plugin. When IE loads the plugin archive, it will display a warning under the URL about the ActiveX control. Click this warning, then select Install ActiveX Control. IE will download and install formsPlayer. When IE's Security warning pops up, click Install to go ahead with the installation. Once formsPlayer is installed, you'll be redirected to a page with links to several examples. View any of them to verify your installation. One form, several presentations Because the data model and presentation are separated in an XForms document, the user's browser can render the form's elements using whatever makes the most sense and provides the most usability. For example, if the user is asked to select one item from a list, a Web browser might present the list as a standard radio button group. In your cell phone's browser, this same list could be rendered as a pop-up menu, which would be easier to navigate using the phone's direction wheel. This doesn't require any special CSS or even JavaScript to detect the user's browser (an error-prone mistake many Web sites make), it's handled automatically by the browser's XForms implementation. Adapting like this is difficult with plain HTML forms because the data and presentation are mixed together too tightly. Because the XForms model is XML, you can also use technologies like XSLT or JavaScript (through the DOM) to present that model using any interface you'd like, from plain HTML or XHTML for users without XForms support, to proprietary GUIs. Tight integration with XML XForms documents must be valid XML (such as XHTML), and instances of the data model (used to provide default values, among other things; you'll see these in action in a later article in this series) are XML documents. You can even load data model instances from external XML files loaded on the user's machine or the server. This tight integration with XML makes it easy to integrate your XForms data with other technologies that support XML input and output, such as databases, without the need for additional scripting between the database and the form being presented to the user. Save forms offline and submit them later One of the interesting features that XForms brings to your browser is the ability to save a form's contents (any data in the fields, plus any "hidden" data stored in the data model) to a file. By providing additional <xf:submission> elements with a put method, you can store this data as an XML file in your local filesystem or on the server. You can then load it again later to continue where you left off, all without having to use additional scripting or database access. This also shows you another of the XForms advantages; you can have any number of submission actions associated with a single form (see Listing 3). In HTML, you can only have one action per form. Listing 3. Adding some data saving and loading to the form Again, the changes from your previous XForms experiment have been highlighted in bold. Let's take a more detailed look at the changes. First of all, you've added a data model instance (inside the <xf:instance> element). This contains a root for the data (the aptly-named <data> element; note that the empty xmlns attribute is a requirement here), which in turn contains the data you need for your form, the <query> you reference down in the form's <xf:input> element. The data found in this <query> element is the default query string, and will be displayed in the <xf:input> element when it gets rendered. Next, there's an <xf:bind> element, which makes the <query> data required; if the <query> is empty, none of the <xf:submit> buttons will do anything. Last, you've added two new <xf:submission> actions to the <xf:model> that let you save your data to a file (via the put method) and load it from a file without reloading the entire page (using the get method; the replace="instance" attribute reloads the data model instance only). At the bottom of the page two more <xf:submit> elements have been added so you can save and load the data. Figure 6 shows you what this now looks like in Firefox. Note how the Find field is filled in from the default that you've included in the data model instance and the new Save and Load buttons. Figure 6. The new and improved form If you click the Save button at this point, you'll get a file named XFormsQuery.xml in your /tmp directory containing the data model instance (see Listing 4). To test the Loading functionality, change the Find string, and then click Load; your Find string will be replaced with the original one, loaded from the XFormsQuery.xml file in /tmp. Listing 4. The saved data model instance There are some options for controlling the output, but you haven't used any of them here. In any case, the Save and Load functions are working, without any sort of scripting. The XForms standard adds a powerful new abstraction between a form's data model and its presentation, as well as providing the ability to use a single form with several different submission actions. XForms elements can also validate data and the tight integration with XML lets you work directly with data from any other XML-aware application. Saving a form's data for use later is also easy with XForms. Stay tuned for Part 2 to learn how to create a basic XForms model and form. Information about download methods Learn - Visit the XForms home at W3C. - XForms.org: The Nexus for Intelligent Web Apps contains a treasure-trove of information and links on XForms. - Read Part 2 in this series, Introduction to XForms. - Read Part 3 in this series, Introduction to XForms. - Read about Web Forms 2.0, a similar but competing spec. - Get ready for XForms (devleoperWorks, Septebmer 2002) provides a useful overview of this important technology. - Read John Boyer's blog on XForms, Web Forms 2.0 and the future of XML content on the web. - SVG and XForms, a Primer (developerWorks, November 2003) provides an overview of the two technologies and highlights the potential synergies between them. - Read XForms Essentials by Micah Dubinko from O'Reilly Media. - For a good starting point for XForms research, read Ten Favorite XForms Engines from XML.com. - For an interactive, cross-platform tutorial on W3C XForms, visit the XForms institute. - Get a historical perspective on the origins and purpose of XForms in this brief history of SGML. - To get a good grounding in XML, read the Introduction to XML tutorial (developerWorks, August 2002). - Learn all about XML at the developerWorks XML zone. Get products and technologies - Get the XForms extension for Mozilla, Firefox, or Seamonkey. - Get the XForms plugin for Internet Explorer 6. - Get the Trial: Lotus Forms (formerly Workplace Forms product). Discuss >>IMAGE.
http://www.ibm.com/developerworks/xml/library/x-xformsintro1/
crawl-002
refinedweb
2,196
59.94
Hi,. The default is to show the clock in 24-hour format. This cannot be changed using the built-in commands. However, you could create a TCL EEM policy (provided your device supports EEM) which could capture the "show clock" command and display the time format however you want. For example, create a directory, flash:/policies to hold your EEM scripts. Then copy a policy script into that directory. The script, clock_pol.tcl would look like: ::cisco::eem::event_register_cli pattern "show clock" sync yes occurs 1 namespace import ::cisco::eem::* namespace import ::cisco::lib::* set date [clock format [clock seconds] -format {%I:%M:%S %p %Z %a %b %d %Y}] puts $date exit 0 Then, configure it: event manager directory user policy "flash:/policies" event manager policy clock_pol.tcl type user Then every time you run "show clock" you will get something like: 07:45:01 PM EST Sat Dec 01 2007 As for formats and NTP, NTP doesn't worry about how the time is displayed. Time is synced using the number of seconds since the beginning of the epoch. This value is in UTC, and is the same regardless of timezone or time display format. Stated another way, if your NTP server displays its time in 12-hour format, a host can sync to that server, and display its time in 24-hour format (and vice versa). Hi, Thank you for your response. Another questions: does the same apply for computers? In other words, I would like to synchronize my callmanger servers using my core L3 switch. This switch displays the time in the 24 hour format but the server uses the 12 hour format. Can this be done? Thanks again. Yes, this can be done. Displaying the time has nothing to do with how NTP sends updates. The NTP updates will ALWAYS be in UTC.
https://community.cisco.com/t5/network-management/ios-catalyst-time-format/td-p/919086
CC-MAIN-2020-10
refinedweb
308
72.87
Most profiling tools provide a profile of method calls, showing where the bottlenecks in your code are and helping you decide where to target your efforts. By showing which methods and lines take the most time, a good profiling tool can quickly pinpoint bottlenecks. Most method profilers work by sampling the call stack at regular intervals and recording the methods on the stack.[7] This regular snapshot identifies the method currently being executed (the method at the top of the stack) and all the methods below, to the program's entry point. By accumulating the number of hits on each method, the resulting profile usually identifies where the program is spending most of its time. This profiling technique assumes that the sampled methods are representative, i.e., if 10% of stacks sampled show method foo( ) at the top of the stack, then the assumption is that method foo( ) takes 10% of the running time. However, this is a sampling technique , so it is not foolproof: methods can be missed altogether or have their weighting misrecorded if some of their execution calls are missed. But usually only the shortest tests are skewed. Any reasonably long test (i.e., seconds rather than milliseconds) normally gives correct results. [7] A variety of profiling metrics, including the way different metrics can be used, are reported in "A unifying approach to performance analysis in the Java environment" by Alexander, Berry, Levine, and Urquhart, IBM Systems Journal, Vol. 39, No. 1,. Specifically, see Table 2-1 in this paper. The JDK comes with a minimal profiler, obtained by running a program using the java executable with the -Xrunhprof option (-prof before JDK 1.2, -Xprof with HotSpot). This option produces a profile data file called java.hprof.txt (java.prof before 1.2). The filename can be specified by using the modified option -Xrunhprof: file=<filename> (-prof:<filename> before 1.2). When using a method profiler, the most useful technique is to target the top five to ten methods and choose the quickest to fix. The reason for this is that once you make one change, the profile tends to be different the next time, sometimes markedly so. This way, you can get the quickest speedup for a given effort. However, it is also important to consider what you are changing so you know what your results are. If you select a method that is taking 10% of the execution time and then halve the time that method takes, you speed up your application by 5%. On the other hand, targeting a method that takes up only 1% of execution time gives you a maximum of only 1% speedup to the application, no matter how much effort you put in. Similarly, if you have a method that takes 10% of the time but is called a huge number of times, with each individual method call being quite short, you are less likely to speed up the method. On the other hand, if you can eliminate some significant fraction of the calling methods (the methods that call the method that takes 10% of the time), you might gain speed that way. Let's look at the profile output from a short program that repeatedly converts some numbers to strings and inserts them into a hash table: package tuning.profile; import java.util.*; public class ProfileTest { public static void main(String[ ] args) { //Repeat the loop this many times int repeat = 2000; //Two arrays of numbers, eight doubles and ten longs double[ ] ds = {Double.MAX_VALUE, -3.14e-200D, Double.NEGATIVE_INFINITY, 567.89023D, 123e199D, -0.000456D, -1.234D, 1e55D}; long[ ] ls = {2283911683699007717L, -8007630872066909262L, 4536503365853551745L, 548519563869L, 45L, Long.MAX_VALUE, 1L, -9999L, 7661314123L, 0L}; //Initializations long time; StringBuffer s = new StringBuffer( ); Hashtable h = new Hashtable( ); System.out.println("Starting test"); time = System.currentTimeMillis( ); //Repeatedly add all the numbers to a stringbuffer //and also put them into a hash table for (int i = repeat; i > 0; i--) { s.setLength(0); for (int j = ds.length-1; j >= 0; j--) { s.append(ds[j]); h.put(new Double(ds[j]), Boolean.TRUE); } for (int j = ls.length-1; j >= 0; j--) { s.append(ls[j]); h.put(new Long(ls[j]), Boolean.FALSE); } } time = System.currentTimeMillis( ) - time; System.out.println(" The test took " + time + " milliseconds"); } } The relevant output from running this program with the JDK 1.2 method profiling option follows. (See Section 2.3.2 later in this chapter for a detailed explanation of the 1.2 profiling option and its output.) CPU SAMPLES BEGIN (total = 15813) Wed Jan 12 11:26:47 2000 rank self accum count trace method 1 54.79% 54.79% 8664 204 java/lang/FloatingDecimal.dtoa 2 11.67% 66.46% 1846 215 java/lang/Double.equals 3 10.18% 76.64% 1609 214 java/lang/FloatingDecimal.dtoa 4 3.10% 79.74% 490 151 java/lang/FloatingDecimal.dtoa 5 2.90% 82.63% 458 150 java/lang/FloatingDecimal.<init> 6 2.11% 84.74% 333 213 java/lang/FloatingDecimal.<init> 7 1.23% 85.97% 194 216 java/lang/Double.doubleToLongBits 8 0.97% 86.94% 154 134 sun/io/CharToByteConverter.convertAny 9 0.94% 87.88% 148 218 java/lang/FloatingDecimal.<init> 10 0.82% 88.69% 129 198 java/lang/Double.toString 11 0.78% 89.47% 123 200 java/lang/Double.hashCode 12 0.70% 90.17% 110 221 java/lang/FloatingDecimal.dtoa 13 0.66% 90.83% 105 155 java/lang/FloatingDecimal.multPow52 14 0.62% 91.45% 98 220 java/lang/Double.equals 15 0.52% 91.97% 83 157 java/lang/FloatingDecimal.big5pow 16 0.46% 92.44% 73 158 java/lang/FloatingDecimal.constructPow52 17 0.46% 92.89% 72 133 java/io/OutputStreamWriter.write In this example, I extracted only the top few lines from the profile summary table. The methods are ranked according to the percentage of time they take. Note that the trace does not identify actual method signatures, only method names. The top three methods take, respectively, 54.79%, 11.67%, and 10.18% of the time taken to run the full program.[8] [8] The samples that count toward a particular method's execution time are those where the method itself is executing at the time of the sample. If method foo( ) were calling another method when the sample was taken, that other method would be at the top of the stack instead of foo( ). So you do not need to worry about the distinction between foo( )'s execution time and the time spent executing foo( )'s callees. Only the method at the top of the stack is tallied. The fourth method in the list takes 3.10% of the time, so clearly you need look no further than the top three methods to optimize the program. The methods ranked first, third, and fourth are the same method, possibly called in different ways. Obtaining the traces for these three entries from the relevant section of the profile output (trace 204 for the first entry, and traces 215 and 151 for the second and fourth entries), you get: TRACE 204: java/lang/FloatingDecimal.dtoa(FloatingDecimal.java:Compiled method) java/lang/FloatingDecimal.<init>(FloatingDecimal.java:Compiled method) java/lang/Double.toString(Double.java:Compiled method) java/lang/String.valueOf(String.java:Compiled method) TRACE 214: java/lang/FloatingDecimal.dtoa(FloatingDecimal.java:Compiled method) TRACE 151: java/lang/FloatingDecimal.dtoa(FloatingDecimal.java:Compiled method) java/lang/FloatingDecimal.<init>(FloatingDecimal.java:Compiled method) java/lang/Double.toString(Double.java:132) java/lang/String.valueOf(String.java:2065) In fact, both traces 204 and 151 are the same stack, but trace 151 provides line numbers for two of the methods. Trace 214 is a truncated entry, and is probably the same stack as the other two (these differences highlight the fact that the JDK profiler sometimes loses information). All three entries refer to the same stack: an inferred call from the StringBuffer to append a double, which calls String.valueOf( ), which calls Double.toString( ), which in turn creates a FloatingDecimal object. (<init> is the standard way to write a constructor call; <clinit> is the standard way to show a class initializer being executed. These are also the actual names for constructors and static initializers in the class file.) FloatingDecimal is private to the java.lang package, which handles most of the logic involved in converting floating-point numbers. FloatingDecimal.dtoa( ) is the method called by the FloatingDecimal constructor that converts the binary floating-point representation of a number into its various parts of digits before the decimal point, after the decimal point, and the exponent. FloatingDecimal stores the digits of the floating-point number as an array of chars when the FloatingDecimal is created; no strings are created until the floating-point number is converted to a string. Since this stack includes a call to a constructor, it is worth checking the object-creation profile to see whether you are generating an excessive number of objects; object creation is expensive, and a method that generates many new objects is often a performance bottleneck. (I show the object-creation profile and how to generate it later in this chapter under Section 2.4.) The object-creation profile shows that a large number of extra objects are being created, including a large number of FDBigInt objects that are created by the new FloatingDecimal objects. Clearly, FloatingDecimal.dtoa( ) is the primary method to optimize in this case. Almost any improvement in this one method translates directly to a similar improvement in the overall program. However, normally only Sun can modify this method, and even if you want to modify it, it is long and complicated and takes an excessive amount of time to optimize unless you are already familiar with both floating-point binary representation and converting that representation to a string format. Normally when tuning, the first alternative to optimizing FloatingDecimal.dtoa( ) is to examine the other significant bottleneck method, Double.equals( ) , which was second in the summary. Even though this entry takes up only 11.67% compared to over 68% for the FloatingDecimal.dtoa( ) method, it may be an easier optimization target. But note that while a small 10% improvement in the FloatingDecimal.dtoa( ) method translates into a 6% improvement for the program as a whole, the Double.equals( ) method needs to be speeded up to be more than twice as fast to get a similar 6% improvement for the full program. The trace corresponding to this second entry in the summary example turns out to be another truncated trace, but the example shows the same method in 14th position, and the trace for that entry identifies the Double.equals( ) call as coming from the Hashtable.put( ) call. Unfortunately for tuning purposes, the Double.equals( ) method itself is already quite fast and cannot be optimized further. When methods cannot be directly optimized, the next best choice is to reduce the number of times they are called or even avoiding the methods altogether. (In fact, eliminating method calls is actually the better tuning choice, but it is often considerably more difficult to achieve and so is not a first-choice tactic for optimization.) The object-creation profile and the method profile together point to the FloatingDecimal class as being a huge bottleneck, so avoiding this class is the obvious tuning tactic here. In Chapter 5, I employ this technique, avoiding the default call through the FloatingDecimal class for the case of converting floating-point numbers to Strings, and I obtain an order-of-magnitude improvement. Basically, the strategy is to create a more efficient routine to run the equivalent conversion functionality and then replace the calls to the underperforming FloatingDecimal methods with calls to more efficient optimized methods. The best way to avoid the Double.equals( ) method is to replace the hash table with another implementation that stores double primitive data types directly rather than requiring the doubles to be wrapped in a Double object. This allows the = = operator to make the comparison in the put( ) method, thus completely avoiding the Double.equals( ) call. This is another standard tuning tactic, replacing a data structure with one more appropriate and faster for the task. The default profile output gained from executing with -Xrunhprof in Java 2 is not useful for method profiling. The default output generates object-creation statistics from the heap as the dump (output) occurs. By default, the dump occurs when the application terminates; you can modify the dump time by typing Ctrl-\ on Solaris and other Unix systems, or Ctrl-Break on Windows. To get a useful method profile, you need to modify the profiler options to specify method profiling. A typical call to achieve this is: % java -Xrunhprof:cpu=samples,thread=y <classname> (Note that in a Windows command-line prompt, you need to surround the options with double quotes because the equals sign is considered a meta character.) The full list of options available with -Xrunhprof can be viewed using the -Xrunhprof:help option. The profiling option in JDKs 1.2/1.3/1.4 can be pretty flaky. Several of the options can cause the runtime to crash (core dump). The output is a large file because huge amounts of trace data are written rather than summarized. Since the profile option is essentially a Sun engineering tool, it is pretty rough, especially since Sun has a separate (not free) profile tool for its engineers. Another tool that Sun provides to analyze the output of the profiler is the Heap Analysis Tool (search for "HAT"). But this tool analyzes only the object-creation statistics output gained with the default profile output, so it is not that useful for method profiling (see Section 2.4 for slightly more about this tool). Nevertheless, I expect the free profiling option to stabilize and be more useful in future versions. The output when run with the options already listed (cpu=samples, thread=y) already results in fairly usable information. This profiling mode operates by periodically sampling the stack. Each unique stack trace provides a TRACE entry in the second section of the file, describing the method calls on the stack for that trace. Multiple identical samples are not listed; instead, the number of their "hits" is summarized in the third section of the file. The profile output file in this mode has three sections: A standard header section describing possible monitored entries in the file. For example: WARNING! This file format is under development, and is subject to change without notice. This file contains the following types of records: THREAD START THREAD END mark the lifetime of Java threads TRACE represents a Java stack trace. Each trace consists of a series of stack frames. Other records refer to TRACEs to identify (1) where object allocations have taken place, (2) the frames in which GC roots were found, and (3) frequently executed methods. Individual entries describing monitored events, i.e., threads starting and terminating, but mainly sampled stack traces. For example: THREAD START (obj=8c2640, id = 6, name="Thread-0", group="main") THREAD END (id = 6) TRACE 1: <empty> TRACE 964: java/io/ObjectInputStream.readObject(ObjectInputStream.java:Compiled method) java/io/ObjectInputStream.inputObject(ObjectInputStream.java:Compiled method) java/io/ObjectInputStream.readObject(ObjectInputStream.java:Compiled method) java/io/ObjectInputStream.inputArray(ObjectInputStream.java:Compiled method) TRACE 1074: java/io/BufferedInputStream.fill(BufferedInputStream.java:Compiled method) java/io/BufferedInputStream.read1(BufferedInputStream.java:Compiled method) java/io/BufferedInputStream.read(BufferedInputStream.java:Compiled method) java/io/ObjectInputStream.read(ObjectInputStream.java:Compiled method) A summary table of methods ranked by the number of times the unique stack trace for that method appears. For example: CPU SAMPLES BEGIN (total = 512371) Thu Aug 26 18:37:08 1999 rank self accum count trace method 1 16.09% 16.09% 82426 1121 java/io/FileInputStream.read 2 6.62% 22.71% 33926 881 java/io/ObjectInputStream.allocateNewObject 3 5.11% 27.82% 26185 918 java/io/ObjectInputStream.inputClassFields 4 4.42% 32.24% 22671 887 java/io/ObjectInputStream.inputObject 5 3.20% 35.44% 16392 922 java/lang/reflect/Field.set Section 3 is the place to start when analyzing this profile output. It consists of a table with six fields: This column simply counts the entries in the table, starting with 1 at the top and incrementing by 1 for each entry. The self field is usually interpreted as a percentage of the total running time spent in this method. More accurately, this field reports the percentage of samples that have the stack given by the trace field. Here's a one-line example: rank self accum count trace method 1 11.55% 11.55% 18382 545 java/lang/FloatingDecimal.dtoa This example shows that stack trace 545 occurred in 18,382 of the sampled stack traces, and this is 11.55% of the total number of stack trace samples made. It indicates that this method was probably executing for about 11.55% of the application execution time because the samples are at regular intervals. You can identify the precise trace from the second section of the profile output by searching for the trace with identifier 545. For the previous example, this trace was: TRACE 545: (thread=1) java/lang/FloatingDecimal.dtoa(FloatingDecimal.java:Compiled method) java/lang/FloatingDecimal.<init>(FloatingDecimal.java:Compiled method) java/lang/Double.toString(Double.java:Compiled method) java/lang/String.valueOf(String.java:Compiled method) This TRACE entry clearly identifies the exact method and its caller. Note that the stack is reported to a depth of four methods. This is the default depth; the depth can be changed using the depth parameter to -Xrunhprof, e.g., -Xrunhprof:depth=6,cpu=samples,.... This field is a running additive total of all the self field percentages as you go down the table. For the Section 3 example shown previously, the third line lists 27.82% for the accum field, indicating that the sum total of the first three lines of the self field is 27.82%. This field indicates how many times the unique stack trace that gave rise to this entry was sampled while the program ran. This field shows the unique trace identifier from the second section of profile output that generated this entry. The trace is recorded only once in the second section no matter how many times it is sampled; the number of times that this trace has been sampled is listed in the count field. This field shows the method name from the top line of the stack trace referred to from the trace field, i.e., the method that was running when the stack was sampled. This summary table lists only the method name and not its argument types. Therefore, it is frequently necessary to refer to the stack itself to determine the exact method if the method is an overloaded method with several possible argument types. (The stack is given by the trace identifier in the trace field, which in turn references the trace from the second section of the profile output.) If a method is called in different ways, it may also give rise to different stack traces. Sometimes the same method call can be listed in different stack traces due to lost information. Each of these different stack traces results in a different entry in the third section of the profiler's output, even though the method field is the same. For example, it is perfectly possible to see several lines with the same method field, as in the following table segment: rank self accum count trace method 95 1.1% 51.55% 110 699 java/lang/StringBuffer.append 110 1.0% 67.35% 100 711 java/lang/StringBuffer.append 128 1.0% 85.35% 99 332 java/lang/StringBuffer.append When traces 699, 711, and 332 are analyzed, one trace might be StringBuffer.append(boolean), while the other two traces could both be StringBuffer.append(int), but called from two different methods (and so giving rise to two different stack traces and consequently two different lines in the summary example). Note that the trace does not identify actual method signatures, only method names. Line numbers are given if the class was compiled so that line numbers remain. This ambiguity can be a nuisance at times. The profiler in this mode (cpu=samples) suffices when you have no better alternative. It does have an effect on real measured times, slowing down operations by variable amounts even within one application run. But it normally indicates major bottlenecks, although sometimes a little extra work is necessary to sort out multiple identical method-name references. Using the alternative cpu=times mode, the profile output gives a different view of application execution. In this mode, the method times are measured from method entry to method exit, including the time spent in all other calls the method makes. This profile of an application provides a tree-like view of where the application is spending its time. Some developers are more comfortable with this mode for profiling the application, but I find that it does not directly identify bottlenecks in the code. HotSpot does not support the standard Java 2 profiler detailed in the previous section; it supports a separate profiler using the -Xprof option. JDK 1.3 supports the HotSpot profiler as well as the standard Java 2 profiler. The HotSpot profiler has no further options available to modify its behavior; it works by sampling the stack every 10 milliseconds. The output, printed to standard output, consists of a number of sections. Each section lists entries in order of the number of ticks counted while the method was executed. The various sections include methods executing in interpreted and compiled modes, and VM runtime costs as well: A one-line header. For example: Flat profile of 7.55 secs (736 total ticks): main A list of methods sampled while running in interpreted mode. The methods are listed in order of the total number of ticks counted while the method was at the top of the stack. For example: Interpreted + native Method 3.7% 23 + 4 tuning.profile.ProfileTest.main 2.4% 4 + 14 java.lang.FloatingDecimal.dtoa 1.4% 3 + 7 java.lang.FDBigInt.<init> A list of methods sampled while running in compiled mode. The methods are listed in order of the total number of ticks counted while the method was at the top of the stack. For example: Compiled + native Method 13.5% 99 + 0 java.lang.FDBigInt.quoRemIteration 9.8% 71 + 1 java.lang.FDBigInt.mult 9.1% 67 + 0 java.lang.FDBigInt.add A list of external (non-Java) method stubs, defined using the native keyword. Listed in order of the total number of ticks counted while the method was at the top of the stack. For example: Stub + native Method 2.6% 11 + 8 java.lang.Double.doubleToLongBits 0.7% 2 + 3 java.lang.StrictMath.floor 0.5% 3 + 1 java.lang.Double.longBitsToDouble A list of internal VM function calls. Listed in order of the total number of ticks counted while the method was at the top of the stack. Not tuneable. For example: Runtime stub + native Method 0.1% 1 + 0 interpreter_entries 0.1% 1 + 0 Total runtime stubs Other miscellaneous entries not included in the previous sections: Thread-local ticks: 1.4% 10 classloader 0.1% 1 Interpreter 11.7% 86 Unknown code A global summary of ticks recorded. This includes ticks from the garbage collector, thread-locking overhead, and other miscellaneous entries: Global summary of 7.57 seconds: 100.0% 754 Received ticks 1.9% 14 Received GC ticks 0.3% 2 Other VM operations The entries at the top of Section 3 are the methods that probably need tuning. Any method listed near the top of Section 2 should have been targeted by the HotSpot optimizer and may be listed lower down in Section 3. Such methods may still need to be optimized, but it is more likely that the methods at the top of Section 3 need optimizing. The ticks for the two sections are the same, so you can easily compare the time taken up by the top methods in the different sections and decide which to target. The JDK 1.1.x method-profiling output, obtained by running with the -prof option, is quite different from the normal 1.2 output. This output format is supported in Java 2, using the cpu=old variation of the -Xrunhprof option. This output file consists of four sections: The method profile table showing cumulative times spent in each method executed. The table is sorted on the first count field. For example: callee caller time 29 java/lang/System.gc( )V java/io/FileInputStream.read([B)I 10263 1 java/io/FileOutputStream.writeBytes([BII)V java/io/FileOutputStream.write([BII)V 0 One line describing high-water gross memory usage. For example: handles_used: 1174, handles_free: 339046, heap-used: 113960, heap-free: 21794720 The line reports the number of handles and the number of bytes used by the heap memory storage over the application's lifetime. A handle is an object reference. The number of handles used is the maximum number of objects that existed at any one time in the application (handles are recycled by the garbage collector, so over its lifetime the application could have used many more objects than are listed). Heap measurements are given in bytes. Reports the number of primitive data type arrays left at the end of the process, just before process termination. For example: sig count bytes indx [C 174 19060 5 [B 5 19200 8 This section has four fields. The first field is the primitive data type (array dimensions and data type given by letter codes listed shortly), the second field is the number of arrays, and the third is the total number of bytes used by all the arrays. This example shows 174 char arrays with a combined space of 19,060 bytes, and 5 byte arrays with a combined space of 19,200 bytes. The reported data does not include any arrays that may have been garbage-collected before the end of the process. For this reason, the section is of limited use. You could use the -noasyncgc option to try to eliminate garbage collection (if you have enough memory; you may also need -mx with a large number to boost the maximum memory available). If you do, also use -verbosegc so that if garbage collection is forced, you at least know that it has occurred and can get the basic number of objects and bytes reclaimed. The fourth section of the profile output is the per-object memory dump. Again, this includes only objects left at the end of the process just before termination, not objects that may have been garbage-collected before the end of the process. For example: *** tab[267] p=4bba378 cb=1873248 cnt=219 ac=3 al=1103 Ljava/util/HashtableEntry; 219 3504 [Ljava/util/HashtableEntry; 3 4412 This dump is a snapshot of the actual object table. The fields in the first line of an entry are: The entry location as listed in the object table. The index is of no use for performance tuning. Internal memory locations for the instance and class; of no use for performance tuning. Internal memory locations for the instance and class; of no use for performance tuning. The number of instances of the class reported on the next line. The number of instances of arrays of the class reported on the next line. The total number of array elements for all the arrays counted in the previous (ac) field. This first line of the example is followed by lines consisting of three fields: first, the class name prefixed by the array dimension if the line refers to the array data; next, the number of instances of that class (or array class); and last, the total amount of space used by all the instances, in bytes. So the example reports that there are 219 HashtableEntry instances that comprise (collectively) a total of 3504 bytes,[9] and three HashtableEntry arrays having 1103 array indexes (which amounts to 4412 bytes total, as each entry is a 4-byte object handle). [9] A HashtableEntry has one int and three object handle instance variables, each of which takes 4 bytes, so each HashtableEntry is 16 bytes. Sections 3 and 4 give snapshots of the object table memory and can be used in an interesting way: to run a garbage collection just before termination of your application. That leaves in the object table all the objects that are rooted[10] by the system and by your application (from static variables). If this snapshot shows significantly more objects than you expect, you may be referencing more objects than you realized. [10] Objects rooted by the system are objects that the JVM runtime keeps alive as part of its runtime system. Rooted objects generally cannot be garbage-collected because they are referenced in some way from other objects that cannot be garbage-collected. The roots of these non-garbage-collectable objects are normally objects referenced from the stack, objects referenced from static variables of classes, and special objects the runtime system ensures are kept alive. The first section of the profile output is the most useful. It consists of multiple lines, each specifying a method and its caller, together with the total cumulative time spent in that method and the total number of times it was called from that caller. The first line of this section specifies the four fields in the profile table in this section: count, callee, caller, and time. They are detailed here: The total number of times the callee method was called from the caller method, accumulating multiple executions of the caller method. For example, if foo1( ) calls foo2( ) 10 times every time foo1( ) is executed, and foo1( ) was itself called three times during the execution of the program, the count field should hold the value 30 for the callee-caller pair foo2( )-foo1( ). The line in the table should look like this: 30 x/y/Z.foo2( )V x/y/Z.foo1( )V 1263 (assuming the foo*( ) methods are in class x.y.Z and they both have a void return). The actual reported numbers may be less than the true number of calls: the profiler can miss calls. The method that was called count times in total from the caller method. The callee can be listed in other entries as the callee method for different caller methods. The method that called the callee method count times in total. The cumulative time (in milliseconds) spent in the callee method, including time when the callee method was calling other methods (i.e., when the callee method was in the stack but not at the top, and so was not the currently executing method). If each of the count calls in one line took exactly the same amount of time, then one call from caller to callee took time divided by count milliseconds. This first section is normally sorted into count order. However, for this profiler, the time spent in methods tends to be more useful. Because the times in the time field include the total time that the callee method was anywhere on the stack, interpreting the output of complex programs can be difficult without processing the table to subtract subcall times. This format is different from the 1.2 output with cpu=samples specified, and is similar to a 1.2 profile with cpu=times specified. The lines in the profile output are unique for each callee-caller pair, but any one callee method and any one caller method can (and normally do) appear in multiple lines. This is because any particular method can call many other methods, and so the method registers as the caller for multiple callee-caller pairs. Any particular method can also be called by many other methods, and so the method registers as the callee for multiple callee-caller pairs. The methods are written out using the internal Java syntax listed in Table 2-1. There are free viewers, including source code, for viewing this file: Vladimir Bulatov's HyperProf (search for HyperProf on the Web) Greg White's ProfileViewer (search for ProfileViewer on the Web) The biggest drawback to the 1.1 profile output is that threads are not shown at all. This means that it is possible to get time values for method calls that are longer than the total time spent in running the application, since all the call times from multiple threads are added together. It also means that you cannot determine from which thread a particular method call was made. Nevertheless, after re-sorting the section on the time field rather than the count field, the profile data is useful enough to suffice as a method profiler when you have no better alternative. One problem I've encountered is the limited size of the list of methods that can be held by the internal profiler. Technically, this limitation is 10,001 entries in the profile table, and there is presumably one entry per method. There are four methods that help you avoid the limitation by profiling only a small section of your code: sun.misc.VM.suspendJavaMonitor( ) sun.misc.VM.resumeJavaMonitor( ) sun.misc.VM.resetJavaMonitor( ) sun.misc.VM.writeJavaMonitorReport( ) These methods also allow you some control over which parts of your application are profiled and when to dump the results. The -Xhprof option seems to be simply an alternative name for the -Xrunhprof option. I believe that originally it was called -Xhprof, and then the option was left in although all subsequent documentation used -Xrunhprof. -Xaprof appears to be a simple allocation profiler. It prints the number and total size of instances allocated per class, including array classes, accumulating instances across all threads and creation points. In fact, it seems to be very similar to the tool I describe in the next section. Like other VM profiling tools, it is unfortunately not 100% stable (for example, it core dumps with my 1.4 Windows VM). Nevertheless, it is useful when it works, and it was introduced with 1.3. Using this profiler to monitor the tuning.profile.ProfileTest class used in the example from the "Profiling Methodology" section results in the following output: Allocation profile (sizes in bytes, cutoff = 0 bytes): _ _ _ _ _ _Size_ _Instances_ _Average_ _Class_ _ _ _ _ _ _ _ _ _ _ _ _ 13491592 186025 73 [I 5634592 86602 65 [C 2496352 156022 16 java.lang.FDBigInt 875112 36463 24 java.lang.String 768000 16000 48 java.lang.FloatingDecimal 320000 20000 16 java.lang.Long 256000 16000 16 java.lang.Double 29832 14 2131 [B 14256 594 24 java.util.Hashtable$Entry 8960 6 1493 [S 8112 25 324 [Ljava.util.Hashtable$Entry; 2448 102 24 java.lang.StringBuffer 2312 3 771 [Ljava.lang.FDBigInt; 1600 24 67 [Ljava.lang.Object; 584 9 65 [Ljava.util.HashMap$Entry; 528 22 24 java.util.Locale 440 11 40 java.util.Hashtable 432 9 48 java.util.HashMap 392 4 98 [D 376 3 125 [J 320 7 46 [Ljava.lang.String; 256 4 64 java.lang.Thread ... 23916904 518123 46 --total-- The listing has been truncated, but a full listing is output down to objects and arrays with only one instance created. The primitive arrays are listed using the one-character labels from Table 2-1. The listing is fairly clear. All instances created at any time by the VM are included, whether they have been garbage-collected or not. The first column is the total size in bytes taken up by all the instances summed together; the second column provides the number of those instances created; and the third divides the first column by the second column to give an average size per object in bytes. The only disadvantage seems to be that you cannot take a snapshot. There seems to be no way of registering only those objects created between time 1 (e.g., after initialization) and time 2. Otherwise, this is another useful tool to add to your armory.
http://etutorials.org/Programming/Java+performance+tuning/Chapter+2.+Profiling+Tools/2.3+Method+Calls/
CC-MAIN-2018-47
refinedweb
6,032
65.62
#include <formlayoutattached.h> Detailed Description This attached property contains the information for decorating a FormLayout: It contains the text labels of fields and information about sections. - Since - 2.3 Definition at line 44 of file formlayoutattached.h. Property Documentation The Item the label will be considered a "Buddy" for, which will be the parent item the attached property is in. A buddy item is useful for instance when the label has a keyboard accelerator, which on triggered will be given active keyboard focus to. Definition at line 118 of file formlayoutattached.h. If true a checkbox is prepended to the FormLayout item. Definition at line 100 of file formlayoutattached.h. This property is true when the checkbox of the FormLayout item is checked,. Definition at line 105 of file formlayoutattached.h. This property holds whether the label and the checkbox of the FormLayout item receive mouse and keyboard events. Definition at line 110 of file formlayoutattached.h. If true the FormLayout item is a section separator, a section separator may have different looks: - To make it just a space between two fields, just put an empty item with isSection: - To make it a space with a section title: - To make it a space with a section title and a separator line: Definition at line 95 of file formlayoutattached.h. The label for a form layout field. Definition at line 50 of file formlayoutattached.
https://api.kde.org/frameworks/kirigami/html/classFormLayoutAttached.html
CC-MAIN-2019-51
refinedweb
233
55.13
This page describes how to enable and disable Domain Name System Security Extensions (DNSSEC), verify DNSSEC deployment, and migrate zones to and from Cloud DNS. For a conceptual overview of DNSSEC, see the DNSSEC overview. Enabling DNSSEC for existing managed zones To enable DNSSEC for existing managed zones, see the following steps. Console In the Google Cloud Console, go to the Cloud DNS page. Click the DNSSEC setting for the zone, and under DNSSEC, select On. In the confirmation dialog, click Enable. gcloud Run the following command: gcloud dns managed-zones update EXAMPLE_ZONE \ --dnssec-state on Replace EXAMPLE_ZONE with the zone ID. Python Run the following: def enable_dnssec(project_id, name, description=None): client = dns.Client(project=project_id) zone = client.zone(name=name) zone.update(dnssec='on', description=description) Enabling DNSSEC when creating zones To enable DNSSEC when you are creating a zone, see the following steps. Console In the Google Cloud Console, go to the Cloud DNS page. Click Create zone. In the Zone name field, enter a name. In the DNS name field, enter a name. Under DNSSEC, select On. Optional: Add a description. Click Create. gcloud Run the following command: gcloud dns managed-zones create EXAMPLE_ZONE \ --description "Signed Zone" \ --dns-name myzone.example.com \ --dnssec-state on Replace EXAMPLE_ZONE with the zone ID. Python Run the following: def create_signed_zone(project_id, name, dns_name, description): client = dns.Client(project=project_id) zone = client.zone( name, # examplezonename dns_name=dns_name, # example.com. description=description, dnssec='on') zone.create() return zone Verifying DNSSEC deployment To verify correct deployment of your DNSSEC-enabled zone, make sure that you placed the correct DS record in the parent zone. DNSSEC resolution can fail if either of the following occurs: - The configuration is wrong, or you have mistyped it. - You have placed the incorrect DS record in the parent zone. To verify that you have the right configuration in place and to cross-check the DS record before placing it in the parent zone, use the following tools: You can use the Verisign DNSSEC debugger and Zonemaster sites to validate your DNSSEC configuration before you update your registrar with your Cloud DNS name servers or DS record. A domain that is properly configured for DNSSEC is example.com, viewable using DNSViz. Recommended TTL settings for DNSSEC-signed zones TTL is the time to live (in seconds) for a DNSSEC-signed zone. Unlike TTL expirations, which are relative to the time a name server sends a response to a query, DNSSEC signatures expire at a fixed absolute time. TTLs configured longer than a signature lifetime can lead to many clients requesting records at the same time as the DNSSEC signature expires. Short TTLs can also cause problems for DNSSEC-validating resolvers. For more recommendations about TTL selection, see RFC 6781 section 4.4.1 Time Considerations and RFC 6781 Figure 11. When reading RFC 6781 section 4.4.1, consider that many signature time parameters are fixed by Cloud DNS and you cannot change them. Currently, you cannot change the following (subject to change without notice or update to this document): - Inception offset = 1 day - Validity period = 21 days - Re-sign period = 3 days - Refresh period = 18 days - Jitter interval = ½ day (or ±6 hours) - Minimum signature validity = refresh – jitter = 17.75 days = 1533600 You must never use a TTL longer than the minimum signature validity. Disabling DNSSEC for managed zones After you have removed DS records and waited for them to expire from cache, you can use the following gcloud command to turn off DNSSEC: gcloud dns managed-zones update EXAMPLE_ZONE \ --dnssec-state off Replace EXAMPLE_ZONE with the zone ID. DNSSEC, domain transfers, and zone migration For DNSSEC-enabled zones where DNSSEC has been activated at the domain registry, see the steps in the following sections to ensure proper operation of the domain: When it is transferred to another registrar (or ownership is transferred). When migrating the DNS zone between Cloud DNS and another DNS operator. The technical approach that Cloud DNS uses for these migrations is the KSK Double-DS rollover variant described in RFC 6781 section 4.1.2 Key Signing Key Rollovers. For an informative presentation about DNSSEC and domain transfers and potential pitfalls, see DNS/DNSSEC and Domain Transfers: Are they compatible?. Migrating DNSSEC-signed zones to Cloud DNS If you are migrating a DNSSEC-signed zone to Cloud DNS, make sure that Cloud DNS supports the same KSK algorithm already in use. If not, deactivate DNSSEC at your domain registrar before you migrate the zone, and update the name server records at the registrar to use the Cloud DNS name servers. If the existing KSK and ZSK algorithms are supported in Cloud DNS, you can follow these steps to perform the migration with DNSSEC enabled: Create a new DNSSEC-signed zone in DNSSEC Transferstate. Transferstate lets you manually copy DNSKEYs into the zone. Export your zone files, and then import them into the new zone. Add the DNSKEYs (both KSK and ZSK) from the old zone's zone files. You can also use the digcommand to query the other name servers for DNSKEY records. Add the DS record for the new zone to your registrar. Update the name server records at the registrar to the Cloud DNS name servers for the new zone. Leaving DNSSEC transfer state Before leaving the DNSSEC transfer state, wait until the name server references (NS and DS) to Cloud DNS have propagated to all authoritative registry name servers. Also ensure that the TTL has expired for all old name server DNSSEC resource records (not only the registry parent zone NS and DS records, but also DNSKEY, NSEC/NSEC3, and RRSIG records from the old zone). Make sure that you remove the manually added transfer DNSKEY records. You can then change the DNSSEC state of the zone from Transfer to On. Making this change enables automatic ZSK rotation from the zone. Generally, your zones can safely leave DNSSEC transfer state after a week, and should not remain in DNSSEC transfer state for more than a month or two. You must also remove the DS record for the old DNS operator's zone from your registrar. Migrating DNSSEC-signed zones from Cloud DNS Before you migrate a DNSSEC-signed zone to another DNS operator, make sure that the zone and operator support the same KSK algorithm that you are using. If not, deactivate DNSSEC at your domain registrar before you migrate the zone, and update the name server records at the registrar to use the new name servers. If they support the same KSK (and preferably the same ZSK) algorithms and provide a way to copy existing DNSKEYs to the new zone, you can perform the migration keeping DNSSEC enabled by following these steps: Change the DNSSEC state from Onto Transfer. This stops ZSK rotation. Export your zone file (including DNSKEYs) and import it into the new zone. If the DNSKEYs (both KSK and ZSK) import did not go through, add them manually. Use the digcommand to query the Cloud DNS name servers for your zone for DNSKEY records: dig DNSKEY myzone.example.com. @ns-cloud-e1.googledomains.com. Enable DNSSEC-signing for the new zone, and add a DS record for the new KSK at the registrar. If your registrar cannot support multiple DS records, complete this task in step 6. Optional: Import the new DNSKEYs for the new zone into Cloud DNS. You can use a digcommand similar to the one in step 3 for this, but skip the DNSKEYs that you exported from Cloud DNS. To use the new DNS operator, update the name server records at the registrar. If you can only replace DS records at your registrar, do this now. If the other DNS operator has a process for migrating a DNSSEC-signed zone (such as Dyn), you must perform their steps in parallel with this procedure, after step 1. After you have completed all the necessary steps on the other DNS operator, do the following: Update the DNSSEC state to Off, or delete the zone in Cloud DNS to disable DNSSEC. Remove the DS record for the Cloud DNS zone from your registrar. What's next - To get information about specific DNSSEC configurations, see Using advanced DNSSEC. - To create, update, list, and delete managed zones, see Managing zones. - To find solutions for common issues that you might encounter when using Cloud DNS, see Troubleshooting. - To get an overview of Cloud DNS, see Cloud DNS overview.
https://cloud.google.com/dns/docs/dnssec-config?hl=zh-TW
CC-MAIN-2021-10
refinedweb
1,411
62.88
Hello, can someone please help explain this. I completed function and Scope exercise in which i used const and let to create variables. for example in return I and return II (5/10 and 6/10) in functions. However checking the forums , I saw other post where instead of let , there is var, are we doing the same exercise or did the exercises change? I dont understand this, because i never came across var in my function exercise . Function Confusion of Let and Var The exercises may have changed last autumn, where ES6 syntax was introduced into course. Briefly, var is what we used to (and still can) use to define scope. A variable declared in global scope didn’t really need the keyword since its scope is already defined, but we made a habit of using it just for good practice. Inside a function things are different. Functions define their own scope (environment) and if we declare a variable without the keyword it will end up being a global variable. This is not really a good practice since we are polluting the global namespace with variables that could collide with other parts of the program. var number = 42; function foo(): number = 84; } console.log(number); // 84 See how the function’s number value overwrote the global value? To prevent this we would use var inside the function. That way they are two different variables (since they are in two different scopes). There is one tiny exception to consider… The parameter. var number = 42; function foo(number): return number; } console.log(number); // 42 console.log(foo(84)); // 84 The parameter variable is defined in function scope. Again, two different scopes. The parameter is said to shadow the global variable. var declarations are dynamic, meaning their values and type can be changed on the fly with a new assignment. var str = "Hello"; console.log(str); // Hello str = str.length; console.log(str); // 5 Notice that we do not use var more than once. Just reassignment. I’ll post this now so you can read it while I muster up some more on the topic of const and let. Will edit this post in a short while. There is one thing to add to the above, known as variable leakage. for (var i = 0; i < 10; i++) { console.log(i); } 0 1 2 3 4 5 6 7 8 9 console.log(i); // 10 Notice that the last value of i is still in memory and permitted to leak out of the loop. This might be the effect we desire, but if we don’t, then ES6 block scope gives us a way to prevent it… let. for (let i = 0; i < 10; i++) { console.log(i); } // same output as before console.log(i); // undefined Now we see there is no leakage. i is defined in the block scope of the loop body, and is undefined outside of the block. let variables are like var in that they are dynamic. Their value and or type can be changed on the fly. const is what it implies… A constant. const declared variables are static and cannot be changed once declared. The only exception to this is reference objects such as arrays and objects. Their type cannot be changed but the values they contain are dynamic and can be changed in both type and value. The object length is also dynamic so we can insert or remove elements or key:value pairs. Thank you very much @mtf , its making a little sense, trying to bring in var and to see how different it is from let (at least i can see the difference between var and const), so does that mean that var and let can be used exactly the same way or interchangeably , but the only difference is that let allow no leakage and var does allow leakage out of the loop. Because I have noticed that even though the exercise is not the same, the differences is in the (var and let) the new exercise used let at places where the old exercise used var. is that right? There really isn’t much difference between var and let other than block scope on let. They both treat function scope the same. let number = 42; function foo() { number = 84; } console.log(number); // 84 Thank you, that makes sense. I was just wondering though, a person did the same function exercise yesterday but his function topic (Return I and Return II) contain var , while mine contain let. why the difference? I can only answer in the subjective without actually checking the lesson. Please post a link to the exercise. Thanks. Edit: found the lessons Here is ES5 syntax, function takeOrder(topping, crustType) { orderCount++; console.log('Order: ' + crustType + ' pizza topped with ' + topping); } function getSubTotal(itemCount){ return itemCount * 7.5; } function getTax() { return getSubTotal(orderCount) * 0.06; } function getTotal() { return getSubTotal(orderCount) + getTax(); } var orderCount = 0; takeOrder('bacon', 'thin crust'); takeOrder('cheese', 'thick crust'); takeOrder('anchovies', 'garlic crust'); console.log(getSubTotal(orderCount)); console.log(getTotal()); Order: thin crust pizza topped with bacon Order: thick crust pizza topped with cheese Order: garlic crust pizza topped with anchovies 22.5 23.85 Here is the same thing in ES6 syntax: const takeOrder = (topping, crustType) => { orderCount++; console.log(`Order: ${crustType} pizza topped with ${topping}`); }; const getSubTotal = itemCount => itemCount * 7.5; const getTax = () => getSubTotal(orderCount) * 0.06; const getTotal = () => getSubTotal(orderCount) + getTax(); let orderCount = 0; takeOrder('bacon', 'thin crust'); takeOrder('cheese', 'thick crust'); takeOrder('anchovies', 'garlic crust'); console.log(getSubTotal(orderCount)); console.log(getTotal()); Same output. When we can improve readability with no loss of functionality, the new syntax wins hands down. BUT, it does not matter when it comes down to it. It’s more important that we write code that works as expected than how we actually choose to compose it. var and let only concern themselves with the scope in which they are declared. Thats wonderfully explained, i got it now, Thank you.
https://discuss.codecademy.com/t/function-confusion-of-let-and-var/275701
CC-MAIN-2018-26
refinedweb
996
66.23
#include "clang/Sema/DeclSpec.h" Definition at line 1176 of file DeclSpec.h. Definition at line 1192 of file DeclSpec.h. True if this dimension included the 'static' keyword. Definition at line 1182 of file DeclSpec.h. Referenced by clang::Sema::ActOnCXXNew(). True if this dimension was [*]. In this case, NumElts is null. Definition at line 1185 of file DeclSpec.h. This is the size of the array, or null if [] or [*] was specified. Since the parser is multi-purpose, and we don't want to impose a root expression class on all clients, NumElts is untyped. Definition at line 1190 of file DeclSpec.h. Referenced by clang::Sema::ActOnCXXNew(), and clang::Declarator::isArrayOfUnknownBound(). The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic. Definition at line 1179 of file DeclSpec.h.
https://clang.llvm.org/doxygen/structclang_1_1DeclaratorChunk_1_1ArrayTypeInfo.html
CC-MAIN-2018-09
refinedweb
133
54.9
TL;DR Find out how a vulnerability in DD-WRT allows an unauthenticated attacker to overflow an internal buffer used by UPNP and trigger a code execution vulnerability. Vulnerability Summary DD-WRT is “is Linux-based firmware for wireless routers and access points. Originally designed for the Linksys WRT54G series, it now runs on a wide variety of models”. Use of user supplied data, arriving via UPNP packet, is copied into an internal buffer of DD-WRT. This buffer being limited in size – while user supplied data is not allows a remote attacker to trigger a buffer overflow. CVE CVE-2021-27137 Credit An independent security researchers, Selim Enes Karaduman, has reported this vulnerability to the SSD Secure Disclosure program. Affected Versions DD-WRT with change set 45723 or prior Buffalo devices that ship with DD-WRT should be considered to be vulnerable Vendor Response “Thanks for informing us about this issue. we will fix it ASAP and release a fixed version within the next days including update of our router database.for all devices. Fix can be reviewed here″ Vulnerability Analysis”. By default, UPNP in DD-WRT is disabled as well as only listening on internal network interfaces. UPNP in its nature is an unauthenticated protocol, in UDP form – which makes it both easy to use as well as insecure in nature, as there is no way to enforce authentication on the protocol. If DD-WRT has its UPNP service enabled a remote attacker sitting on the LAN where the DD-WRT device is present can trigger a buffer overflow by sending an overly long uuid value. uuid Depending on the platform DD-WRT is deployed on, there may or may not be mitigation such as ASLR and others, making exploitability dependent on the platform the DD-WRT is installed on. Vulnerable Code By reviewing the source code of ssdp.c it is fairly easy to spot the offending code: ssdp.c An unbound copy from user provided data is copied into a buffer limited to 128 bytes in size. Proof Of Concept Because the UPNP service is not enabled by default, the first step to recreate the vulnerability would be to enable the service which will auto-start it: Launching the PoC script will trigger the upnp service to crash as can be seen a few seconds after you launch the below python script: import socket target_ip = "192.168.15.124" # IP Address of Target off = "D"*164 ret_addr = "AAAA" payload = off + ret_addr packet = \ 'M-SEARCH * HTTP/1.1\r\n' \ 'HOST:239.255.255.250:1900\r\n' \ 'ST:uuid:'+payload+'\r\n' \ 'MX:2\r\n' \ 'MAN:"ssdp:discover"\r\n' \ '\r\n' s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.sendto(packet.encode(), (target_ip, 1900) )
https://ssd-disclosure.com/ssd-advisory-dd-wrt-upnp-buffer-overflow/
CC-MAIN-2022-40
refinedweb
462
51.78
Node.js vs. ASP.NET Web API Much has been said about the Node.js’s great performance so I wanted to test out how it compares to an ASP.NET Web Api backend.I created a simple server for both of the platforms which accepts a POST-request and then responds back with the request’s body. The Node.js and ASP.NET Web Api implementations Here’s the Node.js code: var express = require('express') , app = express.createServer(); app.use(express.bodyParser()); app.post('/', function(req, res){ res.send(req.body); }); app.listen(3000); And here’s the ASP.NET Web Api controller: public class ValuesController : ApiController { // POST /api/values public Task<string> Post() { return this.ControllerContext.Request.Content.ReadAsStringAsync(); } } Benchmark I used Apache’s ab tool to test the performance of the platforms. The benchmark was run with the following settings: - Total number of requests: 100 000 - Concurrency: 100 The benchmark (test.dat) contained a simple JSON, taken from Wikipedia. { "firstName": "John", "lastName" : "Smith", "age" : 25, "address" : { "streetAddress": "21 2nd Street", "city" : "New York", "state" : "NY", "postalCode" : "10021" }, "phoneNumber": [ { "type" : "home", "number": "212 555-1234" }, { "type" : "fax", "number": "646 555-4567" } ] } Here’s the whole command which was used to run the performance test: ab -n 100000 -c 100 -p .\test.dat -T 'application/json; charset=utf-8' The performance test was run 3 times and the best result for each platform was selected. The performance difference between the test runs was minimal. Test Environment The benchmark was run on a Windows Server 2008 R2, hosted on an c1.medium Amazon EC2 –instance: Specs of the instance - 1.7GB memory - 5 EC2 Compute Units (2 virtual cores) Versions - Node.js: 0.6.17 - ASP.NET Web Api: Current release (12.5.2012) - IIS: 7 Both the Node and IIS –servers were run with their out-of-the-box settings. Benchmark Results Conclusion The out-of-the-box performance of the Node.js seems to be better than the performance of the ASP.NET Web Api + IIS7. Tweaking the IIS7’s settings could make the ASP.NET Web Api perform better but for this test the default settings of IIS7 were used. (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) Tech Fun replied on Thu, 2012/05/17 - 4:13pm Bart Czernicki replied on Fri, 2012/05/18 - 3:00pm I am curious what the default IIS settings are on Amazon EC2...does IIS include uncessary headers (?) Also when benchmarking Node versus Web APIs, a proper test would include a series of: cached, non-cached, async and sync requests. Node is going to be faster in direct requests/async 100% requests...once u start mixing things I would assume that ASP.NET Web APIs would quickly catch up, especially as sync requests increase. Also scaling Web APIs should be easier as Tasks, PLINQ etc can take advantage of multiple cores directly from the environment. In Node, you need to sping up multiple node processes and allocate to each core.
http://css.dzone.com/articles/nodejs-vs-aspnet-web-api
CC-MAIN-2013-20
refinedweb
515
67.04
Download Code::Blocks Download the GLUT bin file (first download link) from: Now you are ready to start Code::Blocks and make a new project. Open up Code::Blocks. Start a new Project by going to File, New, Project. Select to make a new GLUT project and press Go to continue. Press Next at this menu Give a project title, and a location where to create the project and then press Next. Let Code::Blocks know where you stored your GL files, then press Next. Leave these unchanged, and press Finish. In the manager window (viewable by pressing Shift-F2), open up the sample source file by double clicking on it. To make your program work, you will need to add at line 14: #include <windows.h> You will need to make a small change to the project's Build Options. Go to Project, Build Options. Select the Linker tab and press Add in the Link Libraries area. Press on the ... button to select a library to add. You need to add the glut32.lib library. Locate this from the directory you placed it in before. After you add the library, it will ask if you want to keep the path relative. Select No. Press OK to select the library. Press OK to close the Project's Build Options. Press F9 to do a Build & Run of your project. After a while you'll get some warnings. Ignore the warnings. If you get errors, check the steps above to make sure you added in the new line at 14, and setup project to use the glut32.lib library file to use. Hopefully you'll get a program displaying the following: If you see the proceeding window, congratulations, GLUT works for you! Return
http://www.sci.brooklyn.cuny.edu/~goetz/codeblocks/glut/
CC-MAIN-2017-09
refinedweb
292
85.49
LPC21xx ppm decoder. More... #include "LPC21xx.h" #include <BOARD_CONFIG> #include "mcu_periph/sys_time.h" Go to the source code of this file. LPC21xx ppm decoder. Definition in file ppm_arch.h. Definition at line 49 of file ppm_arch.h. Referenced by TIMER0_ISR(). Definition at line 47 of file ppm_arch.h. Definition at line 44 of file ppm_arch.h. On tiny (and booz) the ppm counter is running at the same speed as the systic counter. There is no reason for this to be true. Let's add a pair of macros to make it possible for them to be different. Definition at line 43 of file ppm_arch.h. Definition at line 45 of file ppm_arch.h.
http://docs.paparazziuav.org/v5.16/lpc21_2subsystems_2radio__control_2ppm__arch_8h.html
CC-MAIN-2020-50
refinedweb
114
80.88
Database opens were changed in the Berkeley DB 3.0 release in a similar way to environment opens. To upgrade your application, first find each place your application opens a database, that is, calls the db_open function. Each of these calls should be replaced with calls to db_create() and DB->open(). Here's an example creating a Berkeley DB database using the 2.X interface: DB *dbp; DB_ENV *dbenv; int ret; if ((ret = db_open(DATABASE, DB_BTREE, DB_CREATE, 0664, dbenv, NULL, &dbp)) != 0) return (ret); In the Berkeley DB 3.0 release, this code would be written as: DB *dbp; DB_ENV *dbenv; int ret; if ((ret = db_create(&dbp, dbenv, 0)) != 0) return (ret); if ((ret = dbp->open(dbp, DATABASE, NULL, DB_BTREE, DB_CREATE, 0664)) != 0) { (void)dbp->close(dbp, 0); return (ret); } As you can see, the arguments to db_open and to DB->open() are largely the same. There is some re-organization, and note that the enclosing DB_ENV structure is specified when the DB object is created using the db_create() function. There is one additional argument to DB->open(), argument #3. For backward compatibility with the 2.X Berkeley DB releases, simply set that argument to NULL. There are two additional issues with the db_open call. First, it was possible in the 2.X releases for an application to provide an environment that did not contain a shared memory buffer pool as the database environment, and Berkeley DB would create a private one automatically. This functionality is no longer available, applications must specify the DB_INIT_MPOOL flag if databases are going to be opened in the environment. The final issue with upgrading the db_open call is that the DB_INFO structure is no longer used, having been replaced by individual methods on the DB handle. That change is discussed in detail later in this chapter.
http://docs.oracle.com/cd/E17275_01/html/programmer_reference/upgrade_3_0_open.html
CC-MAIN-2015-22
refinedweb
302
65.42