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
Introduction Contents This PEP describes the 'lockstep iteration' proposal. every element in a sequence until the sequence is exhausted [1]. However, for-loops iterate over only a single sequence, and it is often desirable to loop over more than one sequence in a lock-step fashion. In other words, in a way such that the i-th iteration through the loop returns an object containing the i-th element from each sequence. The common idioms used to accomplish this are unintuitive. This PEP proposes a standard way of performing such iterations by introducing a new builtin function called zip. While the primary motivation for zip() comes from lock-step iteration, by implementing zip() as a built-in function, it has additional utility in contexts other than for-loops. Lockstep For-Loops Lockstep for-loops are non-nested iterations over two or more sequences, such that at each pass through the loop, one element from each sequence is taken to compose the target. This behavior can already be accomplished in Python through the use of the map() built- in function: >>> a = (1, 2, 3) >>> b = (4, 5, 6) >>> for i in map(None, a, b): print i ... (1, 4) (2, 5) (3, 6) >>> map(None, a, b) [(1, 4), (2, 5), (3, 6)] The for-loop simply iterates over this list as normal. While the map() idiom is a common one in Python, it has several disadvantages: It is non-obvious to programmers without a functional programming background. The use of the magic None first argument is non-obvious. It has arbitrary, often unintended, and inflexible semantics when the lists are not of the same length: the shorter sequences are padded with None: >>> c = (4, 5, 6, 7) >>> map(None, a, c) [(1, 4), (2, 5), (3, 6), (None, 7)] For these reasons, several proposals were floated in the Python 2.0 beta time frame for syntactic support of lockstep for-loops. Here are two suggestions: for x in seq1, y in seq2: # stuff for x, y in seq1, seq2: # stuff Neither of these forms would work, since they both already mean something in Python and changing the meanings would break existing code. All other suggestions for new syntax suffered the same problem, or were in conflict with other another proposed feature called 'list comprehensions' (see PEP 202). The Proposed Solution The proposed solution is to introduce a new built-in sequence generator function, available in the __builtin__ module. This function is to be called zip and has the following signature: zip(seqa, [seqb, [...]]) zip() takes one or more sequences and weaves their elements together, just as map(None, ...) does with sequences of equal length. The weaving stops when the shortest sequence is exhausted. Return Value zip() returns a real Python list, the same way map() does. Examples Here are some examples, based on the reference implementation below: >>> a = (1, 2, 3, 4) >>> b = (5, 6, 7, 8) >>> c = (9, 10, 11) >>> d = (12, 13) >>> zip(a, b) [(1, 5), (2, 6), (3, 7), (4, 8)] >>> zip(a, d) [(1, 12), (2, 13)] >>> zip(a, b, c, d) [(1, 5, 9, 12), (2, 6, 10, 13)] Note that when the sequences are of the same length, zip() is reversible: >>> a = (1, 2, 3) >>> b = (4, 5, 6) >>> x = zip(a, b) >>> y = zip(*x) # alternatively, apply(zip, x) >>> z = zip(*y) # alternatively, apply(zip, y) >>> x [(1, 4), (2, 5), (3, 6)] >>> y [(1, 2, 3), (4, 5, 6)] >>> z [(1, 4), (2, 5), (3, 6)] >>> x == z 1 It is not possible to reverse zip this way when the sequences are not all the same length. Reference Implementation Here is a reference implementation, in Python of the zip() built-in function. This will be replaced with a C implementation after final approval: def zip(*args): if not args: raise TypeError('zip() expects one or more sequence arguments') ret = [] i = 0 try: while 1: item = [] for s in args: item.append(s[i]) ret.append(tuple(item)) i = i + 1 except IndexError: return ret BDFL Pronouncements Note: the BDFL refers to Guido van Rossum, Python's Benevolent Dictator For Life. - The function's name. An earlier version of this PEP included an open issue listing 20+ proposed alternative names to zip(). In the face of no overwhelmingly better choice, the BDFL strongly prefers zip() due to its Haskell [2] heritage. See version 1.7 of this PEP for the list of alternatives. - zip() shall be a built-in function. - Optional padding. An earlier version of this PEP proposed an optional pad keyword argument, which would be used when the argument sequences were not the same length. This is similar behavior to the map(None, ...) semantics except that the user would be able to specify pad object. This has been rejected by the BDFL in favor of always truncating to the shortest sequence, because of the KISS principle. If there's a true need, it is easier to add later. If it is not needed, it would still be impossible to delete it in the future. -. - zip() with no arguments. the BDFL strongly prefers this raise a TypeError exception. - zip() with one argument. the BDFL strongly prefers that this return a list of 1-tuples. - Inner and outer container control. An earlier version of this PEP contains a rather lengthy discussion on a feature that some people wanted, namely the ability to control what the inner and outer container types were (they are tuples and list respectively in this version of the PEP). Given the simplified API and implementation, this elaboration is rejected. For a more detailed analysis, see version 1.7 of this PEP. Subsequent Change to zip() In Python 2.4, zip() with no arguments was modified to return an empty list rather than raising a TypeError exception. The rationale for the original behavior was that the absence of arguments was thought to indicate a programming error. However, that thinking did not anticipate the use of zip() with the * operator for unpacking variable length argument lists. For example, the inverse of zip could be defined as: unzip = lambda s: zip(*s). That transformation also defines a matrix transpose or an equivalent row/column swap for tables defined as lists of tuples. The latter transformation is commonly used when reading data files with records as rows and fields as columns. For example, the code: date, rain, high, low = zip(*csv.reader(file("weather.csv"))) rearranges columnar data so that each field is collected into individual tuples for straightforward looping and summarization: print "Total rainfall", sum(rain) Using zip(*args) is more easily coded if zip(*[]) is handled as an allowable case rather than an exception. This is especially helpful when data is either built up from or recursed down to a null case with no records. Seeing this possibility, the BDFL agreed (with some misgivings) to have the behavior changed for Py2.4. Other Changes The xzip() function discussed above was implemented in Py2.3 in the itertools module as itertools.izip(). This function provides lazy behavior, consuming single elements and producing a single tuple on each pass. The "just-in-time" style saves memory and runs faster than its list based counterpart, zip(). The itertools module also added itertools.repeat() and itertools.chain(). These tools can be used together to pad sequences with None (to match the behavior of map(None, seqn)): zip(firstseq, chain(secondseq, repeat(None))) References Greg Wilson's questionaire on proposed syntax to some CS grad students
http://docs.activestate.com/activepython/2.7/peps/pep-0201.html
CC-MAIN-2018-43
refinedweb
1,251
61.46
I have 2 lists that I shuffle at the beginning of my oncreate() and then I would like to shuffle them again at a later point when a "new game" button is pressed. The first time they are shuffled I used: final Random rnd = new Random(); final int seed = rnd.nextInt(); rnd.setSeed(seed); Collections.shuffle(Arrays.asList(answerChoices),rnd); rnd.setSeed(seed); Collections.shuffle((resources),rnd); And everything works fine. However when I try to shuffle them again when a "new game" button is pressed i tried using the same as above and I tried changing the name of both rnd and seed and it doesnt work properly. After the second shuffle the lists do not match as they should. any suggestions as to what I should try? A possible solution to your problem is to wrap the values in your two lists in a class. Then add objects of those class to one list and shuffle that, for example: public class Test { public static void main(String[] args) { Random rnd = new Random(); int seed = rnd.nextInt(); rnd.setSeed(seed); List<Pair> pairs = new ArrayList<Pair>(); pairs.add(new Pair(1, "else")); pairs.add(new Pair(2, "bar")); pairs.add(new Pair(3, "pair")); Collections.shuffle(pairs, rnd); for (Pair pair : pairs) { System.out.println(pair.drawable + " " + pair.sequence); } } } class Pair { int drawable; CharSequence sequence; Pair(int drawable, CharSequence sequence) { this.drawable = drawable; this.sequence = sequence; } } Running the code repeatedly will result in different ordered lists, but the values will still be paired.
http://www.dlxedu.com/askdetail/3/6ebfee68cdec7fad8f6009f010d38fd7.html
CC-MAIN-2019-04
refinedweb
254
66.23
Created on 2015-01-11 00:54 by Al.Sweigart, last changed 2018-11-10 23:34 by terry.reedy. This issue is now closed. IDLE cannot display the \b backspace character correctly. From IDLE's interactive shell: >>> print('hello\b\b\b\b\bHELLO') hello◙◙◙◙◙HELLO Whereas from cmd: >>> print('hello\b\b\b\b\bHELLO') HELLO FWIW: On Mac OS X 10.9.5 using Python 3.4.2, IDLE's interactive shell (started from the IDLE.app icon): >>>print('hello\b\b\b\b\bHELLO') helloHELLO From the command line using python3 interactive shell: >>>print('hello\b\b\b\b\bHELLO') HELLO Both return a <class 'str'> for type('hello\b\b\b\b\bHELLO') Interestingly, both behave the same when executing: >>>'hello\b\b\b\b\bHELLO' 'hello\x08\x08\x08\x08\x08HELLO' I'm not sure that IDLE is used much on OS X since the Terminal is easily available. Since K12 education may use it, it would be nice to have consistency across the OSes. As far as I understand, Idle doesn’t interpret any terminal control codes apart from a plain \n for a new line. I know it doesn’t do a carriage return for \r either. For clarification, this happens on Windows 7. It's helpful to keep in mind that IDLE is a Tk application written in Python and, as such, depends on Tk to do nearly everything associated with writing to displays and reading from keyboards and pointing devices. If you try outputting the same string using the Tk shell, wish, you'll see exactly the same behavior as you do in IDLE: $ wish % .text insert 1.0 "hello\b\b\b\b\bHELLO" % pack .text And you'll see the same Tk platform differences. With the native OS X Tk's, the backspace characters aren't displayed; with a Linux or OS X X11 Tk, empty box characters are displayed. That may also depend on which font is in use. In any case, the Tk text widget does not behave the same way in this regard as most terminal emulator windows do would do with backspace characters. So it's up to any Tk app to figure out how it wants to deal with them. This issue has come up before for Tkinter in general: back in 2001, effbot suggested some code to search for and edit backspace runs in Tk text. Presumably something similar could be added to IDLE if there was general agreement that this was desirable (after verifying that it works on all of the Tk platforms that IDLE supports). See Ned, Thanks for the detailed example and confirming my gut instinct that Tk was the root cause of the differences seen between the IDLE's Python interactive shell () and the interactive interpreter invoked from the command line (). As an end user learning Python (such as the elementary education market), the current Standard Library documentation on IDLE guides me to the incorrect conclusion that the "Python shell window (aka interactive interpreter)" in IDLE would behave the same as invoking the interactive interpreter from the command line. It seems reasonable to explicitly state in the Standard Library doc that: "In rare cases, such as text handling with certain special characters (i.e. '\b' in a string), the IDLE's interactive Python shell may return a different response than the Python interactive interpreter invoked from the command line. This is due to IDLE's low level dependence on Tk (Tk itself is not part of Python; it is maintained at ActiveState. reference: first paragraph of)." Going back to msdos, there are graphic chars for all 256 bytes, including may single and double line box-drawing chars. Many In Idle, I see 5 solid white circles. In FireFox, there are 5 empty circles (on dark background, which are chr(9689). When I copy from FF back to Idle (3.4.2, Win7), there are 5 of each. I have no idea if the 9689s are on the site or added by FF. Here is another difference. >>> print('\x03') # console ♥ # heart >>> print('\x03') # idle # lower left single line corner in Idle, box on FF Trying to match console-Idle(tk) print output for control chars even on Windows would be tough. --- I have been planning to add a subsection of the doc that mentions known differences between console interpreter and Idle shell. The result of print() is one of them. Another print difference is that Idle displays many unicode chars that Windows replaces with boxes or ?s, depending on the codepage. I closed #24572 as a duplicate of this. It is the same issue except for printing \r instead of \b. These issues are not about responses to keyboard actions when entering text into an Idle editor window. During entry, just about any cntl/alt/function/shift/key combination can be intercepted to and translated to arbitrary action. They are also not about REPL echo. For 3.4+ Win7, both console Python and Shell echo '\b\t\x08\x09' as '\x08\t\x08\t'. Carol's report suggest that the same is true on Mac also. Both issues *are* about print(s, file=outfile), where s is the result of processing all args except 'file' and outfile defaults to sys.stdout. The print call is the same as outfile.write(s), so outfile (and sys.stdout) could be any object with a write method. >>> print('hello\b\b\b\b\bHELLO') helloHELLO >>> import sys; sys.stdout.write('hello\b\b\b\b\bHELLO'+'\n') helloHELLO (I actually see the same circles as Al, but copy-paste does not seem to work as well for me.) So both issues are about the effect of writing 'control chars', in particular \b and \r, to a file. Well, that depends on the file. Some possibilities are copy as is (StringIO), encode and copy (disk file, socket), ignore, display as one glyph, display as multiple chars, non-destructively backspace (like backspace on typewriters and printing terminals and left-arrow elsewhere), or destructively backspace (like backspace on as most (all?) screen keyboards). After non-destructive movement of the 'cursor' position, the possibilities for following graphical chars are overwrite (like typewriters), replace, and insert (the modes sometimes selected by the Insert key). Non-destructive backspace followed by overwrite (meaning 'HELLO' printed on top of 'hello') is the original meaning of 'backspace'. Having said all this, I am sympathetic to the idea that there should be an option to have 'print(ascii_string)' in user code give the same result in the console and Idle. I think this would best be accomplished by a least-common-denominator SimpleTerm subclass of tkinter.Text put somewhere in the tkinter package. (This would be a new issue that should start on python-ideas list.) However, I would consider something Idle specific. Does the following work the same on *nix and Mac as Windows? >>> print('hello\rHELLO') HELLO # helloHELLO with Win7 Idle Are there any control-chars (other than \n) that work might work in the consoles on all three systems and that should be included? Carol, another difference between the Windows console and Idle is that tk and hence Idle support the entire BMP subset of unicode. This should also be mentioned in the doc. Control characters are named control characters because they are control the output device. Different devices have different capabilities and reacts different on the same codes. Windows console, different sorts of Linux terminals and Tk text widget are different devices. Some prints funny characters, others not, some beeps, others not, some interprets particular flavor of ESC sequences, others not, some allows color and positioning, others not. Python can't unify the behavior of these devices without lost most of functionality as it can't unify the behavior of black-white matrix printer, graphical plotter and 24-bit color LCD monitor. I would close this issue as not related to Python. Ser. --- “run ``import idlelib; idlelib.run`` within a try-except statement”: It might be nice to say what exceptions are expected. My guess is ImportError if Idle or TK is not available, or AttributeError if it is but Idle is not running. “Tk handling of ascii control chars”: I presume you mean stdout and stderr handling, which this bug was originally about (or also input, source code, etc as well?). It might be good to say that output of Unix newlines (\n) is guaranteed to be supported. Also might be worth explicitly pointing out that output of CRLFs is not supported, even if os.linesep is "\r\n". In my experiments between Linux and Wine, this does not appear to depend on the OS. I was thinking AttributeError, as mentioned in the previous sentence. But you are correct that ImportError is possible too. Maybe I should just give the code. try: import idlelib idlelib.run running_idle = True except (ImportError, AttributeError): running_idle = False tk does not 'handle' stdout. Idle does, by inserting strings into a tk text widget. tk does not care where inserted chars come from. tk \b behavior is OS dependent. tk may always ignore \r, but this is different from (at least some) consoles. Attempt 2, with and added paragraph. ... * Except for newline ('\n'), tk handling of ascii control chars may depend on the OS and may by different from text consoles. Both are true for backspace ('\b') and the latter for return ('\r'), which tk ignores. These differences noted above are not bugs. If an application is going to be run repeatedly after being developed with Idle, it should usually be run directly, without Idle. (An exception would be non-gui Windows apps that need tk's better unicode support.) That means testing at least once without Idle. --- Thanks for the comments. I wouldn’t say TK ignores carriage returns, though I agree it would be better if Idle stripped them out. Currently I get a glyph displayed for them, similarly to \b. They wouldn’t copy to my clipboard, so I fudged them after pasting here: >>> _ = stdout.write("CRLF\r\n") # Linux: box-drawing corner piece CRLF┌ >>> _ = stdout.write("CRLF\r\n") # Wine: euro sign CRLF€ OK. "Both are true for backspace ('\b') and return ('\r')." Issue #21995 discussed same issue from cause side, as opposed to result. The new section is partly based on what I wrote above. I am not satisfied with it yet. New changeset ac6ade0c5927 by Terry Jan Reedy in branch '2.7': Issue 21995: Explain some differences between IDLE and console Python. New changeset ca6c9cc77c20 by Terry Jan Reedy in branch '3.4': Issue 21995: Explain some differences between IDLE and console Python. Different . Part of this issue is the difference between typing a character at the keyboard, which produces a key event whose effect is determined by key bindings (some default, some added) and inserting a character into a Text widget, which does not produce an event (except, in some sense, \t and \n). Whether or not a key event results in character insertion depends on key bindings. The visual effect of inserted chars other than \t and \n is determined by the font. (I believe I got the above right.) I believe some terminals treat chars coming over the wire the same as those typed. I am not sure what the Win10 console is doing with control-x keystrokes. >>> import sys; out=sys.stdout.write # use direct write to avoid str(), repr() conversion of control chars >>> out('\x03') 1 # The first char is an empty thin box in my IDLE. >>> # type ^C KeyboardInterrupt As for StackOverflow question, there is tkinter.ttk.Progressbar. IDLE can implement functionality similar to what colorama [1] module does on Windows: translate ANSI escape character sequences into corresponding GUI method calls. For example, \b might be implemented using a .delete() call, \r using .mark_set(), etc. [1] While editing 'IDLE-console differences' (added in the patch above) for #35099, I decided that it should be renamed (to, say, 'Executing user code') and limited to the effect of executing user code in IDLE's execution process instead of a standard python process. Except for a intentional change to make developing tkinter code easier, such effects are unintended and possibly bad for developers using IDLE. This issue is about one aspect of how IDLE's Shell, in the GUI process, displays strings and bytes sent from the execution process via sys.stdout and sys.stderr. My previous revision of the title was wrong and my previous patch not directly relevant. I will make a new patch to add a new section ('Displaying user code output'?) describing various aspects of how Shell displays std text output, starting with this one. Most of the differences from various consoles and terminal are intentional and considered to be net positives. While the handling of control characters is inherited from tk, Serhiy and I have claimed on other issues that displaying one glyph per character has advantages for development as well as disadvantages. (Being about to display all but only the BMP subset of unicode is also inherited from tcl/tk.) One of my unposted ideas is to add an option to the run menu to run edited code in the system console/terminal, detached from IDLE, the same as if the file were run from a command line or directory listing. This would bypass both IDLE's execution and display effects. New changeset 75d9d59ab3a372d3d78e6a1f5e9f256e29d0a9a6 by Terry Jan Reedy in branch 'master': bpo-23220: Explain how IDLE's Shell displays output (GH-10356) New changeset 34fcee9ed81c954d6418241ad546f71e103d3b9b by Miss Islington (bot) in branch '3.7': bpo-23220: Explain how IDLE's Shell displays output (GH-10356) New changeset 7476fefb65075161d57435c8dd7e92437578d3c1 by Terry Jan Reedy (Miss Islington (bot)) in branch '3.6': bpo-23220: Explain how IDLE's Shell displays output (GH-10356) (#10369) I merged a first edition of the new section. It does not include Mac behavior, so will need revision. But I want to do some experiments with tk/inter on various systems before doing so. In the patch for #33000, to cover MacOS behavior, I changed the comment about control chars from 'replaced' to 'replaced or deleted' Users can fill in the details by comparing IDLE on their system to a particular console or terminal.
https://bugs.python.org/issue23220
CC-MAIN-2019-18
refinedweb
2,379
64.2
User:Rcygania2/RulesOfThumb A loose collection of SemWeb-related rules of thumb that I would propose as good practice. Contents - 1 Modelling a dataset in RDF - 2 Designing vocabularies and ontologies - 3 Publishing RDF on the Web - 4 Web Architecture Modelling a dataset in RDF Labels - Make sure that everything has an rdfs:label, either directly specified, or by using some property that is defined as a subproperty of rdfs:label - Don't be overly concerned with ambiguous labels; just consider the resource in isolation. That's because labels cannot do the job of disambiguation anyway, and trying to do it results in artificial and awkward labels. - On untyped literals, if the literal is likely to be understood only by speakers of a single language, then add a language tag. If it is likely to work for speakers of many languages, keep it without a language tag. If the file or dataset has only a few exceptions, then it is perhaps better to go for consistency and mark them the same way as the rest of the file. - If you publish in multiple languages, then perhaps it's a good idea to include a plain literal in a “default language” without a language tag, to make SPARQLing easy. Datatypes - Avoid xsd:string. Just use a plain literal. - For numbers, prefer xsd:decimal and xsd:integer because they are not restricted in accuracy/range. - Avoid defining custom datatypes if you can. Better bake the literal semantics into properties. - Issue: SKOS demands custom datatypes for skos:notation. Just ignore that? - For units of measurement, prefer a pattern such as: ex:length [ ex:meter 5.21 ] Designing vocabularies and ontologies @@@ Interesting advice from TimBL: Naming of properties - Properties that point to documents (information resources) should have names that announce this fact, e.g. userProfile, userPage, userList, eventRecord, eventForm - Relationship nouns make good propery names, e.g “parent” is better than “hasParent” or “isParentOf” (as per TimBL) Focus on one problem:: - [from an email to rdf-schema-dev on 2008-04-05] Some random half-formed thoughts: It's good if the vocabulary covers all my needs for a given problem. It's good if the vocabulary doesn't contain much extra stuff that I don't need to solve my problem. It's good if the purpose and coverage of the vocabulary can be conveyed in a short term or phrase (e.g. “document metadata” or “issue tracking”). It's good if the level of abstraction is consistent throughout the vocabulary, e.g. don't mix high-level concepts like Service and Container into your down-to-earth photo annotation vocabulary. Provide excellent documentation:: - [from an email to rdf-schema-dev on 2008-04-05] Random thoughts again: Some introductory narrative. A bunch of good examples for typical usages of the vocabulary. An UML-style overview diagram if the vocab has more than a few classes. Some tutorial-style text. An excellent reference section with all terms and notes about how they are supposed to be used (including notes on what they are NOT supposed to be used for). Namespace URIs From danbri in an email to the DC Architecture list, 30 March 2010 09:40:47 IST: My current preference / advice (for new work) is for the managers of each serious namespace to invest in a distinct domain name for it, and for us as a community to come up with social machinery for 'watching each other's backs' to ensure that the domains are kept in good working order, fees are paid, etc. Sometimes an additional level of indirection can add as much risk as it saves. Initially when I bought xmlns.com I have idea it could be a home for lots of namespaces, and then the more I thought about it, the less I liked that idea. Each new namespace added to the bucket brings some risk to the others using the domain, by adding to the complexity and burden for subsequent maintainers. So I think a proliferation of independent domain names,while painful in its own way, spreads the risk... Later in the thread: Rule of thumb - when wondering what info to include in a namespace URI, ... try to leave *out* as much as possible And even more concise: First rule of namespace URI design "you're more likely to regret things you included, than things you omitted". For hash namespaces, the RDF document containing the vocabulary should be typed as owl:Ontology and should be the target of any rdfs:isDefinedBy statements. Note, the RDF document's URI is the namespace URI without the trailing hash. Publishing RDF on the Web Metadata in RDF documents - Every RDF document has some relation to the thing(s) it talks about. It is useful to explicitly state what that relation is. For example, in my FOAF file I state that I'm both the foaf:maker and the foaf:primaryTopic of the file. Other useful properties are: rdfs:isDefinedBy, foaf:topic. A concrete benefit is that consumers can pick out the “important” things from the graph. HTML descriptions of URI-denoted things - To create trust into the stability, reliability and availability of a URI, its HTML description should explicitly state the URI, it should contain an explicit Statement of Purpose to the effect that the URI is intended to be used as an identifier for the thing, and it should contain a Publisher Identification. It must provide sufficient information to enable human users to know exactly what is being referred to. (This is inspired by Published Subjects.) Content negotiation - The benefit of CN is that all URIs also work in a standard Web browser, not just in RDF-enabled tools and browsers. Thus it's great for authoring and debugging and when your URIs are exposed to a lot of neophytes (e.g. DBpedia, FOAF, DC). On the other hand, content negotiation is very hard to get right, the devil is in the details and it has turned out to be quite an interop hassle in practice. So, CN should be thought of as icing on the cake, but not a requirement for publishing RDF. - Rule of thumb: If your server solution does CN, then do CN. Otherwise, getting it right will be too much effort. - Keep in mind the advice from On Linking Alternative Representations: Provide links between different variants to make them all accessible. This means, if some HTML can be returned in response to RDF/HTML negotiation, there should be an RDF icon nearby, which points to the RDF variant. Blank nodes - Should be avoided in general. Using a blank node is appropriate if the publisher thinks that no one should ever care about this resource except in the context of looking at another, identified, resource in the same RDF document, e.g. a geo:Point that exists solely to give the location of another resource. Another situation where a blank node would be appropriate is when used as an existential variable, but I've never seen them used that way in a Linked Data context. Linked Data - Have rdfs:label (or a subclass thereof) on everything, always - Have rdfs:label for the document URI, always - Have a foaf:primaryTopic triple connecting document URI and main resource, always - Have as much dc: metadata as possible on the document URI - Think hard about possible external links, to other web pages and other RDF documents and entities. Provide as many as possible. These make all the difference. URI design - RDF URIs are always case sensitive, while from HTTP's point of view, some parts of the URI can change without changing any behaviour. So, be clear about the case of your URIs and stick to it once a decision is made. If in doubt, use as much lowercase as possible. (Story: L3S changed case of the domain name in their URIs, broke a Semantic Web Pipes demo.) Web Architecture Information resources - From Harry Halpin: “If there is a URI that is used to identify a resource one would want to make logical statements about, and these statements do not apply to possible representations of that resource, then one should use the "hash" or 303 redirection to separate these URIs.”
http://www.w3.org/wiki/index.php?title=User:Rcygania2/RulesOfThumb&oldid=50944
CC-MAIN-2014-23
refinedweb
1,370
60.24
I have these three models: public class Card { public int ID { get; set; } public string Name { get; set; } public string Class { get; set; } public string Image { get; set; } } public class Deck { public int ID {get; set;} public string Name {get; set;} public string Class {get; set;} public virtual ICollection<DeckCard> DeckCards {get; set;} } public class DeckCard { public int ID {get; set;} public int DeckID {get; set;} public int CardID {get; set;} } I want to use the DeckCard model as a join table essentially. I need to be able to populate it in my DecksController/Index view. Can anyone give me guidance or point me in the right direction? Note that the Card table is a static table (I don't know if that's the correct term for it but it will be populated and unchanged with whatever cards the game currently has (it's a deck building website)). First. You Not need to Create model(DeckCard) for one to many relations so that EF Automatic Create This Table In Your Database. Second. Add or override OnModelCreating Method in your DbContext Class For Example: MyApplicationDbContext.cs public class MyApplicationDbContext : DbContext { public DbSet<Card> Cards { get; set; } public DbSet<Deck> Decks { get; set; } // This is Model Builder protected override void OnModelCreating(DbModelBuilder builder) { modelBuilder.Entity<Card>() .HasRequired<Card>(_ => _.Card) .WithMany(_ => _.Deck); } } DecksController.cs public ActionResult Index() { var model = context.Card.AsNoTracking().Include(_ => _.Decks).ToList(); return View(model); } For join query with Eager loading l use Include(); also, see below Links: Getting more performance out of Entity Framework 6 Entity Framework Loading Related Entities Configure One-to-Many Relationship With your current entity structure, you can write a join between all three data sets and then do a group by on the DeckId and derive the results. I would create 2 view model classes for this grouped data representation for my view. public class DeckVm { public int Id { set; get; } public string Name { set; get; } public IEnumerable<CardVm> Cards { set; get; } } public class CardVm { public int Id { set; get; } public string Name { set; get; } } Now the join var decksWithCards = (from dc in db.DeckCards join d in db.Decks on dc.DeckID equals d.ID join c in db.Cards on dc.CardID equals c.ID select new { DeckId = d.ID, DeckName = d.Name, CardId = c.ID, CardName = c.Name }) .GroupBy(x => x.DeckId, d => d, (ky, v) => new DeckVm { Id = ky, Name = v.FirstOrDefault().DeckName, Cards = v.Select(h => new CardVm { Id = h.CardId, Name=h.CardName}) }) .ToList(); decksWithCards will be a List<DeckVm> which you can pass to your view. You have to make your view strongly typed to List<DeckVm>
https://entityframeworkcore.com/knowledge-base/41535157/how-to-make-a-join-table-using-ef-core-code-first
CC-MAIN-2021-17
refinedweb
447
55.95
PyZone Archive Files Fredrik Lundh | November 2006 A PyZone archive file represents a collection of documents, such as a zone, in a single XML file. Here’s an outline of this format: <zone name='identifier' last- <article name='identifier' category='list of categories'> <title> article title </title> <body> article body text (an XHTML body fragment), minus the title </body> <comments count='count'> (optional) <comment> text </comment> (optional) ... </comments> <terms source='mechanism'> (optional) <term> phrase </term> ... <terms> ... <source> source url </source> (optional) </zone> Elements # The body element contains XHTML body fragments. Link targets in a body can be either usual “http:” targets (for external links), or special “link:” targets, which need to be converted by the renderer. A link target has the following syntax: link:target-domain:identifier where the target-domain is one of - zone - Articles within this zone. - python - The standard Python namespace, with keywords, builtins, and library functions. To identify what a link points to, start by checking the first part against available keywords, builtins, and library modules, in that order. You can then use remaining parts of the link, if any, to drill down further, or just link to the top-level concept. There’s currently no mechanism to distinguish between builtins and modules with the same name (e.g. repr). - svn - The python source code namespace. This is used to refer to Python source files. The identifier is the full path to the file, relative to the source directory. - c - A C function or macro, either part of C’s standard library, or the Python C library. - pep - Python enhancement proposals. The identifier is the pep number, given as a decimal integer. (the number may or may not have leading zeros, so it should be normalized by the link translator). - rfc - Internet RFC. The identifier is the rfc number, given as a decimal integer. The comments element may be included for articles with comments; if present, it usually only contains a count attribute. You can use the source element, if present, to link back to the page that holds the comments. Each article may also have one or more terms elements. These contain terms and keywords, either added manually, or via automatic term extraction mechanisms. Examples # The Python FAQ staging area is available as an archive file. You can get a copy from this URL: (~400k) If you decide to use this for anything except testing, please use a conditional fetch to make sure that you only download it if it has actually changed. You can use something like: import urllib2 def get_signature(uri): request = urllib2.Request(uri) request.get_method = lambda: "HEAD" http_file = urllib2.urlopen(request) return "/".join(( http_file.headers["last-modified"], http_file.headers["etag"], http_file.headers["content-length"] )) to get get the file signature, and do a full fetch if the signature has changed since you last downloaded the file.
http://effbot.org/zone/pyzone-archive.htm
CC-MAIN-2016-30
refinedweb
475
55.24
Java Interoperability Xtend, like Java, is a statically typed language. In fact it completely supports Java’s type system, including the primitive types like int or boolean, arrays and all the Java classes, interfaces, enums and annotations that reside on the class path. Java generics are fully supported as well: You can define type parameters on methods and classes and pass type arguments to generic types just as you are used to from Java. The type system and its conformance and casting rules are implemented as defined in the Java Language Specification. Resembling and supporting every aspect of Java’s type system ensures that there is no impedance mismatch between Java and Xtend. This means that Xtend and Java are 100% interoperable. There are no exceptional cases and you do not have to think in two worlds. You can invoke Xtend code from Java and vice versa without any surprises or hassles. As a bonus, if you know Java’s type system and are familiar with Java’s generic types, you already know the most complicated part of Xtend. The default behavior of the Xtend-to-Java compiler is to generate Java code with the same language version compatibility as specified for the Java compiler in the respective project. This can be changed in the global preferences or in the project properties on the Xtend → Compiler page (since 2.8). Depending on which Java language version is chosen, Xtend might generate different but equivalent code. For example, lambda expressions are translated to Java lambdas if the compiler is set to Java 8, while for lower Java versions anonymous classes are generated. Type Inference One of the problems with Java is that you are forced to write type signatures over and over again. That is why so many people do not like static typing. But this is in fact not a problem of static typing but simply a problem with Java. Although Xtend is statically typed just like Java, you rarely have to write types down because they can be computed from the context. Consider the following Java variable declaration: final LinkedList<String> list = new LinkedList<String>(); The type name written for the constructor call must be repeated to declare the variable type. In Xtend the variable type can be inferred from the initialization expression: val list = new LinkedList<String> Conversion Rules In addition to Java’s autoboxing to convert primitives to their corresponding wrapper types (e.g. int is automatically converted to Integer when needed), there are additional conversion rules in Xtend. Arrays are automatically converted to List<ComponentType> and vice versa. That is you can write the following: def toList(String[] array) { val List<String> asList = array return asList } Subsequent changes to the array are reflected by the list and vice versa. Arrays of primitive types are converted to lists of their respective wrapper types. The conversion works the other way round, too. In fact, all subtypes of Iterable are automatically converted to arrays on demand. Another very useful conversion applies to lambda expressions. A lambda expression usually is of one of the types declared in Functions or Procedures. However, if the expected type is an interface or a class with a single abstract method declaration, a lambda expression is automatically converted to that type. This allows to use lambda expressions with many existing Java libraries. See Lambda Expression Typing for more details. Next Chapter: Classes and Members
https://www.eclipse.org/xtend/documentation/201_types.html
CC-MAIN-2019-39
refinedweb
569
53.31
Building Agreement Around Docker Labels Building Agreement Around Docker Labels Docker labels are a handy way of adding metadata to Docker images. How can we take this to the next level by leveraging these labels? Read on to find out some good ideas. Join the DZone community and get the full member experience.Join For Free Docker has had support for adding labels to images for a while. From this we get some handy features: everything from being able to filter running containers on the command line to providing hints for a scheduler. Since labels are also exposed via the API, the potential for tools to be built atop good metadata is huge. Take the handy label browsing features of MicroBadger, or the ability to provide minimum-resource information to OpenShift. In taking advantage of these upsides, we want to avoid having duplicate metadata for every tool. That means we need to come to some level of agreement about label names and formats for some common attributes. In my DockerCon EU talk at the end of last year, I made a call for a shared community namespace to start building that agreement. You can check out the slides and the video from my DockerCon EU talk, and the one at Configuration Management Camp in January, if you’re interested in the details. Puppet and Metadata Why is Puppet interested in metadata? Well, lots of Puppet’s features rely on low-level tools providing good data. Package managers like RPM, APK, or APT are incredibly useful and powerful. This isn’t because of the file format (often just a tar file), but because of the information in the manifest or spec file that is made available through a standard API. This shared agreement on the package metadata allows for powerful tools like Puppet to be built on top. So obviously we’d be interested in helping build a shared agreement around container labels. Enter Label Schema Enter Label Schema. A number of people within the container community had similar thoughts, and over time a group of users and software vendors came together at events and online. This included folks from Mesosphere and Puppet, as well as Container Solutions, Weave, Microscaling and more. The initial focus has been on a small (and hopefully obvious) set of labels under the org.label-schema namespace. We’re trying to walk before we run, and are mainly focusing on things that people are already doing (just currently under a variety of namespaces and in inconsistent ways). This is definitely a pave-the-cowpaths effort. At Container Camp in London, we announced a release candidate and are seeking much broader input to a set of shared labels. We think we have the scope down for v1, but I’m sure we’ll see some of the details change a little with more input from a wider group of users. What does this mean in practice? Here’s an example of the kind of labels we’ll soon be adding to our images on Docker Hub. LABEL org.label-schema.vendor="Puppet" \ org.label-schema.url="" \ org.label-schema.name="Puppet Server" \ org.label-schema.version="2.6.0" \ org.label-schema.vcs-url="github.com:puppetlabs/puppetserver.git" \ org.label-schema.vcs-ref="ebd57d487d209bf575fcce26335c8f3e0ad09288" \ org.label-schema.build-date="2016-09-8T23:20:50.52Z" \ org.label-schema.docker.schema-version="1.0" The release candidate describes the labels that exist under the org.label-schema namespace, and describes the purpose and format of the values. A really simple example of what that allows straightaway is querying for all your Puppet provided images in one go: docker images --filter "label=org.label-schema.vendor=Puppet" But the real advantages come as we and others build more tools atop this data. And the best thing for the user is that those tools can be interoperable, based on this simple agreement. What's Next? With the release candidate, we’re seeking as much input as possible. We have a mailing list and you can file issues or make pull requests against the label-schema.org GitHub repository. In addition to your feedback about the specification, I'd love to hear your ideas for tools that shared metadata can make possible. If you've already been building something around container labels, then do join the mailing list and let us know. Gareth Rushgrove is a senior software engineer at Puppet. Learn More - Take a look at the release candidate for v1 of Label Schema and let us know what you think. - You can find all of the Puppet images on Docker Hub. - This work is all part of Project Blueshift, the banner under which we are helping customers embrace the latest infrastructure today. Published at DZone with permission of Gareth Rushgrove , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/building-agreement-around-docker-labels
CC-MAIN-2020-16
refinedweb
829
63.49
This was [posted on -ideas][1], but apparently many people didn't see it because of the GMane migration going on at exactly the same time. At any rate, Antoine Pitrou suggested it should be discussed on -dev instead. And this gives me a chance to edit it (apparently it was markdown-is enough to confuse Hyperkitty and turn into a mess). Pickling uses an extensible protocol that lets any class determine how its instances can be deconstructed and reconstructed. Both `pickle` and `copy` use this protocol, but it could be useful more generally. Unfortunately, to use it more generally requires relying on undocumented details. I think we should expose a couple of helpers to fix that: # Return the same (shallow) reduction tuple that pickle.py, copy.py, and _pickle.c would use pickle.reduce(obj) -> (callable, args[, state[, litems[, ditem[, statefunc]]]]) # Return a callable and arguments to construct a (shallow) equivalent object # Raise a TypeError when that isn't possible pickle.deconstruct(obj) -> callable, args, kw So, why do you want these? There are many cases where you want to "deconstruct" an object if possible. For example: * Pattern matching depends on being able to deconstruct objects like this * Auto-generating a `__repr__` as suggested in [Chris Angelico's -ideas thread][2]. * Quick&dirty REPL stuff, and deeper reflection stuff using `inspect.signature` and friends. Of course not every type tells `pickle` what to do in an appropriate way that we can use, but a pretty broad range of types do, including (I think; I haven't double-checked all of them) `@dataclass`, `namedtuple`, `@attr.s`, many builtin and extension types, almost all reasonable types that use `copyreg`, and any class that pickles via the simplest customization hook `__getnewargs[_ex]__`. That's more than enough to be useful. And, just as important, it won't (except in intentionally pathological cases) give us a false positive, where a type is correctly pickleable and we think we can deconstruct it but the deconstruction is wrong. (For some uses, you are going to want to fall back to heuristics that are often right but sometimes misleadingly wrong, but I don't think the `pickle` module should offer anything like that. Maybe `inspect` should, but I'm not proposing that here.) The way to get the necessary information isn't fully documented, and neither is the way to interpret it. And I don't think it _should_ be documented, because it changes every so often, and for good reasons; we don't want anyone writing third-party code that relies on those details. Plus, a different Python implementation might conceivably do it differently. Public helpers exposed from `pickle` itself won't have those problems. Here's a first take at the code. def reduce(obj, proto=pickle.DEFAULT_PROTOCOL): """reduce(obj) -> (callable, args[, state[, litems[, ditem[, statefunc]]]]) Return the same reduction tuple that the pickle and copy modules use """ cls = type(obj) if reductor := copyreg.dispatch_table.get(cls): return reductor(obj) # Note that this is not a special method call (not looked up on the type) if reductor := getattr(obj, "__reduce_ex__"): return reductor(proto) if reductor := getattr(obj, "__reduce__"): return reductor() raise TypeError(f"{cls.__name__} objects are not reducible") def deconstruct(obj): """deconstruct(obj) -> callable, args, kwargs callable(_args, **kwargs) will construct an equivalent object """ reduction = reduce(obj) # If any of the optional members are included, pickle/copy has to # modify the object after construction, so there is no useful single # call we can deconstruct to. if any(reduction[2:]): raise TypeError(f"{type(obj).__name__} objects are not deconstrutable") func, args,_ _ = reduction # Many types (including @dataclass, namedtuple, and many builtins) # use copyreg.__newobj__ as the constructor func. The args tuple is # the type (or, when appropriate, some other registered # constructor) followed by the actual args. However, any function # with the same name will be treated the same way (because under the # covers, this is optimized to a special opcode). if func.__name__ == "__newobj__": return args[0], args[1:], {} # (Mainly only) used by types that implement __getnewargs_ex__ use # copyreg.__newobj_ex__ as the constructor func. The args tuple # holds the type, *args tuple, and **kwargs dict. Again, this is # special-cased by name. if func.__name__ == "__newobj_ex__": return args # If any other special copyreg functions are added in the future, # this code won't know how to handle them, so bail. if func.__module__ == 'copyreg': raise TypeError(f"{type(obj).__name__} objects are not deconstrutable") # Otherwise, the type implements a custom __reduce__ or __reduce_ex__, # and whatever it specifies as the constructor is the real constructor. return func, args, {} Actually looking at the logic as code, I think it makes a better argument for why we don't want to make all the internal details public. :) Here are some quick (completely untested) examples of other things we could build on it. # in inspect.py def deconstruct(obj): """deconstruct(obj) -> callable, bound_args Calling the callable on the bound_args would construct an equivalent object """ func, args, kw = pickle.deconstruct(obj) sig = inspect.signature(func) return func, sig.bind(_args, **kw) # in reprlib.py, for your __repr__ to delegate to def auto_repr(obj): func, bound_args = inspect.deconstruct(obj) args = itertools.chain( map(repr, bound_args.args), (f"{key!r}={value!r}" for key, value in bound_args.kwargs.items())) return f"{func.__name__}({', '.join(args)})" # or maybe as a class decorator def auto_repr(cls): def __repr__(self): func, bound_args = inspect.deconstruct(self) args = itertools.chain( map(repr, bound_args.args), (f"{key!r}={value!r}" for key, value in bound_args.kwargs.items())) return f"{func.__name__}({', '.join(args)})" cls.__repr__ = __repr__ return cls [1]:... [2]:... Some additional things that might be worth doing. I believe this exposes enough to allow people to build an object graph walker out of the `pickle`/`copy` protocol without having to access fragile internals, and without restricting future evolution of the internals of the protocol. See [the same -ideas thread][1] again for details on how it could be used and why. These would all be changes to the `copy` module, together with the changes to `pickle` and `copyreg` in the previous message: class Memo(dict): """Memo is a mapping that can be used to do memoization exactly the same way deepcopy does, so long as you only use ids as keys and only use these operations: y = memo.get(id(x), default) memo[id(x)] = y memo.keep_alive(x) """ def keep_alive(self, x): self.setdefault(id(self), []).append(x) def reconstruct(x, memo: Memo, reduction, *, recurse=deepcopy): """reconstruct(x, memo, reduction, recurse=recursive_walker) Constructs a new object from the reduction by calling recursive_walker on each value. The reduction should have been obtained as pickle.reduce(x) and the memo should be a Memo instance (which will be passed to each recursive_walker call). """ return _reconstruct(x, memo, *reduction, deepcopy=recurse) def copier(cls): """copier(cls) -> func Returns a function func(x, memo, recurse) that can be used to copy objects of type cls without reducing and reconstructing them, or None if there is no such function. """ if c := _deepcopy_dispatch.get(cls): return c if issubclass(cls, type): return _deepcopy_atomic Also, all of the private functions that are stored in `_deepcopy_dispatch` would rename their `deepcopy` parameter to `recurse`, and the two that don't have such a parameter would add it. [1]:... I don't have anything to add on the side of the technical specifics, but I do want to point out another benefit of adding these APIs: a significant improvement in testability, since you will be able to test the reduction and reconstruction behaviours directly, rather than having to infer what is going on from the round trip behavior. Cheers, Nick.
https://mail.python.org/archives/list/python-dev@python.org/thread/AOXKCHRAB5V5AMNINAN45Q5CJNZUEHUR/
CC-MAIN-2021-21
refinedweb
1,278
55.54
Re: [PATCH] emacs: Use `cl-lib' instead of deprecated `cl' I have fixed the remaining issues and added two small commits. See v3. > Or of course you can/should get the tests running locally. The problem was that there are incompatible changes in Emacs 27. I am using Emacs 26 for the time being but will look into these breaking changes later. The first one was easy to work around, but that just revealed a second one... Jonas ___ notmuch mailing list notmuch@notmuchmail.org [PATCH v3 1/3] emacs: Use `cl-lib' instead of deprecated `cl' Starting with Emacs 27 the old `cl' implementation is finally considered obsolete. Previously its use was strongly discouraged at run-time but one was still allowed to use it at compile-time. For the most part the transition is very simple and boils down to adding the "cl-" prefix to some symbols. A few replacements do not follow that simple pattern; e.g. `first' is replaced with `car', even though the alias `cl-first' exists, because the latter is not idiomatic emacs-lisp. In a few cases we start using `pcase-let' or `pcase-lambda' instead of renaming e.g. `first' to `car'. That way we can remind the reader of the meaning of the various parts of the data that is being deconstructed. An obsolete `lexical-let' and a `lexical-let*' are replaced with their regular variants `let' and `let*' even though we do not at the same time enable `lexical-binding' for that file. That is the right thing to do because it does not actually make a difference in those cases whether lexical bindings are used or not, and because this should be enabled in a separate commit. We need to explicitly depend on the `cl-lib' package because Emacs 24.1 and 24.2 lack that library. When using these releases we end up using the backport from GNU Elpa. We need to explicitly require the `pcase' library because `pcase-dolist' was not autoloaded until Emacs 25.1. --- emacs/notmuch-company.el | 5 +- emacs/notmuch-draft.el| 2 +- emacs/notmuch-hello.el| 147 +++--- emacs/notmuch-jump.el | 45 + emacs/notmuch-lib.el | 18 ++-- emacs/notmuch-maildir-fcc.el | 35 +++ emacs/notmuch-mua.el | 76 +++ emacs/notmuch-parser.el | 18 ++-- emacs/notmuch-pkg.el.tmpl | 3 +- emacs/notmuch-show.el | 103 +++-- emacs/notmuch-tag.el | 45 + emacs/notmuch-tree.el | 20 ++-- emacs/notmuch.el | 62 ++--- test/T450-emacs-show.sh | 2 +- test/emacs-attachment-warnings.el | 4 +- test/test-lib.el | 18 ++-- 16 files changed, 304 insertions(+), 299 deletions(-) diff --git a/emacs/notmuch-company.el b/emacs/notmuch-company.el index 3e12e7a9..ac998f9b 100644 --- a/emacs/notmuch-company.el +++ b/emacs/notmuch-company.el @@ -27,7 +27,8 @@ ;;; Code: -(eval-when-compile (require 'cl)) +(eval-when-compile (require 'cl-lib)) + (require 'notmuch-lib) (defvar notmuch-company-last-prefix nil) @@ -65,7 +66,7 @@ (defun notmuch-company (command arg _ignore) (require 'company) (let ((case-fold-search t) (completion-ignore-case t)) -(case command +(cl-case command (interactive (company-begin-backend 'notmuch-company)) (prefix (and (derived-mode-p 'message-mode) (looking-back (concat notmuch-address-completion-headers-regexp ".*") diff --git a/emacs/notmuch-draft.el b/emacs/notmuch-draft.el index e22e0d16..504b33be 100644 --- a/emacs/notmuch-draft.el +++ b/emacs/notmuch-draft.el @@ -152,7 +152,7 @@ (defun notmuch-draft--query-encryption () "Checks if we should save a message that should be encrypted. `notmuch-draft-save-plaintext' controls the behaviour." - (case notmuch-draft-save-plaintext + (cl-case notmuch-draft-save-plaintext ((ask) (unless (yes-or-no-p "(Customize `notmuch-draft-save-plaintext' to avoid this warning) This message contains mml tags that suggest it is intended to be encrypted. diff --git a/emacs/notmuch-hello.el b/emacs/notmuch-hello.el index ab6ee798..bdf584e6 100644 --- a/emacs/notmuch-hello.el +++ b/emacs/notmuch-hello.el @@ -21,7 +21,8 @@ ;;; Code: -(eval-when-compile (require 'cl)) +(eval-when-compile (require 'cl-lib)) + (require 'widget) (require 'wid-edit) ; For `widget-forward'. @@ -47,17 +48,19 @@ (defun notmuch-saved-search-get (saved-search field) ((keywordp (car saved-search)) (plist-get saved-search field)) ;; It is not a plist so it is an old-style entry. - ((consp (cdr saved-search)) ;; It is a list (NAME QUERY COUNT-QUERY) -(case field - (:name (first saved-search)) - (:query (second saved-search)) - (:count-query (third saved-search)) - (t nil))) - (t ;; It is a cons-cell (NAME . QUERY) -(case field - (:name (car saved-search)) - (:query (cdr saved-search)) - (t nil) + ((consp (cdr saved-search)) +(pcase-let ((`(,name ,query ,count-query) saved-search)) + (cl-case field + (:name name) + (:query query) + (:count-query count-query) + (t nil + (t +(pcase-let ((`(,name . ,query) saved-search)) + (cl-case field + (:name name) + (:query query) + (t nil)) (defun notmuch-hello-saved-search-to-plist (saved-search) "Return a copy of SAVED-SEARCH in plist form. @@ -66,7 +69,7 @@ (defun notmuch-hello-saved-search-to-plist [PATCH v3 2/3] emacs: Add simple make target to compile emacs lisp tests --- test/Makefile.local | 4 1 file changed, 4 insertions(+) diff --git a/test/Makefile.local b/test/Makefile.local index 47244e8f..3c043717 100644 --- a/test/Makefile.local +++ b/test/Makefile.local @@ -78,6 +78,10 @@ endif check: test +compile-elisp-tests: + $(EMACS) --batch -L emacs -L test -l notmuch.el -l test-lib.el -f \ + batch-byte-compile test/*.el + SRCS := $(SRCS) $(test_srcs) CLEAN += $(TEST_BINARIES) $(addsuffix .o,$(TEST_BINARIES)) \ $(dir)/database-test.o \ -- 2.26.0 ___ notmuch mailing list notmuch@notmuchmail.org [PATCH v3 3/3] emacs: Use `dolist' instead of `mapcar' for side-effects As recommended by the byte-compiler. --- test/emacs-attachment-warnings.el | 23 +++ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/test/emacs-attachment-warnings.el b/test/emacs-attachment-warnings.el index a23692d7..8f4918ef 100644 --- a/test/emacs-attachment-warnings.el +++ b/test/emacs-attachment-warnings.el @@ -67,16 +67,15 @@ (defvar attachment-check-tests (defun notmuch-test-attachment-warning-1 () (let (output expected) -(mapcar (lambda (test) - (let* ((expect (car test)) -(body (cdr test)) -(result (attachment-check-test body))) - (push expect expected) - (push (if (eq result expect) - result - ;; In the case of a failure, include the test - ;; details to make it simpler to debug. - (format "%S <-- %S" result body)) - output))) - attachment-check-tests) +(dolist (test attachment-check-tests) + (let* ((expect (car test)) +(body (cdr test)) +(result (attachment-check-test body))) + (push expect expected) + (push (if (eq result expect) + result + ;; In the case of a failure, include the test + ;; details to make it simpler to debug. + (format "%S <-- %S" result body)) + output))) (notmuch-test-expect-equal output expected))) -- 2.26.0 ___ notmuch mailing list notmuch@notmuchmail.org [PATCH] emacs/tree: add notmuch-tree-filter This implements the notmuch-tree version of notmuch-show-filter-thread and binds it to the L key. Signed-off-by: William Casarin --- emacs/notmuch-tree.el | 9 + 1 file changed, 9 insertions(+) diff --git a/emacs/notmuch-tree.el b/emacs/notmuch-tree.el index e5c23de2..8f7738d7 100644 --- a/emacs/notmuch-tree.el +++ b/emacs/notmuch-tree.el @@ -328,6 +328,7 @@ FUNC." (define-key map "p" 'notmuch-tree-prev-matching-message) (define-key map "N" 'notmuch-tree-next-message) (define-key map "P" 'notmuch-tree-prev-message) +(define-key map "L" 'notmuch-tree-filter) (define-key map (kbd "M-p") 'notmuch-tree-prev-thread) (define-key map (kbd "M-n") 'notmuch-tree-next-thread) (define-key map "k" 'notmuch-tag-jump) @@ -965,6 +966,14 @@ Complete list of currently available key bindings: (insert (format " (process returned %d)" exit-status))) (insert "\n") +(defun notmuch-tree-filter (query) + "Filter or LIMIT the current tree based on a new query string. + +Reshows the current tree with matches defined by the new query-string." + (interactive (list (notmuch-read-query "Filter tree: "))) + (setq notmuch-tree-query-context (if (string= query "") nil query)) + (notmuch-tree-refresh-view t)) + (defun notmuch-tree-process-filter (proc string) "Process and filter the output of \"notmuch show\" for tree view" (let ((results-buf (process-buffer proc)) -- 2.25.1 ___ notmuch mailing list notmuch@notmuchmail.org Re: Emacs: make browsing URLs friendlier with Helm Hi David,. Yes that patch fixes the issue in Helm. My mistake for searching the list archives for "helm" but not for "ivy"! I had suspected the issue might be similar for other completion frameworks and Keegan confirms this. Ori ___ notmuch mailing list notmuch@notmuchmail.org Re: Emacs: make browsing URLs friendlier with Helm On Friday, 2020-04-24 at 15:46:20 -04, Ori wrote: > > dme. -- Right across from where I'm standing, on the dance floor she was landing. ___ notmuch mailing list notmuch@notmuchmail.org Emacs: make browsing URLs friendlier with Helm
https://www.mail-archive.com/search?l=notmuch%40notmuchmail.org&q=date%3A20200425&a=1&o=newest&f=1
CC-MAIN-2022-33
refinedweb
1,448
51.24
Very strong +1 Advertising On Fri, Feb 2, 2018 at 1:24 PM Reuven Lax <re...@google.com> wrote: > We're looking at renaming the BeamRecord class > <>, that was used for columnar > data. There was sufficient discussion on the naming, that I want to make > sure the dev list is aware of naming plans here. > > BeamRecord is a columnar, field-based record. Currently it's used by > BeamSQL, and the plan is to use it for schemas as well. "Record" is a > confusing name for this class, as all elements in the Beam model are > referred to as "records," whether or not they have schemas. "Row" is a much > clearer name. > > There was a lot of discussion whether to name this BeamRow or just plain > Row (in the org.apache.beam.values namespace). The argument in favor of > BeamRow was so that people aren't forced to qualify their type names in the > case of a conflict with a Row from another package. The argument in favor > of Row was that it's a better name, it's in the Beam namespace anyway, and > it's what the rest of the world (Cassandra, Hive, Spark, etc.) calls > similar classes. > > RIght not consensus on the PR is leaning to Row. If you feel strongly, > please speak up :) > > Reuven > smime.p7s Description: S/MIME Cryptographic Signature
https://www.mail-archive.com/dev@beam.apache.org/msg05154.html
CC-MAIN-2018-09
refinedweb
224
81.73
Revisiting the VI3 SDK? Visit this link first! How long has it been since you have taken a look at the VMware Virtual Infrastructure 3 (VI3) SDK? A month? Two months? Six? Maybe you were originally turned off by the SDK because of its hard-to-use traversal mechanism, or maybe you could never get your application to take less than a good minute to connect to the VI3 SDK web service. If your bad experience was because of the latter, you are in luck. Earlier this fall VMware released a patch for there VimApi namespace that changes the way that the serialization code is generated. The KB article that resolves this issue is located at VimApi. I myself have tried solution #1 and found it to rapidly speed the connection times up. However, truthfully, the process of querying or setting data via the VI3 SDK is still slow. Hopefull VMware is working on this issue and a solution will make it into future releases of ESX. Hope this helps!  Comment on this Post
http://itknowledgeexchange.techtarget.com/virtualization-pro/revisiting-the-vi3-sdk-visit-this-link-first/
CC-MAIN-2017-26
refinedweb
174
73.88
I am trying to get the current running file name in C++. I wrote a simple code that uses both argv[0] and boost current_path() method. The file is compiled into executable file mainWindow. #include "boost/filesystem.hpp" int main(int argc, char* argv[]) { boost::filesystem::path full_path( boost::filesystem::current_path() ); std::cout << full_path.string() << "\n"; std::cout << argv[0] << "\n\n"; return 0; } ../VENTOS/src/loggingWindow/mainWindow /home/mani/Desktop/VENTOS_Redpine argv[0] only contains the command used to execute the the program. This may contain the path. It may contain a relative path. It may contain no path at all. It might not even contain the executable name thanks to symlinks etc.... It might even be empty if the hosting system chooses to provide nothing. It can't be trusted, so you don't want to use this as a basis for evaluating other methods. boost::filesystem::current_path fails you because it only returns the current working directory. This may or may not be the location of the executable because it depends on the directory from which the program was run and whether or not the working directory has been changed by the program. To be honest I'm not sure if there is a sure-fire way to get the process name and path from Boost. There wasn't a few years ago, but time has a way of marching on, you know? There are a slew of questions covering how to get the executable and path (Finding current executable's path without /proc/self/exe looks promising but is stale. That time marching thing again.) but all are platform-specific you may have to do some ifdef or linker wizardry to make this work.
https://codedump.io/share/qglUpuxDgwOS/1/get-the-running-file-name-argv0-vs-boostfilesystemcurrentpath
CC-MAIN-2017-04
refinedweb
288
66.23
Simple partial function application. par is a JavaScript implementation of partial function application (sometimes incorrectly called "currying"). Function#bind? The primary purpose of Function#bind is to create a closure to preserve a function's context (the this variable). Most implementations, including the one in ES 5, also allow partial function application. The functions provided by par also create closures, but they pass their own context along. This means Function#apply, Function#call and method invocation syntax still behave as expected (with the context being set accordingly). If you don't care about contexts (e.g. the function you want to wrap doesn't use this), lpartial and Function#bind can be used interchangeably. There is no native equivalent of rpartial. Another important distinction is that unlike Function#bind, par works in environments that don't support ECMAScript 5, such as legacy versions of Internet Explorer (versions 8 and lower) or Rhino (e.g. the version bundled with Sun JDK 1.6). npm install par git clone parnpm installmake && make dist component install pluma/par Learn more about component. bower install par par module available in the global namespace. var par = ;{return x / y;}var divide4By = ;console; // 0.4var divideBy4 = par;console; // 2.5 var par = ;{// This assumes a modern browser or recent version of IEconsolelog;}; // "I love Internet Explorer!"var sarcastic = par;; // "[sarcasm] I love Internet Explorer! [/sarcasm]" Creates a partially applied function that will append the initial arguments to the left-hand side of the argument list. Creates a partially applied function that will append the initial arguments to the right-hand side of the argument list. Alias for par. This is free and unencumbered public domain software. For more information, see or the accompanying UNLICENSE file.
https://www.npmjs.com/package/par
CC-MAIN-2017-09
refinedweb
289
50.63
Your Account by Tim O'Brien Jack This said, it is pretty heartening to notice how the expert group has widened between JSR-170 and 283: vendors start to take JCR seriously (or they all conspire to make it fail ;-). - - I'm sure that over time and with JSR-283, conventions might emerge that help people tandardize toward a standard set of properties. In fact, the namespaces facility would be a perfect place to start something like this. I'd like to see an independent orgnization create a standard namespace for a specific type of content. There is also a 1.0.1 release coming up with a number of fixes and improvements. Look for the official announcement in a few days. © 2014, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://archive.oreilly.com/pub/post/jsr_170_jcr_content_management.html
CC-MAIN-2014-52
refinedweb
149
65.93
I would like to understand how to reprint multiple lines in Python 3.5. This is an example of a script where I would like to refresh the printed statement in place. import random import time a = 0 while True: statement = """ Line {} Line {} Line {} Value = {} """.format(random.random(), random.random(), random.random(), a) print(statement, end='\r') time.sleep(1) a += 1 Line 1 Line 2 Line 3 Value = 1 Line 1 Line 2 Line 3 Value = 0 end If you want to clear the screen each time you call print(), so that it appears the print is overwritten each time, you can use clear in unix or cls in windows, for example: import subprocess a = 0 while True: print(a) a += 1 subprocess.call("clear")
https://codedump.io/share/LYkPHjpRU8rZ/1/how-to-refresh-multiple-printed-lines-inplace-using-python
CC-MAIN-2017-04
refinedweb
126
65.25
Opened 8 years ago Closed 8 years ago Last modified 7 years ago #9358 closed (fixed) .dates(...) only spitting out a single date, bug in queryset order Description Due to a bug in the add_date_select function (db/models/sql/subqueries.py:400) I am only seeing the latest date (when using SQLite). In [2]: Event.objects.all() Out[2]: [<Event: fsddf on 2009-01-03>, <Event: Fietsen on 2008-10-12>, <Event: Kaas on 2008-10-11>, <Event: Woei on 2008-06-03>] In [3]: Event.objects.dates('event_date', 'day') Out[3]: [datetime.datetime(2008, 6, 3, 0, 0)] Where the latter produces the following SQL code: SELECT DISTINCT django_date_trunc("day", "agenda_event"."event_date") FROM "agenda_event" ORDER BY 1 ASC LIMIT 21 Here, the mysterious ORDER BY 1 clause gets SQLite in confusion. It comes straight from: def add_date_select(self, field, lookup_type, order='ASC'): <snap> self.distinct = True self.order_by = order == 'ASC' and [1] or [-1] We can see that this is indeed the cause by running: In [31]: Event.objects.dates('event_date', 'day').order_by('event_date') Out[31]: [datetime.datetime(2008, 6, 3, 0, 0), datetime.datetime(2008, 10, 11, 0, 0), datetime.datetime(2008, 10, 12, 0, 0), datetime.datetime(2009, 1, 3, 0, 0)] I propose to change the named line into: self.order_by = order == 'ASC' and [field.name] or ['-%s' % field.name] After which the code is working just fine: In [3]: Event.objects.all().dates('event_date', 'day') Out[3]: [datetime.datetime(2008, 6, 3, 0, 0), datetime.datetime(2008, 10, 11, 0, 0), datetime.datetime(2008, 10, 12, 0, 0), datetime.datetime(2009, 1, 3, 0, 0)] FYI: Django version 1.1 pre-alpha, r9231 of trunk Attachments (1) Change History (11) Changed 8 years ago by dokterbob comment:1 Changed 8 years ago by mtredinnick - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 8 years ago by dokterbob I am running sqlite-3.6.2 and pysqlite-2.4.1 on Gentoo prefix on Leopard. About the patch: I agree with you that it shouldn't work, but for me it does. Better than the original code. Remembering from my SQL days, correct code would be something like: SELECT DISTINCT django_date_trunc("day", "agenda_event"."event_date") AS django_date FROM "agenda_event" ORDER BY django_date ASC comment:3 Changed 8 years ago by mtredinnick - Owner changed from nobody to mtredinnick - Status changed from new to assigned - Triage Stage changed from Unreviewed to Accepted As I'm sure you realise, "works for me on one particular database known for taking a bunch of shortcuts" isn't a way to validate a patch, since we have to generate correct SQL so that we run on all databases. Looks like a nice recent version of SQLite, though, so we need to work around it until SQLite learns that part of the spec. comment:4 Changed 8 years ago by dokterbob I'll see if I can find the time to look up the 'official' way we're supposed to do this stuff in SQLite. For now I think other users might actually be helped by my works-for-me patch, allthough I should have realized it's not proper SQL. :) comment:5 Changed 8 years ago by mtredinnick The point is that I don't want to have code that does things way for SQLite and some other way for other databases. The ordering and column selections pieces of the query construction are relatively separated and having to put part of the ordering construction into the db/backends/* part of the code is a bit fugly. Fortunately, we can avoid it. As you note, we can use a named alias for the output column gets around this, so I'll add that into the query. That will also avoid a problem with "order by 1" problems that we've seen on older SQLites on Windows (particularly the SQLite shipped with the Python 2.5 binary). Short version: no need to worry about an SQLite-specific workaround. Assuming the aliased query actually works on SQLite (does it?), I'm going to take that approach. comment:6 Changed 8 years ago by drbob@… - Patch needs improvement set I have just done a few hours of messing around with the Django db code and it seems to me that naming the date column will require an fairly fundamental change in the way .order_by() parses its parameters (right now it only looks in model.opts and extra_select). I can confirm however that working with named aliases DOES work. Perfectly. :) This again gave me the idea to put the Date() in extra_select instead of select, which then automatically does the naming and also allows for named sorting. The trouble here though is that: - Setting select to [None] (line 381) causes the code not to query the database at all. This seems like bad behaviour to me (sometimes you only want extra data) but this is design decision which seems not related to the current bug. - Putting the Date() function directly in extra_select does not call its as_sql method. Directly calling the as_sql function from add_date_select would get us into trouble with pickling, I suppose. It is very likely that similar problems will occur with sorting on aggregate and other 'intelligent' columns as well. Possible solutions for the problem include: - Upgrading to an SQLite 3.6.4 (maybe even 3.6.3). In this version the described problem is fixed. This seems a good workaround solution for now. - Enabling queries for empty selects and using named extra_select columns for all kind of 'intelligence' like this. This means we have to call .as_sql() in extra_select columns. Hereby we implement this kind of functionality in a consistent way (alas, extra_select is what we would have used before .dates() existed), so we would not have to do any .order_by() workaround. Here .dates would simply be a piece of DB abstraction upon the extra_select clausule. django/db/models/sql/subqueries.py: 372 def add_date_select(self, field, lookup_type, order='ASC'): 373 """ 374 Converts the query into a date extraction query. 375 """ 376 result = self.setup_joins([field.name], self.get_meta(), 377 self.get_initial_alias(), False) 378 alias = result[3][-1] 379 select = Date((alias, field.column), lookup_type, 380 self.connection.ops.date_trunc_sql) 381 self.select = [select] 382 self.select_fields = [None] 383 self.select_related = False # See #7097. 384 self.extra_select = {} 385 self.distinct = True 386 self.order_by = order == 'ASC' and [1] or [-1] comment:7 Changed 8 years ago by mtredinnick comment:8 Changed 8 years ago by mtredinnick comment:9 Changed 8 years ago by mtredinnick - Resolution set to fixed - Status changed from assigned to closed In view of the fact that this only affects one release of SQLite and a fixed version was brought out specifically for this bug three weeks later, I'm happy with just documenting around that version of SQLite. The current code would require some reasonable upheaval to avoid this bug in the upstream code just for that one version in one backend. It's not worth it at the moment. comment:10 Changed 7 years ago by anonymous - milestone post-1.0 deleted Milestone post-1.0 deleted "Order by 1" is perfectly valid SQL and not at all mysterious. We need some more details here to work out if it's a bug in a particular version of SQLite or in SQLite in general and what a reasonable way to work around it will be. Ordering by event_date, as you suggest is not, from memory, going to be valid SQL, since all columns that appear in an ordering statement must appear as output columns in the select statement (and we're not selecting event_date, but something derived from event_date, so it's an input column and not an output column). What version of SQLite are you using? On what platform?
https://code.djangoproject.com/ticket/9358
CC-MAIN-2016-36
refinedweb
1,306
65.62
Useful Rubyism's Part 1 Useful Rubyism's Part 1 Join the DZone community and get the full member experience.Join For Free Ruby is the first language I have programmed in that makes me truly enjoy the development process. It's infinitely flexible, object-oriented, and has a lot of great Rubyism's that make it both unique and powerful. I will demonstrate a few of my favorite Rubyism's over the next few articles. Class Method Overloading Don't you just feel dirty every time you have to create a new class type in order to properly encapsulate a custom method that works with native tpes? Or even worse, if you're not into encapsulation, you create a helper function. Well, if you use Ruby, there are no worries. We can simply create our own class methods for the native class types or even overwrite existing class methods. class String def shuffle self.split(//).sort_by{rand}.join end end puts "My Life Is Better Because of Ruby".shuffle #=> "I iya sMeuB t r ceLoBtfeefuReybs" One-Liners Ruby is the king (or queen?) of one-liners. Because nearly everything in Ruby is object-oriented, you can basically write your entire program in one line of code! While that may be a bit extreme, creating one-liners can make your program much more readable and maintainable, especially if you're creating new methods as mentioned above. #Convert sentence to CSV and capitalize each column tbdata = "Ruby is awesome" tbdata.split(/ /).map{|word| word.capitalize}.join(',') #=> "Ruby,Is,Awesome" More to Come! Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/useful-rubyisms-part-1
CC-MAIN-2019-09
refinedweb
281
55.64
Hi there, I have adapted the nmaster ntile layout for the current dwm hg tip. Maybe it could be useful for someone else. You should modify config.h to include (after setting RESIZEHINTS): #define NMASTER 1 #include "nmaster.c" Add a new "ntile" layout Layout layouts[] = { ... { "-|=" , ntile }, ... }; and, finally, two new keybinds: { MODKEY|ShiftMask , XK_j , setnmaster , "+1" } , { MODKEY|ShiftMask , XK_k , setnmaster , "-1" } , I have adapted neither cpt nor tilecols. Of course, thanks for your patch pancake. Kind regards, Nibble Received on Sun Mar 30 2008 - 01:41:26 UTCReceived on Sun Mar 30 2008 - 01:41:26 UTC This archive was generated by hypermail 2.2.0 : Sun Jul 13 2008 - 15:29:14 UTC
http://lists.suckless.org/dwm/0803/5314.html
CC-MAIN-2021-17
refinedweb
115
68.36
28 February 2010 6 comments Zope, Python, IssueTrackerProduct IssueTrackerMassContainer is a simple Zope product that is used to put a bunch of IssueTrackerProduct instances into. It doesn't add much apart from a nice looking dashboard that lists all recent issues and then with an AJAX poll it keeps updating automatically. But what it was doing was it recursively put together all issues across all issue trackers, sorting them and then returning only the first 20. Fine, but once the numbers start to add up it can become a vast sort operation to deal with. In my local development copy of 814 issues, by the use of pympler and time() I was able to go from 7 Mb taking 2 seconds down to using only 8 Kb and taking 0.05 seconds. Here's the initial naive version of the code: def getRecentIssues(self, since=None, recursive=True, batch_size=20, batch_start=0): """ return a list of all the most recent issues """ issues = self._getAllIssues(self.getRoot()) if since is not None: ... # checking variable since issues = [x for x in issues if float(x.getModifyDate()) > since] issues.sort(lambda x,y: cmp(y.getModifyDate(), x.getModifyDate())) return issues[int(batch_start):int(batch_size)] So, instead of making a fat list of issue objects, just turn it into a list of the things we really need. The second version: def getRecentIssues(self, since=None, recursive=True, batch_size=20, batch_start=0): """ return a list of all the most recent issues """ root = self.getRoot() issues = self._getAllIssues(root) issues = [(x.getModifyDate(), '/'.join(x.getPhysicalPath())) for x in issues] if since is not None: ... # checking variable since issues = [(t,i) for (t,i) in issues if float(t) > since] issues.sort() issues.reverse() issue_paths = [x[1] for x in issues[int(batch_start):int(batch_size)]] return [root.unrestrictedTraverse(p) for p in issue_paths] The issue method getModifyDate() returns a Zope DateTime instance which is ridiculously nifty datetime implementation but it sucks in memory use and performance. See this blog about how it sucks compared to mxDateTime and standard lib datetime. So, this time, turn it into a float and then sort. Final version: def getRecentIssues(self, since=None, recursive=True, batch_size=20, batch_start=0): """ return a list of all the most recent issues """ root = self.getRoot() issues = self._getAllIssues(root) issues = [(float(x.getModifyDate()), '/'.join(x.getPhysicalPath())) for x in issues] if since is not None: ... # checking variable since issues = [(t,i) for (t,i) in issues if t > since] issues.sort() issues.reverse() issue_paths = [x[1] for x in issues[int(batch_start):int(batch_size)]] return [root.unrestrictedTraverse(p) for p in issue_paths] And the results for my local copy of 818 issues?: Version 1: 7842736 bytes (7.5 Mb) 2.1547999382 seconds Version 2: 834880 bytes (0.79 Mb) 0.210245847702 seconds Version 3: 87448 bytes (85 Kb) 0.0538010597229 seconds Granted, Zope will release this memory by the garbage collector but why even let it get that big if you have concurrent hits or if anything gets stuck for longer than necessary. Python 2.4 can free memory used but not return it to the operating system to reuse unless the process dies (this was fixed in Python 2.5). That's a memory usage improvement of about 90 fold and a speed improvement of about 40 fold. Fry-IT has huge issuetracker instances and at the time of writing keeps 6668 "active" issues across all projects. Follow @peterbe on Twitter It seems like you might be able to do a bit better with generators and the "key" argument to the sort functions: def key(item): return (x.getModifyDate(), '/'.join(x.getPhysicalPath())) return sorted( (item for item in self._getAllIssues(root)), key=key, reverse=True)[int(batch_start):int(batch_size)] If you really wanted to be efficient, you could use a generator heapq.nlargest to avoid building the full list at all. But I guess a list of floats and strings probably isn't so bad. Thanks for the tip. Sorting 6668 tuples only takes about 0.03 seconds on my laptop :) My current problem when I turn the list of issue objects into a list of tuples. That's taking more than 3 seconds. I'm going to solve it by remembering what the oldest timestamp was of those shown the first time and, as a cached value, use that to never look into containers older than that. Nice one. pympler looks awesome, thanks for the example. Hello. We are using a quite heavily customized version of an older IssueTracker at Pilot Systems. We have a very huge amount of issues : around 250 trackers with more than 50 000 issues in total. To be able to cope with that amount of data, we are using the Zope catalog as much as we can, for any dashboard-like feature we developed for our needs. Did you try using a catalog with an index on the date and doing a catalog(sort_on = getModifyDate)[:20] ? This should be even more efficient since it doesn't load from the ZODB the full Issue objects, and much simpler than having to fiddle with hand-optimizing every single sorting. Hi Gael, First of all I can't maintain two ZCatalog instances since the will only index in the nearest ZCatalog instance object which is the one inside the tracker. What I could do however, is use each trackers ZCatalog to pull out the 20 most recent issues which means that if you have 10 trackers the total number of things to worry about is 20 x 10 brains which I then sort in an aggregate and from those 20x10 brains I pick out the first 20 and turn them into objects. I'll try that instead. When time allows.
https://www.peterbe.com/plog/massive-improvement-on-sorting-a-fat-list
CC-MAIN-2019-09
refinedweb
958
64.41
So there is an exercise that says I should create a program to measure which function is faster,a normal one,or a inline one. Here's the code: #include <iostream> #include <string> #include <assert.h> #include <ctime> using namespace std; clock_t t; inline void f1(){ t=clock()-t; if(t!=0) cout << "f1 " << t << endl; } void f2(){ t=clock()-t; if(t!=0) cout <<"f2 " << t << endl; } int main() { for(int i = 0;i<10000;i++){ t=clock(); f1(); } for(int i = 0;i<10000;i++){ t=clock(); f2(); } } The problem is f1 appears 4 times and f2 appears 2 times.As you can see I set the functions so they'll show text only if the time difference is bigger than 0. Why does the inline function get executed slower?! Shouldn't it be faster?
http://www.gamedev.net/topic/640834-shouldnt-inline-functions-be-faster/
CC-MAIN-2014-52
refinedweb
137
82.65
react-router React的完善的路由库 React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought. 文档 & 帮助 - Guides and API Docs - Change Log - Stack Overflow - Codepen Boilerplate Please use for bug reports Note: If you are still using React Router 0.13.x the docs can be found on the 0.13.x branch. Upgrade information is available on the change log. For questions and support, please visit our channel on Reactiflux or Stack Overflow. The issue tracker is exclusively for bug reports and feature requests. 浏览器支持 We support all browsers and environments where React runs. 安装 $ npm install history [email protected] Note that you need to also install the history package since it is a peer dependency of React Router and won't automatically be installed for you in npm 3+. <script src=""></script> 你可以在 window.ReactRouter找到库。 它是什么滋味? import React from 'react' import { render } from 'react-dom' import { Router, Route, Link } from 'react-router' const App = React.createClass({/*...*/}) const About = React.createClass({/*...*/}) // etc.> <Route path="/" component={App}> <Route path="about" component={About}/> <Route path="users" component={Users}> <Route path="/user/:userId" component={User}/> </Route> <Route path="*" component={NoMatch}/> </Route> </Router> ), document.body) 谢谢 Thanks to our sponsors for supporting the development of React Router. React Router was initially inspired by Ember's fantastic router. Many thanks to the Ember team. Also, thanks to BrowserStack for providing the infrastructure that allows us to run our build in real browsers.
https://wohugb.gitbooks.io/react-webpack-cookbook/content/react-router/index.html
CC-MAIN-2021-04
refinedweb
269
57.67
Data is categorized according to different types. A Topic represents a thing (such as a physical entity, a substance or a building). Each Topic is associated with a number of Types, for example the Salvador Dali topic might be associated with Painting and Surrealism. A group of related Types are organized into a Domain. For example, the books domain contains types for book, literature subject and publisher. Domains, Types and Properties are further organized into namespaces which can be thought of top-level containers to reference items. For example, the /ennamespace contains human-readable IDs and URLs for popular topics. Similarly, the /wikipedia/ennamespace gives a key that can be used to formulate a URL representing the corresponding article on Wikipedia. This extra structure allows precise concepts to be expressed, with no ambiguity. FreeBase has a number of web services you can use to interrogate the database. The web services accept and return JSON. The most basic services just give you information about the status and version in JSON format. The Text.JSON package provides a method for reading / writing JSON in Haskell. This, coupled with Network.HTTP, makes making basic requests very simple. More advanced requests use the MQL to express queries to Freebase. The underlying database is best thought of as a directed graph of nodes and relationships. Each node has a unique identifier and a record of who created the node. A node has a number of outgoing edges which are either relationships between other nodes of a primitive value. For example the /en/iggy_popnode might be linked to the /en/the_passenger/via the >/music/album/artistproperty. Relationships between nodes can have property values associated with them, for example /en/the_passengermight be linked to /music/track/lengthwith 4:44. The Query Editor provides a way of running these queries in a web browser and this, together with the Schema Explorer allow you to get explore the data available in Freebase. Queries are expressed as JSON and consist of a JSON object from which the blanks are filled in. As an example, if I submit the following query with a blank array, then the returned value has the null filled in with the correct details (apparently Indiana Jones was released 23rd May 1984). { query: { type: "/film/film" name: 'Indiana Jones and the Temple of Doom', initial_release_date: null } } The Freebase documentation gives an example of a basic web app built using PHP and I thought it'd be a good learning exercise to convert this over to a functional programming language. Haskell has quite a few web frameworks, including Snap, HappStack and Yesod. Yesod had the strangest name, so it seemed like the logical choice. Yesod uses some extensions to Haskell, Type Families, quasi-quoting and Template Haskell. Quasi-quoting and TH are particular exciting as they allow a HAML like syntax to be used as statically compiled Haskell. Each Yesod application has a site type that is passed to all functions and contains arguments applicable to the whole site, such as database connections and global settings. URLs are handled by a routing table which, again, is statically compiled and means you can not create an invalid internal link. Neat! For the basic album lister app, we define three really simple routes. A home page, a URL to call to get the albums, and a link to the static files. Note that the static files is again checked at compile time. If the relevant JS/CSS files don't exist, then the application fails to compile! The getHomeRroute handler (which ends in capital R by convention) simpler just renders a Hamlet template. A little bit of JavaScript in script.jsmakes an Ajax call to retrieve the list of bands. And the basic example from the MQLRead documentation is converted over. I've only spent a few hours with Yesod but I'm definitely impressed so far, good documentation and easy to get something simple done! The complete code is on my github page
http://www.fatvat.co.uk/2010/08/freebasing-with-haskell.html
CC-MAIN-2013-20
refinedweb
664
55.64
The discussion of primitive data types in Chapter 5 mentions that you can create a string using an array of type char. However, Java has a better way of dealing with strings—the String class in the java.lang package, which is always imported, and hence always available to you. You have already seen examples that use this String class, so now we will discuss it in more detail, as well as the methods that are supplied with it. Why does Java use a class for strings instead of a built-in data type? This is because built-in data types or primitives are restricted to the few operators built into the language for math and manipulation purposes (like + and -). You spend so much time preparing, converting to and from, manipulating, and querying strings, that you gain significant programmer productivity from a class (versus a built-in primitive data type) given all the methods that can be supplied with it for common string operations. For example, how many times have you written justification, trimming, and conversion code for text strings? Why not have language-supplied methods to save you the drudgery? In RPG, such language-supplied functionality comes in the form of op-codes and built-in functions. In an object-oriented language, it comes in the form of methods on a simple self-contained class. Indeed, it is through string classes in object-oriented languages that you first start to appreciate the power and elegance of objects. This great ability to encapsulate the useful methods or functions commonly needed by programmers into a class data type drives home the potential of objects and OO. For example, to support a new operation, you need only add a new method, versus designing a new operator into the language. An important note about strings in Java is that the language designers slightly relaxed their strict object-oriented rules to allow strings to be concatenated directly with a built-in operator—the plus operator (+). They also allowed an intuitive means of instantiating strings that does not force you to use formal object-instantiation syntax (as they did for compile-time arrays). This underlies the importance of strings and string manipulation to every programmer and their invariable prominence in every program. The more intuitive and convenient it is to use strings in a language, the more accepted that language is by programmers. Certainly, Java's goal is to "keep it simple." If you prefer to stick to more formal rules, though, you can do that, too. In other words, if you prefer to instantiate a string in the formal way and use a method call, concat, to concatenate two strings, instead of just using the + operator, that's fine. For example, you can use an intuitive style like this: String text1 = "George"; String text2 = "Phil"; String finalText = text1 + " and " + text2; System.out.println(finalText); Alternatively, you can use a formal style like this: String text1 = new String("George"); String text2 = new String("Phil"); String finalText = new String(text1); finalText = finalText.concat(" and "); finalText = finalText.concat(text2); System.out.println(finalText); The output of both examples is "George and Phil," as you would expect. These examples show that there are two ways to initialize strings—by implicitly equating them to string literals or by explicitly allocating an instance of the String class using the new operator. Once you create your strings, you can manipulate them using the many methods supplied with the String class. These samples also highlight the two means of adding strings together in Java, either via the intuitive plus operator or via the concat method of the String class. Note that in the latter, the string passed as a parameter is appended to the string represented by the String object. The actual String target object is not affected. Rather, a new String object is created and returned. Thus, the method call has no side effects. Can you guess the output of the following? String finalText = "George"; finalText.concat("and Phil"); System.out.println(finalText); The answer is "George", not "George and Phil" as you might initially expect. Do not get caught by this common mistake. Another important consideration is string equality in Java. You cannot use the equality operator (==) to compare two string objects, like this: if (text1 == text2) Rather, you must use the equals method, which returns true if the target string and the passed-in string are equivalent, like this: if (text1.equals(text2)) ... This is the single most common mistake when using the String class. The problem is that the use of natural instantiation and the plus operator for concatenation tend to make you think of strings as primitive data types in Java. However, they are actually objects of the String class—that is, object reference variables. Like all object reference variables, they actually contain a memory address of the class instance, and as such, the equality operator only tells you if the two variables refer to the same address, which they almost never do. The operator does not have the intelligence to make a decision about whether all characters are the same and the strings are the same length. Rather, the code inside the equals method is required for this. You are all the more prone to this pitfall as an RPGIV programmer, because RPG IV has a free-form IF op-code syntax that does allow you to compare two strings (alphabetic fields) using the equality operator, as in: IF STRING1 = STRING2 Take care in your Java coding to avoid this bug, as you will not notice it for a while, given that the compiler will not complain about it. Equality testing of object references is legal, after all, for those cases when you want to know if two variables actually do refer to the same allocated instance in memory. RPG does not have a pure string data type similar to the String class in Java. In fact, in RPG III, you were quite restricted in character field functionality. You only had room for six character literals, and so you often had to resort to compile-time arrays to code longer literals. You had the MOVE, MOVEA, and MOVEL op-codes, and the CAT, CHECK, CHEKR, COMP, SCAN, SUBST, and XLATE op-codes. In RPG IV, life is much better! You define a string field as a fixed-length character field: DmyString S 20A INZ('Anna Lisa') In this example, the first field, mystring, is defined as a 20-character alphanumeric field, and is initialized to an initial value of 'Anna Lisa' using the INZ keyword for initializing. The keyword area of the D-spec is from column 44 to 79, giving lots of room, and literals that don't fit even in this can be continued by placing a plus or minus character in the last position and continuing the literal on the next line. Once you have defined a character field, you can perform operations on it by using the same op-codes as in RPG III, plus the EVAL and EVALR op-codes, and many handy built-in functions, as you shall see. Also, you can use the plus operator for concatenation and the free-form IF statement can do comparisons of strings. You can assign a string to a variable using the traditional MOVE and MOVEL op-codes or the new free-format EVAL or EVALR op-codes with the assignment statement, as shown in Listing 7.1. Listing 7.1: Assigning Strings with EVAL and EVALR in RPG IV D string1 S 10A D string2 S 10A C EVAL string1 = 'abc' C EVALR string2 = 'abc' The EVAL op-codes are only for assignment, but are preferred to the older MOVE op-codes because they have a free-format factor-two from column 36 to 79, and can continue onto the next lines, where they get all columns from 8 to 79. This means you can write expressions that are as long as you want! The difference between EVAL and EVALR is that the latter right-justifies the target string into the source field. So, in the example in Listing 7.1, string1 contains 'abc ' while string2 contains ' abc'. In addition to assigning literals or other fields to string fields, you can assign special figurative constants to them to initialize the values. Specially, you can assign *BLANKS to blank out the whole field, or *ALL'X...' to assign and repeat whatever literal you specify for x..., for example: C EVAL string1 = *BLANKS C EVAL string2 = *ALL'AB' In this example, string1 becomes ' ' while string2 becomes 'ABABABABAB'. Note that these figurative constants can also be specified at declaration time on the D-spec as the parameter to the INZ keyword. RPG III and IV use single quotes to delimit a string literal, while Java uses double quotes. Also, strings in RPG are fixed in length and always padded with blanks if needed to achieve this length. So, if you display the contents of the myString field in the example, you would see 'Anna Lisa '. This is different than Java, where the size of the string is always exactly as long as the text last assigned to it. You never explicitly specify the length of a string in Java, this is done implicitly for you, for example: String name = "Phil"; // new string, length four name = "George"; // assigned to a new value, length six The length of a string is exactly the length of its current contents, which can be changed with an assignment statement. The new value is never padded or truncated by Java. If you want padding with blanks, you have to explicitly specify the blanks in your literal, like this: String myString = "Phil "; // new string, length eight In fact, the idea of dynamically sized string fields that always hold the exact text they have been assigned, instead of being padded, is so wonderful that RPG itself now supports it as well. As of V4R2, you can code the VARYING keyword on a character field to have it behave similar to Java, as in: DmyString S 20A INZ('Anna Lisa') D VARYING You still have to code a length, but that is used only as the maximum so the compiler knows how much memory to allocate. If you used DSPLY to print the contents of this field to the console and put quotes around the result, you would see 'Anna Lisa'—exactly the value it was initialized to, with no padding. This is nice. In both RPG and Java, you might want to include an embedded quote. Since these are the delimiters, you have to use special syntax to embed them. In RPG, you double-up the embedded quote, like this: DwithQuote S 20A INZ('Phil''s name') In Java, you use the same backslash escape sequence you saw in Chapter 5: String withQuote = "Phil says " do you get it? ""; Finally, remember that every character in Java requires two bytes of storage, even in String objects. This does not affect you as a programmer, other than to make life much easier when supporting multiple languages or countries, since you do not have to worry about codepage conversions or CCSIDs. We mention it because RPG IV also now has this capability, as of V4R4. Rather than using an A for the data type column, you can code a C, identifying this field as containing Unicode characters. You can convert between character and Unicode fields, and vice versa, using regular EVAL, EVALR, MOVE, and MOVEL operations, or the new %UCS2 built-in function. We don't cover the details of Unicode fields in RPG IV here, but if you are writing international applications, you should have a look. Further, if you are planning to have RPG code that calls Java code, or vice versa, then the Unicode data type is a perfect match for Java's String objects when passing parameters between the languages. Table 7.1 compares all available string-manipulation op-codes and built-in functions in RPG IV to those methods available in Java. Java offers more functionality than shown here, as you will see shortly. The next sections examine each of the operations listed in Table 7.1 and give examples of them for both RPG and Java. Where there is no matching method in Java, as in the case of XLATE and CHECK, you will learn how to write a method yourself to simulate the function. Let's start with string concatenation for both RPG and Java, looking at an example to illustrate the use of this function. Suppose you have two fields: one contains a person's first name and the other contains the last name. You need to concatenate the two fields and print out the result. This is easy to do in both languages, since both support concatenating strings. In RPG, you use the CAT op-code, as shown in Listing 7.2. Listing 7.2: Concatenating Strings in RPG Using the CAT Op-code D first S 10A INZ('Mike') D last S 10A INZ('Smith') D name S 20A INZ(' ') C* Factor1 OpCode Factor2 Result C first CAT last:1 name C name DSPLY This example uses two fields, first to represent the first name and last to represent the last name. It declares and initializes these fields right on the D-spec. However, in more complex applications, these fields may be read from the screen or from a file on disk. They can even be passed in via the command line. The C-spec uses the CAT op-code to concatenate field first to field last in factors one and two. The result of the concatenation is placed in the field name, which is specified in the result column. Notice also that:1 is specified in factor two in order to tell the compiler to insert one blank between the field values when concatenating them. The DSPLY op-code displays the value of name, which is "Mike Smith", as you would expect. Listing 7.3 illustrates the same example written in Java. Listing 7.3: Concatenating Strings in Java Using the CONCAT String Method public class Concat { public static void main(String args[]) { String first, last, name; first = "Mike"; last = "Smith"; name = first.concat(" ").concat(last); System.out.println("The name is: " + name); } } // end class Concat This example uses the String object to declare all the string variables, namely: first, last, and name. As mentioned earlier, by declaring the string variables and initializing them, all three string objects are created and initialized (that is, no new keyword is required to instantiate the object). Because you want to append a blank to the first name and then add the last name to that, two concat operations are necessary; there is no equivalent to RPG's :1 trick. The double concatenation could have been done in two steps, but we chose to do it in one. We can do this because the concat method returns the concatenated string, which can then be used directly as the object of a subsequent concat operation. Notice that we use the string to be concatenated as the object in the concat call, and pass in as a parameter the string to concatenate to it. The result is returned from the call, which is placed in the name variable. Then, the result is displayed using the println method. Double quotes are used around the blank literal, but because it is only one character, single quotes could also have been used, as there are two overloaded concat methods—one that takes a string and one that takes a single character. Did you notice another concatenation in the previous example? If you did, you have a sharp eye. The println method concatenates the string literal "The name is :" to the object reference variable name using the plus operator. This is another way of concatenating two strings. In fact, this is a fast way of concatenating two strings in an expression for both RPG and Java. RPG supports the same + operator for concatenation in an expression. Table 7.2 replaces the CAT op-code of the previous example with the EVAL op-code, and the concat Java method with the + operator. Clearly, the use of the plus operator is a plus for programmers! Next, let's take a look at the substring op-code in RPG and the corresponding substring method in Java. In RPG, you use the SUBST operation code to extract a substring from a string starting at a specified location for a specified length, as shown in Listing 7.4. Listing 7.4: Substringing Strings in RPG Using the SUBST Op-code D* 12345678901234567890123456789 DWhyJava S 30A INZ('Because Java is for RPG pgmrs') D first S 4A D second S 6A D third S 3A D sayWhat S 15A C 4 SUBST WhyJava:9 first C 6 SUBST WhyJava:14 second C 3 SUBST whyJava:21 third C EVAL sayWhat = C first+' '+second+' '+third C sayWhat DSPLY C EVAL *INLR = *ON This example takes a string with the value "Because Java is for RPG pgmrs" and retrieves different strings from it to make up the string "Java is for RPG". To do this, it declares three different character fields and a field to store the results. As the example illustrates, the SUBST op-code takes the number of characters to substring in factor one, and takes the source as well as the starting position for the retrieval in factor two. For example, the first SUBST operation receives the value Java and places it in the result field first. When all of the values have been retrieved, the concatenation operator concatenates all fields. Finally, the result of the field is displayed using the DSPLY operation code. The result is "Java is for RPG". Because of RPG's fixed-field padding rules, we had to declare all the fields to be the exact length needed to hold the result. As an alternative, we could have coded them all to be a maximum length, such as 20, and then used the VARYING keyword on their D-spec definitions. Listing 7.5 illustrates an equivalent example, written in Java, using the substring method of the String class. The parameters for the substring method have the beginning index value as the first parameter and the ending index as the second parameter. There are some subtle differences compared to RPG: Otherwise, the logic is similar to RPG's and easy enough to follow. There is also a second version of the substring method, which takes as input only one parameter—the starting position (again, zero-based). This returns a string containing all characters from that starting position to the end of the target string. Listing 7.5: Substringing Strings in Java Using the SUBSTRING String Method public class Substring { public static void main(String args[]) { String whyJava, first, second, third, sayWhat; // 01234567890123456789012345678901234 whyJava = "Because Java is for RPG Programmers"; first = whyJava.substring(8,12); second = whyJava.substring(13,19); third = whyJava.substring(20,23); sayWhat = first + " " + second + " " + third; System.out.println(sayWhat); } } // end class Substring Why is it that the second parameter has to be one past the actual ending column? It turns out this makes some processing easier. For example, you don't normally know exactly what column to start the substring operation in, and what column to end it in. Instead, you will often determine this programmatically, by searching for a specific delimiting character such as a blank or comma or dollar sign. This is done in Java using the indexOf method that you'll see shortly, but it is very simple to use. You give it the character to find, and it returns the zero-based position of that character (and you can specific what position to start the search). Well, when you are searching for the ending delimiter, you will subsequently be substringing up to the character position right before that delimiter, so this funny rule of Java's substring method makes it a little easier. For example, we could have written the first substring example from Listing 7.5 as this: first = whyJava.substring(8,whyJava.indexOf(' ')); We don't want to string you out, so we'll move on now to the next topic. In RPG IV, you can also use the %SUBST built-in function to accomplish the same thing in expressions. The syntax of this is %SUBST(string:start{:length}). The parameters are the same as the op-code SUBST, as you see in the following example: EVAL secondWord = %SUBST('RPG USERS':5:5) EVAL secondWord = %SUBST('RPG USERS':5) In both cases, the result is "USERS". Note the similarities to Java's substring method, notwithstanding the "gotcha's" mentioned. One of the more commonly used functions in almost all languages is the ability to search one string for the occurrence of another. For example, you might have a string like "Java is for RPG users" and you want to find the position of the substring "RPG". Once you know this, you can simply extract the characters found after it. By searching for substrings, you can avoid hard-coding the substring parameters when you don't know the positions at compile time. You can use the SCAN operation code for this, as Listing 7.6 illustrates. Listing 7.6: Scanning Strings for Substrings in RPG Using the SCAN Op-code D* 123456789012345678901 Dstr S 40A INZ('Java is for RPG users') Didx S 3P 0 C 'RPG' SCAN str idx C idx DSPLY C EVAL idx = %SCAN('RPG':str) C idx DSPLY C EVAL *INLR = *ON This example defines a string field named str and initializes it to "Java is for RPGusers". It finds the location of the substring "RPG" in the main string using SCAN, placing the desired substring in factor one, the source string in factor two, and the resulting field to contain the numeric index value in the result column. When the operation is executed, idx will contain the position where the substring was found, which is 13 in this example. Note that RPG allows you to specify the start location for the search in the second part of factor two. If the start location is not specified, as in this example, the default is to start at the first character. This example also shows the %SCAN built-in function, which offers the same functionality as the op-code, but can be used in free-format expressions. The second DSPLY operation also results in 13. You could specify an optional :start parameter on the %SCAN function. For Java, this is a simple operation, since Java supplies an indexOf method in its String class, as shown in Listing 7.7. This method takes one or two parameters. The first is the string you are looking for, and the optional second is the start location of the search (the character position). Again, this is a zero-based position, not a one-based position as in for RPG. If you do not specify the start location, as with RPG, the default start value will be set to the first character position (that is, zero). In the example, the value that is printed is 12 (zero-based, again, so 12 is the thirteenth character). The indexOf method returns -1 if the given substring is not found in the input String object. Listing 7.7: Scanning Strings for Substrings in Java Using the indexOf String Method public class Scan { public static void main(String args[]) { // 012345678901234567890 String str = new String("Java is for RPG users"); int idx = str.indexOf("RPG"); System.out.println("RPG occurs at: " + idx); } } In addition to indexOf, Java also supplies a handy lastIndexOf method, which will search backwards for a given substring. Again, it has an optional second parameter for specifying where to start the search, but this time the search continues backward from that start position. Finally, both indexOf and lastIndexOf support either a string parameter, as you have already seen, or a single character parameter when searching for an individual character, as in: int dollarPos = myString.indexOf('$'); Trimming is the process of removing leading or trailing blanks from a string, and both languages have built-in support for it. In RPG, three built-in functions make it easy to trim blanks. Listing 7.8 shows the %TRIM built-in function. Listing 7.8: Trimming Blanks in RPG Using the %TRIM Built-in Function D leftright S 40A INZ(' Java is for- D RPG users ') D temp S 40A C* C EVAL temp = %TRIM(leftright) + '.' C temp DSPLY C EVAL *INLR = *ON This example uses %TRIM on the EVAL op-code to trim both leading and trailing blanks in the field leftright, placing the result in temp. Note that it concatenates a period to the trimmed string so that you can see the trimmed result before RPG pads it back out to the declared length of 40. After the operation, the field contains the following: "Java is for RPG users. " In Java, this task is also easy to accomplish, using the appropriately named trim method, as shown in Listing 7.9. Listing 7.9: Trimming Blanks in Java Using the trim String Method public class Trim { public static void main(String args[]) { String str = " Java is for RPG users "; str = str.trim(); System.out.println("Trimmed: '" + str + "'"); } } // end class Trim The result is "Trimmed: 'Java is for RPG users'". Note again that Java does not pad strings out to some pre-declared length, so we did not have to concatenate a period. Easy stuff. However, what if you only want to remove leading blanks? Or trailing blanks? In RPG it is very easy, since the language supports two additional built-ins, %TRIML and %TRIMR, for trimming left (leading) and right (trailing) blanks. However, Java has only the TRIM method, and unfortunately, no TRIML and TRIMR methods. It is not brain surgery or VCR programming to write your own code to do this, however, and you will do so by the end of the chapter, after learning about the StringBuffer class. Determining the length of a string, to decide if it is empty or needs truncation or padding, is a simple task in both languages. In RPG IV, you simply use the %LEN built-in function, specifying a field or string literal or built-in function as a parameter, as shown in Listing 7.10. Listing 7.10: Getting the Length of a Field in RPG IV D aString S 40A INZ(' Java is forD RPG users ') D len1 S 9 0 D len2 S 9 0 C* C EVAL len1 = %LEN(aString) C EVAL len2 = %LEN(%TRIM(aString)) C len1 DSPLY C len2 DSPLY C EVAL *INLR = *ON This code shows two examples of the %LEN built-in function—one takes a character field as input and the other takes a nested built-in function call %TRIM as input. The displayed output of this program is 40 and 21. Why 40 for the first one, even though the string on the INZ keyword is 35 long? Because the field is declared as 40 characters long. If you were to add the VARYING keyword to the definition of aString, you would get 35 from the %LEN built-in function. In Java, you invoke the length method, as shown in Listing 7.11. When you run this example, you get 35 and 21. Remember that in Java, characters are two bytes long, because they are Unicode characters. However, the length returned by the length method is the number of characters, not the number of bytes—the latter is actually two times the former. The same is true for RPG Unicode fields and the %LEN built-in function. All String class methods that take or return an index number deal with the character position, not the byte offset, so you rarely need to worry about the fact that characters are two bytes long. Listing 7.11: Getting the Length of a String in Java public class Length { public static void main(String args[]) { String aString = " Java is for RPG users "; int len1 = aString.length(); int len2 = aString.trim().length(); System.out.println(len1); System.out.println(len2); } } // end class Length So far, you have seen RPG op-codes compared to available Java methods. As you recall from Table 7.1, a few RPG op-codes or built-ins are simply not available in Java. For example, the XLATE op-code in RPG has no apparent equivalent in Java—at least, not yet. What to do in this case? Write your own method! First, let's review the RPG support. Listing 7.12 shows an example of the RPG XLATE op-code. Listing 7.12: Translating Characters in RPG Using the XLATE Op-code D from C CONST('GPR4') D to C CONST('VAJA') D source S 4A INZ('RPG4') D target S 4A C from:to XLATE source target C target DSPLY C EVAL *INLR = *ON As you know, XLATE translates the source string in factor two to another sequence of characters, depending on the from and to strings specified in factor one. The result of this translation is placed in the result field. In particular, all characters in the source string with a match in the from string are translated to the corresponding characters in the to string. The rule is that the lengths of the from, to, and source strings must all be the same. The example translates R to J, P to A, G to V, and 4 to A, respectively. With the value RPG4 in the source string specified in factor two, the result is JAVA after the operation. Note that we decided to make the from and to fields constants, using RPG IV's syntax for constants. Java has no corresponding method in its String class, but it does have a related method named replace, which takes two character parameters as input. It replaces all occur- rences of the first character in the target string object with the second character. It sounds similar to RPG's XLATE, except that replace only replaces a single character, not a string of characters. Not to worry—you can write your own Java method that emulates RPG's XLATE op-code by using the replace method repeatedly, once for each character in a given string of from characters. What is interesting is that you cannot extend String (discussed in a later chapter) because the Java language designers made it final, preventing this. Thus, String augmentation methods like this will be created as traditional, standalone functions—that is, they will be defined as static, and take as parameters whatever they need. But even static methods must exist in a class, so we create them in an arbitrary class named RPGString, which is where all of the remaining methods in this chapter will go. Listing 7.13 is the Java equivalent to RPG's XLATE op-code. (For consistency, we have named the method xlate.) The required parameters are, of course, the source string to be translated, followed by the from and to strings, and finally the start position, where the translation should start. To be consistent with Java's string methods, this start position is zero-based. To be consistent with RPG, the start position value should be optional, defaulting to the first character if not passed. To support an optional parameter at the end of the parameter list in a Java method, simply supply a second method with the same name that does not specify or accept that last parameter, which we have done. This second overloaded method can simply call the first full version of the method and pass in the default value for the missing parameter. In this case, this is zero for the first character. Listing 7.13: Translating Characters in Java Using the xlate Method public class RPGString { public static String xlate(String source, String fromChars, String toChars, int start) { String resultString; // minimal input error checking if (fromChars.length() != toChars.length()) return new String("BAD INPUT!"); if (start > source.length() || start < 0) return new String("BAD INPUT!"); // first off, get the substring to be xlated... resultString = source.substring(start); // xlate each fromChars char to same pos in toChars for (int i = 0; i < fromChars.length(); i++) resultString = resultString.replace(fromChars.charAt(i), toChars.charAt(i)); // now append xlated part to non-xlated part resultString = source.substring(0,start) + resultString; return resultString; } // end xlate method public static String xlate(String source, String fromChars, String toChars) { return xlate(source, fromChars, toChars, 0); } // end xlate method two } // end RPGString class The code in the first and primary xlate method is reasonably straightforward—you first check to make sure the input is valid, then create a substring of the source that excludes the characters before the given start position. Next, for every character in the from string, you use the String class replace method to replace all occurrences of that character with the character in the corresponding position of the to string. Finally, you append that to the substring of the source up to the start position, and return this resulting string. To get an individual character out of a string, you must use the charAt method and supply the zero-based index of the character. To test this, we supply a main method in our class so that we can call it from the command line and see the results. (This idea of supplying a main method for test cases for of your handwritten classes is a good idea, by the way.) Listing 7.14 shows the test case, which tests both versions of the method—first without specifying a start position, and then with specifying a start position. Listing 7.14: Testing the xlate Method public static void main(String args[]) { /*——————————————————*/ /* Test xlate method */ /*——————————————————*/ // "012345678901234567890"; String src="RPGP is for you Joo!"; String from = "RPG"; String to = "Jav"; System.out.println("Input string : '" + src + "'"); src=RPGString.xlate(src, from, to); System.out.println("Output string1: '" + src + "'"); from = "J"; to = "t"; src=RPGString.xlate(src, from, to, 16); System.out.println("Output string2: '" + src + "'"); } //end main method Note the calls to xlate are qualified with the class name RPGString. Because this method is in the same class as the method being called, this is not necessary. However, we did this to illustrate how code in any other class would have to look. The example translates the characters in RPG to the corresponding characters in JAVA, and then translates the character J to the character t, starting at position 16 (again, zero-based). If we started at zero, the first J would be translated, which is not what we want. The final result is as follows: Input string : 'RPGP is for you Joo!' Output string1: 'JAVA is for you Joo!' Output string2: 'JAVA is for you too!' One function you'll often require is string translation to uppercase or lowercase. There is no language-supplied function for this in RPG, but there is in Java. However, you can accomplish this task in RPG using, once again, the XLATE op-code, using all lowercase characters for the from string and all uppercase characters for the to string, as shown in Listing 7.15. Listing 7.15: Translating Case in RPG Using the XLATE Op-code D LOWER C 'abcdefghijklmnopqrstuvwxyz' D UPPER C 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' D string S 30A INZ('Java is for rpg users') C string DSPLY C LOWER:UPPER XLATE string string C string DSPLY C EVAL *INLR = *ON Two named constant strings, LOWER and UPPER, are defined to contain all the lowercase characters and their matching uppercase characters. To illustrate how this works, a field named string is defined containing the string "Java is for rpg users". Next, the XLATE op-code is used with the value 'LOWER:UPPER' in factor one and the string variable in the result column. After executing this operation, the result is the whole string in uppercase: 'JAVA IS FOR RPG USERS'. Need we say this is a great opportunity for a procedure? It could be named, say, Upper-Case, and take a string as input and return the uppercase version. Of course, it would only support single-length character fields unless you used VARYING length fields and specified the OPTIONS(*VARSIZE) keyword for the procedure parameter. In Java, converting strings from uppercase to lowercase and vice versa is even simpler, as Java supplies intuitive methods to do this. The first is toUpperCase, which translates the target String object to all uppercase. The second is toLowerCase, which translates the target String object to all lowercase. For example, see Listing 7.16. Listing 7.16: Translating Case in Java Using the toUpperCase and toLowerCase Methods String str = new String("Java for RPG Programmers"); str = str.toUpperCase(); System.out.println("String in uppercase: " + str); str = str.toLowerCase(); System.out.println("String in lowercase: " + str); Compiling and running this example results in the following: String in uppercase: JAVA IS FOR RPG USERS String in lowercase: java is for rpg users As with translating characters, RPG has language support to easily handle checking for the existence of characters, while Java does not have a supplied method. RPG has two op-codes, CHECK and CHECKR. These operations verify that each character in a given search string specified in factor one is among the characters in the base string specified in factor two. Each character in the given search string is compared with all of the characters specified in the base string. If a match exists, the next character is verified. Otherwise, the index value indicating the position of the unmatched character in the search string is placed in the result field, and the search is stopped. If a match is found for all characters in the search string, zero is returned in the result field. In the case of CHECK, verification of characters begins at the leftmost character, whereas for CHECKR, verification starts at the rightmost character. Listing 7.17 shows two examples, one for CHECK and the other for CHECKR. Listing 7.17: Verifying Character Existence in RPG Using the CHECK and CHECKR Op-codes D NUMBERS C CONST('0123456789') D pos S 9 0 D base S 7A INZ('*22300*') C NUMBERS CHECK base:2 pos C pos DSPLY C NUMBERS CHECKR base:6 pos C pos DSPLY C EVAL *INLR = *ON Checking characters is most commonly used to check if a numeric field contains alphanumeric characters or vice versa. The example in Listing 7.17 checks to see if a string of numeric digits contains any alphanumeric characters. It starts by defining the set of numeric digits, zero through nine, and storing them in the constant field NUMBERS. The character field base is initialized to string "*22300*" and is the field to be checked. After executing the CHECK operation, the value in the result field is 7. It is not 1, as you may have expected, because the second part of factor two, which is the start position, contains 2. This tells the compiler to start verification at the second position. The following CHECKR operation code uses similar parameters as the CHECK op-code, except that the start position is specified to be six, which is the position to start from. If a start position was not specified, it would default to the ending character position. The result after executing the CHECKR is one in the pos result field. Note also that the result field for both operations can be a numeric array. As mentioned earlier, Java does not have methods similar to CHECK and CHECKR for character verification. As with character translation, you need to write your own methods to take care of this. Listing 7.18 contains the code to accomplish character verification. (Note that the same class name RPGString is used as in the previous example, thus building up a number of useful static string methods in this same class.) Listing 7.18: Verifying Character Existence in Java Using check Methods public static int check(String search, String base, int start) { // minimal error checking if (start >= base.length() || start < 0) return -2; // scan each char of base for match in search... for (int idx = start; idx < base.length(); idx++) if (search.indexOf(base.charAt(idx)) == -1) return idx; // return constant indicating match found for all return -1; } public static int check(String search, String base) { return check(search, base, 0); } Two check methods are defined to simulate RPG's CHECK op-code: one takes a starting position index and the other does not. The latter simply calls the former with zero for the starting position. The algorithm first checks the validity of the input parameters, then scans each character in the given base string for an occurrence in the given search string. If all characters have a match, the special constant -1 is returned. Otherwise, the index position of the first non-matching character in the base string is returned. To be consistent with Java String class methods, the methods accept a zero-based starting position and return a zero-based index position. Because of this, they cannot return zero when all characters match, as RPG does, because zero is a valid index position. For this reason, they return -1. Listing 7.19 defines two more methods, this time to simulate CHECKR with and without a starting position parameter. These are similar to the check methods; the only changed lines are shown in bold. Basically, you need to loop backwards through the base string, and you need to default to the last character position when no start position parameter is passed. Listing 7.19: Verifying Character Existence from the Right in Java with checkR Methods public static int checkR(String search, String base, int start) { // minimal error checking if (start >= base.length() || start < 0) return -2; // scan each char of base for match in search... for (int idx = start; idx >= 0; idx—) if (search.indexOf(base.charAt(idx)) == -1) return idx; // return constant indicating match found for all return -1; } public static int checkR(String search, String base) { return checkR(search, base, base.length()-1); } Listing 7.20 shows the code in main to test these methods. Listing 7.20: Testing the check and checkR Methods in Java String digits = "0123456789"; String test = "*22300*"; int result; result = RPGString.check(digits, test); System.out.println("result is: " + result); result = RPGString.check(digits, test, 1); System.out.println("result is: " + result); result = RPGString.checkR(digits, test); System.out.println("result is: " + result); result = RPGString.checkR(digits, test, 5); System.out.println("result is: " + result); Compiling and running it gives the following: result is: 0 result is: 6 result is: 6 result is: 0 The usual purpose in using the RPG CHECK op-code is to verify that a given string contains numeric data. This is possible in Java with our new check method. However, for completeness, we show you another way. The Character class discussed in Chapter 5 is a class version of the char data type in Java. You will find in this class a number of worthwhile methods, including one named isDigit. This is a static method that takes any single character and returns true if the character is a digit from zero to nine. So, to test a whole string, you can simply call this method for each of the characters, as shown in the isNumeric method in Listing 7.21. Listing 7.21: A Method for Testing if a String Is All Numeric Digits public static boolean isNumeric(String inputString) { boolean allNumeric = true; for (int idx=0; idx Recall the discussion at the beginning of the chapter about the concat method, and how it does not affect the String object on which you invoke it, but rather returns a new String object. You have seen that this is also true of other string manipulation methods like toUpperCase and replace. This is because the String class is immutable—that is, you cannot change a String object, you can only use methods that return new String objects. In many cases, the original string object is no longer used and is swept up by the garbage collector. This read-only behavior of strings can have performance implications for calculations that do a lot of string manipulating. For example, this is true of any code that builds up a string by concatenating characters inside a loop. For this reason, Java supplies a second string class named StringBuffer that is mutable—it can be changed directly using supplied methods. This class is completely independent of the String class. That is, although some methods are common between the two, StringBuffer also has its own unique set of methods for altering the object directly, which you will see shortly. If you need to dynamically change the strings in your method, you should use StringBuffer instead of String. Both classes support methods to convert back and forth between them. For example, you can use a StringBuffer object to do your string manipulation, and then, once the string is complete, convert it back to a String object using the toString method supplied in StringBuffer for this purpose. In fact, this conversion back and forth between String and StringBuffer classes has the added advantage of allowing you to use methods available in both classes by simply converting from one class to the other. You will almost always want to accept and return String objects, not StringBuffer objects, from your methods, so this conversion is often done at the beginning and end of your method. For example, methods for significant string manipulations might follow this format: public String workOnString(String input) { StringBuffer workString = new StringBuffer(input); // do manipulation work on the workString variable return workString.toString(); } How do you declare a string using the StringBuffer class? You must use the formal way, with the new operator, optionally specifying a string literal or String object as input: StringBuffer aName = new StringBuffer("Angelica Farr"); There are no language extensions to allow intuitive instantiation like '= "this is a string"' as there are for Strings. Similarly, there are no language extensions for easy concatenation of StringBuffer objects using the plus sign as there are for Strings. (Of course, use of + is allowed between StringBuffer objects inside the System.out.println parameter string, as it is for all data types.) To concatenate strings to a StringBuffer object, use the append method: StringBuffer quotedName = new StringBuffer("George"); quotedName.append(" and ").append("Phil"); Notice how this method does have a side effect on the object it works against, so you do not need to equate the result to another variable as you would with the concat method in the String class. This method returns the current StringBuffer object, so you can string together multiple method calls in one statement, as shown here. The append method is also convenient in that there are many overridden versions of it supporting all the primitive data types as the parameter, and conversion to a string literal is done for you, for example: boolean flag = true; StringBuffer output = new StringBuffer("flag value = ").append(flag); System.out.println(output); // "flag value = true" This results in the output "flag value = true". The append method also accepts String objects as input. In fact, it will accept any object as input! For objects, it simply calls the object's toString method to convert it to a string. You do not always want to change your string by appending to it, sometimes you want to insert new strings into the middle of it. The StringBuffer class supports this with an insert method, with a number of overridden methods similar to append, allowing all manner of data types to be inserted after being converted to string format. All versions of the insert method take an integer insertion-point index as the first parameter and the actual string or other data type to be inserted as the second parameter, as in: StringBuffer string1 = new StringBuffer("GORE"); string1.insert(1,"E"); string1.insert(4,"G"); System.out.println(string1); This results in the output "GEORGE". Notice the insertion point given is the character position before the desired insertion point. In addition to append and insert, there are setChar and getChar methods for changing a particular character value in place and retrieving the character value at a specified zero-based position. A method named getChars can return a substring, but in the form of a character array, not a String. This could, however, be converted to a StringBuffer by using the version of append or insert that accepts a character array as input. There is also an interesting method named reverse that reverses the content of a string, such that "Java" would become "avaJ". Presumably, there is a use for this somewhere! Maybe it's used for writing out the letters "ECNALUBMA" on the front of ambulances! StringBuffer objects support the notion of capacity—a buffer length that is greater than or equal to the length of the string literal contained in the StringBuffer. Behind the scenes, the StringBuffer class uses an array of characters to hold the string. The array is given an initial default size, and as the string grows, the array often needs to be reallocated with a bigger size. This behind-the-scenes work is done for you, but there are methods to explicitly set the size (i.e., the capacity) of this buffer. You can thereby optimize performance by predicting the final size you will eventually require, minimizing the need for costly reallocations. It is by judicious use of capacity planning that you can most benefit from using a StringBuffer as a scratchpad to build up a computed string. When instantiating an empty StringBuffer, you can specify the initial capacity by passing in an integer value, like this: StringBuffer largeString = new StringBuffer(255); Note that the default capacity for an empty StringBuffer object is 16. Aside from setting the initial capacity at instantiation time, you can also use the ensureCapacity method to ensure that the current buffer is at least as large as the number you pass as an argument. If it is not, the buffer size or capacity is grown to the size you specified. Despite the method name, ensureCapacity does not return a boolean value—in fact, it does not return anything. There is also a method for returning the current capacity, which is named capacity. It takes no arguments, and returns an integer value. This notion of capacity and its two methods is also available in other classes in Java that contain growable lists, such as the Vector class discussed in Chapter 6. While you have ensureCapacity and capacity methods for working with a StringBuffer object's buffer size, you also have setLength and length methods for working with the actual string's size. This is always less than or equal to the capacity. You can use setLength to grow or shrink the string's size, effectively padding it (with null characters, which are hex zeros) or truncating it. Note that if you set the length of the string to be greater than the capacity, the capacity is automatically grown, just as it is when you grow a string past its capacity using append. On the other hand, if you truncate a string, the capacity is not reduced. Listing 7.22 will help you see the difference between capacity and length. Listing 7.22: The Difference between Length and Capacity in the StringBuffer Class public class TestStringBuffer { public static void main(String args[]) { StringBuffer test1 = new StringBuffer(20); // capacity test1.append("12345678901234567890"); // string System.out.println(); System.out.println("String = "" + test1 + """); System.out.println("Capacity = " + test1.capacity()); System.out.println("Length = " + test1.length()); test1.setLength(50); // string length System.out.println("———————————————-"); System.out.println("String = "" + test1 + """); System.out.println("Capacity = " + test1.capacity()); System.out.println("Length = " + test1.length()); test1.setLength(10); // string length System.out.println("———————————————-"); System.out.println("String = "" + test1 + """); System.out.println("Capacity = " + test1.capacity()); System.out.println("Length = " + test1.length()); } // end main method } // end TestStringBuffer class Running this class results in the following: String = "12345678901234567890" Capacity = 20 Length = 20 ——————————————————————————————-- String = "12345678901234567890 Capacity = 50 Length = 50 ———————————————-———————————————- String = "1234567890" Capacity = 50 Length = 10 The length is always the current number of characters held in the buffer, while the capacity is the maximum number of characters the buffer can hold without having to be resized internally. Notice how calling setLength with a value of 50 extends the actual string itself to be 50 characters long, but it uses the null character (all zeros) to pad, so you never see the ending quote. You'd have to subsequently replace all those null characters with blanks to get what you probably wanted. Also notice how the capacity always increases in size when needed, while it never decreases in size automatically. Now let's go back to the trim operation and see how to implement trim-right and trim-left functionality in Java. A previous section showed how both RPG and Java have built-in functions for simultaneously trimming both leading and trailing blanks. It also mentioned that RPG has built-in functions for explicitly stripping either trailing-only or leading-only blanks, using the %TRIMR or %TRIML functions. In Java, however, you must implement this functionality yourself if you need it, which you will see shortly. First, Listing 7.23 reviews these built-in functions in RPG. Listing 7.23: Trimming Leading and Trailing Blanks in RPG with %TRIML and %TRIMR D input S 16A INZ(' Java for U ') D result S 16A C EVAL result = %TRIML(input) + '.' C result DSPLY C EVAL result = %TRIMR(input) + '.' C result DSPLY C EVAL *INLR = *ON The input string is " Java for U ". Predictably, the result after %TRIML is "Java for U .", and the result after %TRIMR is " Java for U." Note that the concatenating of the period after the trim right lets you see the result before RPG pads the result field back to its declared length. That would not be necessary if the VARYING keyword had been defined on the result field. It is that easy to trim leading or trailing blanks in RPG, since the language directly supports it. Java, on the other hand, has no supplied methods in either its String or StringBuffer classes, so you must write your own. With the use of the StringBuffer class previously discussed, however, this is not very difficult. You again create two methods as static, pass in as a parameter the string to operate on, and place the methods in an RPGString class. To be consistent with RPG, call the two methods trimr and triml. Because you will be doing a reasonable amount of manipulation on the strings, start out in both cases by creating a StringBuffer temporary object from the given String object, and in both methods end by using the toString method of StringBuffer to convert the scratchpad object back to a String that can be returned. The trimr method is the easiest, as you just need to find that last non-blank character and truncate the StringBuffer at that point, using the setLength method. Listing 7.24 shows this. Note that this method has to test for the case when it is given a string that is all blanks, in which case it just does setLength(0). Listing 7.24: Trimming Trailing Blanks in Java with a trimr Method public static String trimR(String input) { if (input.length() == 0) // error checking return input; StringBuffer temp = new StringBuffer(input); int idx = temp.length()-1; // find last non-blank character while ( (idx >= 0) && (temp.charAt(idx) == ' ') ) idx—; // truncate string if (idx >= 0) temp.setLength(idx+1); else temp.setLength(0); return temp.toString(); } // end trimR method The triml method is a little more complicated because it involves shifting the characters left, from the first non-blank character. This is best accomplished by brute-force, character-by-character copying. The most efficient way to do this is to use a StringBuffer object that has been initialized to a sufficient capacity, as with the temp2 variable in Listing 7.25. Listing 7.25: Trimming Leading Blanks in Java with a triml Method public static String trimL(String input) { if (input.length() == 0) // error checking return input; StringBuffer temp1 = new StringBuffer(input); int idx, idx2; // find last non-blank character idx = 0; while ( (idx < temp1.length()) && (temp1.charAt(idx) == ' ') ) idx++; // truncate string if (idx < temp.length()) { // copy characters to new object int newSize = temp1.length() - idx; StringBuffer temp2 = new StringBuffer(newSize); for (idx2 = 0; idx2 < newSize; idx2++, idx++) temp2.append(temp1.charAt(idx)); return temp2.toString(); } else { temp1.setLength(0); return temp1.toString(); } } // end trimL method Again, some additional complexity is added by the need to handle the case when an all-blank string is given as input. As usual, we write test-case code in the main method to drive and demonstrate these new methods, including the all-blank test case, which is shown in Listing 7.26. Listing 7.26: Testing the triml and trimr Methods System.out.println("———————————-———————————"); System.out.println("Testing trimR method..."); System.out.println("———————————-———————————"); String paddedString = " Java For RPG Programmers "; String trimmedRight = RPGString.trimR(paddedString); System.out.println(""" + trimmedRight + """); String blankString = " "; trimmedRight = RPGString.trimR(blankString); System.out.println(""" + trimmedRight + """); System.out.println("——————————————————-———-"); System.out.println("Testing trimL method..."); System.out.println("—————————————————-————-"); paddedString = " Java For RPG Programmers "; String trimmedLeft = RPGString.trimL(paddedString); System.out.println(""" + trimmedLeft + """); trimmedLeft = RPGString.trimL(blankString); System.out.println(""" + trimmedLeft + """); The result of compiling and running this is what you would expect: ——————————————————————- Testing trimR method... ———————————-——————————— " Java For RPG Programmers" "" ———————————-——————————— Testing trimL method... ———————————-——————————— "Java For RPG Programmers " "" Easy enough? Not really, we admit, but then again, now you can simply call these methods. However, for completeness, we should also mention there are alternatives that are more inefficient but easier to code. To trim only leading or only trailing blanks, for example, you could use the String trim method if you first take care to add a non-blank character to the appropriate end of the string before the trim operation, then remove it after, like this: String input = " a test "; String trimmedLeft, trimmedRight; trimmedLeft = (input + '.').trim(); trimmedLeft = trimmedLeft.substring(0,trimmedLeft.length()-1); trimmedRight = ('.' + input).trim(); trimmedRight = trimmedRight.substring(1); Often, when writing string-parsing code, you will want to extract individual words. Java recognizes this need and supplies a utility class in the java.util package named StringTokenizer that does this automatically. This is a good class to know about, as it can save significant coding effort in those cases where a word-by-word extraction of a given string is required. It is instantiated by specifying the String object to parse. Subsequent iteration through the words, or tokens, is accomplished by the two methods hasMoreTokens and nextToken, as shown in Listing 7.27. Listing 7.27: Testing the StringTokenizer Class in Java public static void main(String args[]) { String inputString = "Mary had a little lamb"; StringTokenizer tokens = new StringTokenizer(inputString); String nextToken; System.out.println(); while (tokens.hasMoreTokens()) { nextToken = tokens.nextToken(); System.out.println(nextToken); } } Running this gives the following: Mary had a little lamb What delimits or separates words or tokens? By default, it is blank spaces, but this can be explicitly specified at instantiation time, by entering all delimiting characters as a string, for example: String sample = " $123,456.78 "; StringTokenizer words = new StringTokenizer(sample, " $,."); This specifies four delimiter characters: the blank, dollar sign, comma, and period. You can also specify delimiters as part of the nextToken method call, in the event they are different per token. For your information, the above little example yields the tokens "123", "456", and "78". This same functionality requires a little more work in RPG, as you have to write it yourself. However, the code is not so difficult, as shown in Listing 7.28. Since you are a seasoned RPG IV programmer by now, we will not dissect this example, but rather leave that to you. In fact, we recommend that you turn this into a reusable procedure. Listing 7.28: Listing 7.28: Scanning for Delimiter Characters in RPG D formula C 'A * 2 / 3 - Num' D tempstr S 10A D start S 2P 0 INZ(1) D end S 2P 0 INZ(0) C DOW (start <= %LEN(formula)) C EVAL end = %SCAN(' ':formula:start) C IF end = 0 C EVAL end = %LEN(formula)+1 C ENDIF C EVAL tempstr= C %SUBST(formula:start:end-start) C tempstr DSPLY C EVAL start=end+1 C ENDDO C EVAL *INLR = *ON There are a number of remaining methods in the String class that offer additional functionality beyond what RPG supplies. Rather than describe them all, we leave them to your own discovery. However, Table 7.3 provides a brief summary of some of the more interesting ones. Refer to the JDK documentation for the java.lang.String class for more detailed information. This chapter introduced you to the following concepts: We hope this discussion of strings did not tie you in knots!
http://flylib.com/books/en/2.163.1/string_manipulation.html
CC-MAIN-2018-05
refinedweb
10,181
60.65
SWINGS SWINGS WHAT ARE THE DIFFERENCES BETWEEN AWT AND SWINGS How to write the code for date in swings - Struts swings JSP & Swings JSP & Swings How to integrate jsp and swings swings question swings question how to change the background color with the help of color values by using swings swings for webnms swings for webnms if i am expanding node of jtree then i want to collapse previous expanding node of jtree in swings how is it possible Swings JTable Swings JTable add values to JTable with four coloums,two of them are comboboxes Swings & JSP Swings & JSP Hai all, Can we use Swing components in a JSP?? Suppose if we enter details in a swing dialog box..and If we want the result in a JSP..is that possible??? Thank you swings header swings header have a string1 it contains 3 parts,for example "123456 service hello" and string2 contains text "change request " like this. and the string3 should contain "123456 +(second string)+ hello" "second string can Swings and JDBC Swings and JDBC Hi.. I am vinay.. I am developing a small application using swings and mysql. I am sending part of the code here.. The problem is i need to update the mysql fields with values which are gettin from dynamiclly Swings - Applet Swings Sir, I have developed an application in swings i want to call that class in applet. is it possible. or otherwise is there any way to deploy java class in browser. Give an example... Thanks in advance... Hi java swings - Java Beginners java swings Do you want to add textfields on the JPanel how to create frame in swings how to create frame in swings how to create frame in swings Image Movement using Swings Image Movement using Swings How to move image using Swings Swings/awt - Swing AWT Swings/awt Hi, how to write action listeners to the Buttons in RichTextEditor tool bar.. thanks in advance...it's Urgent... i am very much new to Swings Swings - JDBC swings - JDBC JTree -Swings java swings jlist in swings java swings - Java Beginners java swings Hi, I need the code for click the refresh button then list values will be refresh.Please send the code ........... Thanks, Valarmathi java code using swings java code using swings code that should be able to enter data of student details using all swings into the access database using jdbc connectivity An application using swings and vector methods An application using swings and vector methods Hi, I want an application in Java swings which uses good selection of Vectors methods about swings - Java Beginners about swings Dear sir,Good evening, i am doing mca sir,i am doing the project in swings,so plz provide the material about swings sir Thank you Hi Friend, Please visit the following link swings - Java Beginners java swings Hi, I need the code for joptionpane with jcombobox. my requirement is click on add button,one joptionpane will come.from the option pane i need to select the combobox values. Please send the sample code java swings - Swing AWT java swings I am doing a project for my company. I need a to show the performance of the employees by using bar bharts. Please give me how can we write the code for bar charts using java swings. Hi friend, I am swings window header swings window header i have a string1 it contains 3 parts,for example "123456 service hello" and string2 contains "change request " like this. and the string3 should contain "123456 "........." hello" ".........." can struts struts Hi what is struts flow of 1.2 version struts? i have struts applicatin then from jsp page how struts application flows Thanks Kalins Naik Please visit the following link: Struts Tutorial making of dynamic textfields using swings making of dynamic textfields using swings How to make dynamic textfields using java swings another frame by using awt or swings another frame by using awt or swings how to connect one frame to another frame by using awt or swings how can we store the encrypted passwaord in swings? how can we store the encrypted passwaord in swings? how can we store the encrypted passwaord in swings java swings - Java Beginners java swings Hi, I already posted the question for three times.... I have two listboxes.If i select first value in the first listbox and moved to second listbox.The next time the same value will not able to move the first java swings - JavaMail java swings Hi sir,i am doing a project on swings,i don't have any knowledge about the layoutmanagers,so my project is very very burden to me,so plz provide a material to me for understand the layout manager easily,plz help me struts struts how to start struts? Hello Friend, Please visit the following links:... can easily learn the struts. Thanks AWT-swings tutorial - Swing AWT AWT-swings tutorial hello sir, i am learnings swings and applets.. i want some tutorials and some examples related to swings.. thank you sir..waiting for your answer. Hi friend, I am sending you How will you retrieve a collection of records from business logic to presentation logic in framework difference between applet and swings -rectangular whereas Heavy weight components are rectangular 5) Swings java swings - Java Beginners java swings Hi, I have two classes(two tabbed panes). how can i get the one class jtextfield value into another class method. Please send the code as sson as possible. Thanks, Valarmathi Hi Friend, Try swings - Java Beginners swings how to add an image to combobox? i searched for this in google, but i got very difficult programs. i am beginner in java swings . i want a small example to add a image .gif file to combobox list. thank you Hi Beans in Swings table Beans in Swings table Hi Sir/Madam.... I am Trying Develop an Swing from which include an table which displays the data from mysql table and i am adding one Jtextfield in each row in the last column and i want to update swings - Java Beginners swings how to upload images using swings Hi Friend, Try the following code: import java.awt.*; import java.io.*; import javax.swing.*; import java.awt.image.*; import java.awt.event.*; import struts struts i have one textbox for date field.when i selected date from datecalendar then the corresponding date will appear in textbox.i want code for this in struts.plz help me swings - Java Beginners swings how t upload images in swings. thanks Hello Friend, Try the following code: import java.io.*; import java.sql.*; import java.util.*; import java.awt.*; import java.awt.event.*; import Struts Struts why in Struts ActionServlet made as a singleton what is the specific reason how it useful in the webapplication development? Basically in Struts we have only Two types of Action classes. 1.BaseActions java swings - Java Beginners java swings Hi, This is my code. How can i set the jtextfield validation in numeric value only. Please change the code.If i insert otherthan number it displays error message. package com.zsl.ibm.mqtool; import java swings - Java Beginners java swings Hi , I have two listboxes.I want to move one listbox value into another listbox using add button. I have the code....Please check this.I can't able to move the values from listbox into another one. Please struts - Struts Struts s property tag Struts s property tag Struts - Struts Struts examples for beginners Struts tutorial and examples for beginners
http://roseindia.net/tutorialhelp/comment/92174
CC-MAIN-2014-15
refinedweb
1,259
70.13
DLSYM(3) Linux Programmer's Manual DLSYM(3) NAME dlsym, dlvsym - obtain address of a symbol in a shared object or exe- cutable SYNOPSIS #include <dlfcn.h> void *dlsym(void *handle, const char *symbol); #define _GNU_SOURCE #include <dlfcn.h> void *dlvsym(void *handle, char *symbol, char *version); Link with -ldl. DESCRIPTION condi- tions, then call dlsym(), and then call dlerror(3) again, saving its return value into a variable, and check whether this saved value is not NULL. There are two special pseudo-handles that may be specified in handle: RTLD_DEFAULT Find the first occurrence of the desired symbol using the default shared object search order. The search will include global symbols in the executable and its dependencies, as well as symbols in shared objects that were dynamically loaded with the RTLD_GLOBAL flag.). The function dlvsym() does the same as dlsym() but takes a version string as an additional argument. RETURN VALUE On success, these functions return the address associated with symbol. On failure, they return NULL; the cause of the error can be diagnosed using dlerror(3). VERSIONS dlsym() is present in glibc 2.0 and later. dlvsym() first appeared in glibc 2.1. ATTRIBUTES For an explanation of the terms used in this section, see attributes(7). +------------------+---------------+---------+ |Interface | Attribute | Value | +------------------+---------------+---------+ |dlsym(), dlvsym() | Thread safety | MT-Safe | +------------------+---------------+---------+ CONFORMING TO POSIX.1-2001 describes dlsym(). The dlvsym() function is a GNU exten- sion. NOTES History The dlsym() function is part of the dlopen API, derived from SunOS. That system does not have dlvsym(). EXAMPLE See dlopen(3). SEE ALSO dl_iterate_phdr(3), dladdr(3), dlerror(3), dlinfo(3), dlopen(3), ld.so(8) COLOPHON This page is part of release 4.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2015-08-08 DLSYM(3)
http://man.yolinux.com/cgi-bin/man2html?cgi_command=dlsym
CC-MAIN-2017-22
refinedweb
313
67.96
Basic Pandas Pandas is a data analysis library written in Python. In this post, I will show you how powerful it is to help you quickly get some insight from different dataset. Install pyenvInstall pyenv We will install pyenv first, pyenv is a conveient tool if you want to use multi python version in your laptop. $ brew install pyenv Install python 3 and pandasInstall python 3 and pandas We use python 3 here $ pyenv install 3.5.0 $ pyenv global 3.5.0 $ pyenv rehash $ pip install pandas Start coding!Start coding! Ok, let's start our pandas adventure! By the way Visual Studio Code is the best editor to work with pandas. Don't forget to install python extension First, we need to import pandas library. Just create a demo.py file, and add the line below. import pandas as pd Download quiz.csv and users.json which is used to demo pandas's utility You can read json file using pd.read_json, it will store the data in DataFrame, you can imagine DataFrame like a virtual table ## read data from json and store in dataframe user_df = pd.read_json('users.json') ## show first 5 data user_df.head() Load csv data, basically the same operation like above, just different file format, pandas suport a lot file format like json, csv, excel... quiz_df = pd.read_csv('quiz.csv') quiz_df.head() Now we can start find some insight in data, first let's try to find max year in quiz # find max year in quiz data max_years = quiz_df['years'].max() print(max_years) Try to get data with max year in quiz, pandas use boolean mask to filter data, you will find boolean mask is a powerful tool when you want to query data with some complicate condition quiz_df['years'] == max_years quiz_df[quiz_df['years'] == max_years] # aggregate average years in quiz data mean_years = quiz_df['years'].mean() print(mean_years) #%% # agregate familiar language count result = quiz_df["familiar language"].value_counts() print(result) #%% # find user using the most popular language popular_language = result.index[0] quiz_user_with_popular_language = quiz_df[quiz_df['familiar language']==popular_language] print(quiz_user_with_popular_language) # join quiz with user using right join #%% quiz_with_user = pd.merge(user_df, quiz_df, how='right', left_on = 'email', right_on = 'email') print(quiz_with_user) # drop na user data #%% result = quiz_with_user.dropna() print(result) # find user willing to use code editor result = result[result['will you want to use code editor']=='T']
https://www.codementor.io/benyeh/basic-pandas-6l6v90hjg
CC-MAIN-2017-47
refinedweb
390
65.42
0 so i got finally done with make my player move right and left, and 1st level. now i want to make my player shoot bullets. i kind of now logic behind it but i need some help. and please let me know if you have a better method of bullet class. my plan: 1)create bullet class - done 2)when user hit space bar add bullet in arraylist - i think iam done not sure 3)print arraylist in paint method - need help bullet.java public class bullet { private int x, y; private int dx = 10; private int width = 10; private int height = 10; private boolean dead = true; //dead mean you can not see the bullet. so when game start no bullet private int bullet_limit = 50; //limit how many times can player shoot private int bullet_range = 200; //set how far a bullet can go. private BufferedImage bullet_image; //get image of bullet ..... //move my bullet public void SHOOT_MOVE() //move bullet { x += dx; if(x > bullet_range) //kill bullet if it get above bullet range { dead = false; } } //draw image of bullet. i didnt added code for adding this image but its works fine public void paint(Graphics g) { g.drawImage(bullet_image, x, y, width, height, null); }//end of paint method } alright so far good. i created a bullet and i am moving it right. now i am store the bullet in arraylist where ever user hit space bar. player.class public class player { ... bullet bullet_class; ArrayList<shoot> store_bullets = new ArrayList<shoot>(); //store bullets ... //set and get methods public ArrayList<shoot> getBULLETS() { return store_bullets; } public void setBULLETS(shoot value) //add bullets { store_bullets.add(value); } .... public void KEYS() //i am calling this method in main(actionPerformed) method. so it keep updateing when i hit space bar { if(space) //boolean var. when user hit space bar { bullet_class = new bullet(x, y); //create bullet store_bullets.add(bullet_class); //add in arraylist bullet_class.SHOOT_MOVE(); //update bullet move } } now i want to print arraylist<bullet> in main method. public class main ...{ .... public void paintComponent(Graphics g) { .... for(int i = 0; i < player_class.store_bullets.size(); i++) { ....paint(g); } } } this line is way wrong. i dont now how to print arraylist<bullet>. and display image on screen. ....paint(g);
https://www.daniweb.com/programming/software-development/threads/450887/player-shoot-bullets-class
CC-MAIN-2017-43
refinedweb
367
75.71
In a competitive world, there is a definite edge to developing applications as rapidly as possible. This can be done using PyGTK which combines the robustness of Python and the raw power of GTK. This article is a hands on tutorial on building a scientific calculator using pygtk. Well, let me quote from the PyGTK source distribution: "This archive contains modules that allow you to use gtk in Python programs. At present, it is a fairly complete set of bindings. Despite the low version number, this piece of software is quite useful, and is usable to write moderately complex programs." - README, pygtk-0.6.4 We are going to build a small scientific calculator using pygtk. I will explain each stage, in detail. Going through each step of this process will help one to get acquainted with pygtk. I have also put a link to the complete source code at the end of the article. This package is available with almost every Linux distributions. My explanation would be based on Python 1.5.2 installed on a Linux RedHat 6.2 machine. It would be good if you know how to program in python. Even if you do not know python programming, do not worry ! Just follow the instructions given in the article. Newer versions of this package is available from : The tutorial has been divided into three stages. The code and the corresponding output are given with each stage. First we need to create a window. Window is actually a container. The buttons tables etc. would come within this window. Open a new file stage1.py, using an editor. Write in the following lines to it : from gtk import * win = GtkWindow() def main(): win.set_usize(300, 350) win.connect("destroy", mainquit) win.set_title("Scientific Calculator") win.show() mainloop() main() First line is for importing the methods from the module named gtk. That means we can now use the functions present in the gtk library. Then we make an object of type GtkWindow and name it as win. After that we set the size of the window. The first argument is the breadth and the second argument is the height. We also set the title of our window. Then we call the method by name show. This method will be present in case of all objects. After setting the parameters of a particular object, we should always call show. Only when we call the show of a particular object does it becomes visible to the user. Remember that although you may create an object logically; until you call show of that object, the object will not be physically visible. We connect the signal delete of the window to a function mainquit. The mainquit is an internal function of the gtk by calling which the presently running application can be closed. Do not worry about signals. For now just understand that whenever we delete the window (may be by clicking the cross mark at the window top), the mainquit will be called. That is, when we delete the window, the application is also quit. mainloop() is also an internal function of the gtk library. When we call the mainloop, the launched application waits in a loop for some event to occur. Here the window appears on the screen and just waits. It is waiting in the 'mainloop', for our actions. Only when we delete the window does the application come out of the loop. Save the file. Quit the editor and come to the shell prompt. At the prompt type : python stage1.py Remember, you should be in Xwindow to view the output. A screen shot of output is shown below. Let us start writing the second file, stage2.py. Write the following code to file stage2.py. from gtk import * main(): win.set_usize(300, 350) win.connect("destroy", mainquit) win.set_title("Scientific Calculator")) : y,x = divmod(i, cols) table.attach(button[i], x,x+1, y,y+1) button[i].show() close.show() box.pack_start(close) win.show() mainloop() main() The variables rows and cols are used to store the number of rows and columns, of buttons, respectively. Four new objects -- the table, the box, the text box and a button are created. The argument to GtkButton is the label of the button. So close is a button with label as "closed". The array , button_strings is used to store the label of buttons. The symbols that appear in the keypad of scientific calculator are used here. The variable button is an array of buttons. The map function creates rows*cols number of buttons. The label of the button is taken from the array button_strings. So the ithe button will have the ith string from button_strings as label. The range of i is from 0 to rows*cols-1. We insert a box into the window. To this box we insert the table. And in to this table we insert the buttons. Corresponding show of window, table and buttons are called after they are logically created. With win.add we add the box to the window. Use of text.set_editable(FALSE) will set the text box as non-editable. That means we cannot externally add anything to the text box, by typing. The text.set_usize, sets the size of the text box and the text.insert_defaults inserts the null string as the default string to the text box. This text box is packed into the starting of the box. After the text box we insert the table in to the box. Setting the attributes of the table is trivial. The for loop inserts 4 buttons into 9 rows. The statement y,x = divmod(i, cols) would divides the value of i by cols and, keeps the quotient in y and the remainder in x. Finally we insert the close button to the box. Remember, pack_start would insert the object to the next free space available within the box. Save the file and type python stage2.py A screen shot of the output is given below. Some functions are to be written to make the application do the work of calculator. This functions have been termed as the backend. These are the lines that are to be typed in to scical.py. This is the final stage. The scical.py contains the finished output. The program is given below : from gtk import * from math import * toeval=' ' myeval(*args): global toeval try : b=str(eval(toeval)) except: b= "error" toeval='' else : toeval=b text.backward_delete(text.get_point()) text.insert_defaults(b) def mydel(*args): global toeval text.backward_delete(text.get_point()) toeval='' def calcclose(*args): global toeval myeval() win.destroy() def print_string(args,i): global toeval text.backward_delete(text.get_point()) text.backward_delete(len(toeval)) toeval=toeval+button_strings[i] text.insert_defaults(toeval) def main(): win.set_usize(300, 350) win.connect("destroy", mainquit) win.set_title("Scientific Calculator: scical (C) 2002 Krishnakumar.R, Share Under GPL.")) : if i==(rows*cols-2) : button[i].connect("clicked",myeval) elif (i==(cols-1)) : button[i].connect("clicked",mydel) else : button[i].connect("clicked",print_string,i) y,x = divmod(i, 4) table.attach(button[i], x,x+1, y,y+1) button[i].show() close.show() close.connect("clicked",calcclose) box.pack_start(close) win.show() mainloop() main() A new variable ! toeval has been included. This variable stores the string that is to be evaluated. The string to be evaluated is present in the text box, at the top. This string is evaluated when the = button is pressed. This is done by calling the function myeval. The string contents are evaluated, using python function eval and the result is printed in the text box. If the string cannot be evaluated (due to some syntax errors), then a string 'error' is printed. We use the try and except for this process. clear, the close and the =, will trigger the function print_string. This function first clears the text box. Now it appends the string corresponding to the button pressed, to the variable toeval and then displays toeval in the text box. close button then, the function calcclose is called, which destroys the window. If we press the clear button then the function mydel is called and the text box is cleared. In the function main, we have added the 3 new statements to the for loop. They are for assigning the corresponding functions to the buttons. Thus the = button is attached to myeval function, the clear is attached to mydel and so on. python scical.py at the shell prompt and you have the scientific calculator running. 8. Conclusion 78 of Linux Gazette, May 2002 !
http://www.tldp.org/LDP/LGNET/issue78/krishnakumar.html
CC-MAIN-2014-49
refinedweb
1,430
69.79
You can think of it as a shortcut. Take for example these two scenarios public class Person{ private int age; private String name; You can think of it as a shortcut. Take for example these two scenarios public class Person{ private int age; private String name; I guess what you should ask yourself is, "why do I want these variables Static?" Static refers to the class itself, not an instance of the class. Think if what you are trying to do is logical or... What error are you getting? You need to call code in a valid thread, like main. check line 110 and make sure that the string you are manipulating is not empty/null You need to allocate space for numberGenerator if it is an object, other wise you are calling a method on an object with no address to point to. Better yet you need to explicitly set the data type... your variable names can not start with a number. You need to rename them. You also want to look into data types, int cannot be a list of characters. you can use system.out.print() I suggest breaking this up into multiple methods, you shouldn't have your fileIO in an action listener Look into Random class. Random rand = new Random(); int n = rand.nextInt(50) + 1; //50 is the maximum and the 1 is our minimum Where did getBytes come from? I think you should write down a generic flow of your main program in order to get the logic down first something like get user input for binary change binary... you are forgetting the () at the end of your method call Because look at your methods, you are passing in parameters, you need to match your method signatures in order to use them. If you have a method like this public void setNum(int aNum){... isn't that what your volume method is for? You can call the volume method on your sphere one and sphere 2, returning the values into seperate variables then comparing that way. there is no such thing as a standard method. All methods are the same, they behave the way you code them to. A mutator method is something that changes a value, where as an accessor method is a... You can start by getting user input, 2 variables for sphere 1 radius and sphere2 radius. Then have an if else statement that compares those 2 values to see which one is bigger. Try to break down your... Seems to me that you should know, you already have those methods created. You just have them named set instead of get. You didnt write this code did you lol You don't have a getbinaryToDecimal() method, you have a setbinaryToDecimal() you need to make those methods public BintoDectoHextoAsciiClass(String hexvalue,String outputvalue,int decimalvalue, String hexStringvalue) that is not 3 strings, that is 3 strings and an int either change the parameters,... You will then have to pass an int when calling your constructor from main, right now you only have a constructor in main that has 3 string parameters. You still don't have a constructor that ONLY takes 3 strings, right now you have a constructor that takes 3 strings and an int What have you changed? just above the for loop you need to flush the newline character. An easy way to do this is add a line like this in.nextLine(); After entering an integer you hit the enter key which is left in the... You do not have a constructor that takes only 3 Strings for parameters. You need to either create one, or pass in different parameters from main to your constructor. Keep two 1d arrays. After you have those values you can run a nested loop that goes newMatrix.length times put an if statement in there that whenever you are on the last column or row add in...
http://www.javaprogrammingforums.com/search.php?s=3a66fbe96d32739885e522b16636ba4b&searchid=1724791
CC-MAIN-2015-35
refinedweb
656
72.16
I'll state my problem first, the code is below if you need to see what I did. I have the contents of a file being stored in a char array, if I use printf() with %c and loop through each item the correct output is displayed. If I used %s only a portion of the information is displayed, only the first couple characters in the array. Any help in figuring out why that is would be greatly appreciated. If you need to know, I'm using Dev-C++ 4.9.9.1 The file I'm opening is a Bitmap image of 1 white pixel, created in MS Paint saved as a 24bit bitmap. When you create it (at least in Windows), it should be a 58byte file. My output is as follows exactly:My output is as follows exactly:Code:#include <cstdlib> #include <stdio.h> #include <fstream> using namespace std; int main(int argc, char *argv[]) { char ch='a'; // Char Buffer char* fbuf=NULL; // Message Buffer int flen=0; // File Length fstream fin ("1px.bmp"); // Open File if (fin.is_open()) // If the file is_open() { // First get the length of the file fin.seekg(0, ios::end); // point to the end flen = fin.tellg(); // get the position fin.seekg(0, ios::beg); // return the pointer fbuf = new char[flen]; // initialize Message Buffer int tmp=0; // to track current position // (i will use tellg() instead later) while (!fin.eof()) // while we are not at the end of the file { fin.get(ch); // grab a single char fbuf[tmp] = ch; // store it in the Message Buffer tmp++; // incriment the temporary position int } fin.close(); // we're done with the file so close() it } printf ("Content (c):\n"); for (int j=0; j<flen; j++) // here I incriment j:0->flen { printf ("%c", fbuf[j]); // printing out each char one at a time } printf ("\n\n"); printf ("Content (s):\n"); printf ("%s", fbuf); // here instead I print as a string (char array, correct?) // the end printf ("\n\n"); system ("PAUSE"); return EXIT_SUCCESS; } Code:Content (c): BM: 6 ( ☺ ☺ ☺ ↑ ♦ Content (s): BM:
http://cboard.cprogramming.com/cplusplus-programming/85466-printf-output-confusion.html
CC-MAIN-2015-48
refinedweb
348
79.6
Some of the error messages documented in this chapter are documented more fully in the appropriate man pages. Some of the error messages documented in this chapter are documented more fully in the appropriate man pages. Error messages can appear in pop-up windows, shell tool command lines, user console window, or various log files. You can raise or lower the severity threshold level for reporting error conditions in your /etc/syslog.conf file. In the most cases, the error messages that you see are generated by the commands you issued or the container object (file, map, table or directory) your command is addressing. However, in some cases an error message might be generated by a server invoked in response to your command (these messages usually show in syslog). For example, a "permission denied" message most likely refers to you, or the machine you are using, but it could also be caused by software on a server not having the correct permissions to carry out some function passed on to it by your command or your machine. Similarly, some commands cause a number of different objects to be searched or queried. Some of these objects might not be obvious. Any one of these objects could return an error message regarding permissions, read-only state, unavailability, and so forth. In such cases the message may or may not be able to inform you of which object the problem occurred in. In normal operation, the naming software and servers make routine function calls. Sometimes those calls fail and in doing so generate an error message. It occasionally happens that before a client or server processes your most recent command, then some other call fails and you see the resulting error message. Such a message might appear as if it were in response to your command, when in fact it is in response to some other operation. When working with a namespace you might encounter error messages generated by remote procedure calls. These RPC error messages are not documented here. Check your system documentation. error messages in this appendix are sorted alphabetically according to the following rules: Capitalization is ignored. Thus, messages that begin with "A" and "a" are alphabetized together. Nonalphabetic symbols are ignored. Thus, a message that begins with _svcauth_des is listed with the other messages that begin with the letter "S." Error messages beginning with (or containing) the word NIS+ are alphabetized after messages beginning with (or containing) the word NIS. Some error messages might be preceded by a date or the name of the host, application, program, or routine that generated the error message, followed by a colon. In these cases, the initial name of the command is used to alphabetize the message/ Many messages contain variables such as user IDs, process numbers, domain names, host names, and so forth. In this appendix, these variables are indicated by an italic typeface. Because variables could be anything, they are not included in the sorting of the messages listed in this appendix. For example, the actual message sales: is not a table (where sales is a variable) would be listed in this appendix as: name: is not a table and would be alphabetized as: is not a table among those messages beginning with the letter "I". Error messages that begin with asterisks, such as **ERROR: domainname does not exist, are generated by the NIS+ installation and setup scripts. They are alphabetized according to their first letter, ignoring the asterisks.:
http://docs.oracle.com/cd/E19455-01/806-1387/6jam692fs/index.html
CC-MAIN-2017-04
refinedweb
578
52.09
XamlType Constructor (String^, String^, IList<XamlType^>^, XamlSchemaContext^) Initializes a new instance of the XamlType class based on the XAML namespace and a string name for the type. This constructor is exclusively for analysis and XAML-node recording of type usages that are known to not have backing in the supporting type system and XAML schema context. Assembly: System.Xaml (in System.Xaml.dll) Parameters - unknownTypeNamespace - Type: System::String^ The XAML namespace for the type, as a string. - unknownTypeName - Type: System::String^ The name of the type in the provided unknownTypeNamespace XAML namespace. - typeArguments - Type: System.Collections.Generic::IList<XamlType^>^ The type arguments for a XamlType that represents a generic type. Can be (and often is) null, which indicates that the represented type is not a generic type. - schemaContext - Type: System.Xaml::XamlSchemaContext^ XAML schema context for XAML readers or XAML writers. Use this constructor only for "unknown" types where a XAML type that maps to an underlying type system is unavailable. This constructor might not produce a result where XamlType::IsUnknown is true. Instead, the default reflector logic reports the underlying type as XamlLanguage::Object. However, this behavior can change because of the LookupIsUnknown override. Available since 4.0
https://msdn.microsoft.com/en-us/library/dd292677.aspx?cs-save-lang=1&cs-lang=cpp
CC-MAIN-2018-05
refinedweb
199
50.63
USE [SQLUTL] GO /****** Object: StoredProcedure [dbo].[Test_Sp] Script Date: 10/26/2016 16:08:23 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= ALTER PROCEDURE [dbo].[Test_2_Sp] @firstNum int, @secondNum int AS BEGIN LINENO 18 EXEC sp_addmessage @msgnum = 50001, @severity = 16, @msgtext = N'This is a user defined error message test_2_sp', @lang = 'us_english'; DECLARE @ContactID_str nvarchar(16); BEGIN TRY --select @firstNum + @secondNum as result --Un-comment me and watch the error come and go??? RAISERROR (50001, -1,-1) WITH Log; -- END TRY BEGIN CATCH declare @ErrorMessage nvarchar(max), @ErrorSeverity int, @ErrorState int; select @ErrorMessage = ERROR_MESSAGE() + ' Line ' + cast(ERROR_LINE() as nvarchar(5)), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(); raiserror (@ErrorMessage, @ErrorSeverity, @ErrorState); END CATCH EXEC sp_dropmessage 50001, 'all'; END namespace SQLUTL.Code.WebForms.Public { public partial class EE_Conn_Exception : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string ConnectionStringName = "SQLUTLtest"; //string con = @"Data..."; SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionStringName].ToString()); using (SqlCommand cmd = new SqlCommand("Test_2_Sp", sqlcon)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@firstnum", "1"); cmd.Parameters.AddWithValue("@secondnum", "0"); sqlcon.Open(); try { SqlDataAdapter adp = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); adp.Fill(dt); Response.Write("Hello"); } catch(Exception ex) { Response.Write(ex.Message); } finally { Response.Write("</br>finally"); } } } } } Are you are experiencing a similar issue? Get a personalized answer when you ask a related question. Have a better answer? Share it in a comment. From novice to tech pro — start learning today. In a simple (but a long) narrative, here's why using a DataSet works. A DataSet is a collection of Data Tables. Hence, when filling up a DataSet, the system will wait until the entire command has completed execution and the Fill method fills up all the DataTables. This is especially useful when you have stored procedures that return multiple result sets (or DataTables as they are called on the .NET side of things). Restricting myself to the sample SP; - When the statement (SELECT @firstNum + @secondNum) was commented, we could capture the exceptions even when using a DataTable. This is because the SP never returned anything else - the only statement was a RAISEERROR - When the statement was uncommented, the stored procedure actually returned a result set (one column with the sum of the two numbers). This result set was one DataTable and hence the DataTable was successfully filled by the .NET code. Now, while the stored procedure continued executing and generated an exception with the RAISEERROR, there was nothing in the .NET code to wait for the execution to complete and "catch" the exception. This is why your code gave your varying results. I hope the explanation above helped in understanding the internals. I tried to keep the narrative as simple as I could. Still if there is some confusion, do drop a line. Have a good week-end! Will check this today and let you know. Regards, Pawan This is the issue we have been working on for 7 long days. With respect I would like more eyes on this problem. How do I get more sql/c# experts looking at this? Regards Sam Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee. Can you update your C# code to the following? Basically, rather than just filling up the DataTable, I am trying to get a DataSet first. This would fail if an exception has been generated. (I tried this on a WinForms App, hence the MessageBoxes. Request you to update the code as necessary). Open in new window Did you try to remove the catch from SQL to check if the one in C# works? Fill method does not trigger InfoMessage method you are not able to capture the messages. InfoMessageHandler is not raised within the scope of the executing command object that why it is not bubble up to command object's method. The are executing in a different thread. Open in new window SP Code Open in new window Hope it helps !! If you are fetching data from the server, ExecuteNonQuery() will not work because it cannot "Query" data. Read more here - Thank you all for your attention. I am not sure what I can do to assist. Other than continuing to search the internet to find an example/solution of someone's post who had the same problem, as I have been doing for 8 days now :-). Let me know. Vitor, yes I need a structure to catch Sql errors at the Sql level and address the error there if possible OR pass them up to a level they can be dealt with. Knowing where the error originated effects how the errors are resolved. I am new but I read/thought/think that "catch at source and bubble up until it is resolvable" is the proper way to deal with exceptions and errors. Thanks Again for all your assistance and sharing your experience. Regards Sam Yes, just finished. It did solve the problem. Sorry I somehow missed this this morning. I think it would be helpful to others If we could know why this works with a "DataSet" and not a "DataTable". Let me know if there will be another post or not on why. So I can properly credit and close this question. Thanks Again this has been an eight day issue. My Best Regards Sam I will have a good weekend now that I won't be still working on this. You and everyone have a good weekend also! Namaste~ Sam
https://www.experts-exchange.com/questions/28979394/Bubble-user-defined-Sql-RAISERROR-to-c-exception.html
CC-MAIN-2018-13
refinedweb
949
57.98
cougaar - Framework cougaar can any oone help in couggar framework i having following problems 1.how to add a plugin to dynamic created agent if more of agents... server developed based on cougaar dynamic creation of multiple drop-down menus dynamic creation of multiple drop-down menus can anybody plz help me in coding for dynamic creation of multiple drop-down menus in a webpage using ajax/js/html/css dynamic mail link creation - JSP-Servlet dynamic mail link creation I wanna create a dynamic link like mail opening pages ( dynamic of data that specifying use by hyperlinks ) HELP ME Cougaar IDE Cougaar IDE CougaarIDE -- An Integrated Development Environment for Cougaar CougaarIDE is being developed by Cougaar Software Inc., to support developers interested agent technology agent technology how to move data from one database to another Table Creation Table Creation create the table for the following fields.its very urgent for me.plz help me S.No,Category( From the home page),Name of the Candidate( After registering and after selecting the category),Age,Title of the project Table Creation to make such table? plz help.........   id creation but in jsp it shown internal error? how to write above code in jsp please help me i Open Source Agent Systems written in Java help regarding creation of last year project help regarding creation of last year project i dont know whether i picked up the right category or not. actually m a last year bsc it student. i... to this topic like what DB i require or what to do .....plz help mobile agent Random Creation of password Random Creation of password Dear Sir I have created a form with some details in it.When clicking on the submit button it gives me a password... to generate a random password and insert into database... Please help me out Dynamic form Dynamic form I need to make a dynamic form using jsp for example, i will need a list of items which when we select one option another list... clicked we have a new list created on the same form. Thanks for your help   PHP Dynamic CheckBox PHP Dynamic CheckBox Help with Dynamic Checkbox in PHP dynamic form dynamic form I need to make a dynamic form using php, for example, i will need a list of items which when we select one option another list... very much for your help Here is a php application that creates xml creation in java xml creation in java HI, I need a java program to create an xml file... therez a tutorial in your site to create an xml file at http... program... can you pls help... Thanq in advance Hi Friend, Try JSP User-Agent JSP User-Agent JSP User-Agent is used to display the user-agent. The page displayed you the name of the client requested the page object creation - MobileApplications classname(); } it doesnt work ..can any one help Dynamic pages - Struts Dynamic pages I want to recreate a page on click and then enter data in my database via struts1.1 please help me what can i use or what help i can get from dynamic drop down list dynamic drop down list I want to create 2 drop down list, where it takes value from database and the two list are dependent..means if I select... on the value chosen from the previous. want code in javascript and jsp, Can you help Dynamic web pages Dynamic web pages hi, i am just creating a web page using html and javascript. i want to give it a eye catching look using javascript. I just want...; zoom out, image loading from database etc. please guide me & help me, so Dynamic Line draw in JSp Dynamic Line draw in JSp In my application. I have one source selected from listbox and multiple targets selected from checkboxes. After submitting... for your help jar File creation - Swing AWT i convert my java file to jar file? Help me Dynamic link in JSP Dynamic link in JSP Hii everyone...I have stuck from last 2 days... stuck with this LINK ...How to generate this dynamic link n all? I have tried from 2 days much on it. But i am not getting it. Please, help me. Thank you Jar file creation - Swing AWT no reference prob is shown... Answer n pls help its urgent... If u r using Dynamic check box problem Dynamic check box problem In my project i have used a dynamic table... dynamically]. Now my problem is that i can't access those values from that dynamic check boxes ... pleas help me as soon as possible... 1)application.jsp Dynamic tree using textarea data Dynamic tree using textarea data I need to create a dynamic tree by using text area data(words) as child nodes in struts. Any body please help me. "very urgent". thanks in advance Dynamic include of multiple files Dynamic include of multiple files I want to include a series of small files, based on a string. For instance, if the string was: String fileString... for quotes; putting quotes doesn't help, since there's no file "fn". Any way to do second selectbox of dynamic second selectbox of dynamic hello friends i hava a code like this and could any body help me with editing code and send me code. i am getting city values but i can't location values of city from database.thanks in advance how to insert value in dynamic table how to insert value in dynamic table i am creating a project... a dynamic table for every company.but whenever i'm inserting values to the company... showing an error invalid syntax on year. please help me to solve JSP: Dynamic Linking - JSP-Servlet JSP: Dynamic Linking Hi I am fetching data as a search result from... of that id. can u help me in doing this.... Hi Friend, Here is the code which will help you in solving your problem. You can use )"> method JSP:Dynamic Linking - JSP-Servlet JSP:Dynamic Linking Hi This is extension to my previous question... to the id so that full details could be displayed of that id. can u help me in doing... friend, Code to help in solving the problem : "view1.jsp" All component creation - Java Server Faces Questions . This link will help you. Please visit for more information. http Apache POI Excel creation - Development process ; Hi friend, Code to help creating excel sheet using POI Dynamic table data to Excel in JSP Dynamic table data to Excel in JSP Iam trying to export dynamic data to excel . But it is displaying only static data .Kindly help viewtrial.jsp <%@page import="java.sql.*"%> function des_setEnable password protected zip file creation exmpale coded neaded - JSP-Servlet password protected zip file creation exmpale coded neaded am able to create a zip file and able to read the file but password protection need please help please help please help please send me the code of dynamic stack in java without using the built in functions resize dynamic image in jsp - JSP-Servlet resize dynamic image in jsp Sir, I am saving the images in mysql database with Blob. An I am retrieving the images with this code.... If you will help me, I will be very grateful to you. Thanking You How to insert dynamic textbox values into database using Java? these dynamic textbox values to database(Oracle 11g)...Please help me out. I have...How to insert dynamic textbox values into database using Java? Hi I am trying to insert dynamic textbox values to database, my jsp form have 2 Creation of xml Creation of xml Hi, I need to fetch details from my database and to create a xml file containing all those datas...My database datas are in key value pair... AppID Label Value 12345 Applicant name XXXX 12345 Masterno Creation of methods Creation of methods I have a only single class and its having only one method ie., main method only.... i need to develop another method that is to reduce my switching code package org.bankPackage.one; import java.util.Scanner DYNAMIC BINDING DYNAMIC BINDING WHAT IS DYNAMIC BINDING how to move records from one table to other based on its creation time how to move records from one table to other based on its creation time ... to second table based on the record creation time means the records should not be present in first table after creation of two days,and it has to move reports creation Image_creation object creation package creation.   dynamic report dynamic report i need complete code for generating dynamic report in jsp. Any help is appreciated. I am using jsp. Any help how to make two types of user for a web dynamic project how to make two types of user for a web dynamic project Hello everyone, I am doing a dynamic web project using jsp and mysql so my problem... everything in project..can someone help me regarding this. how to make two types of user How to: generic array creation How to: generic array creation How to: generic array creation dynamic polymorphism dynamic polymorphism Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate dynamic polymorphism Dynamic loading of Combo box list using servlet - JSP-Servlet Dynamic loading of Combo box list using servlet I have the category... database dynamically, when I select the category? Plz help me. Hi friend...; Hi friend, dynamic bombobox in servlet object creation - Subversion object creation in Java In how many ways we can create objects in Java Dynamic keyword Dynamic keyword hi....... What is the dynamic keyword used for in flex? give me the answer ASAP Thanks Ans: Dynamic keyword-> Specifies that instances of a class may possess dynamic properties added How to find the size of a dynamic webpage using java... eg : Youtube........ How to find the size of a dynamic webpage using java... eg : Youtube........ package newpack; import java.io.BufferedInputStream; import...... Please help... Thanks, Ramit the above code is running on JAVA object creation - Java Beginners object creation I need object creation in depth(with stack,pc registers).Any one can provide me if possible with video/audio Dynamic retrieval od data from database and display it in the table at jsp Dynamic retrieval od data from database and display it in the table at jsp Hi friends.... Am creating software for chit fund.. I want to display... the data from the mysql database... pls its urgent.. help me frnds....   exe file creation - JDBC exe file creation hi i have done a project in java swings.project name is format migrator.means db migrator. now my aim is create EXE FILE for my project. pls do consider creation of installer - Java Magazine creation of installer plz tell me how can be create installer for any developed application in java? visit the following url izpack.org.. it will helps u dynamic polymorphism dynamic polymorphism give an example for dynamic polymorphism? Dynamic polymorphism is where a class overrides a superclass method... seen at runtime, so they are considered dynamic. Here is an example dynamic retrival of data from mysql database to dropdownlist in jsp dynamic retrival of data from mysql database to dropdownlist in jsp Hello, Am having problem in my project... i want to retrive the data from mysql... urgent.. help me frnds.. Here is an example that retrieve the dept dynamic textfields dynamic textfields Hi, I am a fresher and joined recently in one company. they gave me a desktop application project using swings.here is my detailed spec Screen 1 - The user enters the ingredients from a food product, saves Session creation and tracking Session creation and tracking 1.Implement the information persistence across servlet destroy or servlet container start/stop. Write a servlet such that when it is stopped (either by container shutdown or servlet stop xml file creation in java xml file creation in java how to create xml file in java so that input should not be given from keyboard. and that file should be stored. Please visit the following links: creation of database - SQL creation of database hi, where to and how to execute SQL queries? Hi nanju mysql>CREATE DATABASE search; mysql> SHOW DATABASES; mysql> USE search mysql>create table Emp (fname VARCHAR(20 dynamic jquery statement dynamic jquery statement dynamic jquery statement creation button using objective c creation button using objective c creation button using objective c dynamic calender dynamic calender hi i need the code to "insert date using GUI" Hi Friend, Try the following code: import java.awt.*; import java.awt.event.*; import javax.swing.*; class DatePicker{ int month bean creation exception bean creation exception hi i am getting exception while running simple spring ioc program Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class dynamic query dynamic query DECLARE QUERY VARCHAR2(32767); FIN_QUERY VARCHAR2(32767); CURSOR C IS (select distinct PORTFOLIO from MPE_TEST1); CURSOR C2 IS SELECT DISTINCT PORTFOLIO_LEVEL, PORTFOLIO FROM MPE_TEST1 ORDER create dynamic array in javascript create dynamic array in javascript How to create dynamic array in javascript php dynamic array checking php dynamic array checking php dynamic array checking Chatbox creation problem Chatbox creation problem i have one chat box in my web site and i assigned fixed position to that div.that is workin in mozill but it is not working in ie . thank you`print ("<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 creation of table using a Java swing creation of table using a Java swing how to create a table dynamically in Java swing i want to store dynamic number of value on one jsp and retrieve them on other. i want to store dynamic number of value on one jsp and retrieve them on other... of result processing i have dynamic number of drop downs on a single page which... these different variables value on next page. plz help me, my whole project have web site creation Regarding Database Creation Array Creation - JSP-Servlet Object creation - Ajax
http://www.roseindia.net/tutorialhelp/comment/83176
CC-MAIN-2015-40
refinedweb
2,358
63.09
I need help with a lab I'm doing. In this lab you have to show the number of odd digits a number has, for example the number 4135 would have three odd digits. I've already done a lab where it tells you if a number is odd or even but I don't know how to change it and make it to do what it needs to. This is my code for the odd or even lab: /** * It reads and number and determines if that number is even or add. */ import java.util.Scanner; public class Odd_or_Even { public static void main(String [] args) { Scanner reader = new Scanner (System.in); int answer; System.out.print("Enter 1 to enter a number or 2 to quit -> "); answer = reader.nextInt(); while (answer == 1) {calculate(); System.out.print("Want to enter another number? Enter 1 for yes or 2 to quit -> "); answer = reader.nextInt(); } if (answer == 2) System.out.println("Thanks for using this program"); else { System.out.println("Error this number ("+answer+") is not an option try again."); } } public static void calculate() { Scanner reader = new Scanner (System.in); int num; int finalresult; System.out.print("Enter your number -> "); num = reader.nextInt(); finalresult = num%2; if (finalresult == 0) System.out.println("Your number ("+num+") is an even number"); else System.out.println("Your number("+num+") is and odd number"); }
https://www.daniweb.com/members/925617/marifergarz/posts
CC-MAIN-2020-10
refinedweb
227
61.12
Theme files Shopify themes are made up of Liquid template files, each serving their own unique purpose. For example, collection.liquid is used to display multiple products, and product.liquid is used to show the details of a single product. Shopify themes also include a settings_schema.json file, which is a form that makes it easy for the user to customize the look-and-feel of the theme. Theme structure A Shopify theme includes the following directories: Assets The assets directory is rendered as the Assets folder in the theme editor. It contains all the assets used in the theme, including images, stylesheets, and javascript files. Use the asset_url filter to reference a theme asset in your templates. Configs The config directory is rendered as the Configs folder in the theme editor. It includes a settings_schema.json file and a settings_data.json file. Layouts The layout directory is rendered as the Layouts folder in the theme editor. It contains theme layout templates, which by default is the theme.liquid file. All Liquid templates inside the templates folder are rendered inside the theme.liquid file. In addition to the theme.liquid, stores on Shopify Plus also have a checkout.liquid layout file. Locales The locales directory is rendered as the Locales folder in the theme editor. It contains the theme's locale files, which are used to provide translated content for the theme. Among other files, this folder contains the default English locale file, en.default.json. Sections The sections directory is rendered as the Sections folder in the theme editor. It contains a theme's sections, which are reusable modules of content that can be customized and re-ordered by users of the theme. Snippets The snippets directory is rendered as the Snippets folder in the theme editor. It contains all the theme's Liquid snippet files, which are bits of code that can be referenced in other templates of a theme. Use the Liquid render tag to load a snippet into your theme. Templates The templates directory is rendered as the Templates folder in the theme editor. It contains all other Liquid templates, including those for customer accounts: Alternate templates There might be cases where you need a different markup for the same template. For example, you might want a sidebar on one product page but not in another. The workaround for this is to create alternate templates. To create an alternate template: Inside the Edit HTML/CSS, click Add a new template. In the modal that appears, select the type of template that you want to create and enter a name. Navigate to the admin page for the content that you want to apply the alternate template to, and look for the drop-down under the Template heading. Select the template that you want to apply, and hit Save. Alternate templates inside if statements There might be cases where you have several versions of a template and want to write an if statement that applies to all of them. For example, you might have multiple alternate product templates and need to output a message for all product templates. The template object has several convenient attributes to help with this. {% if template.name == 'product' %} We are on a product page! {% endif %} {% if template.suffix != blank %} We are on an alternate template! {% endif %}
https://shopify.dev/tutorials/develop-theme-files
CC-MAIN-2021-10
refinedweb
553
66.44
#include <vtkAssembly.h> Inheritance diagram for vtkAssembly: vtkAssembly is an object that groups vtkProp3Ds, its subclasses, and other assemblies into a tree-like hierarchy. The vtkProp3Ds and assemblies can then be transformed together by transforming just the root assembly of the hierarchy. A vtkAssembly object can be used in place of an vtkProp3D since it is a subclass of vtkProp3D. The difference is that vtkAssembly maintains a list of vtkProp3D instances (its "parts") that form the assembly. Then, any operation that transforms (i.e., scales, rotates, translates) the parent assembly will transform all its parts. Note that this process is recursive: you can create groups consisting of assemblies and/or vtkProp3Ds to arbitrary depth. To add an assembly to the renderer's list of props, you only need to add the root of the assembly. During rendering, the parts of the assembly are rendered during a hierarchical traversal process. Assemblies can consist of hierarchies of assemblies, where one actor or assembly used in one hierarchy is also used in other hierarchies. However, make that there are no cycles (e.g., parent->child->parent), this will cause program failure. If you wish to create assemblies without any transformation (using the assembly strictly as a grouping mechanism), then you may wish to consider using vtkPropAssembly. Definition at line 73 of file vtkAssembly.h.
https://vtk.org/doc/release/5.0/html/a01164.html
CC-MAIN-2021-31
refinedweb
221
56.15
Quoting Eric W. Biederman (ebiederm@xmission.com):> Srivatsa Vaddagiri <vatsa@in.ibm.com> writes:> > > On Mon, Apr 02, 2007 at 09:09:39AM -0500, Serge E. Hallyn wrote:> >> Losing the directory isn't a big deal though. And both unsharing a> >> namespace (which causes a ns_container_clone) and mounting the hierarchy> >> are done by userspace, so if for some installation it is a big deal,> >> the init scripts on initrd can mount the hierarchy before doing any> >> unsharing.> >> > Yes I thought of that after posting this (that initrd can mount the> > hierarchies), so this should not be an issue in practice ..> >> >> Can you think of a reason why losing a few directories matters?> >> > If we loose directories, then we don't have a way to manage the> > task-group it represents thr' the filesystem interface, so I consider> > that bad. As we agree, this will not be an issue if initrd> > mounts the ns hierarchy atleast at bootup.> > I suspect that could be a problem if we have recursive containers.> Even by having a separate mount namespace for isolation you really> don't want to share the mount. If you can see all of the processes> you do want to be able to see and control everything.Are you asking about what happens if initrd in a vserver asks to mount -t container -o ns,cpusets /containers?I suppose in that case it would make sense to allow a separate mountinstance with it's own superblock, with s_root pointing to the dentryfor the container the vserver is in?> I guess I want to ask before this gets to far. Why are all of the> namespaces lumped into one group? I would think it would make much> more sense to treat each namespace individually (at least for the> user space interface).> > Eric-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2007/4/3/139
CC-MAIN-2014-15
refinedweb
328
63.49
Learning Resources for Software Engineering Students » Author(s:) Yu Pei, Henry Reviewers: Chester Sng, Lin Si Jie C# is a general purpose, multi-paradigm, garbage collected, cross-platform language by Microsoft, and part of the .NET platform. Some claim C# is Microsoft's answer to Java due to the fact that the two languages have a lot of similarities. Given below are brief explanations of the key characteristics of C# mentioned above. General purpose:. --(source: [Wikipedia]()) Multi-paradigm: Programing Paradigms are used to describe Programming Languages based on their features. Some commonly referred paradigms are Object-Oriented Programming (which primarily organizes code into objects that contain a state) and Functional Programming (where code represents a sequence of stateless functions.) C# supports both Object-Oriented and Functional Programming, and many others that can be found here. Garbage Collected: The intialization, storage and handling of variables require memory. Garbage Collection is a form of automatic memory management, where memory that is no longer referenced by the program will be deallocated. You may read more about Garbage Collection. Cross-Platform: Cross-Platform software is software that can be run across multiple platforms, which may require recompilation depending on the software. Common platforms include Windows, MacOS and Linux, and for mobile platforms Android and iOS. The benefits of writing Cross-Platform software is that developers will only need to primarily maintain 1 code base and be able to deploy to multiple platforms. Below is an example of of a simple C# program: //Comments can be marked with // or /**/ //Namespaces are similar to packages, except the file does not need to be physically in the directory using ProjectName.Utils; namespace ProjectName.Model { //Subclassing BaseClass class MyClass : BaseClass { ... //Method declaration public static void Main(String[] args) { //Variable definition string message = "Hello World!"; Console.WriteLine(message); } } } Developers that work with C# commonly use Visual Studio as their IDE and also as a build tool for compilation into common application/library formats, such as .exe or .dll. Using Visual Studio for C# development offers great convenience as it has an integrated testing framework, MSTest. This section covers some noteworthy features of C# syntax (some of them are found in other languages such as Java and Swift). In C#, you can construct an Object, Array or Collection in a single statement as shown. This can be useful when writing tests, as test data will be better organised, as compared to calling the actual constructor. public BookShelf(Book[] books, param2, param3, param4) { this.books = books // Do something with param 2, 3, 4 } // Without use of Object Initializer BookShelf shelf1 = new BookShelf(books, param2, param3, param4) // With use of Object Initializer BookShelf shelf2 = new BookShelf() { books = { book1, book2 }; }; In the above example, we want to test a BookShelf's behaviors only related to the Book[] array. Instead of having to unnecessarily use param2, 3, 4 in construction, we can initialize a BookShelf only with the Book[] that we wanted to use. Sometimes, it may be useful to defer execution or capture a local context for later execution. Context capturing is reflected below: //Capturing local context public class Context { //GetCounter returns a nullary (0 argument) function. The function returns an integer when executed. public static Func<Int> GetCounter() { //Inside the context of this function, there is an integer variable count. int count = 0; //GetCounter is returning a function. return () => { //The function increments the count variable inside this context, which is initialized to 0. count++; //It then returns the current count value. return count; } } } Func<Int> counter = Context.GetCounter(); //Every time the function is called, the variable count in the captured context would increment by 1, and its new value will be returned. counter(); //Returns 1 counter(); //Returns 2 The ability to capture the value count outside of the defined function scope that returns count, is called a closure. If you wish to read more about closures, you may consult this article by dixin Normally to guard against null pointers, an if branch or a guard clause that checks against null is used. Below is a code example of conventional null pointer handling. public static Car ManufactureCar() { return (hasError) ? null : new Car(param1, param2); } public void AddFuelTank() { fuelTank = (hasError) ? null : new FuelTank(param3); } Car car = Car.ManufactureCar(); Double fuelLeft = 0; if (car != null) { car.AddFuelTank(); fuelTank = car.GetFuelTank() if (fuelTank != null) { fuelLeft = fuelTank.GetFuel(); } } DoSomethingTo(fuelLeft); In C#, null handling does not need to be done the conventional way. C# has Nullable features, such as collaescing operators ?? and null conditional operators .?. Some may find this similar to optionals in Swift. Applying these features appropriately not only results in shorter and more concise code in general. It makes it easier to reduce the use of indentation as well. Nullables may appear less intuitive to new users, so its value may differ between communities. public static Car ManufactureCar() { return (hasError) ? null : new Car(param1, param2); } public void AddFuelTank() { fuelTank = (hasError) ? null : new FuelTank(param3); } Car car = Car.ManufactureCar(); //Call Drive method of car if not null car?.AddFuelTank(); //Get amount of fuel left with default value 0 Double fuelLeft = car?.GetFuelTank()?.GetFuel() ?? 0; DoSomethingTo(fuelLeft); Some explanation of what Double fuelLeft = car?.GetFuel() ?? 0 does: car.GetFuel(). car?.GetFuel()evaluates to null. ??operator sees null, so the entire expression defaults to 0. If ??sees a non-null value, the default value is not used. More can be read about Nullables here The list of features in C# can be quite long. This article only shows you selected features for their usefulness and ability to represent code more concisely. Some features that were not listed are Async/Await and Default Interface Implementation. If you wish to explore other features, you may consult this article and others online. C# is high in demand (as per source1, source 2). It is especially well-suited for Windows apps. It also thrives in game programming because the popualr game engine Unity has great cross-platform compatibility for desktop, web, mobile and console, and has extensive support for 2D/3D games, VR/AR games and games that require networking. C# can even be used on non-Windows environments as the .NET framework has cross platform support via the Mono project. Getting started with C# is not difficult. You can download Visual Studio and follow the setup instructions for C# programming here. If you are new to C# but have some familiarity with Java, you may follow the tutorial at Sololearn. It is a rather comprehensive tutorial that teaches fundamental syntax and concepts in C#. If you feel that certain parts of the tutorial are too simple, you can also skip them. If you are entirely new to programming, you may find more hands on practice with simpler steps at CSharp net. This tutorial tends to be more rigorous and goes through in great detail the steps, starting from installing a development environment, to writing basic C# programs and finally topics commonly used in real applications, such as file handling and debugging. If you wish to skip certain parts of the tutorial, the structured contents are displayed on the right side of the website. If you want to have a go at maintaining and enhancing a small project, you may find this fictitious airline reservation system project to be a good starting point. It covers commonly used components of a software, such as UI (Application User Interface), data storage and handling, and the logic behind the program (such as buying a ticket). More similar projects can be found at 1000projects.org. If you feel that you have a grasp of C# fundamentals but find it difficult to write programs of bigger scale, you may consult CSharp corner for a list of design patterns that you may employ to better organise and plan your program structure. Sometimes, you may find that you have problems collaborating on a C# project. This may be due to some common misconceptions and mistakes you are commiting without realisation. You may reduce these problems by reading about some common mistakes in C# programming. If you want to develop a desktop application for Windows, you may consult Microsoft's documentation on creating an application with the Windows Presentation Foundation, a framework that is commonly used for creating UI for Windows Applications that has many useful features for building your UI.
https://se-education.org/learningresources/contents/csharp/IntroductionToCSharp.html
CC-MAIN-2019-26
refinedweb
1,381
55.54
itext pdf - Java Interview Questions itext pdf sample program to modify the dimensions of image file in itext in java HiIf you want to know deep knowledge then click here and get more information about itext pdf program. Adding images in itext pdf Adding images in itext pdf Hi, How to add image in pdf file using itext? Thanks Hi, You can use following code... image in the pdf file. Thanks itext pdf itext pdf i am generating pdf using java i want to do alignment in pdf using java but i found mostly left and right alignment in a row. i want to divide single row in 4 parts then how can i do Examples of iText . Inserting image in the pdf file...; How to wrap image in the pdf file... are using to make a pdf file through java program.   itext chunk . iText is a framework for creating pdf files in java. A Chunk...*. These two package will help us to make and use pdf file in our program. Now create... document writer that writes PDF syntax to concerned file by a FileOutputStream itext version ; In this program we are going to find version of the iText jar file which is using to make a pdf file through the java program. In this example we need..., com.lowagie.text.pdf.PdfWriter class is used to write the document on a pdf file. To make What is iText in Java? What is iText in Java? Hi, What is iText in Java? How to create PDF in Java? Thanks Hi, Check the tutorial: Examples of iText. itext - Java Beginners itext Hi, Can we add contents to the back side of an itext..., new FileOutputStream("imagesWrapPDF.pdf")); document.open(); Image image... Technologies."); document.add(para); document.add(image); document.close generating itext pdf from java application - Java Beginners generating itext pdf from java application hi, Is there any method in page events of itext to remove page numbers from pdf generated frm.../java/itext/index.shtml Open Source PDF Open Source PDF Open Source PDF Libraries in Java iText is a library that allows you to generate PDF files on the fly...: The look and feel of HTML is browser dependent; with iText and PDF you can regarding the pdf table using itext regarding the pdf table using itext if table exceeds the maximum width of the page how to manage How to read PDF files created from Java thru VB Script How to read PDF files created from Java thru VB Script We have created the PDF file thru APache FOP but when we are unable to read the data thru... file? Java PDF Tutorials iText support android? - MobileApplications iText support android? would iText support android? i ve linked the iText.jar file with my android project developed in eclipse... //code Document document = new Document(PageSize.A4, 50, 50, 50, 50: ChapterAuonumber Itext ChapterAuonumber Itext I'm new to Itext ,Please provide some example of using ChapterAutonumber in Itext pdf to text pdf to text how to covert pdf file (which contain table and text) into word or excel file using use Add text into the pdf File - Development process Add text into the pdf File Hi friend, How can i insert or Add text into the pdf file from the exsting one in java.. Thanks in Advance...:// PDF creation in JAVA - JSP-Servlet file and i want to write something into pdf file....before creation. Upto creation i have done but how to write data into pdf. File Writer is not working... visit the following link: Pdf Viewer Pdf Viewer How to diplay the pdf files in java panel using...); JLabel label=new JLabel("Select File"); final JTextField text=new...){ JFileChooser fileChooser = new JFileChooser(new File("C Inserting image in the pdf file Inserting image in the pdf file  ... insert a image in a pdf file irrespective of the fact whether it exists... to make and use pdf file in our program. Now create a file named imagesPDF Create PDF from java report. i want to create report in pdf file from my database in mysql. Now i use IReport too create pdf file, can't work...., pleas tell me a tutorial/source code to create pdf file from database call from java programming. thank you Header file Header file when we use, Scanner input=new Scanner(System.in); this statement in a java program,which header filemust be imported to the program? Hi Friend, Import the package java.util.*; Thanks Rotating image in the pdf file Rotating image in the pdf file  ... insert a image in a pdf file and rotate it irrespective of the fact whether... will help us to make and use pdf file in our program. Now create a file named Javah - Header File Generator Javah - Header File Generator  ... source code. The name of the header file and the structure declared within it are derived from the name of the class. By default javah creates a header file pdf landscape . iText is a framework for creating pdf files in java. In this tutorial... to make and use pdf file in our program. Now create a file named... PDF syntax to concerned file by a FileOutputStream. If the pdf file doesn't reading from pdf reading from pdf how can i read specific words from pdf file? Java Read pdf file import java.io.*; import java.util.*; import...) { } } } For the above code, you need to download itext api Generating PDF reports - JSP-Servlet /itext/helloServletPDF.shtml PDF reports Hello everyone i have submitted several... Question I am try to generate a pdf report using jsp .... i want to export. Merging multiple PDF files - Framework Merging multiple PDF files I m using the iText package to merge pdf files. Its working fine but on each corner of the merged filep there is some... the files are having different font.Please help reading from pdf to java - Java Beginners reading from pdf to java How can i read the pdf file to strings in java. I need the methods of reading data from file and to place that data... that will read the pdf file and write into another pdf file.But first of all download Convert Text To PDF into the add() method of the document class to generate a pdf file. Download iText API required for the conversion of a text file into the pdf file from http...; Here we are discussing the convertion of a text file into a pdf file Convert ZIP To PDF ; Lets discuss the conversion of a zipped file into pdf file... by using the string class constructor.Generate a pdf file by using... to the document by using doc.add(p). Create a pdf file and pass this document pdf image extractor - Development process pdf image extractor hi deepak , can u pls tell me how to extract a text from a image in a pdf in java. for example bank stmt. i want to extract text from thet image which is in pdf. pls help me. Regards for each for each Sir, is it possible to write bubble sort in java using for each loop ? or any two related nested loops using for each? Thanks in advance Java code to convert pdf file to word file Java code to convert pdf file to word file How to convert pdf file to word file using Java send data thru parallel port - Java Beginners send data thru parallel port Hi, I want to print send data to printer thru parallel port.How can it be possible thru java code convert an pdf file to html in Java convert an pdf file to html in Java Hi all, How to convert an pdf file to html in Java? Currently all my data is generated into a report in pdf... implementing this, is there any source code in java? Thanks Image using Java coding Image using Java coding Hai, Display image in pdf file using Java coding through Xsl file.. Please help me.. xsl file generate the pdf file Finding page count in any file count in any file (doc,ppt,pdf,image,etc...). Is there any universal API to deal with any file irrespective of the file extension.Its bit urgent. Please let me... into PDF. But I dont think so it converts any file into PDF. Thanks, Srinivas how to get description for each file how to get description for each file hi, how to get description for each file using php or java script..... condtion:two text boxes for each... for each file without description dont upload..... u have any idea......code Task manager enable and disable thru java Task manager enable and disable thru java I would like to know, how to enable and disable task manager using java. Kindly, please Let me know pdf Metadata will help us to make and use pdf file in our program. Now create a file named... PDF syntax to concerned file by a FileOutputStream. Now open the document... pdf Metadata   Removal of XML header Removal of XML header I need to retrieve a few records from the file at a time to generate xml.But each time while retrieving the records from the file, I dont want the XML header to appear again..How do I achieve this?What converting html file into pdf - Struts converting html file into pdf i want to convert html file into pdf file using java code please help me Javah - Header File Generator Javah - Header File Generator  ... source code. The name of the header file and the structure declared within it are derived from the name of the class. By default javah creates a header file PDF Comparator . Also, i need to write the generate a new pdf file which should highlight the difference of the pdf file by changing its background color, and when we place the mouse cursor over it, it should pop-up the contents of the next pdf file which PDF to Word Conversion - Java Beginners PDF to Word Conversion Hello, Can we convert a PDF document to Microsoft word document thru Java. If its not possible in Java, is it possible in any other language how to create pdf file using java and itextjar how to create pdf file using java and itextjar How to create pdf file having paragraphs and alignments done using java and itextjar 5.10 version.? hope i get quick response Creating Multiple Lists how you can make lists into a pdf files. You can make lists and also make sublist You can make ordered list or symbolic list. iText...); listItem = new ListItem("Core Java" how to set image - EJB in this pdf, how can i set pls help me sir, my image in E:/rose.jpg,how can set this jpg to my pdf file...how to set image public ActionForward execute(ActionMapping mapping 'Hello World' file from a servlet (PDF, HTML or RTF). 'Hello World' file from a servlet (PDF, HTML or RTF...; In this program we are going to tell you how we can create three file rtf,pdf and html... of servlet to display "Hello Word " on PDF,RTF and HTML format using iText Tips and Tricks ; Send data from database in PDF file as servlet response... in the form of a PDF document using Servlet. This program uses iText, which is a java library containing classes to generate documents in PDF, XML, HTML, and RTF Excel / Doc to PDF conversion using Acrobat9 - Development process and POI library to convert doc file into pdf file. import java.io.*; import...Excel / Doc to PDF conversion using Acrobat9 Hi, I need to convert .xls / .doc files to .pdf files using Acrobat9. Please suggest the possible java - Java Beginners java Hii Can any ome help me to Write a programme to merge pdf iles using itext api. Hi friend, For solving the problem visit to : Thanks header files header files do you have a all header files of java pdf file measurement pdf file measurement  ... on a pdf file,. To make the program for changing the pdf version firstly we have... through java program. First ad the value in the paragraphs then add it finally Creating files of PDF's thumnails server. You can then use following code to create PDF thumbnail image. <?php $im = new imagick('myfile.pdf'); $im->setImageFormat( "jpg" ); header...Creating files of PDF's thumnails Hi, How to create PDF's thumbnail Count instances of each word Count instances of each word I am working on a Java Project that reads a text file from the command line and outputs an alphabetical listing... going wrong...could anyone help to put me in the right direction? From my text file convert data from pdf to text file - Java Beginners convert data from pdf to text file how to read the data from pdf file and put it into text file(.txt How to adjust a size of a pdf file How to adjust a size of a pdf file  ... adjust the size of a pdf file irrespective of the fact whether it exists or not. If it exists then its fine, otherwise a pdf file will be created.  Image display in pdf Image display in pdf i am trying to display a image in pdf using xsl fo but " [ERROR] Error while creating area : Error with image URL: images... go through the following link: Display image in pdf
http://roseindia.net/tutorialhelp/comment/93353
CC-MAIN-2014-15
refinedweb
2,244
72.66
Forum:Wikia-credits block is spam From Uncyclopedia, the content-free encyclopedia. It looks like we still have problems with Special:Export on this site. The export function does export the article text, but spams this onto the end of every page: - <div id="wikia-credits"><br /><br /><small>From [ Uncyclopedia], a [ Wikia] wiki.</small></div> This rubbish is then being pulled in by various robots and reposted back to the original site. The end-result looks basically like vandalism. Nyp has recently been trying to repair some of the damage done here on en.uncyclopedia: - ! - Category:Blasphemy - Category:Islam - Abdul Alhazred - Absurdity - Adam Smith - Alone in the Dark - America - BACON - Badminton - Bahamut - Balrog - Banjo-Kazooie - Bar - Beatallica - Belize - Benin - Betty Boop - Big Bang - Big Mac - BIONICLE - Black power - Blink-182 - Bon Jovi - Cafeteria - Chrono Cross - Comic Book - Conquer Online - Dead Rising - Dino Crisis - Disgaea - Duck Hunt - F.E.A.R. - Final Fantasy Mystic Quest - Harvest Moon - Infinity - Kingdom Hearts II - Mecca - Microsoft - Raspberry - Starfox - Uncyclopedia:Anniversaries/April 1 - Uncyclopedia:Anniversaries/April 14 - Uncyclopedia:Anniversaries/April 3 - Uncyclopedia:Anniversaries/April 7 - Uncyclopedia:Anniversaries/August 2 - Uncyclopedia:Anniversaries/January 6 - Uncyclopedia:Anniversaries/July 31 - Uncyclopedia:Anniversaries/July 9 - Uncyclopedia:Anniversaries/May 7 - Uncyclopedia:Anniversaries/September 6 - Worst 100 Bands of All Time Quite the list; quite a few front-page templates appear here. Unfortunately, if Wikia has broken Special:Export, the problems are going to recur. Banning all 'bots from the site isn't an option, as it would mean having to generate thousands of interwiki links manually. Blaming the operators of the 'bots (if they're even still active) is also no help, as the problem is being caused not by the robot itself but by Wikia. Garbage in, garbage out. The issue has been raised before in other fora, primarily on the central Wikia, with no viable solutions offered. The matter is out of my hands (I have not run any 'bots on Wikia since July 2006) but I do see this as a problem that does need to be resolved. Cleaning up this mess by hand is a long, slow and impractical approach. Wikia needs to fix this. --Carlb 17:58, 13 April 2008 (UTC) - My question is why the hell Wikia needs to whore its name onto every single damn thing that they host. I remember when Rangeley came around when the Wikia Spotlight arrived, and he was suitably pissed off. Everyone eventually got him to stop his complaining, but now I can see why he voiced his distaste with it. Yes, we know Uncyclopedia is a Wikia wiki. Yes, we know there are other wikis hosted by it. If a person wants to know that, they can look at the bottom of the page and see the "hosted by Wikia" logo, click on it, and then learn all about the different wikis we have. I'm pretty sure it's become clear that WIKIA HOSTS UNCYCLOPEDIA. Neither I nor anyone else enjoys being raped in the eyes with declarations of this type. It's getting to a point where I, someone who quite understands Wikia's place here, am getting disillusioned by the constant attempts to stick the name to our wiki.~~ Sir Ljlego, GUN [talk] 18:04, 13 April 2008 (UTC) - Until it gets fixed, I'll just run wikipedia:WP:AWB on the bots' contribs. Give me a list of the bots, and I'll add them to the list of contribs it's checking right now. – Sir Skullthumper, MD (criticize • writings • tweetings) 18:09 Apr 13, 2008 - Do the interwiki bots use special:export? Which are the bots spaming back in? And who's exporting anyway? where to? maybe to that mirror page which drives so much traffic away from this site? If that's the case we should ask wikia to swap that message for viagra adds.---Asteroid B612 (aka Rataube) - Ñ 15:52, 14 April 2008 (UTC) - Well they need to make money from uncyclopedia somehow, right? And in lieu of ads, they need to drive people to wikis where there are ads. That's business 101. For what it's worth, against crappy wikia credits spam. - Though can't the bots use the mediawiki API instead of the export function? You can get all the info Special:Export gives, and way more. And the revision data isn't spammed with wikia's credits message. Compare this API query (showing just about all the information you could possibly get from the page) to the result of Special:Export. • Spang • ☃ • talk • 19:48, 14 Apr 2008 - Actually all I did is do a search on "wikia-credits", search in all namespaces and then I removed that line of spam"credits". • nyp 11:21, 15 April 2008 That's just what we advise generally. Set your bot to find and remove text with id="wikia-credits". That's the solution we came up with when there were complaints about the addition initially. I don't know bots, but I understand this isn't a big change to make. As Spang said, gotta pay the rent. This helps ensure that anyone using content from here (like, say, CarlB's fork of Uncyclopedia ;) will be linking back here and to Wikia. I don't think that's too much to ask... in fact, some form of attribution is part of the license (this form isn't ideal, but it's something). --- sannse (talk) 15:48, 15 April 2008 (UTC) Attribution to the original author(s) is part of the license. Wikia is not the author. A link to the original article's history in the user tabs or sidebar would therefore be more appropriate. Feeding spam to the site robots locally seems rather pointless, though? --72.140.46.227 18:30, 15 April 2008 (UTC) Solution Check out Uberfuzzy's patch to fix this issue. Also, forks are lame. — Sir Manticore 05:54, 16 April 2008 (UTC) - Well, this workaround seems to work; and if a page has the credits before, it removes them (but I'm not sure if it's a desirable effect because the page can be exported/imported from another wiki...) --ChixpyBot 15:28, 21 April 2008 (UTC)
http://uncyclopedia.wikia.com/wiki/Forum:Wikia-credits_block_is_spam
crawl-002
refinedweb
1,037
63.19
IRandom Link to irandom IRandom is a random number generator. The class can only be used when you have an instance of a World (Such as in an Event handler), it can not be in recipes. Importing the package Link to importing-the-package It might be required for you to import the package if you encounter any issues (like casting an Array), so better be safe than sorry and add the import. import crafttweaker.util.IRandom; Getting the IRandom Link to getting-the-irandom You can get an instance of IRandom by using an IWorld instance. Once you have an IWorld instance, you can simply do: ZenScriptCopy world.random ZenMethods Link to zenmethods nextInt()returns the next pseudorandom int, ranging from Integer.MIN_VALUE to Integer.MAX_VALUE nextInt(int bound)returns the next pseudorandom int, ranging from [0, bound) nextInt(int min, int max)returns the next pseudorandom int, ranging from [min, max] nextFloat()returns the next pseudorandom float, ranging from [0.0f, 1.0f) nextDouble()returns the next pseudorandom double, ranging from [0.0, 1.0) nextFloat(float min, float max)returns the next pseudorandom float, ranging from [min, max] nextDouble(double min, double max)returns the next pseudorandom double, ranging from [min, max] nextBoolean()returns the next pseudorandom boolean String getRandomUUID()returns a random UUID The ranges above are presented in using the mathematical interval notation, you can read more about it here
https://docs.blamejared.com/1.12/en/Vanilla/Utils/IRandom
CC-MAIN-2022-27
refinedweb
235
50.26
Scatter plots are the go-to for illustrating the relationship between two variables. They can show huge amounts of data, but often at a cost of being able to tell the identity of any given data point. Key data points can be highlighted with annotations, but when we have a smaller dataset and value in distinguishing each point, we might want to add images instead of anonymous points. In this tutorial, we’re going to create a scatter plot of teams xG & xGA, but with club logos representing each one. To do this, we’re going to go through the following steps: - Prep our badge images - Import and check data - Plot a regular scatter chart - Plot badges on top of the scatter points - Tidy and improve our chart All the data and images needed to follow this tutorial are available here. Setting up our images To automate plotting each image, we need to have some order to our image locations and names. The simplest way to do this is to keep them all in a folder alongside our code and have a naming convention of ‘team name’.png. The team names match up to the data that we are going to use soon. All of this is already prepared for you in the Github folder. Import data To start with, our data has three columns: team name, xG for and xG against. Let’s import our modules, data and check the first few lines of the dataframe: import pandas as pd import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox df = pd.read_csv(‘xGTable.csv’) df.head() We have our numbers to plot, but we need to add a reference for each team’s badge location in a new column. As we took the time to match the badge file names against the team names, this is really simple – we just add ‘images/‘ before and ‘.png’ after the team name. Let’s save this in a new column called ‘path’: df[‘path’] = df[‘Squad’] + ‘.png’ df.head() Plot a regular scatter chart Before making our plot with the badges, we need to create a regular scatter plot. This gives us the correct dimensions of the plot, the axes and other benefits of working with a matplotlib figure in Python. Once we have this, we can get fancy with our badges and other cosmetic changes. We have covered scatter plots before here, so let’s get straight into it. fig, ax = plt.subplots(figsize=(6, 4), dpi=120) ax.scatter(df[‘xG’], df[‘xGA’]) Super simple chart, and without annotations or visual cues we cannot tell who any of the points are. Adding badges will hopefully add more value and information to our plot. Adding badges to our plot Our base figure provides the canvas for the club badges. Adding these requires a couple of extra matplotlib tools. The first one we will use is ‘OffsetImage’, which creates a box with an image, allows us to edit the image and readies it to be added to our plot. Let’s add this to a function as we’ll use it a few times: def getImage(path): return OffsetImage(plt.imread(path), zoom=.05, alpha = 1) OffsetImage takes a few arguments. Let’s look at them in order: - The image. We use the plt.imread function to read in an image from the location that we provide. In this case, it will look in the path that we created in the dataframe earlier. - Zoom level. The images are too big by default. .05 reduces their size to 5% of the original. - Alpha level. Our badges are likely to overlap, in case you want to make them transparent, change this figure to any number between 0 and 1. This function prepares the image, but we still need to plot them. Let’s do this by creating a new plot, just as before, then iterating on our dataframe to plot each team crest. fig, ax = plt.subplots(figsize=(6, 4), dpi=120) ax.scatter(df[‘xG’], df[‘xGA’], color=‘white’) for index, row in df.iterrows(): ab = AnnotationBbox(getImage(row[‘path’]), (row[‘xG’], row[‘xGA’]), frameon=False) ax.add_artist(ab) What’s happening here? Firstly, we have created our scatter plot with white points to hide them against the background, rather than interfere with the club logos. We then iterate through our dataframe with df.iterrows(). For each row of our data we create a new variable called ‘ab’ which uses the AnnotationBbox function from matplotlib to take the desired image and assign its x/y location. The ax.add_artist function then draws this on our plot. This should give us something like this: Great work! We can now see who all the points are! Improving our chart Clearly there is plenty to improve on this chart. I won’t go through everything individually, but I’ll share the commented code below for some of the essential changes – titles, colours, comments, etc. # Set font and background colour plt.rcParams.update({'font.family':'Avenir'}) bgcol = '#fafafa' # Create initial plot fig, ax = plt.subplots(figsize=(6, 4), dpi=120) fig.set_facecolor(bgcol) ax.set_facecolor(bgcol) ax.scatter(df['xG'], df['xGA'], c=bgcol) # Change plot spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['left'].set_color('#ccc8c8') ax.spines['bottom'].set_color('#ccc8c8') # Change ticks plt.tick_params(axis='x', labelsize=12, color='#ccc8c8') plt.tick_params(axis='y', labelsize=12, color='#ccc8c8') # Plot badges def getImage(path): return OffsetImage(plt.imread(path), zoom=.05, alpha = 1) for index, row in df.iterrows(): ab = AnnotationBbox(getImage(row['path']), (row['xG'], row['xGA']), frameon=False) ax.add_artist(ab) # Add average lines plt.hlines(df['xGA'].mean(), df['xG'].min(), df['xG'].max(), color='#c2c1c0') plt.vlines(df['xG'].mean(), df['xGA'].min(), df['xGA'].max(), color='#c2c1c0') # Text ## Title & comment fig.text(.15,.98,'xG Performance, Weeks 1-6',size=20) fig.text(.15,.93,'Turns out some teams good, others bad', size=12) ## Avg line explanation fig.text(.06,.14,'xG Against', size=9, color='#575654',rotation=90) fig.text(.12,0.05,'xG For', size=9, color='#575654') ## Axes titles fig.text(.76,.535,'Avg. xG Against', size=6, color='#c2c1c0') fig.text(.325,.17,'Avg. xG For', size=6, color='#c2c1c0',rotation=90) ## Save plot plt.savefig('xGChart.png', dpi=1200, bbox_inches = "tight") This should return something like this: Conclusion In this tutorial we have learned how to programmatically add images to a scatter plot. We created an underlying plot, then looped through the data to overlay a relevant image on each point. This isn’t a good idea for every scatter chart, particularly when there are many points, as it will be an absolute mess. But with limited data points and value in distinguishing between them, I think we have a good use case for using club logos in our example. You might also have luck using this method to distinguish between leagues, or drawing the image for just a few data points that you want to highlight in place of an annotation. Interested in other visualisations with Python? Check out our other tutorials here!
https://fcpython.com/visualisation/creating-scatter-plots-with-club-logos-in-python
CC-MAIN-2022-33
refinedweb
1,195
66.54
pswinpy 0.0.1 A package for sending SMS messages using the PSWinCom SMS Gateway. A Python interface to the [PSWinCom SMS Gateway](). Installation The pswinpy package is distributed through PyPI as both egg, Windows and source. THIS IS NOT YET TRUE!! Basic Usage To use this package, you will need sign up for a Gateway account with PSWinCom. Demo account are available. This piece of code demonstrates how to send a simple SMS message: from pswinpy import API api = API("myUsername", "myPassword") api.sendSms(4712345678, "Strange women lying in ponds distributing swords is no basis for a system of government!") Properties Receiver and message text are the two mandatory properties when sending a message. You may specify additional properties by using named arguments. For instance this is how you would specify a sender: api.sendSms(4712345678, "It's just a flesh wound.", sender="BlackKnight") Properties currently supported are: - sender - TTL - time to live in minutes - tariff - the amount (in local currency as cents/"ører") to charge the receiver - serviceCode - service code for sending GAS messages. Requires that tariff is set. See [wiki]() for details. - deliveryTime - a datetime object specifying when to send the message Specifying Host The package is set to use a particular PSWinCom SMS Gateway by default. The host can be changed globaly by setting the host class property on HttpSender: HttpSender.host = "some.other.host.com" Modes For testing purposes the API provides a couple of modes you can set globally to control how the library works. Mode.test = True License This code is free to use under the terms of the MIT license. - Author: Torbjorn Maro - Keywords: SMS - License: MIT License - Categories - Development Status :: 4 - Beta - Intended Audience :: Developers - License :: OSI Approved :: MIT License - Operating System :: OS Independent - Programming Language :: Python - Programming Language :: Python :: 3 - Topic :: Communications :: Telephony - Topic :: Software Development :: Libraries :: Python Modules - Package Index Owner: tormaroe - DOAP record: pswinpy-0.0.1.xml
http://pypi.python.org/pypi/pswinpy/
crawl-003
refinedweb
320
56.15
Convert Float Array to Int Array in Numpy - Convert a 2D Array From Float to Int Using ndarray.astype()in Numpy - Convert a 2D Array From Float to Int Using ndarray.asarray() Often, we have to convert float values to integer values for a variety of use cases. Similar is the case with Python arrays and NumPy arrays. Using some functions from numpy, we can easily convert 2D float NumPy arrays into 2D integer NumPy arrays. In this article, we will talk about two such methods, ndarray.astype() and numpy.asarray(). Convert a 2D Array From Float to Int Using ndarray.astype() in Numpy NumPy arrays are of type ndarray. These objects have in-built functions, and one such function is astype(). This function is used to create a copy of a NumPy array of a specific type. This method accepts five arguments, namely, dtype, order, casting, subok, and copy. dtype refers to the data type of the copied array. order is an optional argument and it controls the memory layout of the resulting array. All the other options are optional. To learn more about the other parameters of this function, refer to the official documentation of this function here Refer to the following code to understand this function better. import numpy as np myArray = np.array([[1.0, 2.5, 3.234, 5.99, 99.99999], [0.3, -23.543, 32.9999, 33.0000001, -0.000001]]) myArray = myArray.astype(int) print(myArray) Output: [[ 1 2 3 5 99] [ 0 -23 32 33 0]] Convert a 2D Array From Float to Int Using ndarray.asarray() Secondly, we can use the asarray() function. This function accepts four arguments, a, dtype, order, and like. arefers to the input array that has to be converted. dtyperefers to the data type to which the array has to be converted. Interestingly, dtypeis an optional argument, and its default value is inferred from the input itself. orderand likeare also other optional arguments. orderrefers to the output array’s memory layout. To learn more about the arguments of this function, refer to the official documentation of this function here import numpy as np myArray = np.array([[1.923, 2.34, 23.134], [-24.000001, 0.000001, -0.000223]]) myArray = np.asarray(myArray, dtype = int) print(myArray) Output: [[ 1 2 23] [-24 0 0]] In the above code, the data type is mention as int, and the output array is also an integer NumPy array.
https://www.delftstack.com/howto/numpy/numpy-float-to-int/
CC-MAIN-2021-21
refinedweb
407
66.94
Introduction to the Other DeepSee Tools This chapter introduces the other tools for working with DeepSee. MDX Shell DeepSee provides a shell in which you can issue MDX queries to explore your DeepSee cubes and subject areas. This section introduces this shell and lists the supported MDX options and functions. For an introduction to MDX queries, see Using MDX with DeepSee, which contains many examples. Also see the DeepSee MDX Reference. Accessing the MDX Shell To access the MDX shell, start the Terminal and do the following: Switch to the namespace in which you defined the cube or subject area. Enter the following command: Do ##class(%DeepSee.Utils).%Shell()Copy code to clipboard Now you can enter MDX queries like the following: SELECT MEASURES.[%COUNT] ON 0, birthd.decade.MEMBERS ON 1 FROM patients When you do so, the shell executes the query, displays its results to the console, and redisplays the shell prompt, as follows: Patient Count --------------------------------------------------------------------------- Elapsed time: .014128s In the shell: To display a list of cubes and subject areas, enter cube To see the contents of a cube or subject area, enter cube name_of_cube_or_subject_areaNote: This command does not display calculated members and named sets, although you can use these elements in the shell and elsewhere. For a subject area, this command lists all elements, even if those are specified as hidden in the subject area. To exit the shell, enter q To enable query caching, enter cache on. If you set cache off and then run an MDX query in the shell, the MDX shell purges all cached queries for that specific cube system-wide. This could lead to slower performance for other users. To enable the asynchronous mode, enter async on To build a cube, enter build cubename To reset the query cache, enter reset For a list of additional shell options, enter ? Viewing the Indices Used by a Query The DeepSee shell provides a quick way to see the indices that a query uses: Issue the following shell command: stats onCopy code to clipboard Enter the query, preceded by %SHOWPLAN. For example: %SHOWPLAN SELECT aged.[age group].members ON 0, allerd.H1.MEMBERS ON 1 FROM patients WHERE colord.red 0 to 29 30 to 59 60 + 1 additive/colorin 27 19 14 2 animal dander 15 25 8 3 ant bites 15 19 11 4 bee stings 24 27 7 5 dairy products 25 25 4 6 dust mites 28 23 10 7 eggs 19 21 13 8 fish 26 17 11 9 mold 23 23 6 10 nil known allerg 80 82 21 11 No Data Availabl 216 194 92 12 peanuts 26 15 8 13 pollen 29 22 11 14 shellfish 29 23 14 15 soy 25 25 6 16 tree nuts 22 18 8 17 wheat 16 17 8 -------------- Query Plan --------------------- **%SHOWPLAN SELECT [AGED].[AGE GROUP].MEMBERS ON 0,[ALLERD].[H1].MEMBERS ON 1 FROM [PATIENTS] WHERE [COLORD].[RED]** **DIMENSION QUERY (%FindMemberByName): SELECT TOP 1 %ID,Dx327553094 MKEY,Dx327553094 FROM Cubes_StudyPatients.Star327553094 WHERE Dx327553094=? ORDER BY Dx327553094** **EXECUTE PARALLEL: 1x1 task(s) ** **CONSOLIDATE** -------------- End of Plan -----------------Copy code to clipboard Line breaks were added here for readability. DeepSee captures all the indices used by the query and reports them. Note that the query results are not necessarily correct because the query is only partially run; the purpose of %SHOWPLAN is to enable you to see the indices, not to get the query results. Utility Methods The class %SYSTEM.DeepSee includes the most commonly used utility methods. These include: BuildCube() KillCube() ListCubes() Reset() Shell() SynchronizeCube() This class is available via the special variable $SYSTEM, as are all classes in the %SYSTEM package. For example, to build a cube, you can use the following: Do $system.DeepSee.BuildCube("MyCube")Copy code to clipboard The class %DeepSee.Utils includes a large set of utility methods, including: %ExportExcelToFile() — exports a DeepSee query or KPI to a file in Microsoft Excel format %ExportPDFToFile() — exports a DeepSee query or KPI to a file in PDF format %GetAgentCount() — gets the current agent count %GetBaseCube() — gets the name of cube on which a subject area is based %GetCubeFactClass() — gets the name of fact table class associated with a cube %GetCubeLevels() — gets the levels, measures, and relationships defined in a cube %GetDimensionMembers() — gets the list of members of a dimension %GetMetricList() — gets all Ensemble business metrics visible to current user %GetSQLTableName() — gets SQL table name for a given class %ProcessFact() — updates a single fact for a cube %GetMDXFromPivot() — returns the MDX query defined by a pivot table %ExecutePivot() — runs the MDX query defined by a pivot table and optionally returns an instance of %DeepSee.ResultSet %GetResultsetFromPivot() — returns an instance of %DeepSee.ResultSet that holds the MDX query defined by a pivot table and optionally runs that query The class %DeepSee.UserLibrary.Utils includes methods that you can use to programmatically perform the tasks supported in the Folder Manager. These methods include: %AddFavorite() %DeleteFolderContents() %DeleteFolderItem() %Export() %GetFolderList() %ImportContainer() Data Connector The data connector class (%DeepSee.DataConnector) enables you to make arbitrary SQL queries available for use in DeepSee cubes and listings. See the DeepSee Implementation Guide. Result Set API The class %DeepSee.ResultSet enables you to execute MDX queries programmatically and access the results. For information, see the DeepSee Implementation Guide. JavaScript and REST APIs The DeepSee JavaScript API is provided by the file DeepSee.js, which is in the install-dir/CSP/broker directory. This JavaScript library enables you to interact with DeepSee from a client that is based on JavaScript. The functions in this library are a wrapper for a REST-based API for DeepSee. You can also use the REST API directly. For information, see Tools for Creating DeepSee Web Clients.
https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=D2GS_CH_TOOLS
CC-MAIN-2021-10
refinedweb
954
61.06
I can resolve the sync issue by a forced copy of the local file to the server, but I have to do this for every file I update on the Windows I recommend confirming this is the problem before reimaging by logging in as the end user on another machine and syncing files, watching for errors as before. Changes that were made to their attachments are not compatible with the server. However, the users have files from other directories in the Offline Files cache, too. get redirected here If not, something is wrong with your permissions propagation. AN UPDATE: I think I have discovered something! For more news about Jack Wallen, visit his website jackwallen.com. I have no problems to update simple text files with notepad for instance. regards, Christian Reply Mat May 1, 2014 at 15:45 # I've no end of frustration (scrap that - outright hatred) for Offline Files. Awesome Inc. On Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. 'Path' includes all the nested folder names, eg "C:\MyPrograms\Microsoft Office". 'File Names' Privacy statement © 2016 Microsoft. On Win 8, however, forget it. You ought to be able to view their docs. Remember, you have a full backup of this data, so even if something goes completely wrong, you can replace it. Windows 7 Offline Files Not Syncing Automatically Wednesday, December 23, 2009 5:57 AM Reply | Quote 0 Sign in to vote I checked how Office 2007 worked in a Windows 7 environment.Shared folder in a drive on a I see the files in question but the recycle bin items are nowhere to be seen. After disabling offline files for the user I then cleared out their CSC, cleared out However, several users reported that when they looked at the files actually available offline (by starting Manage offline files and clicking View your offline files), they had files not only from I tested to update an old EXCEL file in compatibility mode ( the old file format) and this worked without any problem as well! All rights reserved. This is not SAMBA, (which is evidently a Unix tool). Offline Files Sync Failed Access Denied Get the Path Scan app from here(This is an older version of Path Scanner but you need it because it works with UNC paths - i.e. Template images by latex. Offline Files considers \\server.domain.com\share and \\server\share 2 independent namespaces. Tuesday, February 02, 2010 10:47 PM Reply | Quote 0 Sign in to vote Hi Scotte,Thanks for trying to help.This thread is a little over 3 months old. : )I think Generated Sat, 22 Oct 2016 07:25:03 GMT by s_nt6 (squid/3.5.20) Home Offline Files not syncing Windows 7 by Mercutio879 on Mar 28, 2013 at 1:12 UTC | Windows 7 0Spice Down Offline Files Not Syncing Windows 7 Then I made the folder 'always available offline' and the sync process now seems to work.Regardless, there seems to be something broken in the way 'offline folders' works.I can sum it Sync Failed With Offline Files Windows 7 This is strictly a Windows 7 environment.First Impression: Office 7 appears to be working correctly in regards to Offline Files in a Windows 7 environment.Suggested Workaround: Switch from Unix to Windows Conflicts Contains all the multiple copies of conflicting items in your mailbox. Get More Info The synchronization issues folders contain logs and items that Microsoft Outlook has been unable to synchronize with your Exchange Server or SharePoint server. generated errors in the Sync Center during the synchronization process? The key to do so is the "explorer elevated unelevated factory" registry as described in The only caveat with this method: It's hard to distinguish different explorer instances that run Offline Files Not Syncing Windows 10 With the computer connected to the network and Online I can see the two 0 KB files listed but anytime you try and access them (both PDFs) an error message shows as This feature requires you to use a Microsoft Exchange Server 2003, Exchange Server 2007, or Exchange Server 2010, and a Microsoft SharePoint account. Join Now Last year we turned on folder redirection for our users my documents. useful reference Some documents are there, but nothing from within the last 3 months, it appears. Items normally appear in this folder only when there are failures in synchronizing server items with an Offline Folder file (.ost), which is used when you work offline or use Cached Offline (need To Sync) Powered by Livefyre Add your Comment Editor's Picks IBM Watson: The inside story Rise of the million-dollar smartphone The world's smartest cities The undercover war on your internet secrets Free Newsletters, Local Failures Contains all items that could not be sent to your server. Copy the backup of the data from the client to the server. Although we have run into multiple issues like that and the truth is that Microsoft's solution to offline document management is damned if you do and damned if you don't. Wednesday, February 03, 2010 5:03 PM Reply | Quote Microsoft is conducting an online survey to understand your opinion of the Technet Web site. Windows 10 Offline Files Not Working Help Desk » Inventory » Monitor » Community » Home Redirected Folders + Offline Files + Access Denied = Bad Headache by JGatz on Mar 27, 2014 at 2:02 UTC | By creating an account, you're agreeing to our Terms of Use, Privacy Policy and to receive emails from Spiceworks. Drive DVD drive Display 1024x768 or higher resolution monitor Operating system Microsoft Windows XP with Service Pack (SP) 2, Windows Server 2003 with SP1, or later operating system4 Thursday, December 24, Users afterward kept receiving access denied messages. this page Note: Other redirected folders that can be redirected "officially" did not negatively impact synchronization, e.g. The task was moved to your Local Failures folder. i know onsite here we have to allow users to see and traverse the "USERS$" folder in DFS sot hat Win7 boxes could do offline files 0 Tabasco I'm not stating it is a fault in Windows 7. All rights reserved.Newsletter|Contact Us|Privacy Statement|Terms of Use|Trademarks|Site Feedback TechNet Products IT Resources Downloads Training Support Products Windows Windows Server System Center Browser Office Office 365 Exchange Server SQL Server Tried using the "Unlocker" program mentioned in some other forums to check if the file has any open handles. None were found, and yet the program can't delete the file. I I've read that the better way to do this is to create a share for each user, but that's not really practical. 0 Mace OP Texkonc Mar 28, This quote is a post I found in the digitalspy forum (see my sources) and explains it beautifully. "The simplest explanation is that you've exceeded the maximum path and/or file lengths. I say "problems"; I'm sure there's ONE guy in Redmond to whom many of the answers to my questions are obvious. If you have made changes to items while working offline, and then notice that your changes are not appearing in another Outlook client, Outlook Web Access, or your SharePoint list, you Delete the data from the client. c:\ and that's useless because the path length problem is all about the length of the full UNC path.)Now go online and sync with your server so you can see the I think it is a better strategy to openly admit there are problems with offline folders with Samba based servers. Clicking the InfoBar will bring up a list of conflicting items and allow you to resolve the conflict by determining which item you want to keep. To work around this limitation, you can add individual contacts from within the group to the SharePoint list. I think this goes for every NAS provider more or less, since almost all of them are SAMBA based.... He’s an avid promoter of open source and the voice of The Android Expert. The file share is an EMC VNXe3300 with file deduplication turned on, but thin provisioning off. Then a sync failed notice.One of the biggest data folders does not complete synchronization.The drive is a 250Gb drive about 1/3 full.Can I exclude the 'Recycle bin' from the sync process?If Server Failures Contains items that Outlook failed to synchronize from your Exchange mailbox or SharePoint server. With the amount of Samba based NAS devices out there today together with the new library function in Windows that automatically turns on off line folders as soon as you include
http://dlldesigner.com/offline-files/offline-folder-sync-error.php
CC-MAIN-2017-51
refinedweb
1,455
58.82
current position:Home>Deep understanding of Python features Deep understanding of Python features 2022-01-30 07:22:45 【cxapython】 Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities . This article has participated in 「 Digging force Star Program 」 , Win a creative gift bag , Challenge creation incentive fund 1. Assertion Python The assertion statement is a debugging aid , Not a mechanism for handling runtime errors . assert Condition is False Is triggered when , The following content is the error information . import sys assert sys.version_info >= (3, 7), " Please be there. Python3.7 And above environmental execution " Copy code If the minimum requirement for this project is Python3.7 Environment , So if you use Python3.6 To run this project , This error message will appear . Traceback (most recent call last): File "/Users/chennan/pythonproject/demo/nyandemo.py", line 3, in <module> assert sys.version_info > (3, 7), " Please be there. Python3.7 The above environment is implemented " AssertionError: Please be there. Python3.7 The above environment is implemented Copy code Early termination of the project 2. Cleverly place commas Reasonably format the elements in the list , Easier to maintain We usually do this when we write a list l = ["apple", "banana", "orange"] Copy code Use the following methods to distinguish each item more clearly , Habitually add a comma at the end , Prevent missing commas when adding elements next time , It looks more Pythonic l = [ "apple", "banana", "orange", ] Copy code 3. Underline 、 Double underline and other Pre single underline : _var 1. It's a convention , Methods and variables with a single preceding underscore are used internally only 2. The use of wildcard guided packages from xx import * such , You don't need to import variables with a single underscore in front of them , Unless it defines __all__ Covering this behavior .PEP8 It is generally not recommended to guide the package in this way . Post single underline : var_ If the variable name used is Python Keywords in , For example, to declare class This variable , We can put a single underline after it at this time class_ This is also PEP8 Agreed in Leading double underline : __var Leading double underscores will make Python The interpreter overrides the property name , Prevent from being overwritten by names in subclasses . class Test: def __init__(self): self.foo = 11 self.__bar = 2 t = Test() print(dir(t)) Copy code Looking at the properties of the class, you can find self.__bar Change into _Test__bar, This is also called name rewriting (name mangling), The interpreter changes the name of the variable , Prevent naming conflicts when expanding this type . ['_Test__bar', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'foo'] Copy code If you want to visit __bar, What shall I do? , We can go through t._Test__bar Visit . If we inherit Test Then rewrite __bar What will happen class ExtendTest(Test): def __init__(self): super().__init__() self.foo = "overridden" self.__bar = "overridden" et = ExtendTest() print(et.foo) print(et.__bar) Copy code It turns out that something went wrong AttributeError: 'ExtendTest' object has no attribute '__bar' Copy code The reason is the same as before , Because the interpreter puts __bar The name of is changed to prevent the variable of the parent class from being overwritten . We can access these two classes separately __bar Find that they exist at the same time , It's really not covered . print(et._Test__bar) print(et._ExtendTest__bar) Copy code Get the results 2 overridden Copy code By the way __bar In English, it is generally called dunderbar. Except for double underlined variables , Double underlined method names can also be overwritten by interpreter names . class ManglingMethod: def __mangled(self): return 42 def call_it(self): return self.__mangled() md = ManglingMethod() md.call_it() md.__mangled() Copy code After getting the error message AttributeError: 'ManglingMethod' object has no attribute '__mangled' Copy code Double underline before and after : var The so-called magic method , Its name will not be changed by the interpreter , However, as far as naming conventions are concerned, it is best to avoid using such formal variable and method names Underline : _ 1. _ It can indicate that the variable is temporary or irrelevant for _ in rang(5): print("hello") Copy code 2. It can also be used as a thousand separator before a number for i in range(1000_000): print(i) Copy code 3. It can be used as a placeholder when unpacking tuples . car = ("red", "auto", 12, 332.4 ) color,_,_,mileage = car print(color) print(_mileage) Copy code 4. If you use command line mode , _ You can get the results of the previous calculation >>> 20+5 25 >>> _ 25 >>> print(_) 25 Copy code 4. Custom exception classes We have the following code def validate(name): if len(name) < 10: raise ValueError Copy code If you call this method in other files , validate("lisa") Copy code When you don't understand the function of this method , If the name verification fails , The call stack will print out the following information Traceback (most recent call last): File "/Users/chennan/pythonproject/demo/nyandemo.py", line 57, in <module> validate("lisa") File "/Users/chennan/pythonproject/demo/nyandemo.py", line 55, in validate raise ValueError ValueError Copy code The information in this stack debug backtrace indicates , An incorrect value has occurred , But I don't know why I made a mistake , So we need to follow up at this time validate To find out , At this time, we can define an exception class ourselves class NameTooShortException(ValueError): def __str__(self): return " The length of the entered name must be greater than or equal to 10" def validate(name): if len(name) < 10: raise NameTooShortException(name) validate("lisa") Copy code So if there's another mistake , You can know why you're wrong , At the same time, the calling method is also convenient to catch the specified exception , Don't use ValueError. try: validate("lisa") except NameTooShortException as e: print(e) Copy code 5.Python Bytecode Cpython When the interpreter executes , First, it is translated into a series of bytecode instructions . Bytecode is Python Intermediate language of virtual machine , It can improve the execution efficiency of the program Cpython Do not directly execute human readable source code , Instead, it performs a compact number generated by compiler parsing and syntax semantic analysis 、 Variables and references . such , It can save time and memory when executing the same program again . Because the bytecode generated by the compilation step will be .pyc and .pyo The form of file is cached on the hard disk , Therefore, it is better to execute bytecode than to execute the same code again Python Files are faster . def greet(name): return 'hello, ' + name + '!' #__code__ Can get greet Virtual machine instructions used in the function , Constants and variables gc = greet.__code__ print(gc.co_code) # Command stream print(gc.co_consts) # Constant print(gc.co_varnames) # Parameters transmitted dis.dis(greet) Copy code result b'd\x01|\x00\x17\x00d\x02\x17\x00S\x00' (None, 'hello, ', '!') ('name',) 70 0 LOAD_CONST 1 ('hello, ') 2 LOAD_FAST 0 (name) 4 BINARY_ADD 6 LOAD_CONST 2 ('!') 8 BINARY_ADD 10 RETURN_VALUE Copy code The interpreter is indexing 1 It's about ('hello, ') Find constants , And put it on the stack , And then name Put the contents of the variable on the stack Cpython Virtual machine is based on stack virtual machine , Stack is the internal data structure of virtual machine . The stack only supports two actions : Push and pull Push : Add a value to the top of the stack Out of the stack : Delete and return the value at the top of the stack . Suppose the stack is initially empty , Before executing the first two opcodes (opcode) after , Virtual content (0 It's the top element ) For example, we introduced name by lisa. 0: 'lisa' 1: 'hello, ' Copy code BINARY_ADD Instruction pops two string values from the stack , And connect them Then push the result onto the stack again . 0:'hello, lisa' Copy code Then the next LOAD_CONST take '!' Push to stack . The result at this point 0:'!' 1:'hello, lisa' Copy code next BINARY_ADD The opcode pops the two strings out of the stack again, connects them, and then pushes them into the stack , Generate the final result 0:'hello, lisa!' Copy code Last bytecode RETURN_VALUE , Tell the virtual machine that what is currently at the top of the stack is the return value of the function . The original text comes from my Zhihu column :zhuanlan.zhihu.com/p/267563522 author[cxapython]
https://en.pythonmana.com/2022/01/202201300722307009.html
CC-MAIN-2022-27
refinedweb
1,433
51.78
System Calls sigaction(2) NAME sigaction - detailed signal management SYNOPSIS #include <signal.h> int sigaction(int sig, const struct sigaction *act, struct sigaction *oact); DESCRIPTION The sigaction() function allows the calling process to exam- ine or specify the action to be taken on delivery of a specific signal. (See signal(3HEAD) for an explanation of general signal concepts.) The sig argument specifies the signal and can be assigned any of the signals specified in signal(3HEAD) except SIG- KILL and SIGSTOP. In a multithreaded process, sig cannot be SIGWAITING, SIGCANCEL, or SIGLWP. sa_handler member identifies the action to be associated with the specified signal, if the SA_SIGINFO flag (see below) is cleared in the sa_flags field of the sigaction structure. It may take any of the values specified in signal addi- tion, the signal that caused the handler to be executed will also be blocked, unless the SA_NODEFER flag has been speci- fied. SIGSTOP and SIGKILL cannot be blocked (the system silently enforces this restriction). The sa_flags member specifies a set of flags used to modify the delivery of the signal. It is formed by a logical OR of SunOS 5.8 Last change: 19 Mar 1998 1 System Calls sigaction(2) any of the following values: SA_ONSTACK If set and the signal is caught, and if the LWP that is chosen to processes a delivered signal has an alternate signal stack declared with sigaltstack(2), then it will process the signal on that stack. Other- wise, the signal is delivered on the LWP main stack. Unbound threads (see thr_create(3THR)) may not have alternate signal stacks. SA_RESETHAND res- triction).(2), waitid(2), and the following functions on slow dev- ices argu- ments)). SA_NOCLDWAIT If set and sig equals SIGCHLD, the system will not SunOS 5.8 Last change: 19 Mar 1998 2 System Calls sigaction(2) create zombie processes when children of the calling process exit. If the calling process subsequently issues a wait(2), it blocks until all of the calling process's child processes terminate, and then returns -1 with errno set to ECHILD. SA_NOCLDSTOP If set and sig equals SIGCHLD, SIGCHLD will not be sent to the calling process when its child processes stop or continue. SA_WAITSIG If set and sig equals SIGWAITING, enables generation of SIGWAITING signals. Reserved for use by the threads library. RETURN VALUES Upon successful completion, 0 is returned. Otherwise, -1 addi- tion, if in a multithreaded process, it is equal to SIGWAITING, SIGCANCEL, or SIGLWP. ATTRIBUTES See attributes(5) for descriptions of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | MT-Level | Async-Signal-Safe | |_____________________________|_____________________________| SEE ALSO kill(1), intro(3),), recv(3SOCKET), signal(3C), sigsetops(3C), thr_create(3THR), attributes(5), siginfo(3HEAD), signal(3HEAD), ucontext(3HEAD) NOTES The handler routine can be declared: SunOS 5.8 Last change: 19 Mar 1998 3 System Calls sigaction(2) void handler (int sig, siginfo_t *sip, ucontext_t *uap); The sig argument is the signal number. The sip argument is a pointer (to space on the stack) to a siginfo_t structure, which provides additional detail about the delivery of the signal. The uap argument. SunOS 5.8 Last change: 19 Mar 1998 4
http://www.manpages.info/sunos/sigaction.2.html
crawl-003
refinedweb
533
61.87
ndef RECFILE_H #define RECFILE_H #include "buffile.h" #include "iobuffer.h" // template class to support direct read and write of records // The template parameter RecType must support the following // int Pack (IOBuffer &); pack record into buffer // int Unpack (IOBuffer &); unpack record from buffer template <class RecType> class RecordFile: public BufferFile {public: int Read (RecType & record, int recaddr = -1); int Write (const RecType & record, int recaddr = -1); int Append (const RecType & record); RecordFile (IOBuffer & buffer): BufferFile (buffer) {} }; // template method bodies template <class RecType> int RecordFile<RecType>::Read (RecType & record, int recaddr) // changed { int writeAddr, result; writeAddr = BufferFile::Read (recaddr); if (!writeAddr) return -1; result = record . Unpack (Buffer); if (!result) return -1; return writeAddr; } template <class RecType> int RecordFile<RecType>::Write { int result; result = record . Pack (Buffer); if (!result) return -1; return BufferFile::Write (recaddr); } template <class RecType> int RecordFile<RecType>::Appen { int result; result = record . Pack (Buffer); if (!result) return -1; return BufferFile::Append(); } #endif Both changed lines are marked. Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial Just have a related question about the above code. In general, how do we test or debug a header file (*.h) without a main code (like above) ? Is that the same for visual C++ and C++ ? thanks a lot ! meow.... Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services. I just dumped the posted code into a .cpp file with an empty main() and instantiated a RecordFile<int>. Had to comment out some of the dependencies (buffile.h and iobuffer.h and the classes they contained). I had figured out what the problem was by inspection but figured a quick compile cycle to show that I could fix it would be a good thing before posting a solution. -bcl When you separate the declaration and definition of a FUNCTION (I said variable) with default values for the parameters the default values go on the delcaration ONLY. Thus the bug was the repeat of the "int recaddr = -1" or, more specifically, the " = -1" when defining Read and Write. Append doesn't have the problem because it has no default parameters. Hope what I meant is clearer. -bcl
https://www.experts-exchange.com/questions/20821210/Coding-problem-in-making-a-record-file-C.html
CC-MAIN-2018-30
refinedweb
416
66.84
ICANN Recommends ISOC Run .org TLD 113 Amazing Quantum Man writes "According to ZDNet, ICANN has issued a report recommending that ISOC run the .org TLD. It looks like ISOC would run .org in conjunction with Afilias." mesozoic points out that ISOC is a non-profit organization composed of many for-profit heavyweights, writing "I'm not surprised; are you?" This preliminary report may be disappointing to those who hoped that Paul Vixie and Carl Malamud would be successful in their bid to head up .org. Why Not Read the Right Report? (Score:5, Informative) Lonely Sig Alert: Re:Why Not Read the Right Report? (Score:1) In reading part of it... If you have not done it before, you got wacked. If you are not a business model, you got wacked. So no new comers and no non-business. And Gartner?? I personally have yet to see one report that was not bais in favor of their other clients. Like the MS pages on their site. Like I said, yeah sure. I can see the ads already (Score:3, Funny) So, like, when should we start going to slashdot.com instead of slashdot.org? Re:I can see the ads already (Score:1) Or, when are we going to slashdot.gnu, as soon as mozilla ships with a new default TLD server? (Score:1) ICANN ISOC IAHC I I I I I IEEEEEEEEEEEEE This is bad how? (Score:5, Interesting) So it represents no one company, and when it does something it will do it with industry backing. This is a Good thing. Exactly what can be done with the It is already open to anyone, regardless of whether they are non-profit or not. Re:This is bad how? (Score:3, Insightful) By the way, I make my living writing software for web commerce sites, so I am not opposed to commercial interests using the internet just as freely as geeks and academicians. Re:This is bad how? (Score:1) So it will most likely remain a free-for-all. What do you imagine they might do to restrict your freedom? I'm not saying they can't, but that I can't think of anything right now. Then join (Score:2, Interesting) An ISOC Member Re:This is bad how? (Score:3, Insightful) Think about what you're saying: the for-profit companies are the ones running the not-for-profit domain registration. If there's a fight between two groups over a domain and one of the groups is an industry association (oh, let's say the RIAA), which one do you think would be favored? Re:This is bad how? (Score:2) Re:This is bad how? (Score:1) Did you not read my comment? They already allow for-profit organisations. It is entirely unworkable to set a non-profit agenda for this domain in the future. At some point you're going to have to be grossly unfair to a lot of people which is what we want to avoid. BTW the What was your point again? Re:This is bad how? (Score:2) There can and will be not-for-profit organisations which will threaten income models. If you don't think they'll bail each other out Re:This is bad how? (Score:2) Well, they could unfairly favour large, rich corporations over poor non-profit organisations when settling disputes for one thing. The whole point of .org is to provide a safe place for non-profit orgs to live - if it's being administered by an org that is dominated by big corps and (ex-) directors of ICANN then I can't see that being a good thing. Re:This is bad how? (Score:1) Re:This is bad how? (Score:1) This is a Good thing." And which industry??? The org domain represents charities, clubs, and free software. The ISOC represents the commercial software and telecoms industries. It's no use claiming that everyone will agree, if the org domain is administered by some of the people most hostile to those using the domain. Run with Affilias? I hope not. (Score:2) A) It's in some funky delimited format that doesn't work for any existing WHOIS parser. I tried adding an B) It displays the registrant info. Nobody needs to know who the registrant is. Nine times out of ten it's some employee that either no longer even works for the company or has no authority to make domain decisions. C) It displays the billing info. This means your home address if you happen to use a credit card to pay for the domain. Luckily some registrars will substitute their own info for your personal billing info but even then this seems sloppy. Can someone fill me in on why Affilias can't even seem to get something as trivial as a WHOIS done correctly? And these people want to run No thank you. - JoeShmoe . Re:Run with Affilias? I hope not. (Score:1) Re:Run with Affilias? I hope not. (Score:2) The only people who need to know the billing info for a domain is the registrar. They need to charge the billing contact. The general public has no need to know who pays for a domain. If you have a tech question/problem, you contact the zone contact or the tech contact. If you have a domain dispute or copyright complaint, you can contact the owner or the admin. No one need to contact the billing contact except the registrar who gets paid by them and they can easily keep that information in a separate database for themselves. - JoeShmoe . Re:Run with Affilias? I hope not. (Score:2) B) Displaying the registrant info is my primary reason for using whois at all. If I want the nameservers, I can always use dig. C) If you don't want your billing info made public, don't register your own domain name. Part of owning a domain is using it responsibly, and that means accountability, which only works if people can find you. If you don't want to play by these rules (which have been in place for at least a decade), then find a different game to play. Re:Run with Affilias? I hope not. (Score:2) Why isn't/shouldn't the registrant info be displayed? Because it is always out of date. The registrant fields cannot be changed. If your e-mail address or mailing address changes, you can't change the registrant fields. The only way to change it is to "transfer" the domain to yourself and pay an additional $35/whatever fee. ICANN's rules. Now, all the other contact info, like Owner, Admin, Zone, Tech, Billing can be changed at any time. That is why these fields are the only contact info people should be using. That is why these fields should be the only ones visible. And regarding billing info, so what BS are you proposing? Only corporations are allowed to own domains? Any private citizen who doesn't feel like putting their home information on a publically accessible database is unworthy to own a domain? As I said earlier, why does anyone even need to talk to the billing contact when the person with authority over the domain is the owner or the admin? And if billing info is key to accountability, why do ICANN rules say not to display it? - JoeShmoe . You can't make everyone happy (Score:2, Insightful) I am sure that ICANN critics would be able to find something wrong with every single one of the groups vying for the If the platter fits... (Score:3, Insightful) Hmmm, an alleged non-controversial infrastructure overseer which expanded its mandate, tried to assess an unauthorized tax, and then summarily and unilaterally dismantled its already-small semblance of democracy and accountability (not to mention illegally hid its internal workings to prevent criticism)... yeah, I think "head on a silver platter" is just about right. Re:You can't make everyone happy (Score:3) A person who works for a major corporation has a responsibility to the interests of that corporation, not the other 99% of the entities who use the Internet. A group run by a consortium of these goons (goon. a man hired to terrorize or eliminate opponents. Merriam-Webster's Collegiate Dictionary) will always act in the interest of their companies, and against the interest of everyone else. The result is an official establishment of a tyrannical structure that exists for the purpose of prying money out of the fingers of the many and stuffing it into the pockets of the few. Very few. This is why ISOC's corporate affiliation is important and unacceptable. Yes, I screwed up (Score:1) Bad choice (Score:5, Interesting) Nepotism? (Score:5, Informative) It seems ISOC is a body which is busy reforming itself to reduce the power of individual members [open-isoc.org] Re:nix TLDs (Score:1) Sure, we'll just make up for it by usin one between each digit for reverse dns anyways. Re:nix TLDs (Score:1) Re:nix TLDs (Score:3, Insightful) The top poster did say, "Why not get rid of DNS?" (A different argument, altogether.) but "Why not get rid of TLD?" Is there any longer -- was there in fact ever -- a reason for partitioning the namespace into Re:nix TLDs (Score:1) Right. There _must_ be a root to the domain name tree somewhere; otherwise every computer would have to a unique name. Obviously out of the question. So why the TLDs we have now? Because ICANN stinks, and people knew that a registrar might go stinky; so the (US) military and (US) the government got their own domains, and all the soveriegn nations got their own nation-domain, too. Why are the TLDs limited? Otherwise, I can't tell, when you type slashdot.trolls, if you want the slashdot in the TLD trolls, or (one of) the slashdot.trolls on my local network. - _Quinn Nice to see that ICANN stays close to home... (Score:3, Interesting) I bet its just a front for a corporate trust. alternic (Score:1) because... (Score:3, Interesting) Do you have any more info on this? (Score:2) I've never switched to alternic but I've kind of kept tabs on it a bit. The biggest reason I haven't switched to alternic is because the internet can't work if everyone creates their own alternic. Not for profit? (Score:2) Microsoft (Score:2) ISOC's membership page [isoc.org] lists Microsoft as one of the founding and highest ranking members. I'll just sit back and watch the fireworks. - Is BIND really that bad? (Score:2) Is his software good enough to act as a production DNS server? It seems like it but I've never even heard of it before now. If BIND is so bad and his is so great, how come more people haven't switched over. Or have they? He needs to get one of the big distros to package his stuff. Re:Is BIND really that bad? (Score:1) see for some of them. lycos, btw, switched to it a couple of weeks ago. What about the license for this software? (Score:2) Re:Is BIND really that bad? (Score:1) And there ain't nothin' worse than trying to make a phone call and discovering that the phone book no longer works. ISOC is also made up of individuals (Score:2, Interesting) Re:ISOC is also made up of individuals (Score:3, Interesting) Re:ISOC is also made up of individuals (Score:2) You think I don't? It's been time for over a year to design ways to avoid the use of the resources controlled by these bodies. The flare-lit tip off was when the W3C announced that it was considering counting "standards" that one would need to pay to use as real standards. They have sort of retreated from that proposal, but that was a clear warning. The organizations that have in the past been trustworthy can no longer be counted on. In the past there wasn't that much money to be taken out of the internet, but now that it's seen as a valuable resource, they can't be trusted. So these centers of control need to be designed around *NOW*. We can't afford to wait until they actually move from these hesitant proposals to bold grabs for control. It takes time to design and implement these changes. So now is the time to already have a project in motion. Re:ISOC is also made up of individuals (Score:5, Insightful) Ah, but blockquoth the site openISOC [open-isoc.org]: Seems pretty shady to me... Re:ISOC is also made up of individuals (Score:2) Or would you really rather call it ISOC BOT (I suck butt... "We leave it in your capable hands, ISOC BOT," "Thank goodness ISOC BOT," "I am sick and tired of dealing with ISOC BOT," "Ever since ICANN recognized that ISOC BOT, the .org TLDs have been in the toilet," etc.)? Re:ISOC is also made up of individuals (Score:2) Maybe we can just replace the human Board with a little script that trundles the web automatically.. Re:ISOC is also made up of individuals (Score:2) Re:ISOC is also made up of individuals (Score:2) 2. As an ISOC insider, your statements regarding ISOC's character are to be taken with a grain of salt. Few insiders criticize their own organization. 3. ISOC does not represent the true ideals of the internet. It represents the interests of its corporate members. That MS is listed as one of the "founding members" of ISOC, speaks volumes about ISOC's allegience. An organization which represents the ideals of the internet is the EFF, and that organization would be a good choice for management of Also, I've noticed that though ISOC has links to news regarding Internet Issues, they take no stance on them. This illustrates a clear lack of any backbone. ISOC will cave in to corporate interests in managing Simply put, Not my choice (Score:5, Informative) ICANN's own conflict of interest rules are not this strict. But I consider ICANN's conflict-of-interest policy to be a minimum standard (and a weak minimum at that.) My vote is looking to be cast in favor of the best applicant, not the one that passes bare minimums. I also wonder at the concept that competition is promoted by handing Re:Not my choice (Score:2) Is this likely to improve now that democracy has been successfully removed from ICANN? [slashdot.org] I would think that conflicts are likely to run even deeper once there are no elected members on the board. Thanks for giving the little guy a voice(at least for now), Karl. I voted for you :-) Re:Not my choice (Score:2) And Paul Dixie does ? He is on a self confessed power grab and frankly the guy has VERY scarey ideals. Adopting the lesser of two evils is not a choice I'm prepared to support. They just better carry all records over... (Score:2) (I paniced when I first heard talk about making .org registered non-profits only, so I prepaid for as long as I could, hoping I'd get grandfathered in if it came to that...) .ORG Should b e Organizations/like only (Score:3, Interesting) Every time some corporations like the RIAA or MPAA owns a Now, I'm not saying that any corporation that owns a I have no problem with MS owning microsoft.com, microsoft.org, and microsoft.net, so long as they use those sites in a way true to their "extention". MS.com should be MS' commercial outlet. MS.net should be their network outlet; i.e., a forum for users to discuss their issues. MS.org should be for ideological movements within MS, which (in this case) would be MS' propaganda machine. Re:.ORG Should b e Organizations/like only (Score:1) However, you may note from the above, that whilst the organisation may not make a profit, concerned individuals and suppliers may make a very comfortable income. Re:.ORG Should b e Organizations/like only (Score:2) Here's the thing: people have been registering the domains they want since before you started using the net, which, from your self-righteous and mostly illogical rant, was probably only a couple of years ago. Shutdown your w4rez'd copy of Windows XP, and back away from Dell keyboard. Domains are just domains. ICANN has control of the root servers - your trying to tell them how things "should be" with little logical basis for your arguments will get you rightly laughed at. Re:.ORG Should b e Organizations/like only (Score:2) The correct term is not-for-profit. Their is nothing in US law that says not-for-profits cannot make money. There are more then 27 different kinds of not-for-profits defined by the IRS. Each with their own abilities and benefits. Keep in mind that a not-for-profit owned Hughes Aircraft until 1986. When it sold it the for-profit subsidary for a couple of billion dollars. Hershey's candy is also owned by a not-for-profit. All a not-for-profit means is that the organization does not pay tax's. And is under a tremendous amount of scrutiny by the IRS. If you want to know what to know how much the MPAA and RIAA make. Go to and look it up. You can write the code, but are not fit run it... (Score:2) I find it absolutely amazing that IMS/ISC are rated so poorly, primarily on supposedly technical grounds. Does anyone else find it unbelievable that the people currently running one of the TLD servers for the I find criteria 7 to be stupid; it basicallymeans that "technical" preference should be given to plans from companies that sell add-on mail and web hosting, etc., commercial services. Criteria 8 is also pretty stupid; the answer to the question is "these are the people defining the protocol changes to which the successful applicant will need to adapt". They lost out on #9, as well, even though, according to Gartner, "One of the few proposals that discusses non- technical components of the transition such as staffing, facilities, technical support and community activities."; basically the complain boils down to "they are not a going for-profit registry concern". Verisign still manages registration through *email*, for God's sake! Who the heck are they to cast stones?!? -- Terry Slashdotters should be ashamed of themselves... (Score:1) ICANN goes for the money - Film at 11 (Score:1) What a farce! It is not that I particularly agree or disagreee with the final result - I guess I support both the ISOC bid as well as the Vixie bid. The only real problem I have with the ISOC bid is the conflic of interest issue that Karl Auerbach so astutely points out. Besides the conflict of interest, I'd like to know what the *problems* are that surround the ISOC bid.... anyone? Why aren't *you* a member of ISOC? (Score:4, Insightful) Re:Why aren't *you* a member of ISOC? (Score:2) My main concern with ISOC is that not nearly enough people have joined it and participate in local chapters. I have expressed this concern on the main ISOC email list, and ISOC is gradually moving toward more public participation. - Robin "Roblimo" Miller I for one ... (Score:2) For the Record (Score:1) A sure sign that the report is bogus... (Score:2) It wouldn't work... (Score:2) I've got 20 sites on one IP address...
http://slashdot.org/story/02/08/21/0048224/icann-recommends-isoc-run-org-tld
CC-MAIN-2014-23
refinedweb
3,318
74.19
I need to use it to read the file name from the user. I tried to use fgets but my program is terminating abnormally. How to do error handling for fgets ? Is it sufficient to check if the returned char pointer is null ?? Right now I'm using gets, but I've been told that its dangerous and my gcc compiler gives warning. Code:#include <stdio.h> int main(void) { char fname[50]; FILE *fp; printf("Enter file name\n"); gets(fname); fp = fopen(fname, "r"); if(fp == NULL) { fprintf(stderr, "%s[%d] : ERROR WHILE OPENING THE FILE\n",__FILE__, __LINE__); return (-1); } return 0; }
https://cboard.cprogramming.com/c-programming/104498-can-some-please-demonstrate-fgets.html
CC-MAIN-2017-09
refinedweb
105
73.17
Ternary operator are a substitute for if...else statement. So before you move any further in this tutorial, go through C# if...else statement (if you haven't). The syntax of ternary operator is: Condition ? Expression1 : Expression2; The ternary operator works as follows: - If the expression stated by Conditionis true, the result of Expression1is returned by the ternary operator. - If it is false, the result of Expression2is returned. For example, we can replace the following code if (number % 2 == 0) { isEven = true; } else { isEven = false; } with isEven = (number % 2 == 0) ? true : false ; Why is it called ternary operator? This operator takes 3 operand, hence called ternary operator. Example 1: C# Ternary Operator using System; namespace Conditional { class Ternary { public static void Main(string[] args) { int number = 2; bool isEven; isEven = (number % 2 == 0) ? true : false ; Console.WriteLine(isEven); } } } When we run the program, the output will be: True In the above program, 2 is assigned to a variable number. Then, the ternary operator is used to check if number is even or not. Since, 2 is even, the expression ( number % 2 == 0) returns true. We can also use ternary operator to return numbers, strings and characters. Instead of storing the return value in variable isEven, we can directly print the value returned by ternary operator as, Console.WriteLine((number % 2 == 0) ? true : false); When to use ternary operator? Ternary operator can be used to replace multi lines of code with a single line. However, we shouldn't overuse it. For example, we can replace the following if..else if code if (a > b) { result = "a is greater than b"; } else if (a < b) { result = "b is greater than a"; } else { result = "a is equal to b"; } with a single line of code result = a > b ? "a is greater than b" : a < b ? "b is greater than a" : "a is equal to b"; As we can see, the use of ternary operator may decrease the length of code but it makes us difficult to understand the logic of the code. Hence, it's better to only use ternary operator to replace simple if else statements.
https://cdn.programiz.com/csharp-programming/ternary-operator
CC-MAIN-2020-24
refinedweb
354
66.03
#include <OSnLNode.h> Inheritance diagram for OSnLNodeVariable: Definition at line 1282 of file OSnLNode.h. default constructor. default destructor. varIdx is a map where the key is the index of an OSnLNodeVariable and (*varIdx)[ idx] is the kth variable in the map, e.g. (*varIdx)[ 5] = 2 means that variable indexed by 5 is the second variable in the OSnLNode and all of its children Reimplemented from OSnLNode. Calculate the function value given the current variable values. This is an abstract method which is required to be implemented by the concrete operator nodes that derive or extend from this OSnLNode class. coef is an option coefficient on the variable, the default value is 1.o Definition at line 1288 of file OSnLNode.h. idx is the index of the variable Definition at line 1291 of file OSnLNode.h.
http://www.coin-or.org/Doxygen/CoinAll/class_o_sn_l_node_variable.html
crawl-003
refinedweb
138
54.73
ISNAN(3) BSD Programmer's Manual ISNAN(3) isnan - test for not-a-number libc #include <math.h> int isnan(real-floating x); The isnan() macro determines whether its argument x is not-a-number ("NaN"). An argument represented in a format wider than its semantic type is converted to its semantic type first. The determination is then based on the type of the argument. It is determined whether the value of x is a NaN. NaNs are not supported. The isnan() macro returns a non-zero value if the value of x is a NaN. Otherwise 0 is returned. fpclassify(3), isfinite(3), isinf(3), isinff(3), isnanf(3), isnormal(3), math(3), signbit(3) IEEE Standard for Binary Floating-Point Arithmetic, Std 754-1985, ANSI. The isnan() macro conforms to ISO/IEC 9899:1999 ("ISO C99"). MirOS BSD #10-current March.
http://mirbsd.mirsolutions.de/htman/sparc/man3/isnan.htm
crawl-003
refinedweb
143
60.51
The call_user_func() is an inbuilt function in PHP which is used to call the callback given by the first parameter and passes the remaining parameters as argument. It is used to call the user-defined functions. Syntax: mixed call_user_func ( $function_name[, mixed $value1[, mixed $... ]]) Here, mixed indicates that a parameter may accept multiple types. Parameter: The call_user_func() function accepts two types of parameters as mentioned above and described below: - $function_name: It is the name of function call in the list of defined function. It is a string type parameter. - $value: It is mixed value. One or more parameters to be passed to the function. Return Value: This function returns the value returned by the callback function. Below programs illustrate the call_user_func() function in PHP: Program 1: Call the function This is GeeksforGeeks site. This is Content site. Program 2: call_user_func() using namespace name GeeksForGeeks GeeksForGeeks Program 3: Using a class method with call_user_func() Geeks Geeks Program 4: Using lambda function with call_user_func() GeeksforGeeks References: This article is attributed to GeeksforGeeks.org
https://tutorialspoint.dev/language/php/php-call_user_func-function
CC-MAIN-2021-49
refinedweb
170
57.27
Irene Click10,945 Points What is missing in this code? I put the curly brace and I'm still getting the error. Help! I am getting the error : Not sure what I am missing. ./com/example/model/Course.java:37: error: reached end of file while parsing } ^ Note: JavaTester.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 1 error package com.example.model; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; public class Course { private String mTitle; private Set<String> mTags; public Course(String title) { mTitle = title; mTags = new HashSet<String>(); // TODO: initialize the set mTags } public void addTag(String tag) { // TODO: add the tag mTags.add(new String(tag)); } public void addTags(List<String> tags) { // TODO: add all the tags passed in mTags.addAll(tags); } public boolean hasTag(String tag) { // TODO: Return whether or not the tag has been added if (mTags.contains(tag)) { System.out.println("Tag exists"); } return true; } public String getTitle() { return mTitle; } 3 Answers Irene Click10,945 Points Yonatan thanks but I'm still getting the error. Do i have to change it to like this {}? public boolean hasTag(String tag) { // TODO: Return whether or not the tag has been added if (mTags.contains(tag)) { System.out.println("Tag exists"); } return true; } public String getTitle() { return mTitle; } Yonatan Schultz12,045 Points You just need to add one more closing brace '}' to the end of the file. public String getTitle() { return mTitle; } } Irene Click10,945 Points I did but i get Bummer! I called hasTag with "nope" and got back true, expected false. Tag exists :( Yonatan Schultz12,045 Points Yup! So you've fixed the problem that you raised directly in your question regarding error: reached end of file while parsing }. Doing so has uncovered another bug. The task is expecting that when you pass a String to hasTag it will evaluate whether it has that tag and return a boolean value depending on that. Irene Click10,945 Points Yonathan thanks man. I got it. Wheewww!!! Yonatan Schultz12,045 Points Yonatan Schultz12,045 Points You're just missing a final closing brace at the end of the file. If you look closely at your 'getTitle' method, you'll notice that the indentation of the closing brace is wrong. That's actually the closing brace for Course. I hope that that helps!
https://teamtreehouse.com/community/what-is-missing-in-this-code-i-put-the-curly-brace-and-im-still-getting-the-error-help
CC-MAIN-2019-51
refinedweb
398
68.26
#include "splitzer.h" using namespace std; // find all the lines that refer to each word in the input map<string, vector<int> > xref(istream& in, vector<string> find_words(const string&) = split) { funtion body; } error: line 3, expected initializer before using error: line 6, expected constructor, destructor, or type conversion before "<" token either I don't know what the error is about, or theres nothing wrong in the code (when compared with other codes that works) yet, the code snippet are given by a book. help anyone? Try looking in splitzer.h for an error. What is splitzer.h ? Can you post the full program ? As Bob said, look in splitzer.h for the cause of this error. That is the only possibility as the cause of these errors.
http://www.daniweb.com/software-development/cpp/threads/433693/weird-error
CC-MAIN-2013-20
refinedweb
128
73.37
The title basically says it all, but I will elaborate.. My workstation is running Windows 7 Professional and I have the properties of my VPN connection set to NOT use the default gateway on the remote network (so I'm using my local gateway and am able to browse the internet without issue). Does anybody have any idea what the problem could be? This is very frustrating. Thanks in advance. What DNS servers do the VPN clients get? I'm assuming that Outlook Anywhere is configured to use a public FQDN that can't be resolved whilw connected to the VPN. When the VPN client is connected can it resolve the FQDN of the Exchange server? EDIT 1 Just so I have a better understanding, we're referring to the public FQDN of the Exchange server, right? If so then it's safe to assume that your internal and external DNS namespaces are different (.com and .local, or whatever), right? Edit 2 Now that we've established what the problem is we have to determine what an appropriate solution is. There are a number of ways to tackle this and although I've never encountered your specific problem here are some notes and some suggestions: Notes: RRAS will provide DNS server settings to VPN clients via one of two methods: 1. If the RRAS server is configured to allocate ip addresses to the VPN clients from DHCP (internal DHCP server) then the DNS server settings configured in the DHCP server will be asigned to the VPN clients. 2. If the RRAS server is configured to allocate ip addresses to the VPN clients from a static pool on the RRAS server itself, then the RRAS server will assign whatever DNS server settings are configured in the TCP properties of the NIC on the server that is configured for incoming VPN connections. Suggestions: One way to allow VPN clients to resolve both internal and external DNS records would be to set up another internal DNS server as a forwarding only server (this could probably be the RRAS server itself). On this forwarding DNS server you can configure it to use publicly available DNS servers for external DNS resolution and configure it to use conditional forwarding to use your internal DNS servers for internal DNS resolution. Configure the RRAS server to use a static ip address pool for VPN clients that resides within your LAN subnet (to allow connectivity to internal resources) and set the NIC that is configured for RRAS to use this new DNS server for DNS. This affectively creates a scenario where the RRAS server assigns the DNS server(s) that it's RRAS-bound NIC is configured to use to the VPN clients. When the VPN client needs to resolve an external DNS record the new DNS server will forward the query to whatever public DNS server you've configured it to use. When the VPN client needs to resolve an internal DNS record the new DNS server will forward the query to your internal DNS server, based on the conditional forwarding you configure on the new DNS server. In review this seems a little complicated and may be "over engineering" the solution. You may want to see if anyone else chimes in with a simpler, more "elegant" solution. Set the TCP/IP properties of the VPN adaptor on the RRAS server to include the DNS server that would resolve the mail server FQDN to a VPN address. For more discussion of RRAS and DNS see this thread. By posting your answer, you agree to the privacy policy and terms of service. asked 4 years ago viewed 1516 times active
http://serverfault.com/questions/176284/when-i-connect-to-our-windows-vpn-my-outlook-client-loses-its-connection/176367
CC-MAIN-2014-52
refinedweb
611
57.4
Complex, costly and performs a useless task. The solar powered car darts from its starting position away from the lamp--only to be returned and repeat the cycle. Step 1: Parts: Solar Car--Amazon.com (less than $5.00) Acrylic--estreetplastics.com Servo HS 322--makershed.com Arduino--makershed.com Power supply for lamp--use a low voltage undercabinet supply of 50 watts or greater; regulated 12 volts supplies may not provide enough starting current to illuminate the lamp Software: #include <Servo.h> Servo myservo; void setup () {myservo.attach(5); } void loop () { myservo.write(25); delay (1000); myservo.write (30); delay (50); myservo.write (35); delay (50); myservo.write (40); delay (50); myservo.write (45); delay (50); myservo.write (50); delay (4000); myservo.write (45); delay (100); myservo.write (40); delay (100); myservo.write (35); delay (100); myservo.write (30); delay (100); } Step 2: Step 3: Step 4: This was my first experience with Sugru (soft touch silicon rubber that moulds and sets permanently). This stuff is great! Squish it in your hands like clay, put the pieces together and wait over night. Now the car can't turn around or get wedged in sideways. Build_it_Bob Build_it_Bob And someone might accidentally do something useful :) making something fun and useless is an art, one that's not practised enough by far and yes, some of the greatest inventions are accidents :P (Yes, I could lower the ramp enough to make the car move--but I didn't build an end to the ramp. It would be tricky to keep the car from running off the end by lowering the ramp for movement).
http://www.instructables.com/id/Rigsby-Machine/C7LEQY4GSVJW04Z
CC-MAIN-2015-32
refinedweb
271
69.28
It is important for software engineers to understand how to analyze process dumps so that they can determine why their application is crashing or behaving unexpectedly. However, it can be hard to know where to start with the process. This post aims to be a starting point for a very common situation: debugging a crash dump for a .NET application running on Windows. A crashing application is easily detected in the Windows Event Log when the .NET Framework logs the error, “The process was terminated due to an unhandled exception.” This post describes how to capture dump files for the failing application at the time of crash, and then analyze the dump to figure out what happened. We start by creating a crashing ‘hello world’ application. We review what happens in Windows during an application crash and go over some steps to capture dump files automatically when the application fails. Lastly, we review basic debugger commands to kick-start a crash dump analysis. Writing a Hello World crash program For this exercise, we use the Visual Studio IDE to write and compile our crash application. You can download the free community edition here. Start by creating a new C# console application (.NET Framework), and select a recent edition of the framework such as 4.5 or later. Title the project and solution with ‘HelloWorldCrasher’. When the new project is ready to edit, open the Program.cs file and replace the entire contents with the following code: using System; namespace HelloWorldCrasher { class Program { static void Main(string[] args) { FirstMethod("Hello World! Lets crash!"); } static void FirstMethod(string crashingText) { SecondMethod(crashingText); } static void SecondMethod(string crashingText) { throw new InvalidOperationException(crashingText); } } } This code throws an exception that isn’t handled by our program, which will cause it to crash. Save the file and build the solution (F6 key). In the program’s output folder (bin\debug) you should find the compiled application (*.exe) and symbol file (*.pdb). Navigate to the build output directory and run the *.exe file. It should run, display a stack trace in the console window, and then quit in a couple seconds. The next section discusses the factors that determine how Windows reacts to the crash. User mode exception handlers in Windows When a user mode exception occurs, Windows runs through an ordered list of exception handlers (outlined below) to determine what to do. If the answer to any question below is no, then it continues to the next handler. Here is how it plays out: - Is a user-mode debugger program (such as Visual Studio) attached to the process with the error? - If yes, break-in to the process for live debugging. - Does the executing code have it’s own exception handler? - If yes, let the application deal with the error. - Is a kernel debugger (such as WinDbg) attached and have a breakpoint interrupt? - If yes, Windows will attempt to contact the kernel debugger. - Does the Windows Registry have a postmortem debugger defined in the registry? - If yes, activate the specified debugger to create a dump file or attach to the live process, depending on the specified program and arguments. - If none of the above steps applied: - Windows Error Reporting (WER) takes over. - WER handles the crash and may display an error message if solutions are available. - Process dump files can be written to disk if settings for this are configured (off by default). For full details refer to the MSDN reference documentation here. So what happens on most PC’s? For a default installation, you won’t have a connected live debugger program or a postmortem debugger configured. This means that WER handles the exception and writes the crash event. However, the default configuration for WER is not to save a dump file on disk. In this case, you should see some WER-related events in the Windows Event Log’s Application log for your crash, but no memory dump files (*.dmp) in the folder where WER stores the crash data. Not storing dump files is the default for a lot of good reasons, including security, privacy, and disk space. This is because a full dump file includes the process’s entire memory space at the time of the crash. What if that process memory was several gigabytes in size? What if it included sensitive data like passwords or personally identifiable information (PII)? However sometimes we really do need to capture that full memory dump in order to troubleshoot why our application crashed. A stack trace logged to the event log may not always be enough, and we want to explore deeper to find what was happening in the process at the time of the crash or have specialized tools analyze it. Full dumps allow you to explore the root cause of a crash in a program that you develop or support. Just remember to turn it off once it is no longer needed. How do I automatically capture the crashing process dump file? Because the dump file isn’t created by default, we need to configure registry settings to enable this. You have two choices for enabling capture. The first is to configure the postmortem debugger settings mentioned in step 4 from the previous section. MSDN has a great article on how to do this right here. When you use this option, you specify a debugger program such as Visual Studio, ProcDump, WinDbg, or ADPlus and provide the command switches for those programs to create the dump file, or attach to the process for live debugging if they support that. The second option is to configure WER to create a dump file for your specific application if it crashes. You can go this route if you don’t want live debugging and just need the dump file created on disk for later analysis. This feature is included in Windows, so there is no need to install extra software to create the dump. WER dump settings are configured via the registry as follows: - First create the base WER local dump registry key, if it doesn’t already exist. - HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps - Then, create the application specific dump file settings key. - If the application to save dumps for is HelloWorldCrasher.exe, then make the following: - New Key: HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\HelloWorldCrasher.exe - Registry values under this key: - DumpFolder: [REG_EXPAND_SZ] folder path to store dump files. - DumpType: [REG_DWORD] Specify a value of 2 for full dumps, or 1 for mini-dump (smaller, but not full process memory space). - DumpCount: [REG_DWORD] the number of dumps to save before overwriting old dump files. Default is 10. It should look something like this: After you have configured these settings in the registry for our hello world crashing application, go ahead and re-run the executable file. This time when it crashes we should see a dump file created on disk in the folder we specified. Dump analysis step 1: Install the debug tools The program we will use to analyze this dump file is WinDbg. Its a free tool that comes packaged with the Windows Driver Kit (WDK) or the Windows Software Development Kit (SDK). If you dont already have it installed and you just need WinDbg, you can download one of those installers and uncheck all features except “debugging tools for windows”. For example, after I installed it from the Windows 10 SDK, the debug tools, including WinDBG, were under these directories: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64 C:\Program Files (x86)\Windows Kits\10\Debuggers\x86 Dump analysis step 2: Open WinDbg and the dump file Open the version of WinDbg (x86 or x64) that matches the platform target of the crashing application. For example, if your application is 64 bit, run the 64 bit version of WinDbg. Our crashing application was built with the default anycpu/x86 platform target, so open x86 WinDbg unless you modified the project to target x64. From the file menu, select “open crash dump” (Ctrl+D), and select the dump file created earlier. After maximizing the dump window inside the program, it should look something like this: Dump analysis step 3: Load application symbols The next step here is to load application symbols. This is important because loading symbols in a debugging session helps restore context to the application binary that had information stripped out from it at build time. This includes things like line numbers, variables, function names, etc. Lets enter the next few commands in the command box at the bottom of WinDbg to setup our symbol cache and loading preferences. Enable verbose symbol logging: !sym noisy Set the symbol search path to Microsoft’s public symbol server (for Microsoft owned binaries), and to our application compiled output folder (where our .pdb symbol file is located). Also set the local caching folder to store downloaded symbols. Adjust the cache folder and application private folder to the exact folders on your computer. If the paths aren’t an exact match, the symbols wont load. .sympath srv* .sympath+ cache*C:\debug\symbols .sympath+ D:\Source\HelloWorldCrasher\HelloWorldCrasher\bin\Debug Force reload symbols for this dump. .reload ld* If this worked correctly, we should see that the debugger correctly loaded our private symbols for our application: Dump analysis step 4: Load the SOS extension SOS is a debugging tool extension that makes debugging managed code (.NET applications) easier by providing details about the .NET Command Language Runtime (CLR) environment. It is installed when you install the .NET Framework component. The catch here is that you need the correct SOS version that matches the framework version used in your application, and loading this for older framework versions follows a slightly different process. For .NET 4 and later (like our sample app), just run the following: .loadby sos clr You won’t see any output on successful load. However, if you want to verify that it actually loaded, run the following command to print the loaded extensions: .chain You should see SOS as pictured below: Dump analysis step 5: Run debugging commands Finally we are at the point where we can do something interesting with our crash dump. The best way to start is to run the !analyze extension with the -v switch. This will examine the dump and provide loads of immediately useful output. !analyze -v In this simple crash situation, we got the data for our error message and a stack trace with line numbers. Our ‘Hello World! Lets crash!’ message from code is printed right on screen for us to see: Lets review a few other commands to poke around further. First up is !threads, which is used to print the list of threads that were running at the time of crash. In our case, there were just two threads. You can see which of the two threads has the crash in it. !threads Notice on the left side of the threads list, there is a thread ID. 0 for the first thread, and 5 for the second one, in our example above. We can find the stack trace of a specific thread by switching context to that thread number (‘~’ char, plus the thread id, plus the ‘s’ char), and running !clrstack. We happened to already be on this thread context, but I’m using the command here to demonstrate how to switch if we needed to. Don’t forget to pass the -a parameter to !clrstack. This parameter prints the parameters and locals! ~0s !clrstack -a Notice that the actual parameter name (crashingText) was provided, and you can see a memory address next to it. That address (in blue) is the memory address of the value supplied to that parameter. You can click on that link directly, which runs the !dumpobj command for that specific memory address. This is extremely useful for walking through objects in memory, and easier then manually typing out the memory address to dump. When we dump this particular object, we can see that it is a System.String object, we can see the value, and other useful information. By walking the stacks and dumping objects, we can get a pretty good look into the state of the application at the time the crash occurred. Tips and FAQ - Is the Microsoft symbol server throwing a certificate error? Try using http instead of https in the address. - What does the “Win32 error 0n193 %1 is not a valid Win32 application” error mean when trying to load SOS? This means you likely loaded the wrong platform target of WinDbg (doesn’t match the application’s platform target, either x86 or x64). - Why does Visual Studio prompt to live debug the application crash? This happens when you have Visual Studio set to be the postmortem debugger, and that debugger is enabled. - How do I learn more WinDbg commands to run? Read these helpful resources for WinDbg commands and SOS commands. Summary and Starter Kit We have walked through the entire process of creating a crashing process, capturing the crash dump, and then doing a basic analysis on the dump file. Lets do a final recap and combine the key commands we used into a crash dump debugging starter kit for future reference: Prep symbols and load SOS: # set symbol settings and paths !sym noisy .sympath srv* .sympath+ cache*C:\Debug\SymbolCache .sympath+ D:\Source\MyApplication\MyApplication\bin\Debug # reload symbols .reload ld* # load SOS extension .loadby sos clr Key debugging commands: # view exception analysis, view thread state !analyze -v !threads # thread switch, view stacks, dump objects ~0s !clrstack -a !dumpobj /d <address> This is really only scratching the surface of dump analysis in general, but it should give you a preliminary idea on what’s happening with most .NET application crashes. Good luck and happy debugging! One thought on “How to capture and debug .NET application crash dumps in Windows”
https://keithbabinec.com/2018/06/12/how-to-capture-and-debug-net-application-crash-dumps-in-windows/
CC-MAIN-2021-31
refinedweb
2,311
64.1
One of the class member is member function. A function declared as a member of the class is called a c++ member function. There are many types of member functions and different ways to define the c++ member functions. Types of C++ member functions There are many types of member functions for different purpose. - Manager Functions - Accessor Functions - Mutator Functions Now we discuss each of them briefly. Manager Functions The main task of manager member function is to initialize and later destruction of created objects. e.g. Constructor and De-constructor Accessor Functions The private data member of a class cannot be accessed by any other functions. The accessor member function returns the value of the private member. e.g. class student{ private: int age; public: get_age(){ return age; } }; Mutators The accessor get access to the private member to get the values. The mutator functions modify the data members in a class and usually placed right after the accessors. e.g. class sum{ private: int a; int b; int total; public: void total(int a, int b) { total = a + b; cout << total << endl; } }; Defining the member function There are two ways to define the member function. - Inside the class (inline) - Outside the class Inline function When the function is defined inside the class it is called an inline function. The inline member functions should be small because they are translated directly. For example, class student{ int rollno; int name; char grade; public: char get_grade{ return(grade); } }; Member function defined outside the class Sometimes, the member function is defined outside of the class. But it must be declared inside the class first. The syntax to declare the c++ member function is given below. Syntax return-type <class-name> :: <function-name> (arguments) { } The member function is defined outside of the class using a scope resolution operation (::). Here is an example of function that is defined outside of class. class student { int rollno; int name; char grade; public: char get grade(); }; //function definition char student::get_grade() { return (grade); } References - Balagurusamy. 2008. Object Oriented Programming With C++. Tata McGraw-Hill Education. - Maureau, Alex. 21-Jul-2013. Reviewing C++. Alex Maureau. - Ravichandran. 2011. Programming with C++. Tata McGraw-Hill Education.
https://notesformsc.org/c-plus-plus-member-function/
CC-MAIN-2021-04
refinedweb
365
55.95
Reading from and Writing to the Registry Visual Studio .NET 2003 When programming in Visual Basic .NET, you can choose to access the registry via either the functions provided by Visual Basic .NET or the registry classes of the .NET Framework. The registry hosts information from the operating system as well as information from applications hosted on the machine. Working with the registry may compromise security by allowing inappropriate access to system resources or protected information. In This Section - Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace - Explains how to use the Registry and RegistryKey classes in the Microsoft.Win32 namespace of the .NET Framework to read from and write to a registry key. - Reading from and Writing to the Registry Using Visual Basic Run-Time Functions - Explains how to use the Visual Basic .NET functions, DeleteSetting, GetSetting, GetAllSettings, and SaveSetting, to access the registry. Related Sections - Registry Access Changes in Visual Basic .NET - Provides an explanation of differences between registry access in Visual Basic 6.0 and Visual Basic .NET. - Registry Class - Presents an overview of the Registry class along with links to individual keys and members. Show:
http://msdn.microsoft.com/en-us/library/85t3c3hf(v=vs.71).aspx
CC-MAIN-2014-42
refinedweb
193
59.5
Name | Synopsis | Description | Return Values | Errors | Usage | Attributes | See Also #include <crypt.h> void encrypt(char block[64], int edflag); #include <unistd.h> void encrypt(char block[64], int edflag); The encrypt() function provides (rather primitive) access to the hashing algorithm employed by the crypt(3C) function. The key generated by setkey(3C) is used to encrypt the string block with encrypt(). The block argument to encrypt() is an array of length 64 bytes containing only the bytes with numerical value of 0 and 1. The array is modified in place to a similar array using the key set by setkey(3C). If edflag is 0, the argument is encoded. If edflag is 1, the argument may be decoded (see the USAGE section below); if the argument is not decoded, errno will be set to ENOSYS. The encrypt() function returns no value. The encrypt() function will fail if: The functionality is not supported on this implementation. In some environments, decoding may. Because encrypt() does not return a value, applications wishing to check for errors should set errno to 0, call encrypt(), then test errno and, if it is non-zero, assume an error has occurred. See attributes(5) for descriptions of the following attributes: crypt(3C), setkey(3C), attributes(5) Name | Synopsis | Description | Return Values | Errors | Usage | Attributes | See Also
http://docs.oracle.com/cd/E19082-01/819-2243/6n4i098ua/index.html
CC-MAIN-2016-26
refinedweb
220
55.44
Join devRant Search - "python3" - - Someone on the IP 127.0.0.1 has been creating a lot of bugs in my code, please beware of you notice any connections from that address.17 - - - - USB-C (or Type C) origin story: Manager: okay let's see your presentation Developer: bring usb-key * Inserts key * * Nope * * Flips key, tries again * * Nope * * Flips key, tries again * * Nope * Developer: ahhhhhh , NEVER AGAIN! 5 months later "USB forum publishes new specification"11 - - - - - - Has anyone ever done this? Open devrant See no new posts Close devrant Open devrant Wait what... Close devrant Open Reddit Sees nothing interesting Open devrant Okay... Need a tech break...14 - - Best and worst customer I've had: A bank. Great because they had so much money for projects. Unbearable because everything needed to work in IE6.6 - Servers down..... Everyone : Best day ever. 😎 Screw you guys , I'm going home. Network Engineers : 😭😲😰2 - Was scrolling through LinkedIn and had forgotten i wasn't on devRant. Just thought: - "Man, these rants really suck." - - Now, instead of shouting, I can just type "fuck" The Fuck is a magnificent app that corrects errors in previous console commands. inspired by a @liamosaur tweet... Some gems: ➜ apt-get install vim E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied) E: Unable to lock the administration directory (/var/lib/dpkg/), are you root? ➜ fuck sudo apt-get install vim [enter/↑/↓/ctrl+c] [sudo] password for nvbn: Reading package lists... Done ... ➜ git push fatal: The current branch master has no upstream branch. To push the current branch and set the remote as upstream, use git push --set-upstream origin master ➜ fuck git push --set-upstream origin master [enter/↑/↓/ctrl+c] Counting objects: 9, done. ... ➜ puthon No command 'puthon' found, did you mean: Command 'python' from package 'python-minimal' (main) Command 'python' from package 'python3' (main) zsh: command not found: puthon ➜ fuck python [enter/↑/↓/ctrl+c] Python 3.4.2 (default, Oct 8 2014, 13:08:17) ... ➜ git brnch git: 'brnch' is not a git command. See 'git --help'. Did you mean this? branch ➜ fuck git branch [enter/↑/↓/ctrl+c] * master ➜ lein rpl 'rpl' is not a task. See 'lein help'. Did you mean this? repl ➜ fuck lein repl [enter/↑/↓/ctrl+c] nREPL server started on port 54848 on host 127.0.0.1 - nrepl://127.0.0.1:54848 REPL-y 0.3.1 ... Get fuckked at - - So I created this really cool messaging program for my CS class in high school. Though when I say for - I mean for the students which were bored when the teacher told us how to "resize images in Word". I used python and tkinter to create it all, and didn't even need to touch sockets. (Mostly because I didn't know how to use them back then, but also because I kept the messages in a file on the school nas.) Anyway, the program worked and we used it every week, with me listening to suggestions and improving it each week. I even managed to create a sort of notification system. But sadly, my teacher found out about it and shut it down. Have you ever had a similar experience?9 - - - CAPTCHA meaning: "Completely Automated Public Turing test to tell Computers and Humans Apart". Proof the the CS community is bad at creating acrony - Runs some python3 script in terminal Me: This script is going to take an hour to complete. #After 50 minutes... Me: better copy this line... #Presses CTRL+C instead of CTRL+SHIFT+C Me: Wahhhhhhh7 - - - ARGGHHHH Python!!! why the hell is this a thing... if I specify a default argument, I want it to be a default argument, not get carried over....13 -. - I find it ironic that some python devs hate on nodejs because of npm modules. But then go ahead and create a virtual environment for every new python project.5 - - - I'm currently reading a course in Project Management and I have yet to find an image in the course literature with a person that doesn't suffers from a headache.1 - - - Thank you Syncex for one of the best powershell scripts ever. This literally sped up my laptop and surface :36 - - How do you usually learn a new language? My way is to start a project, then figure it out as I go. I find that books and tutorials are usually better reserved for learning concepts or frameworks.2 - - Worst part about getting a new laptop: losing all my stickers Best part of getting a new laptop: New Stickers!1 - - - - - - - I.2 - - About every project at my last job. Impossible to like any project with a boss that legitimately thinks frames and tables are a better option than learning css. But why not, attribute styling on html-elements are the future indeed.8 - - 1. Building stuff is awesome! 2. It's creative work that actually makes cash 3. I like writing algos and math4 - Reviewing code in a project, found this one: # Todo: Fix horrible parent member check. People may have been killed for better code -- horrible code here -- - I'm looking for a Python mentor. I need someone I can PM for clarification so I can wrap my head around things. Is anyone up to the challenge?19 - Just got a rejection letter.... I haven't applied to a job in a year. These guys took their sweeet-ass time.... lol3 - Programming: 1%: Creating cool things. 105%: Spending two hours trying to figure out some error when all that was wrong was that you forgot to put a semicolon somewhere;12 - - Just sitting here in class, when all the sudden my profs code shows up in the schools hall for no apparent reason... - The new iPhone is gonna have an odd number of pixels in width. I can already feel the anxiety of trying to achieve pixel perfection.7 - - - - What kind of sick joke is it that the url for camelCase on wikipedia is - - - - - Shoutout to all the sales people in every organisation: the thing that you are selling with so much pride, someone smarter than you is making it. Don't be an asshole to the developer. - My final exam for Python3. I had previously failed this course, and the exam only had three questions. If I failed to answer one question I would have to take the course over, and my GPA would fall so hard that I wouldn't be able to take the course again. So I was extremely grave, and extremely anxious beyond belief. I uploaded the two easy answers to the site. And the last one was so baffling to me I stayed 5 minutes extra to figure it out. I nearly failed so badly. My GPA is now 3.6 again. (😤 "Triumph" emoji)2 - - - Life is a constant battle of not knowing whether I want to quit programming forever, or if I just need 8 hours sleep.1 - My last boss insisted on using tables instead of divs and then asked me to make it responsive (every damn time). Also, functions that were over 10k of lines.2 - Do we actually know how many people there are on devRant? Just wondering to see which percent of the community liked the top posts.11 - Switched from Python 2 to Python3 a while ago. The biggest challenge for me is still remembering to use print as a function.2 - I basically need a select few contributors to speed up the development process. Python3 developers, testers and researchers are all welcome6 - I love pipes in R. Really wish more mainstream languages would adopt that *looking at you python, nodejs-tc39, rust, cpp* Just something about doing data %>% group_by(age) %>% summarize ( count= n() ) %>% print As oppose to print(summarize (group_by(data, age), count=n()) )20 - !rant That level of satisfaction when you successfully port a Python2 Project to Python3 and implement proper backward-compatibility - without 2to3! - - I'm learning python3 right now, advises or exercises to practice? I want to learn machine learning. I'm developng on elixir for now. But I hear good stuff about python.7 - - - - My python brings all the devs to the cloud, cause my code is bigger than yours damn right its cleaner than yours I can teach you but I have charge5 - I fucked up. I used the shebang line #!/usr/bin/env python3 in a script that was being ran every 5 minutes with a cron job. This generated an email to a system that dropped a file for processing and sent an age email for each file every minute. Because the Linux OS generated emails didn’t contain a keyword the script closed by design but I forgot to uncomment the delete temp file line. This started on Wednesday before a 4 day weekend. By the time I got in on Monday I was 40GB over my email quota and receiving 2500 emails a minute. I fixed the script and stopped the emails but down I have to clear out those emails. Here it is Wednesday and I am deleting 1 MB every 3 seconds. This is painful.2 - What do you guys think about Visual Studio Code? I personally like it, just wondering your opinions.11 - - - If you start coding in Python3, don't use both tabs and spaces. Just decide for one. It'll save you a good amount of time on bigger projects 😉4 - - - Sometimes I wish I could clone myself 3 times and start a company. Not that I think that I'm that smart, I'm fucking clueless most of the time. But because it's so hard to find people who freaking READ THE DOC - After a solid month of development. My model has finally reached 94% accuracy. And it appears to still be good (without the need to retrain) as new data keeps coming in :3 Oh gawd... I was waiting for this to get this good :32 -. - So I actually prefer npm to most other package managers (with the exception of go's package handling). Like you need to look no further than to pip's hell of package management, to start appreciating how clean npm is. ***Shots fired***6 - I was trying to watch an instructional YouTube Python video (on my Android phone) while it was dark in my bedroom, and then I remembered that Youtube for Android doesn't have a damn dark mode... NOOOOOOOO!!! :( :( Why did you do this to us Google!5 - - All this talk of javascript fatigue, and yet when tools like parceljs come out people still regress to webpack... I don't get it11 - - Booting up my Windows computer at work after 1 year leave. I'm gonna do a Windows Update. I suspect I'm not going to get anything else done today.7 - After a long year of going back to school for a masters. And working my ass off in networking events and internining. I can finally call myself a data scientist by job :D - - I'm using Manjaro now. And I have two questions: How do I install idle3 for python3 and how the fuck do I get rid of this stupid panel?5 - - Serverless.... More like "I want to sound cool so let me blackbox my backend with this premium service and pretend I don't have a server" - - To all the people who complain about writing a delete or update query. Not to talk you down, but seriously. STOP WRITING RAW QUERIES AND USE AN ORM!9 - - So what do you all believe the best first language is and why? I personally say Python or JavaScript because they are simple, and easy to understand8 - DO NOT, i repeat, DO NOT USE "scapy.all" in python3. I spend hours figuring this one out. In one commit i added tests and other tests not connected to my tests started failing. I ran the tests several times and also checked the rng-states, but everything was the same as on the commit before... There was one additional error message i decided to check out, which was the result of "import scapy.all" (that's a module that contains all the scapy-exports). I removed that import and used the right packages and suddenly: all tests passed. Fuck this inconsistent piece of crapware that has its python2-files in the pip3-repo and gave me that hell to debug.2 - - Pursuing knowledge in python, as my first "real" programming language (does bash count? 😂) - wish me luck guys!5 - Google Assistant in iPhone? Seriously? In the opposite way Siri should be introduced to android phones else I would be unable to understand this business decision!6 - I always feel python3 and pip3 are enemy of pip and python. My Mac always is in conflict of each other... Its feels like they are trying to prove each other3 - - - !rant Started learning Python today, whats ur opinion on Jupyter? I thought it to be quite nice:) Also, Python 2.7 or 3? Im using 2.7 right now. Is the transition from 2.7 to three all that big - !rant Julia's mutlithreading macro is soooo awesome and clean for when you want to do computation work :33 -...) - Python is really beginning to turn horrible now. Legacy codes...argh!! why don't developers move already to python3? and all those horrible third party dependencies for only 2 which somehow break after even some mending. God save them. Horrible night.2 - Every fucking time I start win10, I need to make sure I have task manager running on the side. Otherwise some sort of random windows process starts spirilling out of control and needs to be killed. Fucking hate windows.2 - I feel like there should be a rule 34 for nodejs. If you can think of it, there is probably a nose module for it. Take for example PHP.js it's a thing...1 - - Okay, I have seen my share of useless classes, but this takes them all out. This tutorial will literally be around 4 to 5 functions, and about how to set different options.... Literally useless...1 - -10 - - - Any people using Julia here for something real. Like analysis or building applications? Is it worth learning or should I stick to python and cpp ?3 - Just spent a lot of development hours today! Quite more than routine! Not even tired because had great sync with the partner dev! Cheers! - - Opinion: Julia will not catch on, because the two language problem is not a big issue for most people in the industry, and most python data scientist will refuse to migrate. - The worst part about switching code from python 2 to python 3: `map(myfunc, mylist)`, behaves differently, but won't throw an error. It will just show up as nothing.3 - - - Hello I'm thinking of starting gui programming using python could you guys recommend me some good books? I really like books that give exercises and some problems to solve at the end of each chapter like learning python the hard way by zedd shaw12 - - So I have my little program which originally was written with intention to be useful for academics to deal with old fuck HPLC, but they got new one so I am not sure about it usefulness anymore. Basicly it reads HPLC report and take from it table and dilution number from name. I spend like 2 hours trying to read all numbers from string which are between two given chars. Probably I could do it easier with regular expression or not being fucking moron or use sheet of paper to figure it out. Eventually I take traditional pen and paper and solve it in 10 minutes... How to be unproductive 101 -...5 - Reading over a note I left myself "Numbers returned will be slightly off due to new implementation and the Fuck that we use a different dataset" Oh boy. This was there for 2 weeks, Im so lucky no one saw this. - This popped up when I was searching for SimpleHTTPServer in pip. `pip3 search SimpleHTTPServer` and I don't know whether its good or bad. - - -...2 - - - - -.18 - New piece of code which should work perfectly and solve your problem but it is not working just because you forgot to remove an old piece of code you were trying to fix the same problem! Fuck my life!1 - WHY does VS code load up Pandas dataframes so damn slowly? It’s bad enough that it seems to take an extra few seconds to get PyQt5 going, but the dataframes are awful, even with small 50 record Parquet files. I don’t have the attention span to sit there and wait for this without finding myself playing with my phone or surfing. I guess for debugging and testing I should just create a column A, column B, column C dataframe on the fly and give it some 1, 2, 3 kind of values. But, Jesus, man... This shouldn’t take 30 seconds to load a simple form. 🙄2 - - I). - Python Developers, if you are working on a python project or Library developers(python)(3rd party) please move to Python3 there's no need to get stuck on python2. it's fucking horrible when those dependencies break. - - - Anyone ever bought a laptop from ststem76 or from purism? I'm looking for a good laptop for development and gaming. (I'm a Linux fanatic btw)10 - - Trying to contribute to a translation project on Crowdin, then remembering that my 14 day trial is expired. Why does Crowdin, a platform trying to help people get translations for their projects make you pay? Couldn't they have more of like a GitHub payment model (free for basic features, pay to get more)?1 - After trying to print colored text to the console using a portable Python 3 interpreter on Windows I came up with a "solution". I tried pretty much everything possible (I could think of): curses couldn't be loaded, ansi didn't work and installing libraries wasn't really an option, because it's not my device. Fuck portable interpreters and have fun with the "solution". Def color_print(text, color): text = text.replace("\n", "\\\" \\\"") os.system ("powershell \"$host.ui.RawUi.ForegroundColor = \\\"" + color + "\\\"; echo \\\"" + test + "\\\"; $host.ui.RawUi.ForegroundColor = \\\"Gray\\\"") It's slow, unreadable, only works for on Windows and requires powershell and is probably the worst piece of code I ever wrote, but it works 👍.2 - I've been stuck with bootstrap in the last projects at work but I wish to break free. Been looking a bit on material design. What other UI frameworks do you guys use?10 - - - Are there any good SAML 2.0 libraries out there for Node.js or Python? Background: I'm working with SAML 2.0 SSO through ADFS at my current job. Our application server is a Java/Tomcat/Spring beast that I'm becoming more familiar with, and disliking more each time I toy with it. I'd like to move to something I and my team are more familiar with, and can better maintain/update/enhance. So far I've tried (for Node.js) passport-saml and samlify, but neither have great documentation. I've also used python3-saml and it worked well. We're mainly a JavaScript shop, at least in my department, so Node.js would be preferable.3 - -.18 - - - In bed and researching all sorts of things for work. Motivation! But actually making it happen is harder. Slow movement to py3 (better than too fast).1 - - - - Question: what's your opinion on Julia? It seems promising, the macro syntax is neat. But would you use it for data analysis/management or general purpose development? -. - - - Does anyone have any recommendations for command line parsers for Python? I've looked at argparse click docopt so far. I am clearly bad at making informed decisions. - !rant && needAdvice I want to start learning python.. My question now is: Should I go with Python 2 or 3? I heard there are some rather major differences6 - Help. Has Python changed in version 3.6.5, or is there something wrong with my code?! The following doesn't work: import os def main(): console = input("...") rom = input("...") The following does work: import os console = input("...") rom = input("...") def main() :12 Top Tags
https://devrant.com/search?term=python3
CC-MAIN-2019-35
refinedweb
3,392
75
React and Angular — A Contrast A lot has been written about React and Angular in the last few years. Finding a comparison between the two most popular ways to write a modern web application is not hard at all. Why do we need another comparison then? Easy. I’ve found that comparisons are mostly without statistics and a proper methodology to show the difference between the two. Let’s get started. Who is this contrast for? Are you a manager whose team is talking about React and Angular? Read on. If you’re a seasoned UI developer, well, be kind with your comments… Sincerely, this is for everyone and I appreciate all feedback. High level Right off the bat you should know that React and Angular are not comparable. The reason for this is simple. React, by Facebook’s own definition, is a ‘UI library’. Whereas Angular is an all-in-one framework. A quick look at their respective websites will remind you of this fact. ⚛️ React — — A JavaScript library for building user interfaces. 🅰️ Angular — — One framework. Mobile & desktop. If you’re coming from a Java background you may appreciate this analogy: React is to Hibernate as Angular is to Spring With that said, you can use Spring’s Object Relational Mapping capabilities. However, you may choose to use Hibernate, an Object Relational Mapping library. What is a framework for a front-end web UI? In general, what we’re talking about here is a series of modules or features that fills out the Model-View-Controller (MVC) pattern. In terms of React, the out of the box functionality is just the View part of MVC. Whereas, Angular has built solutions for all parts of MVC. A full framework is going to have solutions for these concepts: intra-page routing, whole app state management, and UI rendering / templating. Popularity Angular 1.x is on 8.3% of the top 10,000 sites by traffic (BuiltWith). React is on 1.7% of the top 10,000 sites by traffic (BuiltWith). Angular 2.x is on less than 0.1% of the top 10,000 sites by traffic (BuiltWith). A Google Trends comparison of search terms ‘angular’ and ‘react’ shows that Angular is a more popular search term. While it is unknown what is ultimately being searched for (i.e. interest in angular/react versus I need help with angular/react) it’s clear that Angular has more adoption when you intersect the Google Trends data with the BuiltWith data (Google Trends). It should be noted that Angular 2, which this contrast is built on, is less popular than React, but the reasons for that could be related to the upgrade cycle from Angular 1.x to 2.x requires more effort than dropping in the new version of code. Angular 2 is a major rewrite the requires extensive developer effort to get from 1.x to 2.x. Areas of Contrast Methodology A fair number of the reviews that I’ve seen rely on quality attribute comparisons; performance, scalability, etc. I haven’t seen them all, of course, but feel confident that this contrast is different than others. I will document some of the features that are different between the two solutions, but I will also show you the difference in code on the same application. I decided that the only way to fairly show the differences is to code the same requirements into the two solution formats. However, I didn’t need to code from scratch on both solutions. I just needed to find something that was already coded. Since we know that Angular is a full framework, Angular would have the best implementation of all the features in its own tutorial. Therefore, all I need to do is to code a version of the Angular Tour of Heroes tutorial in React. The results of that code can be seen here, . Thus, the analysis of that coding into React from Angular is in this contrast. What’s included? Back to the feature set, this is what you get with each out of the box. Angular Routing Routing here refers to the movement around components of an individual page. If you needed to show an entirely new page, you could still redirect to a new location as you have always been able to do. However, that has a performance implication as you must render the entire page anew. This is the Controller in MVC. Angular has built a module to Route to different components. Whole Application State Management Angular has a built-in method to manage the state of the data in the application. This is the Model in MVC. HTML Templating Angular uses a special syntax that marks up the HTML to achieve the necessary templating. This is the View in MVC. Locally scoped CSS Angular has created an easy method to scope your CSS to a given component. This is especially useful to create a slightly different experience in your component within the page without any effort. React HTML Templating React uses a newer concept called JSX or JavaScript XML. JSX places the required HTML inside the JavaScript and allows you to use plain JavaScript to template variables or repetitive components. This is the View in MVC. In component state management React can maintain a model of the data for your application at the single component level. Each component can have its own state. In general, the one state is derived from another state via property pass. However, in a full application this leaves a hole for the need to manage the state in its entirety. This is the Model in MVC to some degree. Above, I mentioned components. Components have a varying degree of granularity. They can be as coarse (or coarser) as a grouping of input boxes to collect data from a user, a form, or as fine as one of those input boxes in that form that has specific functionality. The form itself is then a component of components. These concepts are both implementable in React and Angular. Components drive reusability across a larger application. What do you need to get to full strength? Both software solutions need helpers to get a developer productive in his day to day usage. Further, some recommendations are for the benefit of the development lifecycle. Both Need Webpack or similar module bundler Webpack is an effort to bring together multiple packages of JavaScript into fewer bundles. If you’re coming from a Java background, Webpack is similar Maven’s Assembly plugin or WAR plugin. This step is necessary to bring cohesion to the build and version process as you develop more complicated workflows. TypeScript In general, TypeScript is optional for both Angular and React. However, you might strongly consider using this if your developers are full stack and coming from a strongly typed language background (e.g. Java, .NET, etc). TypeScript helps to add the typing that those developers are accustomed to and attempts to remove bugs by including typing at compile time. Of course, at runtime, the code still operates in a type-less fashion. For Angular, TypeScript is a first-class citizen as the Angular team has built Angular in TypeScript. For React, there are plenty of tutorials and code helpers out there to get you started on TypeScript. ES6 Transpiler (Babel or TypeScript) Transpiling is simply ‘transform and compile’. The point of it is to transform code written in the standards (also known as ECMAScript) that have been proposed and passed, but not adopted by the browsers. These features can range from simple syntax changes to new concepts, but in the end, can be ‘transformed’ back into JavaScript that all browsers understand. Included in this topic is transpiling of JSX. JSX is not able to be run in the browser directly. The React website makes mention that JSX is not required. Most developer’s opt-in to JSX for its readability and appearance in the code. React Whole Application State Management Again, this is only referring to the state of the front-end or the Model in MVC. Two common state containers for React are Flux and Redux. In application routing As the Controller in MVC, you may need the ability to completely replace a component with another component to speed the rendering of your UI. Routing is not moving from page to page or redirecting. A redirection cause a complete load of the page. That page has its own lifecycle that does not communicate with the originating page. React Router is a module that can be used to perform this work. Locally Scoping CSS to a Component This is a feature that I found particularly useful in Angular that React does not have out of the box. The concept is that for a given CSS selector it only applies to the component that you assign the CSS to. You can create your own solution for this or use React CSS Modules. HTTP Management Another optional module to React is the notion of Promise or Observable HTTP requests. I won’t get into the details of those concepts, but let just say that they are refinements on the standard asynchronous XMLHttpRequest. You can create your own solution here with a Promise or Observable. Another popular option is the newer ‘fetch’ spec that is appearing in browsers except for Internet Explorer. Code organization In this section, we are going to show some code and discuss the differences between Angular and Reacts approaches. Files In Angular, you would follow a pattern where you would split out your files per UI component domain and contents. Above, we have the Dashboard component of the Angular 2 Tour of Heroes tutorial. The Dashboard component is made up of three files for logic (dashboard.component.ts), templating (dashboard.component.html) and styling (dashboard.component.css). The logic file brings it all together through a pair of statements to refer to the template and style. You can ignore this pattern and put all three parts into the same file. This split out pattern gives you smaller file sizes for easier readability and maintainability. In React, you would generally have one file for the logic and templating and one file for the CSS. Above, in the React version of Tour of Heroes, HeroDashboard.tsx is the logic and template while HeroDashboard.css is the styling. React HeroDashboard and Angular 2 Dashboard components are equivalent in their functionality on the screen. Templating As noted before, Angular combines its own syntax and regular HTML to make an HTML template render at runtime and React uses JSX. Let’s look at some samples. Angular <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div * <h2> {{selectedHero.name | uppercase}} is my hero </h2> <button (click)="gotoDetail()">View Details</button> </div> React > Above, the two snippets are equivalent in their functionality in the UI. Let’s look at a few pieces to note the syntax differences. Looping Angular achieves a loop to create a series of HTML with the line <li *ngFor=”let hero of heroes”. When the Angular JavaScript reads this, it will create the requisite number of <li> (or list items) that the ‘heroes’ array contains from the model. React achieves a loop to create a series of HTML with the line this.props.heroes.map(…). Ultimately this is already JavaScript, so the React JavaScript is not reading this and outputting HTML. Rather, the browser is. Attribute Binding Angular uses {{hero.id}}. React uses {hero.id}. A value is output from the reference to the object and attribute in the model in both cases. Events Angular employs ‘(click)=”onSelect(hero)”’ syntax and React uses onClick={this.setSelected.bind(this, hero)} syntax. React’s syntax is more clear and recognized by IDEs as JavaScript. Logic In general, the logic formats are similar or can be made to be similar with the usage of TypeScript. Below are the examples of Angular and React code to give you a feeling of what coding looks like. Angular import {Component, OnInit} from '@angular/core'; import {Router} from '@angular/router'; import {Hero} from './hero'; import {HeroService} from './hero.service'; @Component({ moduleId: module.id, selector: 'my-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.css'] }) export class HeroesComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; constructor(private router: Router, private heroService: HeroService) { } getHeroes(): void { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } ngOnInit(): void { this.getHeroes(); } onSelect(hero: Hero): void { this.selectedHero = hero; } gotoDetail(): void { this.router.navigate(['/detail', this.selectedHero.id]); } } /* Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at */ React "use strict"; import * as React from "react"; import Hero from "./Hero"; import "../styles/HeroList.css"; export interface HeroListProps { heroes: Array<Hero>; setSelected: (hero: Hero) => void; } interface HeroListState { hero: Hero } export class HeroList extends React.Component<HeroListProps, HeroListState> { state: HeroListState; constructor(props: HeroListProps) { super(props); this.setSelected = this.setSelected.bind(this); this.state = {hero: {id: 0, name: ""}}; } setSelected(hero: Hero) { this.setState({hero: hero}); this.props.setSelected(hero); } render() { return ( > ); } } Organization Both React and Angular are using current ES6 module formats with import and export statements. Angular and React are using the class format that is very popular today as well. The class format has allowed for the transition of developers from other languages (such as Java and .NET) to be easier since the format is recognizable. Flow One difference to note is that Angular is expecting to retrieve data from a HeroService. React is expecting that another component is going to pass to HeroList the data that it needs to know. Both solutions allow for the passing of data to other components. Routing In both cases, Routing is handled by dedicated code that declaratively creates the routes that you are trying to achieve. Angular import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DashboardComponent } from './dashboard.component'; import { HeroesComponent } from './heroes.component'; import { HeroDetailComponent } from './hero-detail.component'; const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent }, { path: 'detail/:id', component: HeroDetailComponent }, { path: 'heroes', component: HeroesComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule {} /* Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at */ React ReactDOM.render( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={App}> <IndexRedirect to="/dashboard"/> <Route path="/dashboard" component={HeroDashboard}/> <Route path="/heroes" component={TourOfHeroes}/> <Route path="/detail" component={HeroDetail}/> </Route> </Router> </Provider> , document.getElementById("anchor")); Above you’ll see that the path’s that you are trying to achieve in the browser’s URL bar are mapped to individual components. Further, a default route is declared when the user attempts the standard entry point. Whole App State Management Referring only to your front-end application, whole app state management is performed in two different ways between React and Angular. Angular’s approach is a bit hands-off, baked-in compared to React’s configure it yourself. Angular also supports two-way data binding. This is where a change can be made to the model/state without the need for the view to update the change through user implemented code. With React you have a few choices to implement whole application state management. Two of the popular implementations are Flux and Redux. With the React Tour of Heroes application I wrote, I used Redux. I find that Redux is less verbose and easier to understand the flow of the data. Locally Scoped CSS A feature that I found very useful in Angular that is automatically configured is locally scoped CSS. Locally scoped CSS is the ability to create a set of CSS selectors that apply to only the component that refers to that CSS. In general, CSS is global over the whole document. You can still achieve global CSS by placing a link tag in your HTML page with Angular. In Angular, with locally scoped CSS, your CSS files are post-processed to place an additional attribute selector to each selector in your file and then that attribute is placed on all the HTML tags in the template for the component. This feature does not exist in React out of the box. You can perform the exact same behavior in React that Angular is doing, but you have code it into your templates and CSS by hand. I did find some potential modules to snap in to handle this behavior, but I did not spend the time to research those. React CSS Modules is one of those plugins. Ramp Up / Training Time While it’s completely impossible to gauge the full ramp up time for every developer, it’s logical to note the training courses offered that would get a developer started. I did choose two sites that ultimately have a cost associated with the programs, but what I was looking for was the time to complete those programs. Angular Udemy — Angular 2 — The Complete Guide — 16.5 hours Pluralsight — Angular 2 Fundamentals — 10 hours React Udemy — Modern React with Redux — appears to cover all of the topics for a full framework model of React — 22.5 hours Pluralsight — Building Applications with React and Redux in ES6 — appears to cover all of the topics for a full framework model — 6.25 hours Modern web development — courses on TypeScript, Bundlers and Transpilers. TypeScript Udemy — Understanding TypeScript — 7 hours Pluralsight — TypeScript Fundamentals and Advanced TypeScript — two courses for full understanding 7.25 hours Bundlers Udemy — Webpack 2: The Complete Developers Guide — 5.5 hours Pluralsight — Webpack Fundamentals — 2.5 hours Transpilers If you use TypeScript a transpiler is included. Training time would be included in the about TypeScript courses. If you use Babel, a very popular transpiler for React, training time is as follows. Udemy — ECMAScript 2015 (ES6), Babel and Webpack Explained — there isn’t a Babel only course on Udemy so this class includes ES6 information too, a bonus — 4.5 hours Pluralsight — Babel: Get Started — 2 hours It’s also worthwhile to note that if your development team is a traditional service based Java or .NET team, it would be a huge benefit to the product being developed if the developers would also take basic JavaScript courses. In the end, it is very important that the developers understand functional programming and the basic constructs of the JavaScript language. For every course and framework above, the discussion all tracks back to basic JavaScript skills to understand the syntax being placed in front of them. Other Considerations If you’re going to take it beyond the browser or if you really like React and Angular, you may consider these points too. Mobile Frameworks React and Angular both offer an integration framework for delivering your application in native and web browser formats. If your application needs a bit more than what a mobile browser can offer, then you can begin to look at integration with the Ionic SDK for Angular and React Native for React. I have some experience with React Native and I can tell you that it is not write-once, run multiple ways. Rather, the lift you get with React Native is a reusable skill set. A component in React for the browser is a component in React Native. How you divide your web application and mobile application into logical chunks, components, is also the same. The one noted difference between React and React Native is the inability to use CSS in a mobile application. Since CSS is naturally baked into your React web application via JSX, you would need to write the React Native application with its screen formatting syntax separately. To note, Ionic is a separate company that is using Angular and other JavaScript features for its framework. Conversely, React Native is developed and maintained by Facebook. Did you know? If you love React, but want more of the framework features that Angular provides, you can use React with Angular. React in this setup would manage all the HTML Templating we reviewed above. Angular would manage whole application state and routing. Summary We’ve covered a lot of ground in this contrast. Overall, the key points to consider about a front-end framework include, HTML Templating, Whole Application State Management and Intra-page Routing. React and Angular have solutions for each of those topics. While those solutions are different they do solve the same problem. The routes to get to where you need the code to be, a shippable product, will come by different means. However, it is important to note that both solutions will give you the desired effect of creating said shippable product for today and beyond. Neither of these solutions are fly-by-night, disappearing tomorrow, flavors of the month, etc. I’ve largely stayed away from opinion in the above text on the basis that if you are reading this then you can and will make your own decisions given the information presented. At this point, I think it’s valuable to note that you cannot go wrong with either choice. Both solutions have a large following in the JavaScript community. Overall, both solutions provide the ability to manage large applications in a defined way that allow for the ease of development.
https://medium.com/dailyjs/react-and-angular-a-contrast-b19210c3fe89
CC-MAIN-2017-47
refinedweb
3,561
56.45
Agenda See also: IRC log, previous 2008-01-31 ACTION: Manu write 2 new tests for img[@src] as subject [recorded in] [CONTINUES] ACTION: [DONE] Ralph ask if tracker can also track public-rdf-in-xhtml-tf [recorded in] Ralph: the answer was 'yes'; I guess I now need to ask for it to be done :) ACTION: Ben followup with Fabien on getting his RDFa GRDDL transform transferred to W3C [recorded in] [CONTINUES] Ben: there was some issue; what was it? something about recursion? Manu: I don't think it was recursion ... I'm processing things in a completely different way ... had no problems until step 9 ... there are some steps that we might not need ... logically some of the other things make some of the checks redundant ... but nothing major that I see ... Mark did note xml:lang / lang question Ben: something deeper ... there was something uncovered in direct translation of the spec to code Manu: parent bnode not initalized ACTION: Ben to add status of various implementations on rdfa.info [recorded in] [CONTINUES] ACTION: [DONE] Ben to respond to comment on follow-your-nose [recorded in] Ben: I forgot to copy the rdfa mailing list -> Re: Best Practices Issue: RDF Format Discovery [Ben 2008-02-06] ACTION: Ben to set up a proper scribe schedule [recorded in] [WITHDRAWN] ACTION: [DONE] Ben to update tracker with todays resolutions. [recorded in] ACTION: Ben to email mailing list to think about last substantive issue on tracker: issue-6 [recorded in] ACTION: Michael to create "Microformats done right -- unambiguous taxonomies via RDF" on the wiki [recorded in] [CONTINUES] ACTION: [DONE] Ralph followup with Dublin Core on what's going on with their namespace URI [recorded in] -> Followup on Dublin Core namespace [Ralph 2008-02-04] Manu: I have an implementation question; how do we detect the difference between an unsafe CURIE and a mailto: URI? Ben: we don't -- can't mix them in the same field Manu: so mailto: looks like an unsafe CURIE? Ben: yes Shane: in what context? Manu: consider test case 78 <benadida> <p rel="foaf:mailbox" resource="mailto:ivan@w3.org"> Manu: if this was @href='mailto:ivan@w3.org' ... we don't know if this is a CURIE Shane: resource has a datatype; by definition the value is only a CURIE if it has '[]' ... and @href does not accept CURIEs ... the spec gives the datatype for each attribute <ShaneM> #s_metaAttributes Ralph: but don't take our word for it here :) make sure you agree that the spec is unambiguous on this question Manu: again, only the XHTML and SPARQL are what we're evaluating Ben, Ralph: SPARQL looks like what we'd expect Ben: typo in the SPARQL "foaf:knows" ... same typo in test 78 ... also, expand the nsprefix to full URIs Shane: another typo; "" Ben: also ';' should be ',' Manu: if we've use foaf:@@ in any existing tests they should fail and there's a flag for that, so we'll catch errors soon Manu: same typos 'foaf knows', same nsprefix issue Ben: is this the best title? Ralph: is "@about sets subject" better? Ben: "@about sets object" Ralph: :) Manu: also tests hanging @rel <Ralph> perhaps "@about sets object for hanging @rel" Ben: consider what else happens if additional markup is inside the P ... not sure if we have consistent views on this ... I think the @resource traverses down the tree ... but it's an edge case and we should defer this Ben: your parser is doing really well if it passes test 81 Manu: again, use full URIs not PREFIX Ben: anyone who actually _uses_ this markup has a twisted mind :) ... 81 looks good to me Manu: thanks to Ivan for making these up ... typo; first triple should end in '.', not ';' ... missing predicate ... in second triple Ben: 82 looks good, with typos corrected Ben: 83 looks good with same typo fixes ... is test 78 with the bnodes named Ben: appears to be the same as 82; probably meant to be different ... probably the second node was meant to be named, like 83 ... add @about to second node ... [as I'm out next week], I'll look at tests 85 - 88 offline and mail comments Ben: reminder, regrets for next week -- both SWD WG and RDFa calls ... regrets for 14-Feb and 21-Feb Manu: I'll attend the SWD call Shane: the XHTML2 WG resolved to request Last Call transition <ShaneM> record of resolution [adjourned]
http://www.w3.org/2008/02/07-rdfa-minutes.html
CC-MAIN-2016-44
refinedweb
741
67.59
On Mon, Sep 28, 2009 at 03:44:03PM -0700, Andrew Morton wrote:> On Mon, 28 Sep 2009 16:06:00 -0400> Neil Horman <nhorman@tuxdriver.com> wrote:> > > Augment /proc/<pid>/limits file to support limit setting> > > > It was suggested to me recently that we support a mechanism by which we can set> > various process limits from points external to the process. The reasoning being> > that some processes are very long lived, and it would be beneficial to these> > long lived processes if we could modify their various limits without needing to> > kill them, adjust the limits for the user and restarting them. While individual> > application can certainly export this control on their own, it would be nice if> > such functionality were available to a sysadmin, without needing to have each> > application re-invent the wheel.> > > > As such, I've implemented the below patch, which makes /proc/pid/limits writable> > for each process. By writing the following format:> > <limit> <current value> <max value>> > to the limits file, an administrator can now dynamically change the limits for> > the respective process. Tested by myself with good results.> > > > Confused. This appears to allow processes to cheerily exceed their> inherited limits, without bound. See sys_setrliit()'s> > if (new_rlim.rlim_cur > new_rlim.rlim_max)> return -EINVAL;> Gaahh! You're right, in my worry to get all the string parsing right, I didn'teven consider the semantics of setrlimit. > It might allow user A to diddle user B's limit too, I didn't check?> No, it can't do that. file permissions only allow the process owner and root tomodify the limits.> And it cheerily avoids security_task_setrlimit() too.> Yeah, it completely breaks that. Sorry.> Apart from those somewhat fatal problems, it's all a bit unpleasing that> we now have two ways of setting rlimits, one of which is a superset of> the other. Perhaps a better way would be a new sys_setrlimit2() which> takes a pid (in the current pid namespace, one assumes). Then deprecate> sys_setrlimit().> Do you think its worth adding a syscall just for this? I think theres merit inthis feature (I wrote it :)), but I'm not sure if syscall is really warranted.you're above notes are obviously a problem, but I think they can be fixed. Itseasy to make sure that if the writing user is the process owner and restrict themax value raising, and the selinux check can be added.clearly I rescind this patch (sorry for the noise). I'll see if I can add thechecks needed above and repost.Neil> >> > ...> >> > +static ssize_t proc_pid_limit_write(struct file *file, const char __user *buf,> > + size_t count, loff_t *ppos)> > +{> > + char *buffer;> > + char *element, *vmc, *vmm;> > + unsigned long long valuec, valuem;> > + unsigned long flags;> > + int i;> > + int index = -1;> > + size_t wcount = 0;> > + struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode);> > +> > +> > + if (*ppos != 0)> > + goto out;> > +> > + if (count > 128)> > + goto out;> > + buffer = kzalloc(128, GFP_KERNEL);> > +> > + if (!buffer)> > + goto out;> > +> > + element = kzalloc(sizeof(buffer), GFP_KERNEL);> > + vmc = kzalloc(sizeof(buffer), GFP_KERNEL);> > + vmm = kzalloc(sizeof(buffer), GFP_KERNEL);> > +> > + if (!element || !vmm || !vmc)> > + goto out_free;> > +> > + wcount = count - copy_from_user(buffer, buf, count);> > + if (wcount < count)> > + goto out_free;> > +> > + i = sscanf(buffer, "%s %s %s", element, vmc, vmm);> > +> > + if (i < 3)> > + goto out_free;> > +> > + for (i = 0; i <= strlen(element); i++)> > + element[i] = tolower(element[i]);> > +> > + if (!strncmp(vmc, "unlimited", 9))> > + valuec = RLIM_INFINITY;> > + else> > + valuec = simple_strtoull(vmc, NULL, 10);> > +> > + if (!strncmp(vmm, "unlimited", 9))> > + valuem = RLIM_INFINITY;> > + else> > + valuem = simple_strtoull(vmm, NULL, 10);> > +> > + for (i = 0; i < RLIM_NLIMITS; i++) {> > + if ((lnames[i].match) &&> > + !strncmp(element, lnames[i].match, > > + strlen(lnames[i].match))) {> > + index = i;> > + break;> > + }> > + }> > +> > + if (!lock_task_sighand(task, &flags))> > + goto out_free;> > The function silently does nothing if lock_task_sighand() fails.> > > + if (index >= 0) {> > + task->signal->rlim[index].rlim_cur = valuec;> > + task->signal->rlim[index].rlim_max = valuem;> > + }> > +> > + unlock_task_sighand(task, &flags);> > +> > +out_free:> > + kfree(element);> > + kfree(vmc);> > + kfree(vmm);> > + kfree(buffer);> > +out:> > + *ppos += count;> > + put_task_struct(task);> > return count;> > }> > > > +> > +static const struct file_operations proc_limit_operations = {> > + .read = proc_pid_limit_read,> > + .write = proc_pid_limit_write,> > whitespace got munged.> > > +};> > +> >
https://lkml.org/lkml/2009/9/28/305
CC-MAIN-2016-18
refinedweb
650
56.05
Building a mobile share extension for a React Native app I recently started working on building a share extension so I decided to share my work with the rest of the world. In this tutorial, I’m assuming you are building an app in React Native. You could either build a react native extension for both, or a native iOS and a native Android extension. I’ll be talking about building the native iOS and the React Native extension for both. The only reason I’m going to review the native iOS extension is because it’s more common to want to leverage iOS UI and standard dialogs in the share extension. On the other hand, Android is far less standardized. Building a share extension in React Native has the benefit of mostly working on both platforms without nearly as much additional overhead. On top of that, you’re working in Javascript, which [to me, a humble web dev] is easier and faster than working with Objective-C or Swift. When building a share extension, it’s generally expected that you have authentication around your app in some form or fashion. Though since it’s not really required, I’ll gloss over that pretty quickly right now. The practice I’ve found most effective, is to first fetch oauth credentials when logging in on the app and then store those in an app group bucket for iOS or use Shared Preferences on Android. You then fetch them in a similar fashion when making your request. First, we need to add a Share Extension project to each build. Open your project file in Xcode and add a new “target”, select share extension for the type, and name it. You’ll have a ShareViewController object and header file generated within your project. Open your project file and select your share extension target. Open the “Link binaries with libraries” dropdown and hit add. I went ahead and added all of the libraries under “Workspace” except for the Tv-OS. In your info.plist file, make sure you add the following: <key>NSExtension</key> <dict> <key>NSExtensionAttributes</key> <dict> <key>NSExtensionActivationRule</key> <dict> <key>NSExtensionActivationSupportsWebURLWithMaxCount</key> <integer>1</integer> <key>NSExtensionActivationSupportsImageWithMaxCount</key> <integer>10</integer> <key>NSExtensionActivationSupportsText</key> <true/> </dict> </dict> <key>NSExtensionMainStoryboard</key> <string>MainInterface</string> <key>NSExtensionPointIdentifier</key> <string>com.apple.share-services</string> </dict> This defines the data types that will activate your share extension. If you’re using app groups to share credentials, this is where you would enable app groups in both the main target app and the share extension app. You’ll need to get on your developer.apple.com account to add the capability to your certificate and create the group. Right click the java folder of your existing project and select new → package and add your share package (I’d recommend [your existing package].share for the name). You’ll want to make sure that in your AndroidManifest.xml you see your activity listed. Inside of it, you should add an intent filter that looks like this: <intent-filter> <action android: <category android: </intent-filter> <intent-filter> <action android: <category android: <data android: </intent-filter> <intent-filter> <action android: <category android: <data android: </intent-filter> <intent-filter> <action android: <category android: <data android: </intent-filter> The first filter opens the view, the second one allows you to receive data. Note the mimeType data field and SEND vs. SENDMULTIPLE. Now that we have the projects set up, we can dive into the implementation for iOS, then React Native on iOS, and lastly React Native on Android. I won’t go through much React Native code because you can build that however you want. Let’s start by opening the given ShareViewController.h and having the class inherit from SLComposeServiceViewController. You’ll need to #import <Social/Social.h> and then in your .m file implement the following: - (BOOL)isContentValid {} - (void)didSelectPost {} - (void)loadView {} isContentValidis called to determine if the post button is tappable. didSelectPostis called when the user presses the post button loadViewis called once the dialog shows up and is where we load data from the app groups bucket. The default here is going to have a cancel and a post button at the top and a text dialog and a preview of the content if it isn’t just plaintext. In our loadView we want to do the following: Defining didSelectPost should make a POST request to your server to share the data. I’d recommend adding cocoa pods to your app and using the AFNetworking module. That’s a majority of what you need to build out your share extension in objective c. I’m going to assume that you’ve already built the React Native component. It should be pretty much the same as any other component. Ignore the above changes to the .h and .m files. Open your ShareViewController.h and make sure the class inherits from UIViewController<RCTBridgeModule>. Then open up the .m file and add the following methods: Everything is pretty similar to a normal React Native app, except I’ve used share.ios for the bundle URL instead of index.ios, so you should create a share.ios.js file and import your component and register it using the AppRegistry. The data method will fetch the extension data, and the close method will close your extension. Also, don’t forget the RCTEXPORT_MODULE(); call. In your React Native component, you can now: import { NativeModules } from 'react-native'; const ShareExtension = NativeModules.ShareExtension; Then, calling ShareExtension.data and ShareExtension.close will fetch the data and close the extension respectively. You will also want a method that loads the context like this one here. The extractDataFromContext method referenced in the gist above should be the similar to the loadContext method from the iOS Native section, except it will pass the data into the callback. Here’s the signature: - (void)extractDataFromContext:(NSExtensionContext )context withCallback:(void(^)(NSString *value, NSString contentType, NSException *exception))callback {} That should be about everything you need to do to get your react native component showing up as a share extension. For the react native extension on Android, we add ShareActivity.java , ShareApplication.java , ShareModule.java , and SharePackage.java . ShareActivity.java This file just needs a definition for the getComponentName method like such: You’ll want to replace “MyShareExtension” with the name of your React Native component here. ShareModule.java This just defines the name that we export with, and the close method. And here is an example of the processIntent method. SharePackage.java Imports the share module and exports it as a React Native module. ShareApplication.java This should be the same as any other React Native application. You can copy the base code from a React Native app. The only difference is you should only need to add your SharePackage from above to the list of ReactNative packages imported. There you have it. A 10,000 feet walkthrough of building a share extension for a React Native app. I don’t claim to be an outstanding mobile dev, and this was one of my first attempts at working with Objective-C in case you haven’t noticed. Let me know if you have issues that I can assist with, or if there are any errors in the information I shared above. Thanks!
http://brianyang.com/building-a-mobile-share-extension-for-a-react-native-app/
CC-MAIN-2017-43
refinedweb
1,221
56.15
NAME fpathconf, pathconf - get configuration values for files SYNOPSIS #include <unistd.h> long fpathconf(int fd, int name); long pathconf(constfpathconf(), pathconf() │ Thread safety │ MT-Safe │ └────────────────────────┴───────────────┴─────────┘ CONFORMING TO POSIX.1-2001, POSIX.1-2008. NOTES Files with name lengths longer than the value returned for name equal to _PC_NAME_MAX may exist in the given directory. Some returned values may be huge; they are not suitable for allocating memory. SEE ALSO getconf(1), open(2), statfs(2), confstr(3), sysconf(3) COLOPHON This page is part of release 4.04 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
http://manpages.ubuntu.com/manpages/xenial/en/man3/fpathconf.3.html
CC-MAIN-2018-13
refinedweb
115
56.96
I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use Class.forName().newInstance(). Is there an equivalent in Python? Thanks for the responses. To answer those who want to know what I’m doing: I want to use a command line argument as the class name, and instantiate it. I’m actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. getattr() works great. Thanks much. Reflection in python is a lot easier and far more flexible than it is in Java. I recommend reading this tutorial There’s no direct function (that I know of) which takes a fully qualified class name and returns the class, however you have all the pieces needed to build that, and you can connect them together. One bit of advice though: don’t try to program in Java style when you’re in python. If you can explain what is it that you’re trying to do, maybe we can help you find a more pythonic way of doing it. Here’s a function that does what you want: def get_class( kls ): parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__( module ) for comp in parts[1:]: m = getattr(m, comp) return m You can use the return value of this function as if it were the class itself. Here’s a usage example: >>> D = get_class("datetime.datetime") >>> D <type 'datetime.datetime'> >>> D.now() datetime.datetime(2009, 1, 17, 2, 15, 58, 883000) >>> a = D( 2010, 4, 22 ) >>> a datetime.datetime(2010, 4, 22, 0, 0) >>> How does that work? We’re using __import__ to import the module that holds the class, which required that we first extract the module name from the fully qualified name. Then we import the module: m = __import__( module ) In this case, m will only refer to the top level module, For example, if your class lives in foo.baz module, then m will be the module foo We can easily obtain a reference to foo.baz using getattr( m, 'baz' ) To get from the top level module to the class, have to recursively use gettatr on the parts of the class name Say for example, if you class name is foo.baz.bar.Model then we do this: m = __import__( "foo.baz.bar" ) #m is package foo m = getattr( m, "baz" ) #m is package baz m = getattr( m, "bar" ) #m is module bar m = getattr( m, "Model" ) #m is class Model This is what’s happening in this loop: for comp in parts[1:]: m = getattr(m, comp) At the end of the loop, m will be a reference to the class. This means that m is actually the class itslef, you can do for instance: a = m() #instantiate a new instance of the class b = m( arg1, arg2 ) # pass arguments to the constructor Assuming the class is in your scope: globals()['classname'](args, to, constructor) Otherwise: getattr(someModule, 'classname')(args, to, constructor) Edit: Note, you can’t give a name like ‘foo.bar’ to getattr. You’ll need to split it by . and call getattr() on each piece left-to-right. This will handle that: module, rest = 'foo.bar.baz'.split('.', 1) fooBar = reduce(lambda a, b: getattr(a, b), rest.split('.'), globals()[module]) someVar = fooBar(args, to, constructor) def import_class_from_string(path): from importlib import import_module module_path, _, class_name = path.rpartition('.') mod = import_module(module_path) klass = getattr(mod, class_name) return klass Usage In [59]: raise import_class_from_string('google.appengine.runtime.apiproxy_errors.DeadlineExceededError')() --------------------------------------------------------------------------- DeadlineExceededError Traceback (most recent call last) <ipython-input-59-b4e59d809b2f> in <module>() ----> 1 raise import_class_from_string('google.appengine.runtime.apiproxy_errors.DeadlineExceededError')() DeadlineExceededError: Yet another implementation. def import_class(class_string): """Returns class object specified by a string. Args: class_string: The string representing a class. Raises: ValueError if module part of the class is not specified. """ module_name, _, class_name = class_string.rpartition('.') if module_name == '': raise ValueError('Class name must contain module part.') return getattr( __import__(module_name, globals(), locals(), [class_name], -1), class_name) It seems you’re approaching this from the middle instead of the beginning. What are you really trying to do? Finding the class associated with a given string is a means to an end. If you clarify your problem, which might require your own mental refactoring, a better solution may present itself. For instance: Are you trying to load a saved object based on its type name and a set of parameters? Python spells this unpickling and you should look at the pickle module. And even though the unpickling process does exactly what you describe, you don’t have to worry about how it works internally: >>> class A(object): ... def __init__(self, v): ... self.v = v ... def __reduce__(self): ... return (self.__class__, (self.v,)) >>> a = A("example") >>> import pickle >>> b = pickle.loads(pickle.dumps(a)) >>> a.v, b.v ('example', 'example') >>> a is b False This is found in the python standard library, as unittest.TestLoader.loadTestsFromName. Unfortunately the method goes on to do additional test-related activities, but this first ha looks re-usable. I’ve edited it to remove the test-related functionality: def get_object(name): """Retrieve a python object, given its dotted.name.""" parts = name.split('.') parts_copy = parts[:] while parts_copy: try: module = __import__('.'.join(parts_copy)) break except ImportError: del parts_copy[-1] if not parts_copy: raise parts = parts[1:] obj = module for part in parts: parent, obj = obj, getattr(obj, part) return obj Tags: class, java, python
https://exceptionshub.com/does-python-have-an-equivalent-to-java-class-forname-2.html
CC-MAIN-2021-21
refinedweb
911
55.64
I used a Python script in Power Query to pull data from a Google Sheet. It works fine in PBI Desktop, but I get an error for the automated refresh: You can't schedule refresh for this dataset because the following data sources currently don't support refresh: Discover Data Sources Query contains unknown function name: Python.Execute Unknown function name: Python.Execute is a valid Mashup library function name format. Hence fail the operation. This is the Python script that works on desktop but not for sched. refresh (anonimized the spreadsheet key): import numpy as np import pandas as pd pd.options.mode.chained_assignment = None import re import gspread import csv from oauth2client.service_account import ServiceAccountCredentials from df2gspread import df2gspread as d2g import glob from datetime import datetime from datetime import date import calendar import requests from dateutil.parser import parse def connect_to_gsheets(): scope = ['',''] credentials = ServiceAccountCredentials.from_json_keyfile_name(r'C:\Users\Laila\Documents\Python Scripts\google_spreadsheet_secret_key.json', scope) gc = gspread.authorize(credentials) return gc,credentials def read_cost_sheet(): gc,credentials = connect_to_gsheets() spreadsheet_key = 'xxxx' spreadsheet = gc.open_by_key(spreadsheet_key) worksheet = spreadsheet.worksheet("DATA") list_of_lists = worksheet.get_all_values() data=pd.DataFrame(list_of_lists) data.columns = data.iloc[0] return data cost_data=read_cost_sheet() print(cost_data) I can't find what part of the script throws the error. Solved! Go to Solution. Do you have a gateway installed and is Python installed on the gateway? Proud to be a Super User! Adding this just in case the first solution doesn't work for other people: - Something that works for me is in the PBI file change the privacy level for Python to "Private" and republish. Do you have a gateway installed and is Python installed on the gateway? Proud to be a Super User! I did not, had not realized that was necessary, but I now installed it and it worked! how did you do that. Thanks in advance Proud to be a Super User! Power Platform release plan for the 2021 release wave 2 describes all new features releasing from October 2021 through March 2022. Microsoft received the highest score of any vendor in both the strategy and current offering categories.
https://community.powerbi.com/t5/Power-Query/Query-contains-unknown-function-name-Python-Execute/m-p/1427775
CC-MAIN-2021-39
refinedweb
354
59.09
I am trying to only have the words print out if they occur the same number of times as in the fibonacci sequence. If a words show up 1,2,3,5,8 etc then it will print up. I have gotten the program to print up the words based on how many times the appear. I am having trouble figuring out how to use the sequence in my program. Any tips or examples would be very appreciated. def fib(): a,b = 0, 1 while 1: yield a a, b= b, a+b: if len(word) > 1: word_freq[word] = word_freq.get(word, 0) + 1 print(sorted(word_freq.items(), key=lambda item: item[1])) // I am pretty sure something with the seqeunce should go into the above line // but have been unable to figure it out. print('Bye')
https://www.daniweb.com/programming/software-development/threads/359795/using-fibonacci-seqeunce
CC-MAIN-2018-26
refinedweb
137
81.53
OpenWhisk supports an open API, where any user can expose an event producer service as a feed in a package. This section describes architectural and implementation options for providing your own feed. This material is intended for advanced OpenWhisk users who intend to publish their own feeds. Most OpenWhisk users can safely skip this section. There are at least 3 architectural patterns for creating a feed: Hooks, Polling and Connections. In the Hooks pattern, we set up a feed using a webhook facility exposed by another service. In this strategy, we configure a webhook on an external service to POST directly to a URL to fire a trigger. This is by far the easiest and most attractive option for implementing low-frequency feeds. In the “Polling” pattern, we arrange for an OpenWhisk action to poll an endpoint periodically to fetch new data. This pattern is relatively easy to build, but the frequency of events will of course be limited by the polling interval. In the “Connections” pattern, we stand up a separate service somewhere that maintains a persistent connection to a feed source. The connection based implementation might interact with a service endpoint via long polling, or to set up a push notification. Feeds and triggers are closely related, but technically distinct concepts. OpenWhisk processes events which flow into the system. A trigger is technically a name for a class of events. Each event belongs to exactly one trigger; by analogy, a trigger resembles a topic in topic-based pub-sub systems. A rule T -> A means "whenever an event from trigger T arrives, invoke action A with the trigger payload. A feed is a stream of events which all belong to some trigger T. A feed is controlled by a feed action which handles creating, deleting, pausing, and resuming the stream of events which comprise a feed. The feed action typically interacts with external services which produce the events, via a REST API that manages notifications. The feed action is a normal OpenWhisk action, but it should accept the following parameters: The feed action can also accept any other parameters it needs to manage the feed. For example the cloudant changes feed action expects to receive parameters including ‘dbname’, ‘username’, etc. When the user creates a trigger from the CLI with the --feed parameter, the system automatically invokes the feed action with the appropriate parameters. For example,assume the user has created a mycloudant binding for the cloudant package with their username and password as bound parameters. When the user issues the following command from the CLI: wsk trigger create T --feed mycloudant/changes -p dbName myTable then under the covers the system will do something equivalent to: wsk action invoke mycloudant/changes -p lifecycleEvent CREATE -p triggerName T -p authKey <userAuthKey> -p password <password value from mycloudant binding> -p username <username value from mycloudant binding> -p dbName mytype The feed action named changes takes these parameters, and is expected to take whatever action is necessary to set up a stream of events from Cloudant, with the appropriate configuration, directed to the trigger T. For the Cloudant changes feed, the action happens to talk directly to a cloudant trigger service we‘ve implemented with a connection-based architecture. We’ll discuss the other architectures below. A similar feed action protocol occurs for wsk trigger delete, wsk trigger update and wsk trigger get. It is easy to set up a feed via a hook if the event producer supports a webhook/callback facility. With this method there is no need to stand up any persistent service outside of OpenWhisk. All feed management happens naturally though stateless OpenWhisk feed actions, which negotiate directly with a third part webhook API. When invoked with CREATE, the feed action simply installs a webhook for some other service, asking the remote service to POST notifications to the appropriate fireTrigger URL in OpenWhisk. The webhook should be directed to send notifications to a URL such as: POST /namespaces/{namespace}/triggers/{triggerName} The form with the POST request will be interpreted as a JSON document defining parameters on the trigger event. OpenWhisk rules pass these trigger parameters to any actions to fire as a result of the event. It is possible to set up an OpenWhisk action to poll a feed source entirely within OpenWhisk, without the need to stand up any persistent connections or external service. For feeds where a webhook is not available, but do not need high-volume or low latency response times, polling is an attractive option. To set up a polling-based feed, the feed action takes the following steps when called for CREATE: whisk.system/alarmsfeed. pollMyServiceaction which simply polls the remote service and returns any new events. This procedure implements a polling-based trigger entirely using OpenWhisk actions, without any need for a separate service. The previous 2 architectural choices are simple and easy to implement. However, if you want a high-performance feed, there is no substitute for persistent connections and long-polling or similar techniques. Since OpenWhisk actions must be short-running, an action cannot maintain a persistent connection to a third party . Instead, we must stand up a separate service (outside of OpenWhisk) that runs all the time. We call these provider services. A provider service can maintain connections to third party event sources that support long polling or other connection-based notifications. The provider service should provide a REST API that allows the OpenWhisk feed action to control the feed. The provider service acts as a proxy between the event provider and OpenWhisk -- when it receives events from the third party, it sends them on to OpenWhisk by firing a trigger. The Cloudant changes feed is the canonical example -- it stands up a cloudanttrigger service which mediates between Cloudant notifications over a persistent connection, and OpenWhisk triggers. The alarm feed is implemented with a similar pattern. The connection-based architecture is the highest performance option, but imposes more overhead on operations compared to the polling and hook architectures.
https://apache.googlesource.com/openwhisk/+/HEAD/docs/feeds.md
CC-MAIN-2020-45
refinedweb
1,002
51.58
Details Description Try this in Groovy Console: @Grapes( [@Grab(group='org.spockframework', module='spock-core', version='0.2'), @Grab(group="junit", module="junit", version="4.7")]) class HelloSpock extends Specification { def "can you figure out what I'm up to?"() { expect: name.size() == length where: name << ["Kirk", "Spock", "Scotty"] length << [4, 5, 6] } } Output: 1 compilation error: unable to resolve class Specification at line: 1, column: 1 This means that Spock is not on the compile class path. When I @Grab JUnit and Spock individually by introducing a fake class, script works as expected. (Well, not quite. I need to add JUnitCore.run(HelloSpock) because otherwise, the test class is no longer found.) By the way, if Ivy was fully compatible with Maven, the JUnit @Grab wouldn't be necessary, because JUnit is a mandatory compile-time dependency of Spock. Admittedly, Ivy's transitive dependency resolution is more correct than Maven's, but at the cost of breaking compatibility. Is there a way to tweak this? Issue Links - is related to GROOVY-3861 AST transforms of spock do not take effect when the library is loaded using @Grab Activity I think I just lost the import at some point when investigating this issue. After fixing the import, I'm back at: Exception thrown: org.junit.runner.JUnitCore java.lang.ClassNotFoundException: org.junit.runner.JUnitCore That's what you see after my recent commit in trunk. Otherwise you'll just get "Error running JUnit 4 test." Adding the JUnit @Grab with @Grapes doesn't make a difference, but adding it on a fake class solves the ClassNotFoundException problem: import spock.lang.* @Grab(group="junit", module="junit", version="4.7") class Fake {} @Grab(group='org.spockframework', module='spock-core', version='0.2') class HelloSpock extends Specification { def "can you figure out what I'm up to?"() { expect: name.size() == length where: name << ["Kirk", "Spock", "Scotty"] length << [4, 5, 6] } } // we have to run the spec manually because GroovyShell doesn't know what to do if two classes are present new org.junit.runner.JUnitCore().run(HelloSpock).failureCount I tried a change with which the following script is working fine (but only from 2nd attempt onwards - details follow). import spock.lang.* @Grab(group='org.spockframework', module='spock-core', version='0.2') class HelloSpock extends Specification { def "can you figure out what I'm up to?"() { expect: name.size() == length where: ignored = println ("where: \n p0=$p0\n p1=$p1") name << ["Kirk", "Spock", "Scotty"] length << [4, 5, 6] } } Now, this code does not get executed correctly when you try for the first time. It fails with the error: Test Failure: initializationError(HelloSpock) org.spockframework.runtime.InvalidSpeckError: Class 'HelloSpock' is not a Speck, or has not been compiled properly This is happening because before grab brings in spock-jar on the classpath, the scanning for AST transformations has already happened, so the class does not get a chance to undergo spock related AST transformations and when run, it is not recognized as a speck. 2nd time onwards that issue is not there as the classpath has spock-jar now and the script correctly undergoes spock's AST transformation also and it is then run correctly as JUnit4 test. Since the AST transformation issue mention above is not related to the current JIRA, I want to commit the patch that makes the above script work(2nd time onwards) and mark this issue as fixed. Let me know if someone sees any issue with that. I will be interested in knowing views about the AST transformation issue and how it might be taken forward. Should scanning for AST transformation happen once more after GrabAnnotationTransformation has fetched stuff and updated the classpath? Still waiting for comments - for the confirmation that the issue that now remains has nothing to do with this JIRA (see previous comment for details) - before I go ahead and apply the patch. Roshan, I am not clear what your patch will do. As on the issue directly... If the grab annotation would be visited first in ResolveClass, including fetching the dependencies, then it would work I guess. But to me it becomes more and more clear that we should go with the following... make an annoation resolving try in conversion. And make the second, complete scan including failures normally in ResolveVisitor. Attaching the patch here. GroovyShell checked whether a class was a JUnit4 test or a TestNG test with the correct class loader but then executed the tests using a different class loader (Class.forName()). That is why it was not seeing the JUnit4 classes that the GroovyShell loader was seeing after @grab added spock/junit4 URLs to it. The changes regarding the issue that will remain - possibly doing 2 scans to find transformations or some other approach - can be taken as an improvement/JIRA outside this one, right? Although spock here is junit4 based, even execution of TestNG tests by GroovyShell had the same issue, so I corrected that as well here itself. the patch looks good to me. As for the transform recognition... yes, that should be an issue of its own Jochen, I tried adding a unit test case for the scenario reported here, but had to revert it because the @Grab download of groovy jar failed on the bamboo box for some reason. I removed the test case because it was a shaky one anyway and one that I was able to put in only for 1.6.x version and not for trunk for the following reason: - Apart from JUnit 4.7, spock-2.0 also was bringing in groovy-all-1.6.3 in the classpath. With trunk version, even locally I was getting java.lang.NoSuchMethodError: org.codehaus.groovy.ast.ModuleNode.getImport(Ljava/lang/String;)Lorg/codehaus/groovy/ast/ClassNode;, which, I guess, was because GCL was now seeing 2 different groovy versions on the classpath. I have locally tested it and I am fairly comfortable with it having tested it locally on 1.6.x and then you have seen it too. Let me know if you see any issue in me marking it "fixed". We can also wait for Peter to verify it from groovyconsole as reported in JIRA, if you want. I can confirm that HelloSpock now works from the second run onwards. The reason why you are getting NoSuchMethodError is that getImport() has changed incompatibly between Groovy 1.6 and 1.7. Spock 0.2 only works with Groovy 1.6. Thanks for confirming that, Peter. That incompatibility of getImport() is what I also meant to point to point out when I mentioned that after @Grab(bing) spock, groovy is seeing both 1.6 and 1.7 on its classpath and is running into that error. So, the plan is that we mark this JIRA as fixed as it has fixed the issue that was reported and then open another, linked JIRA to try to bring in some changes in AST transformation scanning so that this spock script can run from first attempt itself. Are you ok with that? Sure! Thanks for your work, Roshan. You're welcome, Peter. Fixed. Hi Peter, I have fixed it in 1.6.6 now. Can you please try with the latest 1.6.6 snapshot and see if this spock script execution now works from groovyconsole - from the first run itself? Thanks. Works fine now. I don't think that the compilation error you are getting here is due to any Grape bug. Your script should be like: Since spock.lang.* package is not a default import into groovy, you need to tell in the script which package class Specification could be found in. Also, looking at the grape executing your script, I noticed that it was retrieving junit-4.6 correctly as the dependency, so you should not need @Grab JUnit. Can you first try with the spock.lang.Specification and then without the Junit @Grab?
http://jira.codehaus.org/browse/GROOVY-3851?focusedCommentId=196703&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2014-10
refinedweb
1,320
64.91
Download presentation Presentation is loading. Please wait. Published byThomas Romero Modified over 3 years ago 1 1 eXtensible Markup Language 2 XML is based on SGML: Standard Generalized Markup Language HTML and XML are both based on SGML 2 SGML HTMLXML 3 HTML was designed to display data and to focus on how data looks. HTML is about displaying information, while XML is about describing information XML was designed to describe data and to focus on what data is. It is important to understand that XML was designed to store, carry, and exchange data. XML was not designed to display data. 3 4 XML stands for EXtensible Markup Language XML is a markup language much like HTML XML was designed to describe data XML tags are not predefined. You must define your own tags Extensible: can be extended to lots of different applications. Markup language: language used to mark up data. Meta Language: Language used to create other languages. XML uses a Document Type Definition (DTD) or an XML Schema to describe the data 4 5 Harry Potter J. K. Rowling 1999 Scholastic 5 6 Harry Potter J. K. Rowling 1999 Scholastic 6 8 1. XML is used to Exchange Data With XML, data can be exchanged between incompatible systems 2. XML and B2B With XML, financial information can be exchanged over the Internet. 3. XML can be used to Share Data With XML, plain text files can be used to share data. 8 9 4. XML is free and extensible XML tags are not predefined. we must "invent" your own tags. 5. XML can be used to Store Data With XML, plain text files can be used to store data. 6. XML can be used to Create new Languages XML is the mother of WAP and WML. 7. HTML focuses on "look and feel XML focuses on the structure of the data. 9 10 My First XML Introduction to XML What is HTML What is XML XML Syntax Elements must have a closing tag Elements must be properly nested 10 11 Element content book Mixed content Chapter Simple content para Empty content prod 11 12 Names can contain letters, numbers, and other characters Names must not start with a number or punctuation character Names must not start with the letters xml (or XML, or Xml, etc) Names cannot contain spaces Avoid "-" and "." in names. For example, if you name something "first-name," it could be a mess if your software tries to subtract name from first. Or if you name something "first.name," your software may think that "name" is a property of the object "first." 12 13 Names should be short and simple XML documents often have a corresponding database, in which fields exist corresponding to elements in the XML document. Attribute values must always be enclosed in quotes, but either single or double quotes can be used. Ex: 13 14 XML elements can have attributes. Attributes are used to provide additional information about elements. In HTML. The SRC attribute provides additional information about the IMG element. In XML 14 15 Data can be stored in child elements or in attributes. Attributes : Anna Smith Elements: female Anna Smith 15 16 A well-formed XML document conforms to XML syntax rules and constraints, such as: The document must contain exactly one root element and all other elements are children of this root element. All markup tags must be balanced; that is, each element must have a start and an end tag. Elements may be nested but they must not overlap. All attribute values must be in quotes. 16 17 According to the XML specification, an XML document is considered valid if it has an associated DTD declaration and it complies with the constraints expressed in the DTD. To be valid, an XML document must meet the following criteria: Be well-formed Refer to an accessible DTD-based schema using a Document Type Declaration: 17 18 The Document Type Definition (DTD) forms the basis of valid documents because it establishes the grammar of an XML vocabulary, which in turn determines the structure of XML documents. A DTD is necessary for performing document validation, which is an important part of XML content development and deployment. 18 19 ELEMENT is used to declare element names Ex: ATTLIST To declare attributes 19 20 TypesDescription CDATAUnparsed character data Enumerateda series of string values IDA unique identifier IDREFA reference to an ID declared somewhere NMTOKEN A name consisting of XML token characters NMTOKENS Multiple names consisting of XML token characters. 20 22 InternalDTDs Placing the DTD code in the DOCTYPE tag in this way products.xml 1 XYZ 300.00 XYZ descr 1000 22 23 SYSTEM the definitions are developed and used by the same comp or PUBLIC if the definition can be used by public 23 24 products.dtd products.xml 24 27 Xml Xsl Xsd 27 28 28 Apples Bananas African Coffee Table 80 120 29 XML Schema is an XML-based alternative to DTD. An XML schema describes the structure of an XML document. The XML Schema language is also referred to as XML Schema Definition (XSD). 29 30 An XML Schema: defines elements that can appear in a document defines attributes that can appear in a document defines which elements are child elements defines the order of child elements defines the number of child elements defines whether an element is empty or can include text defines data types for elements and attributes 30 31 1.Simple elements 2.Complex elements 31 32 A simple element is an XML element that can contain only text. It cannot contain any other elements or attributes. Xml: abc Xml schema: 32 33 33 34 34 35 35 37 A complex element is an XML element that contains other elements and/or attributes. 37 40 DTD supports types ID,IDREF,CDATA etc., Schema supports all primitive and user defined data types DTD supports No specifier, ?, *, + sign Schema hava minOccurs and maxOccurs attributes XML Schemas are extensible to future additions XML Schemas are richer and more powerful than DTDs XML Schemas are written in XML 40 41 An XML parser is a piece of code that reads a document and analyzes its structure. The parser is the engine for interpreting our XML documents The parser reads the XML and prepares the information for your application. How to use a parser 1. Create a parser object 2. Pass your XML document to the parser 3. Process the results 41 42 import com.ibm.xml.parser.*; import java.io.*; public class SimpleParser {public static void main (String a[]) throws Exception {Parser p=new Parser("err"); FileInputStream fis=new FileInputStream(a[0]); TXDocument doc=p.readStream(fis); doc.printWithFormat(new OutputStreamWriter(System.out)); } 42 43 There are two common APIs that parsers use. DOM is the Document Object Model API SAX is the Simple API for XML 43 44 DOM uses a tree based structure. DOM reads an entire XML document and builds a Document Object. The Document object contains the tree structure. The top of the tree is the root node. The tree grows down from this root, defining the child elements. DOM is a W3C standard. Using DOM, we can also perform insert nodes, update nodes, and deleting nodes. 44 45 Node: The base data type of the DOM. Methods: Element: Attr: Represents an attribute of an element. Text: The actual content of an Element or Attribute Document: Represents the entire XML document. A Document object is often referred to as a DOM tree. 45 46 46 Node getChildNodes(), getNodeName(), getNodeValue(), hasChildNodes(). Document createElement(), createAttribute(), createTextNode(), Element NodeList getLength() item() 47 SAX parsers are event-driven The parser fires an event as it parses each XML item. The developer writes a class that implements a handler interface for the events that the parser may fire. 47 48 DocumentHandler Functions in this interface startDocument() startElement() endElement() endDocument() void setDocumentLocator(Locator) void characters(char[ ],int start,int length) This event fires when text data is found in the XML Document 48 class HandlerBase is a sub class of DocumentHandler also called Adapter Class. 49 DOMSAX Uses more memory and has more functionality Uses less memory and provides less functionality The entire file is stored in an internal Document object. This may consume many resources The developer must handle each SAX event before the next event is fired. For manipulation of the document, DOM is best choice For simple parsing and display SAX will work great 49 Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/252471/
CC-MAIN-2017-22
refinedweb
1,422
61.87
#include <RW_Mutex.h> #include <RW_Mutex.h> Inheritance diagram for ACE_RW_Mutex: These are most useful for applications that have many more parallel readers than writers... USYNC_THREAD 0 Initialize a readers/writer lock. Implicitly destroy a readers/writer lock. [private] Note, for interface uniformity with other synchronization wrappers we include the <acquire> method. This is implemented as a write-lock to safe... Acquire a read lock, but block if a writer hold the lock. Acquire a write lock, but block if any readers or a writer hold the lock. Dump the state of an object. Reimplemented in ACE_RW_Thread_Mutex. Return the underlying lock. Unlock a readers/writer lock. Explicitly destroy a readers/writer lock. Note that only one thread should call this method since it doesn't protect against race conditions. Note, for interface uniformity with other synchronization wrappers we include the <tryacquire> method. This is implemented as a write-lock to be safe... Returns -1 on failure. If we "failed" because someone else already had the lock, <errno> is set to <ebusy>. Conditionally acquire a read lock (i.e., won't block). Returns -1 on failure. If we "failed" because someone else already had the lock, <errno> is set to <ebusy>. Conditionally acquire a write lock (i.e., won't block). Conditionally upgrade a read lock to a write lock. This only works if there are no other readers present, in which case the method returns 0. Otherwise, the method returns -1 and sets <errno> to <ebusy>. Note that the caller of this method *must* already possess this lock as a read lock (but this condition is not checked by the current implementation). Declare the dynamic allocation hooks. [protected] Readers/writer lock....
https://www.dre.vanderbilt.edu/Doxygen/5.4.3/html/ace/classACE__RW__Mutex.html
CC-MAIN-2022-40
refinedweb
280
61.83
Hi, I wrote the following function to determine the maximum depth of a binary tree, but it feels somewhat cumbersome to me. I'd truly appreciate it if you could help me improve it (make it shorter if possible and more elegant), albeit it works great: Any insightful comments will be highly appreciated! :-)Any insightful comments will be highly appreciated! :-)Code:int findMaxDepth(Node * tree, int curr){ int left, right; if (!tree) return 0; right = findMaxDepth(tree->right, curr + 1); left = findMaxDepth(tree->left, curr + 1); curr = (curr > right) ? curr : right; return (left > curr ? left : curr); } PS All the variations thereof which I saw online, and in other sources, find the maximum depth + 1, not the ACTUAL maximum depth. The above function yields the actual depth as desired.
http://cboard.cprogramming.com/csharp-programming/157831-recursion-actual-maximum-depth-bt.html
CC-MAIN-2015-11
refinedweb
128
64.61
THE MINNEAPOLIS JOURNAL. ' PRICE TWO CENTS. ALL FOR THE CIVIL SERVICE President's Reason for Cabi- net Changes. POWER OF EXECUTIVE Cabinet Members Must Cease En- croaching Upon It. WHITE HOUSE EASY-GOING ENDS Violation!* of Civil Service Rules by Heads* of Department)* \o Longer Permitted. J-'rom The Journal Bureau, Room 45, Pott Building, Washington. Washington, Dec. 21. —Should there be a reorganization of the Roosevelt cabinet along lines suggested in these dispatches >t--u>rday, it will not indicate any change in governmental policy. President Roose velt intends to pursue the McKinley pol icy, first, because he believes in it, and, second, because he said publicly at Buf falo that he would; but he feels that the president ought to have freer swing in the departments, now for many years almost exclusively under control of the cabinet chiefs, and ought not to be required to indorse the actions ot these chiefs unless he sees fit to do so. For years the authority of the cabinet has been encroaching on the authority of the president, and this encroachment was greatly intensified under the easy-going administration of President McKinley. Quite naturally the men who were in Mc- Kinley's cabinet do not take kindly to a man who proposes to restore the balance that originally prevailed between the president and his official advisers. And that is about all there is to the case. There has been no personal friction be tween the president and the cabinet and there will be none: The president Is clearly within the rights of his office in insisting on reviewing at will the acts of his advisors and in reserving the privil ege of ignoring their recommendations. The fact that for years these rights have not been exercised does not nullify them. Men, who under McKinley, were given practically full authority, naturally do not relish the idea of curtailment under Mc- Klnley's successor. And if several of them, following out a purpose which was expressed, but for other reasons, during McKlnley's lifetime, conclude to resign, their places will promptly be filled and the general policies of the administration will remain unchanged. The general pub lic has nothing at stake In friction which the past few days has developed, and probably will indorse the president's In tention to assume full responsibility for and have full share in the various impor portant matters which the cabinet gen tlemen for a long time have been gradu ally monopolizing. Back of this friction, for the most part, is federal patronage. The chief trouble with Postmaster General Smith was the rather loose manner in which he permittorl postoffice appointments to be made. For years the civil service law in thi3 depart ment has been flagrantly and quite open ly violated. When the civil service blan ket was thrown over the rural free de livery force, many people slipped in and got under cover without any right. This Drillers Find Boat and Cargo Special to The Journal. Sioux City. lowa. Dec. 21.—A bill of shipment from St. Louis of a cargo of hats caps and shoes for Tootle & Jackson arrived here to-day just forty-five years late' Ely Brothers of Holt, Mo., in drilling on their farm struck a steamboat and found it laden with goods for this firm, both of whom died thirty-five years ago. The boat was buried fifty feet, twenty miles from the Missouri river's present channel. Rec ords bere show that Tootle & Jackson lost four steamboats about that time. THE END OF THE WAR IN SIGHT AGAIN. is but one illustration. Many more could be furnished if necessary. Secretary Gage had a grievance because the president would not indorse in his message to congress the asset banking scheme and the Overstreet bill for making gold and silver controvertible. This legis lation Gage thought was important. The president said he thought the country cared nothing about it. Another trouble with Secretary Gage was in New York city federal patronage. The president did not follow Gage's recommendations. In fact, he Is understood in at least one instance to have acted without consulting him. In the treasury department, also, the civil service rules on numerous occasions have been more honored in their breach than in their observance. Mr. Roosevelt, with hia intense feeling regarding the civil serv ice, could not be expected to indorse cabinet officers who were negligent at this point. "The best men for public office" is the president's motto; and that motto will probably be lived up with the cabinet, just as it has been thus far with the senators and members of congress. Of course, thia is a new proposition, for few people in high official life in Washington have tak en civil service reform seriously; but it is quite natural that Mr. Roosevelt should make it with emphasis. He has taken hold, of certain details heretofore con trolled by the cabinet expressly for the purpose of seeing that the spirit of the law is lived up to. It should be said in this connection, as further explaining the feeling of certain cabinet officers, that they did not relish the criticism implied by the president's course. ALLIANCE Friends of the Tawney- Grout bill in both houses NOT TO BE. of congress say there i 3 nothing in the report that there is likely to be an alliance between the- oleo, ship subsidy and river and har bor members. Such an alliance would be all powerful, and nothing could stand against it, but there are many good rea sons why it will not be made. In the first place, so far as the oleo people are concerned, there is no need for it. The Tawney-Grout bill has a splendid follow ing in both houses, and will probably pass without questionable support such as has been proposed. It is barely possible that th«> subsidy folks are anxious for the al liance, but it always takes two to make a bargain. So far as can be known at this time, the senate committee on agriculture is pretty evenly divided between the two forces—oleo and anti-oleo. Of the repub licans, Proctor, Hansbrough, Foster, Dol liver and Quarles are supposed to favor the Tawney-Grout bill. All of the demo crats, Bate. Money, Heitfield and Simmons are against it; Warren, a republican, 1b also against it, because he represents a cattle state. Here, then, are five votes for and five against. The eleventh mem ber of the committee is Senator Quay of Pennsylvania, who Is being claimed by both sides; but there are reasons for be lieving that he is favorable to the bill. Quay is sick, and. has gone to Florida for the winter, but he will probably be in Washington in time for a committee vote should it be needed. —W. W. Jermane. MORE POSTMASTERSHIPS. Special to The Journal. Washington, Dec. 21.—Postmasters ap pointed to-day: Minnesota—Collis, Trav erse county. J. E. Murray. lowa^—Chil licothe, Wapello county, A. E. Belman; Mark, Davis county, R. B. Andrews. North Dakota—Donnybrook, Ward county, Patrick King; Garske, Ramsey county, W. V. Bake; Glencoe, Emmons county, W. J. Taylor; Omio, Emmons county, George Westcott; Standy, Richland county, M. K. Harris. South Dakota — Ludlow, Ewing county, Amanda Maoh; Terraville, Lawrence county, H. O'Connor. Wiscon sin—Hamlln, Burnett county, Simon Jen sen; Hempel, St. Croix county, A. O. Spen cer; Robinson, Walworth county, John Gavin; Union Mills, lowa county, Sever Anderson. MRS. DALE RELEASED. New York, Dec. 21. — Mrs. Elizabeth Dale, who was held in custody at St. Mary's hospital, Hoboken, pending the re sult of an investigation into the death of, her 5-year-old daughter Emmeline, was released on $5,000 bail to-day. SATURDAY EVENING, DECEMBER 21, 1901. CRANE Governor of Massachusetts Is Offered Gage's Place in the Cabinet. Governor Hesitates, but Is ,P Expected Finally to A -i_ Accept. From The Journal Jiivreau, Jloom 4,5, Post Building, Washington. Washington, Dec. 21.—1t is said to-day on high authority that Governor Crane of Massachusetts may be secretary of the treasury if ho will. The president has made the offer. —w. W. Jermane. Boston, Dec. 21.—A close friend of Gov ernor W. Murray Crane to-day stated that the. governor had been offered the treas ury portfolio by President Roosevelt and said the governor had asked for time un til next Monday, before deciding whether or not he would accept. A message from Dalton, Governor Crane's home, received here to-day says that Governor Crane is considering the question and is inclined to accept the position. Family and busi ness considerations are the cause of the governor's hesitation. "Washington, Dec. While no official confirmation can be obtained at the White House, it is believed that President Roose velt has offered the treasury portfolio to Governor Crane of Massachusetts and the latter now has the tender under advise ment. One of the difficulties in the way of Governor Crane's acceptance is under stood to be his connection with the com pany at DaltoD, Mass., which furnishes 1 the paper for government notes. This paper is prepared by a secret process, and the government's contract with the Dal ton company is a large one. Should Gov ernor Crane accept the treasury port folio, it is considered probable that he would dispose of his interest in the paper company. New JTorh Sun Special Service Washington, Dec. 21.— Winthrop Murray Crane, governor of Massachusetts was a caller at the White House yesterday and breakfasted with the president. The significance of Mr. Crane's early break fast at the White House is that he may have caught there the secretaryship of the treasury, if not for himself then for some ether good New England republican. President Roosevelt has determined to go to that section of the country for a successor to Secretary Gage, and for sev eral days he has been asking New Eng land congressmen about Governor Crane and about other New Englanders who have special qualifications as business men and financiers. In his search the name of Governor Crane was suggested j or came to him and he was at once in vited to Washington. The result of the conference was that Governor Crane now has under consideration the question of whether he could so arrange his politi cal and business affairs as to accept the secretaryship of the treasury if it should be formally offered to him. The few per sons who knew of his visit here and its import have the impression that the gov ernor will succeed in doing this. Mr, Crane is an able business man and a politician of the Henry G. Payne order. He is to be inaugurated for his second term as governor Jan. 1, but that cere mony would not necessarily be Interfered with if it should be decided that he is to go into the cabinet, as Secretary Gage's formal resignation is not yet handed in and could be made to take effect at such time as would be agreeable to Governor Crane and his political obliga tions. BURNED JCTA CRISP Mrs. Ruble's Clothes Caught Fire While Preparing Supper. Special to The Journal. Mason City, lowa, Dec. 21.—While put ting cobs in the stove to prepare supper i last night, Mrs. . Charles Ruble of Swale- I dale, was burned to a crisp. ; :. LOSES HALF A MILLION Austrian Count's Three Hours at Cards Very Costly. , Vienna, Dec. 21.—1n. the Vienna Jockey club Count Potooki lost $500,000 ; during three hours' card playing. Count Palla i vincini won most oX the money, , iLONG'S "OK" ! IS AFFIXED > ■■;"■■■•■'.■■■ > . , • • ■ n > Secretary Approves Schley I Court's Findings. : > ■■ > ,— _ I . \ INCIDENT NOT CLOSED > > Attorney Rayner Mentions Arbi > ■ ■..■•■ --> trarlness and Tyranny. > ■■' '*■' - ' "-*. -: ''. .■'' -■•■*..,'.' . '."•*■'■ j > .. ; .--_ '•■■■' ■ ; —■ « > COURT OF ARBITRATION WANTED >. . ; > : ' Admiral Schley Will Appeal to the - . President to Appoint Such I a. Body. ' Washington, Dec. 21.—Secretary Long ■ has disposed finally of the Schley case ' so far as the navy department is con • cerned, by acting upon the findings and ' conclusions of the court of inquiry. These > i are the secretary's words: [; The department has read the testimony in , this case, the . arguments of counsel at the , ! trial, the court's findings of fact, opinion • ■ and recommendation; the individual memo • ; randum of the presiding member; the state- ruent of exceptions to the said finding and \ opinion by the applicant; the reply to said . . statement by the judge advocate of the court ■ ■ and his associate and the brief this day sub ' mitted by counsel for Rear Admiral Samp ' son, traversing the presiding member's view , as to who was in command at the battle of i Santiago. And after careful consideration the findings ' of fact and opinion of the full court are ap ' proved. ' . As to the points on which the presiding | member differs 1 from : the majority of the ■ ' court, the opinion of the majority is ap ' j proved. [ I As to the further expression of his views , by the same member with regard to the question of command on the morning of July j3, 1898, and of the title to. credit for - the ' I ensuing victory, the conduct of ; the court in making no finding and rendering no opinion , on these questions is approved— indeed it I could with propriety take no other course— 1 evidence on these questions during the in | quiry having been excluded by the court. The department approves the recommenda tion of "the court that no further proceed ings be had in the premises. The department records its appreciation of the arduous labors of the whole court. —John D. Long, Secretary of .the Xaty. The secretary also has declined the ap plication of Admiral Sampson's counsel to enter upon an inquiry into the question of command and has notified Admiral Schley's counsel of that fact as a reason for declining to hear them on that point. The text of the secretary's letter to Ad miral Sampson's attorneys end; to Ad miral Schley follows: Washington, D. C, Dec. 20, Gentle men: In view of the department's approval, this day, of the recommendation "of the court of inquiry in the case of .Rear Admiral Schley, that no further proc ■■'"■■ o , be had. ■ and .of the fact^tfaut the (T&p*ticii of -command was excluded from consideration by the court, the department will take no action upon the brief filed by you in behalf of Rear Admiral William T. Sampson.' Very respectfully, " - —John D. Long, Secretary. Messrs. Stayton, Campbell & Theall, New York. Long to Schley. , Following is the text of the notice to Admiral Schley: Washington, Dec. 21, 1901.—Sir: Referring to the department's letter of the 13th inst., you are advised that action has been taken to-day upon the findings and recommendation* of the court of inquiry in your case and upon the minority opinion of the presiding officer and upon the indorsement indorsing such ac tion is herewith transmitted for your informa tion. In response to your request of 18th inst., and hereby acknowledged, that if a protest should be filed by Rear Admiral W. T. Samp son, relative to the question of command of the United States naval -forces during the battle of Santiago and credit for the victory I of that battle, you be accorded an opportunity to answer through your counsel or oral argu ment against such protest, you are advised that a .brief on this subject has' this day been filed by Messrs. Stayton, Campbell & Stay ton in behalf of Admiral Sampson. In view, however, of the department's ap proval of the recommendation of the court of inquiry that no further proceedings be had, and of the fact that the question of com mand was excluded from consideration by the court, no action will be taken upon said brief, and reply to that effect (copy in closed) has this day been made to counsel for Admiral Sampson. Very respectfully, • —John D. Long, Secretary. Rear Admiral Winfleld S. Schley, U. S. N., retired, Washington, D. C. BOARD OF ARBITRATION Admiral Scliley Will Request the President to Appoint One. If etc Ttorie Sun Special S*rvio» Washington, Dec. 21. — Admiral Schlej has determined on another move in his endeavor to offset the effect of the ad verse conclusions of Admirals Dewey, Benham and Ramsay. Incidentally this is intended obviously to keep his name before the public. Realizing that his petition for a rehear ing will be denied by the secretary of the navy, he has decided, according to an announcement made from • Schley head quarters, to appeal to President Roose velt to sanction the appointment of a board of arbitration to pass on his case, the board's decision to be final. The scheme calls for the selection of three ar bitratorsone by President Roosevelt, one by Admiral Sampson and one by Ad miral Schley. They are to review all the evidence of the court of inquiry and hear further evidence bearing on the conduct of Admiral . Sampson in the war with Spain. When they have done this they are to report fully their findings and opinion, from which there shall be no ap peal. | It is safe to say that this appeal will be rejected. If its purpose is to get Mr. Roosevelt on record on the Schley case, Admiral Schley will be successful.- Should i congress pass the bill promoting Samp- ' son, Schley and Captain Clark to the grade of vice admiral it will be vetoed by President Roosevelt for the reason that it seeks to interfere with the exclusive right of the executive to make nomina tions and "by and with the advice and consent of the senate" to make appoint ments. No president has ever permitted congress to infronge on this right. Admiral Sampson's friends and support ers in the navy are indignant over the attempt of Admiral Schley and. his ad visers to secure reward for that officer through the sympathy felt for Admiral. Sampson. The bill which proposes to pro mote Sampson, Schley and Clark was pre pared by the Maryland delegation in con gress and is intended to take the place of the other measures which were framed at the dinner given here this week by General Felix Agnus of the Baltimore Continued on Second Page. JAMES J. HILL EXPLAINS The President of the Northern Securities Co. Makes a Detailed Statement of Condi tions Leading to Present Situation. He Intimates That He and Morgan Saved the N. P. From Baneful Domination of Har riman Interests-Battle of Giants. James X Hill, president of the North ern Securities company, to-day issued a statement to the press embodying the pur poses of the Northern Securities com pany and the events which led to its for mation. He makes an important point in the fact that the threatened Union Pa cific domination of Northern Pacific af fairs would have been detrimental to the interests of the northwest. He states flatly that the Northern Securities com pany and its plans do not tend in any way to a consolidation of the properties. His statement, in full, is as follows: "I have been absent from Minnesota for more than two months, and during that time there has been a wide discussion throughout the state of what has been generally called a consolidation or a merger of the Northern Pacific and Great Northern railroads, and in this discussion statements have been made which are so widely different from the facts that I feel called upon to make a conservative state ment of just what has been done in the past and what will be done in the future. "When the Northern Pacific failed and the banking-house of J. P. Morgan & Co. reorganized it, myself and frien&w were holders of a large amount of the com pany's securities. After the reorganiza tion was completed we bought about $26, --000,000 of Northern Pacific stock, both common and preferred. Some of this stock was afterward sold, but a large amount has been held from that time to the present. Burlington Purchase Explained. "About a year ago the Union Pacific company bought the Huntington and other interests in the Northern Pacific and at the same time made an effort to buy the control of ,the Chicago, Burlington & Quincy. "With these lines in the hands of the Union Pacific interest, both the Northern Pacific and Great Northern could be largely shut out of the states of Nebraska, Kansas, Missouri, South Dakota, lowa, Illinois and Wisconsin, except by using other lines of railway, some of which were in the market for sale, and might at any time pass under the control of or be come joined with the Union Pacific inter ests. We then, of the Northern Pacific, made proposals to .the directors of the Burlington to buy their entire property. When this transaction was about Being closed, the people who represented the Union Pacific company, and who had pre viously tried to buy the Burlington, asked to be allowed .to share with us in the pur chase of that company. This proposal we refused for the reason that it would" de feat our object in buying the Burlington, and further it was against the law of several of the states in which the longest mileage of the Burlington was located. Union Pacific's Bold Move. At that time, against the oposition of more southern lines, both the Northern Pacific and Great Northern had put into effect a low colonization rate and were carrying daily thousands of people into the northwest, many of whom were com ing from Kansas and Nebraska along the lines of the Union Pacific. This move ment was at its height in the month of April and though after we had closed the purchase of the Burlington the Union Pacific people undertook the boldest ef fort that ever was made in this country and bought over $60,000,000 of stock of the Northern Pacific in the markets of Europe and the United States. I was in Panama Canal Co. Bound to Sell Paris, Deo. 21.—At a meeting of the board of the directors of the Panama Canal company, Thursday, President Hutin and M. Chorron, the director of works, re signed. The report presented at the general meeting of the shareholders of the company here this afternoon reviews the negotiations for the sale of the canal property to the United States and says: The decision of the isthmian commission was evidently due to a mis understanding which must be dissipated. We shall ask you to give us full powers to negotiate with the government of the United States under the reserve of submitting for your approval the figure upon which the representatives of the American government agreed and the manda tory to whom we shall entrust the continuance of the negotiations. Our negotiator will be instructed to notify the American government that we are prepared to set aside the valuations which have been considered as the price asked and which have been Judged unacceptable, and we offer to take as a basis and point of departure of the discussion we so licit, and which we believe will not be refused, the figures and declara tions contained in the conclusions of the isthmian commission's report. We shall, however, give our mandatory power to close the discussion by proposing a fixed price. We hope this simple, categorical offer will exercise a favorable influence upon the future negotiations. We regret that M. Hutin and M. Chorron have separated themselves from us in this question by their resignations, which have been ac cepted. M. P. Forot, the former controller general of the army, and M. Bourgeois, the former receiver of finances, will replace them. After an uproarious session, the shareholders almost unanimously voted to adopt the proposition set forth in the report empowering the board to conclude the sale and cession to the United States of all the Panama Canal company's prop erties, subject to the limitations specified above. 28 PAGES-FIVE O'CLOCK. New York at the time, and after Messrs. Morgan & Co. were aware of the action of the Union Pacific people, it was found that together we held about $26,000,000 of Northern Pacific common stock, and, in asmuch as the common stock by a right of a contract made with the preferred stock holders when the company was reorgan ized and the stock issued, had the priv ilege of paying off the preferred stock at par on the first day of January of any year until 1917, Messrs. Morgan & Co. then bought in London and New York about $16,000,000 of the common stock of the Northern Pacific." U. P. Domination Feared. "At the same time the Union Pacific interests, having already so large an in vestment, bid the stock up until there was the largest stock corner ever known. The common stock in three or four days went up to $1,000 per shaVe. I explained to my friends how that, with control of the Northern Pacific, the Union Pacific wouldi control the entire northwest and of the west from Mexico to the Canadian line, except for the Great Northern. So great was this effort to get control that one of my friends in London, who owned $2,000, --000 or Northern Pacific common, was of fered end refused $14,000,000 for hia stock. "The result was that Messrs. Morgan & Co. and ourselves «wned 42,000,000 out of 80,000,000 of the Northern Pacific com mon with the privilege of paying off the $75,000,000 of Northern Pacific preferred. The Union Pacific people owned $37,000,000 of the common and about $40,000,000 of the preferred, which was a clear majority of all the stock of the Northern Pacific and claimed the exclusive control of the Northern Pacific railway and their owner ship and control of one-half the Bur lington." When it was known that these preferred shares could and would be paid off and before the annual election, mutual nego tiations resulted in Mr. Morgan giving them a representation on the Northern Pacific board. When I was advised of my election I notified them that I could not legally act as a director of the Northern Pacific and Great Northern at the same time, and I resigned after the first meet ing of the board. Genesis of Northern Securities Co. "Several of the gentlemen who have long been interested in the Great North ern and its predecessor, the St. Paul, Minneapolis & Manitoba, and who have always been among its largest share hold era but not the holders of a majority of its stock, whose ages are from 70 to 86 years, have desired to combine Jheir in dividual holdings in corporate form and in that way secure permanent protection for their interests and a continuance of the policy and mangement which has done so much for the development of the north west and the enhancement of their own property in the northwest and as else where. Out of this desire has grown the Northern Securities company. It became necessary (in order to prevent the North ern Pacific from passing under the con trol of the Union Pacific interests and with it the Joint control of the Burling ton) to pay off the 75,000 of Northern Pa cific preferred. The enormous amount of cash required for this purpose from a comparatively small number of men made it necessary for them to act together In a large and. permanent manner, through the medium of a corporation, and the Northern Securities company afforded thorn the means of accomplishing this object without the necessity of asking a separate company to finance the trans actions for the Northern Pacific; while, at the same time, the credit of the North ern Securities company would be much stronger aa it would also hold a credit able amount of Great Northern and other securities. The Northern Securities company is or- . ganized to deal in hlgh-clas saecurlties, to hold the same for the benefit of its share-holders and to advance the inter ests of the corporations whose securities it owns. Its powers do not include the operation of railroads, banking, mining nor the buying or sellng of securities or propertias for others on commission; it is purely an investment company and the object of its creation is simply to enable those who hold its stock to continue them respective interests in association to gether and to prevent such Interests from being scattered by death or otherwise; to provide against such attacks as had) ben made upon the Northern Pacific by a rival and competing interest whose main pased, the gentleman in charge started o investment was hundreds of miles from the northwest and whose only object in buying control of the Northern Pacific was to benefit their southern properties by re straining the growth of the country be tween Liake Superior and Puget sound and by turning away from the northern lines the oriental traffic which must follow, placing on the Pacific ocean of the largest ships of the world. Effect on Public Interests. "The foregoing is a brief and absolute ly correct statement of whole subject and its truth can easily be verified by th« state of Minnesota or any other state or person having sufficient interest to inves tigate the facts which are all matters of record. "Now, as to the effect of what has been done upon the public interests of tn« country; let me ask a few questions which, I want every candid and honest man to answer for himself. : Did the Union Pacific people : : with their railway lines extend- : : ing from Omaha and New Orleans : : to California and Oregon, through : : the several states in the middle : : west and south, purchase a ma- : ": jority of the stock of the North- : : em Pacific company for the pur- : : pose of aiding that company, and : : increasing the growth and pros- : : perity of the northern country, or : : was it for the purpose of restrict- : : ing such growth and aiding the : : development of their enormous : : interests hundreds of miles to the : : south? : : Did they purchase the Northern : : Pacific and its Interest in the Bur- : : llngton for the purpose of build- : : ing up the Asiatic trade between : : the northern zone lying from St. : : Paul and Minneapolis to the Pa- : : ciflc coast, or in order to control : : the Oriental trade for their own : : southern railway lines through : : their own seaports, over their : : own Bhips? t Thinks His Action Helpful. "In defeating their control of thel Northern Pacific and retaining in the hands of those who had built it up and with it the entire northwest, did we Injure or benefit the people of the north west? "Did I by inducing my friends to hold their Northern Pacific comtmon stock and act jointly with Messrs. Morgan & Co. when this stock was selling at 600 to $1,000 a share, thus preventing the Union Pacific from controlling the northwest, in jure or benefit every interest, agricultural, business and otherwise of the entire coun try between Lake Superior and the Pacific ocean? "Had we sold our 20,000,000 of North ern Pacific even at $300 a share, amount* ing to $60,000,000, or nearly forty mil lions more than its present value, and transferred to the Union Pacific control of the entire country between Canada and Mexico, what law of Minnesota would wo have violated? Could we nit"legally have put the money in our pockets and let the country learn what it was to be dominated by a parallel and competing railroad? "Why did Governor Van Sant sit still from May until November while a major ity of the stock of the Northern Pacific company was controlled by "a parallel and competing railway company in clear opposition, until myself and friends have, by our efforts and with our own money, relieved the northwest, not as a rival parallel or competing railway, but doing what we clearly have the right to do as individuals or working together for greater permanency and security as a financial corporation? "Has there ever been a case in the his« tory of this country when men hava dropped their money profit and stood as firmly by the interests of the communl ties which had grown up with their own and largely by their own efforts and capi« tal? Not a "Consolidation." "The public Is Interested in having a good railway service and at fair and rea sonable rates. The past is gone ana speaks for itself; I can speak for the fu« ture, and I have no hesitation whatever in saying that the increased volume of traffic both through and local will enable the companies to reduce their rates In sroporttoß to th» volume of such traflt xml | txt
http://chroniclingamerica.loc.gov/lccn/sn83045366/1901-12-21/ed-1/seq-1/ocr/
CC-MAIN-2016-22
refinedweb
5,515
57.2
Opened 2 years ago Last modified 18 months ago #20752 assigned Bug Error signals are not reliable, especially when dealing with database errors Description In core.handlers.base, unhandled exceptions are processed as such: except: # Handle everything else, including SuspiciousOperation, etc. # Get the exception info now, in case another exception is thrown later. signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) Which delivers the error signal to the various handlers (database transaction resets, things like Sentry etc). However, the code that dispatches signals aborts the dispatch if any of the handlers fail (to try..except block): for receiver in self._live_receivers(_make_id(sender)): response = receiver(signal=self, sender=sender, **named) responses.append((receiver, response)) return responses This is perfectly reasonable in most cases, but is problematic when dealing with top-level error handling, as this prevents the unhandled error from reaching handlers that just want to report it. This is very noticeable in cases where "something bad" happens to the database connection, as the first handler is always the database rollback handler, which only catches DatabaseError, which excludes a lot of errors that can and do crop up in production def _rollback_on_exception(**kwargs): from django.db import transaction for conn in connections: try: transaction.rollback_unless_managed(using=conn) except DatabaseError: pass I think that it will be better to have the error signal dispatcher defer except raising until after all the handlers were called (or just swallow them all). Alternatively, a different signal for error reporting is possible, but I think that's a little confusing. Thoughts? Attachments (2) Change History (19) comment:1 Changed 2 years ago by anonymous - Needs documentation unset - Needs tests unset - Patch needs improvement unset Changed 2 years ago by tal@… patch comment:2 Changed 2 years ago by tal@… - Has patch set comment:3 Changed 2 years ago by shai - Easy pickings set - Needs tests set - Patch needs improvement set send_robust() implies (correctly) that errors are expected. But the current patch proposes to just silence them, and that seems wrong to me. Also, if you see a real problem, can you provide a test that exemplifies it (and can be used to verify that the solution is correct)? comment:4 Changed 2 years ago by tal@… I was on the fence on send_robust(): I generally dislike mechanisms that just swallow exceptions, because it makes bugs slip through the cracks. On the other hand, some signal handlers (db rollback) are actually extremely likely to raise an exception if something bad happened to the underlying connection, which is what we were seeing. You can simulate something like this by closing the underlying connections. You can simulate it by doing something like: from django.db import connection connection.connection.close() At a view or a middleware. Some alternatives to send_robust: 1) implement something that will aggregate the exceptions and just raise a "SignalHandlersException" container at the end. No exceptions are lost, but I question the overall value of it in this scenario. 2) Print out exceptions to stderr, which is what django actually ends up doing when the error signal handler go rogue. I'm leaning towards option 2. comment:5 Changed 2 years ago by ianawilson I like option 2 as well, but to take it just one step further, what do you think of doing a logger.error() call with the stacktrace? Seems to me that this gives the most control and flexibility to developers. comment:6 Changed 2 years ago by tal@… shai: while I agree with you on silencing errors being wrong, it does seem like a problem with send_robust, as it's actually pretty sensible to rely on the existing "robust" dispatch. I can also have send_robust emit a call to logger.error (as proposed by Ian) as a part of this patch, although it might be a little out of scope :) What do you think? Right now we're working around this issue by doing some setattr magic: def make_unhandled_signal_safe(): from django.core import signals as core_signals setattr(core_signals.got_request_exception, 'send', core_signals.got_request_exception.send_robust) and we would very much like to get rid of it :) comment:7 Changed 2 years ago by schacki - Owner changed from nobody to schacki - Status changed from new to assigned comment:8 Changed 2 years ago by schacki Please find my patch attached. I have changed the core handler in a way such that: - the initial error is logged as expected, so the root cause of the trouble is visible and not covered by any other exceptions - all connected handlers are completely executed as expected, so no unexpected side-effects from one handler to the other - any exceptions from the handlers are logged to the error log, so no errors pass silently. I have also tried to add unit tests. Unfortunately, I have not managed, to really read the logging output. Any help is appreciated. Changed 2 years ago by schacki comment:9 Changed 2 years ago by schacki I have just sent this pull request: comment:10 Changed 2 years ago by ptone - Component changed from Core (Other) to HTTP handling - Easy pickings unset - Triage Stage changed from Unreviewed to Accepted - Version changed from 1.5 to master I agree there is some room to improve the robustness of the handler here in the case of "something bad happened". Signal receiver's shouldn't be doing anything fancy when getting the "got_request_exception" signal (basically heeding the warning in the docstring of "handle_uncaught_exception", but the handler itself should be robust against any poorly written signal handler. Another related place the handler could be more robust is in "handle_uncaught_exception" itself. While hopefully rare, someone could have attempted to install some fancy 500 handler which itself raises some unforseen exceptoin - so maybe a try except is needed there as well, with some logging, and then returning a minimal 500 ala: return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') Also it is not clear to me why the more robust sending of the signal step shouldn't just be rolled into handle_uncaught_exception. Those two steps occur together every single time in the handler, so I'm not sure why they need to be separate steps - sending the signal could easily be considered as "part of" handling the uncaught exception. comment:11 Changed 2 years ago by ptone - Cc preston@… added comment:12 Changed 2 years ago by schacki I have changed the code as follows: - Refactored the got_request_exception handling into handle_uncaught_exception. This makes to code much cleaner and the process more transparent - The inital exception, that triggered the handle_uncaught_exception is the main focus. I.e. this exception is logged first, this exception is raised if settings.DEBUG_PROPAGATE_EXCEPTIONS is True. This makes debugging and analyzing the root cause of all the trouble much easier (which was one of the reasons, why this ticket was raised), nevertheless all follow-up errors are still logged. - Implemented proposal from ptone, to make the resolve500 more robust. - Commented the code in handle_uncaugh_exception to make the process and ideas behind it more transparent. comment:13 Changed 2 years ago by schacki - Cc schacki added comment:14 Changed 2 years ago by schacki Hi all, may I ask on the status here. Anything I could/should? Thanks (was not aware that I was not logged in while writing my previous message) comment:15 Changed 2 years ago by ptone schacki - there aren't any steps to do you haven't already, thank you for the patch. I myself have not been able to make time to give it another review, I hope to be able to late this week, or early next. You can always try to recruit any member of the Django community to review the patch (not just core members), more eyes is always better. Thank you for your patience. comment:16 Changed 21 months ago by anubhav9042 The PR looks good to me. I am not marking it as RFC though, because it would be better if core-dev does that. comment:17 Changed 18 months ago by aaugustin The PR doesn't apply any more. Oh, just saw that the defer thing is implemented in send_robust(). Maybe just switch it from send() to send_robust() then?
https://code.djangoproject.com/ticket/20752?cversion=0&cnum_hist=12
CC-MAIN-2015-48
refinedweb
1,372
51.58
The JRuby community is pleased to announce the release of JRuby 1.2.0RC2 Download: JRuby 1.2.0RC2 has fixed many many compatibility issues and continued to improve general performance. Due to popular demand we have a new versioning system. 1.x.y was our old number system where x was the major release and y was the minor release. Our new system just chops off the vestigial '1.' from the front. 1.3, 1.4, ..., 1.x will just be minor releases of our current major release. ***Please try your apps against 1.2.0RC2 ASAP and report problems*** Highlights: - Improved Ruby 1.9 support (via --1.9) - Compiler now works - Almost all of the missing 1.9 methods have been added - New experimental --fast flag which does more aggressive optimizations - Large scale compiler and runtime cleanup and performance audit - Parsing is 3-6x faster now. - Preliminary android support (Ruboto) - Rails pathname issue fixed on Windows - Major bug triage since last release - 1052 revisions since 1.1.6 - 232 bugs fixed since 1.1.6 ***Bugs fixed since RC1*** key summary JRUBY-3455 1.2RC1 case - when clause evaluation does not short-circuit JRUBY-3456 rails command causes project to be created in the wrong directory JRUBY-3460 java.lang.ClassCastException: org.jruby.RubyObject building jruby-rack JRUBY-3461 Minor code conventions documentation typo JRUBY-3449 jruby-complete-1.2RC1.jar seems to break FFI JRUBY-3464 1.2.0 RC1 fails on Solaris x86_64 JRUBY-3376 Need FFI platform files generated for x86_64 linux JRUBY-3378 JRuby needs a new release of JFFI JRUBY-3466 NPE at org.jruby.runtime.callsite.RespondToCallSite.isCacheInvalid JRUBY-3467 bug with *one* extra space on shebang with jruby-1.2rc1 JRUBY-2795 Process.setpriority failure in rubyspecs on Mac OS X, Soylatte JRUBY-3370 Need Constantine release for JRuby 1.2 JRUBY-3402 extract command still tries to run but fails; remove entirely or fix JRUBY-3457 ast script is not making it into the dist packages JRUBY-3447 Rails console gets stuck on "quit" JRUBY-3451 Random method undefined error after change in r.8491 JRUBY-3448 UNIXSocket file descriptor leak JRUBY-3424 File.expand_path does not correctly follow directory changes from Dir.chdir JRUBY-3450 Problem with jitting ruby block in JRuby 1.2 RC1 JRUBY-3444 Multi-line string interpolation parses under MRI but gives a parse error on JRuby ***Bugs fixed since 1.1.6*** Key Summary JRUBY-414 Serialization of wrapped Java objects could be handled as user-marshalled data by Marshal JRUBY-551 JRUBY-549 bfts test_file_test failures JRUBY-750 defineAlias reports original name and not aliased one in stack traces JRUBY-852 jirb exits on ESC followed by any arrow key followed by return JRUBY-1079 IO.sysopen not defined JRUBY-1201 TCPSocket.new(dest_adrr, dest_port, src_addr, src_port) missing from JRuby JRUBY-1235 DRb hangs when transferring Ruby objects created in Java JRUBY-1401 Pathname#realpath fails for Windows drive letters JRUBY-1470 FileTest methods only work with string arguments JRUBY-1555 DST bug in second form of Time.local JRUBY-1576 multi-byte character encoding probrem JRUBY-1606 File.expand_path does not work as expected JRUBY-1639 Exception when stopping WEBrick running the new rails application JRUBY-1803 Support Ruby 1.9 M17N strings JRUBY-1853 define_method methods do not display the correct stack trace, may not be using frame safely JRUBY-1854 def is almost 3x slower in JRuby JRUBY-1855 EOF handling in case of reading program from standard input JRUBY-1872 next statement should return the argument passed, not nil JRUBY-1884 handling of file close while reading differs from mri JRUBY-1950 -i flag not supported JRUBY-2003 rexml pretty printing wrap() error JRUBY-2040 new samples/jnlp dir: includes both unsigned and signed examples that work in Java 1.5 and 1.6 JRUBY-2108 IOWaitLibrary ready? returns nil when ready JRUBY-2120 Wrong stacktraces from exceptions about wrong number of arguments JRUBY-2131 Select with nil arrays should throw an exception JRUBY-2139 jruby.compile.frameless=true cause "Superclass method 'initialize' disabled." JRUBY-2168 test_io (test_copy_dev_null) fails under WinXP JRUBY-2170 Very unverbose message when problem with native library exists JRUBY-2174 Method#to_proc.call invocations much slower than normal Method#call invocations JRUBY-2180 break performance is slower than MRI, sometimes slower than interpreted JRUBY-2211 SNMP Requests does not timeout properly JRUBY-2252 Kernel#exec should not raise SystemExit JRUBY-2262 Java toString() mapping to invoke(... to_s ...).toString() doesn JRUBY-2264 Include Nailgun in release binary packages JRUBY-2285 Regression: rubyspec run with -V option breaks JRuby JRUBY-2288 UDP locking problems when receiving from multiple senders on same port JRUBY-2296 convertToRuby does not work if to_s does not return a String (but for example nil) JRUBY-2305 File output cuts off at a certain point? JRUBY-2307 DRb from MRI server to JRuby client fails with long messages JRUBY-2326 Invalid cast during parsing of recursive.rb in facelets-2.3.0 (org.jruby.ast.YieldNode cannot be cast to org.jruby.ast.BlockAcceptingNode) JRUBY-2328 Overriding require causes eval to give wrong _FILE_ in certain circumstances JRUBY-2333 usage of unexistant variable in REXML::SourceFactory JRUBY-2346 Nailgun does not compile under HP-UX JRUBY-2353 Process.kill breaks up JRuby, while works in MRI on Windows JRUBY-2369 'ant spec' failures on on MacOS JRUBY-2389 java.util.ConcurrentModificationException JRUBY-2410 Multiple assignment could be made faster by not returning unused array JRUBY-2424 running with -rprofile with multithreaded test causes NPE JRUBY-2426 JRuby trunk does not build with IBM JVM 1.5 JRUBY-2435 Aliasing eval and other "special" methods should display a warning JRUBY-2455 "jruby" script failed to find JRUBY_HOME leads to class not found JRUBY-2484 unicode symbol not supported as in MRI JRUBY-2504 JAR URLs are inconsistently supported by APIs that access the filesystem JRUBY-2506 Marshal/IO.eof bug JRUBY-2518 Dir["some glob"] doesn't work for files inside a jar JRUBY-2521 Compilation Warning for Sun proprietary API using JRUBY-2522 Can not execute JRuby 1.1.1 "ant test" with IBM JDK JRUBY-2542 DATA.flock causes ClassCastException JRUBY-2545 Recursively locking on a mutex results in deadlock JRUBY-2548 JRuby conversion of String to Java String is arcane JRUBY-2557 NPE when yielding method JRUBY-2603 Couple of new rubyspec failures for URI library JRUBY-2655 TCPSocket.new('localhost', 2001) connects on the wrong interface JRUBY-2661 specs hang under Apple Java 5 JRUBY-2672 BasicSocket#close_read and #close_write not working JRUBY-2675 jirb + jline do not work in cygwin JRUBY-2699 If user's PATH contains '.' and 'jruby' resolves to './jruby', JRUBY_HOME is incorrectly set to '.', leading to 'NoClassDefFoundError' JRUBY-2727 ActiveScaffold 1.1.1 fails with JRuby 1.1.2, probable path problem JRUBY-2732 org.jruby.util.RubyInputStream is unused JRUBY-2757 Compiled argument processing and arity checking are too large, too much bytecode JRUBY-2759 Time Zone "MET" maps to Asia/Tehran JRUBY-2761 Thread#wakeup fails when sleep is called with a parameter JRUBY-2772 Zlib::Deflate doesn't appear to deflate JRUBY-2782 "No such file or directory (IOError)" when JAR file named in java.class.path but not active filesystem JRUBY-2788 Make Time.now monotonically increasing JRUBY-2794 Failure in String#crypt specs, Mac OS X, Soylatte JRUBY-2796 Missing constant in Process::Constants on Mac OS X (darwin) JRUBY-2797 File.expand_path rubyspec failure on Mac OS X, Soylatte JRUBY-2802 JRuby wrapped Java objects formerly exposed readers for non-public fields JRUBY-2804 IO.popen of 'yes' process hangs on close JRUBY-2815 System triggered from inside of tracing behaves oddly JRUBY-2817 File.chown works with 64bit JDK, but raises NotImplementedError on 32 bit JDK JRUBY-2820 Most Etc methods behave diferently on Windows under x32 and x64 JVMs JRUBY-2826 Array#pack('w') is broken (exceptions and wrong results) JRUBY-2830 String#unpack with 'w' is completely unimplemented JRUBY-2845 -S switch breaks if you have directory in pwd matching name of file in bin/PATH JRUBY-2846 gem generate_index broken JRUBY-2849 CCE using proc{} in AR callbacks JRUBY-2855 Classpath search order is not respected by require when classpath includes both jars and directories JRUBY-2858 test_file.rb::test_opening_readonly_file_for_write_raises_eacces() fails with "IOError: Permission denied" on FreeBSD 7.0 amd64 + java 1.6.0_07 JRUBY-2861 Cannot call super inside a method that overrides a protected method on Java base class JRUBY-2868 ThreadService.getRubyThreadFromThread supports only one non-rubynative thread at a time. JRUBY-2896 jruby -S picks up script from local directory JRUBY-2898 Exception trying to use BSF (java.lang.NoClassDefFoundError: org/apache/bsf/util/BSFEngineImp) JRUBY-2901 JRuby does not support options in shebang line JRUBY-2917 Missing peephole optimizations in parser, compiler JRUBY-2921 Newly overridden methods are not called if the old superclass method has already been called JRUBY-2933 Ruby runtimes are pinned to memory due to ChannelStream JRUBY-2941 popen IO lockup with multiple threads JRUBY-2950 Net::IMAP#authenticate stalls / blocks in recent versions of JRuby JRUBY-2951 repeated popen call may throw NULL pointer exception JRUBY-2970 Timeout.rb is not working in special cases (Thread may block whole application). JRUBY-2974 multi-byte exception message turned into garbled characters when Java Exception nested NativeException. JRUBY-2979 File#getc fails on illegal seek when reading from /dev/ttyS0 on Linux JRUBY-2981 alias_method_chain pattern is extremely show on jruby JRUBY-2982 Unicode regular expressions by UTF-8 don't work JRUBY-2988 jirb does not echo characters to the terminal after suspend and resume in the shell JRUBY-2997 Dir[] results in NPE depending on permissions JRUBY-2999 Regression: Inheriting method with same name from two Java interfaces causes Java classloader error JRUBY-3000 integration issues with Java classes containing inner classes JRUBY-3003 ArrayStoreException in compiler when calling Array.fill JRUBY-3005 Stomp gem hangs in Stomp::Client#subscribe JRUBY-3007 Message method value of Exception is missing in Java when exception raised in ruby JRUBY-3011 java classes with non-public constructors are incorrectly instantiated JRUBY-3017 DRb "premature header" error on JRuby client JRUBY-3035 Get Rails tests running in a CI server somewhere before 1.1.6 release, to ensure no future breakages JRUBY-3038 Unable to insert YAML into t.text field (behavior different from Ruby 1.8.6) JRUBY-3054 Thread#status is "run" when thread is blocking on condition variable JRUBY-3055 permission javax.management.MBeanServerPermission "createMBeanServer"; JRUBY-3061 NKF(unsupported Q encode stream) JRUBY-3065 New public LoadService#findFileToLoad method JRUBY-3071 Illegal seek error trying to read() from pipe JRUBY-3073 JRuby script engine does not load on IBM JDK JRUBY-3076 RubyUDPSocket.send tries to do inet address lookup, pauses too long for inet6 failure JRUBY-3077 Update ruby_test tests and incorporate changes into build JRUBY-3085 Add constant caching for Colon2 and Colon3 (specific module and Object cases) JRUBY-3088 "RStone" port of PyStone is slower on JRuby than 1.9 JRUBY-3089 Digest::Base stores in memory all bytes passed to the digest, causing OutOfMemoryError JRUBY-3103 Compiler closures use two different binding mechanisms, need better construction and caching logic JRUBY-3109 Update stdlib to an appropriate 1.8.6 patchlevel JRUBY-3116 ArrayIndexOutOfBoundsException in tmail JRUBY-3120 Regression: error serializing array of objects with custom to_yaml def to yaml JRUBY-3125 Some Socket constants not supported. JRUBY-3127 Inconsistent DynamicScope instances in evalScriptlet JRUBY-3128 Different jruby behaviour that ruby 1.8.6/1.8.7/1.9 when running file that is named as one of required file. JRUBY-3142 Dir.pwd correctly displays dirs with unicode characters in them JRUBY-3146 Time#_dump RubySpec failures JRUBY-3147 Time#_load RubySpec failures JRUBY-3148 Array#fill spec failures JRUBY-3152 Process.times returns invalid values JRUBY-3158 Wrong ruby methods called on object of same class from Java code. JRUBY-3160 REXML returns error for add_attribute JRUBY-3174 FFI MemoryPointer#get_string(0, x) gets confused by null byte in the buffer JRUBY-3175 Cloning java byte array returns incorrect object JRUBY-3177 ConcurrentModificationException JRUBY-3178 http spec tests fail when webrick starts on address 0.0.0.0 JRUBY-3179 JRuby can't handle do/end blocks within String-inlined expressions JRUBY-3180 Class in default package can't be reopened under Java namespace JRUBY-3187 JRuby command line scripts do not work with spaces in the path JRUBY-3190 method `module_eval' for main:Object should be undefined? JRUBY-3204 IO.read and IO.readlines do not take a block JRUBY-3207 super error message is inaccurate when superclass doesn't implement method. JRUBY-3208 ant task api-docs runs out of memory, patch included JRUBY-3211 builder library is slower in JRuby than in MRI JRUBY-3214 load and require don't work correctly for .class files JRUBY-3217 Memory Leak with Adopted Threads JRUBY-3218 Import is sometimes confused by unquoted class name JRUBY-3221 Rubinius -bad instanceof tests in RubiniusMachine for attempt at fast path evaluation JRUBY-3224 Array#to_java with java object reference doesn't carry over object identity JRUBY-3226 Including more than one java interface stops Test::Unit execution JRUBY-3232 Zlib::GzipReader.each_line yields compressed data JRUBY-3233 JRuby with Rails 2.2.2 unable to instantiate a java class JRUBY-3234 Difference in require behaviour with MRI with ".rb" suffix JRUBY-3238 Jruby 1.1.7 still leaking weakreferences JRUBY-3242 Performance degradation on write operations JRUBY-3244 [PATCH] Support atime updates via utime JRUBY-3248 jruby can't load file produced with jrubyc JRUBY-3250 test_java_pkcs7.rb - Problem coercing Bignum into class java.math.BigInteger JRUBY-3251 ConcurrencyError bug when installing Merb on JRuby JRUBY-3253 Lack of default jruby.home in embedded usage causes NPE JRUBY-3254 Make JRuby's Time#local behave more like MRI JRUBY-3255 jruby -S script/server fails in Rails application JRUBY-3257 RaiseException#printStrackTrace doesn't deal well with nil messages JRUBY-3262 JRuby 1.1.6 regression: ClassFormatError if Ruby superclass of Ruby class implements super-interface of Java interface JRUBY-3267 patch attached to update eclipse .classpath to refer to bytelist-1.0.1.jar JRUBY-3269 SystemStackError with YAML.dump JRUBY-3270 using activerecord 'to_xml' method crashes JRuby (and debugger) JRUBY-3274 Many new Array#pack failures in updated RubySpecs JRUBY-3275 New ARGF spec failures JRUBY-3276 New IO#readpartial and IO#seek spec failures JRUBY-3277 Constant lookup should omit topmost lexical scope; not bail out on first Object-hosting lexical scope JRUBY-3280 patch attached to update eclipse .classpath to add new jars in build_lib/ JRUBY-3287 Add public RubyInstanceConfig#setCompatVersion JRUBY-3289 ArgumentError: dump format error() when unmarshalling Rails session and EOFError when unmarshalling hash with containing value of type ActionController::Flash::FlashHash JRUBY-3290 Float range to restrictive in FFI code JRUBY-3296 Etc.getpwuid should raise TypeError if invalid type JRUBY-3298 Kernel.srand calls #to_i on number JRUBY-3303 [1.9] splat of array at front of assignment broken (same for other grammatical constructs) JRUBY-3305 Fixnums & Floats should be coerced to the narrowest java.lang.Number when passed to a java method that expects Object JRUBY-3307 tempfile.rb sucks in JRuby JRUBY-3308 Deadlock between RubyModule.includeModule() and RubyClass.invalidateCacheDescendants() JRUBY-3310 Race condition in JRuby when Active Support is overriding Kernel.require JRUBY-3314 Pull in final 1.9.1 stdlib when released JRUBY-3316 Group expression class path fails to parse JRUBY-3317 require "tempfile"; Dir.tmpdir fails JRUBY-3318 If 'jruby' executable is a relative symlink, JRuby won't start JRUBY-3324 Error in string encoding conversion JRUBY-3328 Incorrect behavior for case/when when true or false are the first conditions JRUBY-3329 Major divergence in threading behaviour between Ruby 1.8.6 and JRuby 1.1.6 JRUBY-3331 to_f near Float::MAX JRUBY-3332 ConcurrentModificationException In Application Startup JRUBY-3339 java.lang.ArrayIndexOutOfBoundsException in RubyArray.java JRUBY-3340 String#unpack('m') fails with ArrayIndexOutOfBoundsException JRUBY-3351 Tempfile defaults to a directory that does not exist on Windows JRUBY-3360 Pure-Java tempfile does not use a #make_tmpname callback JRUBY-3361 Compiled case/when blows up with arrays as when clauses JRUBY-3362 attr_accessor, attr_reader, attr_writer, and attr not obeying visibility JRUBY-3363 OutOfMemoryError when using soap4r on jruby 1.1.6 JRUBY-3365 Objects with custom to_yaml methods break collection to_yaml JRUBY-3366 Faulty marshalling error blows up in ActiveSupport JRUBY-3367 Dir.glob processes nested braces incorrectly JRUBY-3372 [PATCH] FFI: passing nil for a declared string parameter blows up JRUBY-3373 [PATCH] FFI: assigning Struct to a pointer fails JRUBY-3374 [PATCH] FFI::ManagedStruct instantiated objects are of the wrong class JRUBY-3375 'attr' implementation is incompatible with MRI 1.9.1 behavior JRUBY-3377 Need FFI platform files generated for x86_64 darwin JRUBY-3386 Array#eql? rubyspec failure JRUBY-3387 Array#== rubyspec failure JRUBY-3390 RubySpec: Numeric#coerce calls #to_f to convert other if self responds to #to_f JRUBY-3392 RubySpec: Thread.stop resets Thread.critical to false JRUBY-3397 defined? CONST is not following proper constant lookup rules JRUBY-3398 Attributes defined from Java tried to use current frame for visibility JRUBY-3405 popen breaks input channel for IRB JRUBY-3407 FFI Stack Level Too Deep on Library.send(:method, args) JRUBY-3408 FFI non-string args for methods are turned into strings anyway JRUBY-3410 Add -y flag to debug the parser JRUBY-3411 JRuby does not build or run on AIX due to exceptions in org.jruby.ext.ffi.Platform JRUBY-3420 [PATCH] Added basic_word_break_characters method to Readline JRUBY-3432 String#hash needs to be made encoding-aware JRUBY-3436 [PATCH] FFI should allow passing nil as a callback parameter JRUBY-3437 pid-returning methods should make a best effort to get a real pid JRUBY-3439 super in top level go boom
http://docs.codehaus.org/pages/diffpages.action?pageId=117900397&originalId=228174295
CC-MAIN-2015-11
refinedweb
3,011
51.28
Recently Ahmad, our test intern, created a WPF weather user control and it came out really nice. Take a look. The code is available on code plex .. The code also includes a sample which is demo desktop weather gadget using the usercontrol. The user control provides 2 dependency properties, IsMaximized and ShowMinimizeButton.... The first property decides whether to show the control in a minimal form just as the Vista weather gadget behaves in the sidebar. The second property decides whether to show the minimize button. In xaml, you need to reference the dll as follows xmlns:y="clr-namespace:WeatherReaderMVC;assembly=WeatherReaderMVC" ... <y:WeatherReaderUI The setting dialog is a popup so it comes up on top of your app. The control was created with reusability and extensibility in mind. Currently it connects to the MSN xml feed. Changing the feed requires a slight tweaking in code since the xml tags differ from site to site. Please do take a look at the code .... :) PingBack from MSBuild MSBuild Task for SharePoint - MakeCab [Via: Steve ] ASP.NET Ajax with the ASP.NET MVC Framework... Link Listing - November 26, 2007 Woaw ... very nice. I wish it didn't take 15 seconds to load on a P4-3.4Ghz with 2Gb RAM and those 42Mb of RAM for execution ... Trademarks | Privacy Statement
http://blogs.msdn.com/llobo/archive/2007/11/26/wpf-weather-reader-user-control.aspx
crawl-002
refinedweb
218
61.02
Content count469 Donations0.00 CAD Joined Last visited Days Won2 Community Reputation19 Good About Mzigaib - RankIllusionist - Birthday 04/09/1975 Contact Methods - Website URL Personal Information - NameMichel - LocationBrazil - Mzigaib started following Blurring/Filtering Procedural Textures, SideFX is Cracking!, COPS - Merging nodes not combined ? and and 3 others - COPS - Merging nodes not combined ? Mzigaib replied to CinnamonMetal's topic in CompositingI suggest to use the layer COP in this case. Hair inherit groups from skin Mzigaib posted a topic in General Houdini QuestionsI am using the Houdini hair tools to groom a character and I hit a wall where I need have my skin groups transferred to my guides where Houdini doesn't do that by default, let me know if I am wrong, if I use a group transfer SOP it takes a lot of time with a large amount of guides, shouldn't the guides inherit the skin groups by default? Is there a efficient way to do it? I hope I am making sense. Thanks in advance. Use button to set a variable value in a menu script with python Mzigaib replied to Mzigaib's topic in ScriptingThank you so much for your time to explain me that I am totally gona try that, I didn't know that phm() module. I'll let you know what I got. Thanks again! Use button to set a variable value in a menu script with python Mzigaib replied to Mzigaib's topic in ScriptingI think the right question should be how do I access the menu module script from a command button, everywhere I look just explain how to do that If I want to access the module in a digital asset which I think it is not the case. Use button to set a variable value in a menu script with python Mzigaib replied to Mzigaib's topic in ScriptingNo one? Use button to set a variable value in a menu script with python Mzigaib replied to Mzigaib's topic in ScriptingI have my function on my ordered menu list: import os def listDirs(check): result = [] houDir = os.listdir(hou.getenv('JOB')+'/houdini') if check==1: for dir in houDir: result+=[dir,dir] return result else: result=["Nothing","Nothing"] return result return listDirs(check) I want my button on the same node to pass a value '1' to my 'check' variable in that function, how do I do that? I did try on a callback button: hou.pwd().parm('dirList').listDirs(1) But it didn't work, what am I missing? Thanks. Use button to set a variable value in a menu script with python Mzigaib posted a topic in ScriptingI. - Yes I don't use phyton, but thanks anyway. - I found a way: # Check if directory exists set check='' foreach dir(`system(" if [ -d 'your_directory_path_or_not' ];then echo 'yes';else echo 'not';fi")`) if (`strmatch($dir,"not")`==1) set check = 'Not Found' else set check = 'Found' endif end message $check But if anyone have a better and more elegant way let me know. Thanks. Check if directory exists with hscript Mzigaib posted a topic in ScriptingIs there a way to check if a directory exists with hscript? I try this: set txt='' foreach dir(`run('uls -p /mnt/non_existente/directory')`) if ($dir != "") set txt = 'nothing' else set txt = 'all' end message $txt But if the directory doesn't exist it return me nothing, any tips? Thanks. - Thank you so much for giving your time to explain this to me it really help me understand this, I already knew that do something like this in PBR would involve some more complex calculation with Rays I just did know how to do it, in the old micropolygon days I knew that with some loops you could do it with less complex calculation I guess. My intent was to learn how to average the values like in sops and also to learn how to do it and also I like the idea to do all that I can in shaders but thanks to your explanation now I know the caveats so I can decide better if I should in in textures or not. Thanks again for the explanation. - I just bump up in this older thread which describes exactly what I am trying to achieve with no success off course, I am trying to 'blur' a procedural 'soft dots' pattern more than it's own softness using what i saw on the Masterclass about loops but I it's not working for me, can someone point me on the right direction? Thanks. loop_blur_vop_values.hip - Just confirming that parting lines don't work for me, any more tips? - If I do that it uses the parting line guides to create a clump on the floor.
https://forums.odforce.net/profile/5743-mzigaib/
CC-MAIN-2019-43
refinedweb
792
62.31
lcs/lcs.hfile and the namespace lcs Tester ChangeMonitorand exporting value changes to a VCD file Clock FrequencyDivider InOutBus Next: Copying This Userguide, Up: (dir) libLCS is a library for Logic Circuit Simulation developed in 100% C++. One can use this library for design and testing of digital circuit systems. For more information, either continue reading this userguide further, or visit the libLCS website at. This userguide serves as a tutorial introduction and a reference guide to libLCS. New users of libLCS can use it to get started with libLCS. Advanced users of libLCS can use it as a quick reference for the various features of libLCS. However, the development of this userguide is an ongoing process. Hence, kindly bear bear with the incompleteness in few parts, if any. If you find any mistake/error, kindly inform the author by email at sivachandra[AT]gmail[DOT]com. This userguide has been prepared with utmost care in the hope that users of libLCS can use this as a tutorial and as a reference guide. However, the author does not guarantee it to be suitable for any particular purpose and is not responsible for any unlikely loss or injury it may cause to the reader. If you are a new user of libLCS, inorder to understand the basics right, you should read the chapters Preliminaries and Introduction to libLCS in the sequence they have been presented in this userguide. If you have been using libLCS for some time and would like to refer to the usage of a particular feature, then first locate a chapter/section/subsection title in the table of contents pertaining to that feature. The corresponding chapter/section/subsection will explain the purpose and usage of that feature. This userguide was prepared using the GNU Texinfo software.
http://liblcs.sourceforge.net/userguide/index.html
CC-MAIN-2017-22
refinedweb
298
52.09
Consider a problem, where you need to represent hierarchy. For example, organization structure. You want to represent the structure of an organization, where there are different levels such as CEO, CTO, Co-Workers, etc., where, Co-Workers report to the CTO, CTO reports to CEO. Another example is the folder system in operating systems. Where a root folder has sub-folders, and those sub-folders have other sub-folders, and so on. There are other Data Structures, such as Arrays, LinkedList, Stack, Queue, etc., but none of these can represent a hierarchical data. All these structures are linear, and traverse the data linearly. 10 / \ 20 30 / \ \ 35 40 15 A typical tree looks something like the above representation. This type of tree is known as Binary Tree. We will discuss about binary trees later in this article. Let us learn some basic terminologies of a tree data structure. Node: A node is an object of a tree, which stores the value, as well as reference to other nodes. In the above example, a node which has a value ‘20’, and has reference to the other nodes which have value 35 and 40. Root: The node which is at the top of the hierarchy is called root node. In the above example, node with value 10 is a root. Leaf: The node which is at the bottom of the hierarchy is called leaf node. In the above example, node with value 35, 40 and 15 are leaf nodes. Child: The nodes which are just one level below any particular node are called the children nodes in respect of the upper-level node. In the above example, node with value 20 has two children 35 and 40, node with value 30 has one child 15. Parent: The node with is one level up of any particular node is called the parent node in respect to the child node. In the above example, the nodes with value 20 and 30 have a parent node with value 10, the node with value 15 has a parent node with value 30. Subtree: A tree contains many trees inside it and these trees are called subtrees of that tree. In the above example, the tree with root node of value 10 has two children’s nodes with value 20 and 30. These nodes behave as a root node for the nodes just below it. In this case, tree with root node with value 20 is a tree for nodes 35 and 40, but is a subtree for root node with value 10. A tree has subtrees equal to the number of nodes in that tree, because, each node can behave like a subtree in other perspective. Descendants: These are the nodes which lie in the subtree of a node. In the above example, the descendants of the node with value 20 are 35 and 40. Ancestors: The hierarchical nodes which are above a specific node and lie in the same tree branch. In the above example, the node with value 35 has an ancestor 20 as well as 10. This is because, 35 is a descendant of the with root node with value 20 as well as 10. Degree: The number of children of a node is the degree of that particular node. In the above example, the node with value 10 has a degree of 2, while the node with value 30 has a degree of 1. We can define the “Leaf” as the nodes which have a degree of 0. Binary Tree: A binary tree is a tree with each node having a maximum degree of 2. In Java, Binary tree syntax looks like, public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } In C++,) {} }; We create a self referential variable ‘left’ and ‘right’ to assign the reference (in Java) or pointer (in C++) to store the address of the left and right children nodes respectively. There’s an other variable ‘var’ which is used to assign the value to the node. We will explore Binary Trees, their traversal methods and some problems related to them in the upcoming articles.
https://hacktechhub.com/introduction-to-tree-data-structure/
CC-MAIN-2022-40
refinedweb
709
72.36
Opened 7 years ago Closed 7 years ago Last modified 7 years ago #2251 closed bug (fixed) Missing conversion rules for realToFrac causing slowdowns in Int->Double conversions Description GHC.Real and GHC.Float currently have: -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b fromIntegral = fromInteger . toInteger {-# RULES "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int #-} -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b realToFrac = fromRational . toRational {-# RULES "realToFrac/Int->Int" realToFrac = id :: Int -> Int #-} But these avoid some primops that can make these conversions more efficient. {-# RULES "realToFrac/Int->Double" realToFrac = i2d :: Int -> Double #-} int2Double :: Int -> Double int2Double (I# x) = D# (int2Double# x) A rule to use the in2Double# primop over realToFrac directly, improves the running time of this program: import Data.Array.Parallel.Unlifted main = do let c = replicateU n (2::Double) a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double print (sumU (zipWithU (*) c a)) From 113 seconds, to 0.194s! A massive speedup. We should fill out the rules here with at least those for which GHC has primitives: {-# RULES "realToFrac/Int->Double" realToFrac = int2Double :: Int -> Double "realToFrac/Int->Float" realToFrac = int2Float :: Int -> Float #-} to the realToFrac and fromIntegral rules in GHC.Float Change History (5) comment:1 Changed 7 years ago by simonpj - difficulty set to Unknown comment:2 Changed 7 years ago by dons - Resolution set to fixed - Status changed from new to closed I've pushed a patch adding the rules for Int->Double and Int->Float. See: comment:3 Changed 7 years ago by simonpj Thanks! I've found that comments in source files are more often read than those in patch messages, so I've transferred some of your comments into the source file itself. Simon comment:4 Changed 7 years ago by simonmar - Architecture changed from Unknown to Unknown/Multiple comment:5 Changed 7 years ago by simonmar - Operating System changed from Unknown to Unknown/Multiple Thanks Don. Would you care to offer a patch? (Don't forget to include comments that explain how big the performance improvement is; I find that giving a little program in that comment (as you do above) is a great way to capture the idea.) I gather that when you say "...at least those for which GHC has primitives" you mean that there are some important ones missing. If so, propose away. Simon
https://ghc.haskell.org/trac/ghc/ticket/2251
CC-MAIN-2015-32
refinedweb
396
59.43
My book is a First Edition printed in October 2002. This is nitpicky but... The second sentence mentions the FILTER tag twice, when it seems that it should probably only be mentioned once. AUTHOR: This is correct. FILTER should just be included in the list of "advanced tags". However, this is not a serious technical mistake, it's a minor language mistake. The code: You have <% $cd_count %> cd<% $cd_count != 1 ? 's': '' %> is missing the period (.) after the final closing %> tag. The first line of the <%perl> block should read: my @words = $sentence =~ /(S+)/g; The code in the book is missing the '$' sigil on the variable. The second to last line of the example in paragraph 4: esethat ordsway areyay inyay Igpay Atinlay.</pig> should instead be: esethay ordsway areyay inyay Igpay Atinlay.</pig> to be an accurate translation. The word "these" is "esethay" in Pig Latin. AUTHOR: Indeed, my pig latin was mistaken ;) "most of them contain plan Perl" should read "most of them contain plain Perl". It is currently <% $temperature %> degrees. should be: It is currently <% $temp %> degrees. The name "view_user.mas" somehow got turned in one instance into "view_user.max", I think somewhere in the editing process. It should be "view_user.mas" throughout this section. "You should also remember that variables defined via an <%args> block are not visible in a <%shared> block, meaning that the only access to arguments inside a shared block is via the %ARGS hash or one of the request object methods such as request_args." It's not true that you can access args via %ARGS in a shared block. You can only access args via $m->request_args. <& $m->call_next &> should be: % $m->call_next; As written the example would attempt to call a component as specified by the return value of $m->call_next, which probably isn't intended. This paragraph should be intended to match those above it, as it applies to the previous list item. Sometimes we may want to path in a query should read: Sometimes we may want to pass in a query The site admin <input> tag is missing its closing '>'. The closing </form> tag incorrectly appears as <form> There are two errors in this code block: In the Cache::FileCache->new line, there is a missing { before namespace. Add 'use Cache::FileCache' to the <%once> section. The code example show should be: <%filter> s/href="([^"])+"/'href="' . add_session_id($1) . '"'/eg; s/action="([^"])+"/'action="' . add_session_id($1) . '"'/eg; </%filter> These substitution filters also recognize URLs in single quotes. I think they're better than the fix proposed in the official errata. s/(href=)(['"])([^2]+?)2/$1.$2.add_session_id($3).$2/eg; #' s/(action=)(['"])([^2]+?)2/$1.$2.add_session_id($3).$2/eg; # "This example lets you give each developer their own hostename:" ^ should be: "This example lets you give each developer their own hostname:" The reference to HTML::Mason::Request::WithApacheSession is outdated, as the module's name has changed to MasonX::Request::WithApacheSession While you _could_ pass a request_class parameter to the Interp constructor, you probably _should_ be passing it to the ApacheHandler constructor. Because of Mason's "contained object" system, there's no need to create an Interp directly. The ApacheHandler constructor will create one for you and pass it any relevant parameters. Creating an Interp object manually will cause problems if you don't also give it the correct resolver_class parameter. ApacheHandler takes care of this for you. There are two parameters listed with dashes in their name, "Mason-CodeCacheSize" and "Mason-IgnoreWarningsExpr". These are both incorrect, neither should have a dash. It should be mentioned here that current versions of Bricolage (as of 1.4.3) do not yet work with Mason 1.1x, because of API changes in Mason between 1.05 and 1.10. The book covers the Mason 1.1x API, so this might be a little confusing. Hopefully a near-future verson of Bricolage will also support Mason 1.1x. © 2016, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://www.oreilly.com/catalog/errata.csp?isbn=9780596002251
CC-MAIN-2016-07
refinedweb
683
67.35
MATLAB Newsgroup Is there a way to include a carriage return (i'm assuming its a carriage return) at the end of a file using fprintf. The end of the file needs to have the following... 4.60 80.00 3.0 4.60 100.00 2.0 5.10 90.00 1.0 4.10 100.00 30.0 5.10 90.00 1.0 4.60 90.00 1.0 In my text editor it looks like a right-hand arrow, in wordpad it's depicted by a square. Any help would be great. Thanks Jon On 6/1/2011 1:00 PM, Jonathan wrote: > Is there a way to include a carriage return... It's called "newline" and what character(s) it is is platform dependent. doc fopen % Note the discussion on the 't' option for text files doc fprintf -- Are you sure it's not an EOF character instead of a line feed or carriage return?. Thanks Jon On 6/1/2011 3:14 PM, Jonathan wrote: >. ... Oh, I got (apparently) sidetracked by assuming the title had something to do w/ the subject...silly me! :) First things first -- a) why does the existence of a special character at the file matter? In general this "feature" has gone the was of the dodo. b) if, for some reason, it is important, first thing to do is to find out what the actual character(s) is(are). Easiest thing to do there is to open a file w/ a binary editor and look. c) once a) and b) are both known to be true and the output required known, if it's something other than one of the special characters fprintf knows about, I _think_(+) you'll have to write it w/ fwrite() after the last fprintf() of regular text files. (+) Caveat -- I don't recall if there's a C escape sequence in formatted write to write an arbitrary byte in formatted write or not, or if there is, if Matlab has it incorporated. My quick perusal doesn't indicate to me there is but I may be overlooking it. -- I agree with dpb - it shouldn't be necessary. But if it is, control-Z was often used as an EOF character so you might try something like fprintf(fid, '%c', 26); On 6/1/2011 3:56 PM, ImageAnalyst wrote: > fprintf(fid, '%c', 26) Good call for the "workaround", IA. W/ the display page here that does display a boxy-looking character so that is likely what OP has. Shouldn't be needed for anything other than an old 16-bit DOS app,.
http://www.mathworks.com/matlabcentral/newsreader/view_thread/308607
CC-MAIN-2015-18
refinedweb
437
77.06
How could I upload images with this website ?! @trevaun23 @saimon I have a problem. The command "ionic cordova build android didn’t worked correctly. What can i do… @trevaun23 @saimon @ihadeed I’m building a website with ionic . I push data with navCtrl to another page and every thing is working as expected . I get the params form constructor . the problem is when I refresh this page with browser not from ionic app , I get error ‘undefined id for my collection in database’ that’s a result of no params any more . how could I solve this problem ? thanks in advance Hey! Apologies for my late reply but I hope this code answers your question: Since I cant use the Ionic Plugins for uploading images, I use this: In CMD: npm install ng2-file-input in page.module.ts import { Ng2FileInputModule } from 'ng2-file-input'; in page.html <ion-item > <ng2-file-input [browse-text]="'Drop your files here'" [drop-text]="'📁 <br><br>'" [remove-text]="'Off you go'" [id]="'multiFilesInputWithPreview'" (onCouldNotRemove)="onCouldNotRemove($event)" [multiple]="true" (onRemoved)="onRemoved($event)" (onAdded)="onAdded($event)" (onAction)="onAction($event)"></ng2-file-input> </ion-item> in page.ts (Imports) import { Ng2FileInputService, Ng2FileInputAction } from 'ng2-file-input'; in page.ts (Variable Declaration) myFileInputIdentifier:string = "multiFilesInputWithPreview"; public actionLog:string=""; in page.ts (Constructor) constructor( public ng2FileInputService: Ng2FileInputService, in page.ts (Main) public onAction(event: any){ //console.log(event); this.actionLog += "\n currentFiles: " + this.getFileNames(event.currentFiles); // console.log(this.actionLog); } public onAdded(event: any){ this.actionLog += "\n FileInput: "+event; this.actionLog += "\n Action: File added"; // let filename = this.eventData.getfilename(fileentry); // let fileext = this.eventData.getfileext(fileentry); } public onRemoved(event: any){ this.actionLog += "\n FileInput: "+event.id; this.actionLog += "\n Action: File removed"; } public onInvalidDenied(event: any){ this.actionLog += "\n FileInput: "+event.id; this.actionLog += "\n Action: File denied"; } public onCouldNotRemove(event: any){ this.actionLog += "\n FileInput: "+event.id; this.actionLog += "\n Action: Could not remove file"; } resetFileInput() { this.ng2FileInputService.reset(this.myFileInputIdentifier); } logCurrentFiles(){ let files=this.ng2FileInputService.getCurrentFiles(this.myFileInputIdentifier); this.actionLog += "\n The currently added files are: " + this.getFileNames(files); console.log(this.actionLog); } getFileNames(files:File[]){ let names=files.forEach((file) => { var reader = new FileReader(); let filedata = reader.readAsDataURL(file) console.log(filedata); console.log(file.name); var reader = new FileReader(); reader.onload = (function(theFile){ var fileName = file.name; return function(e){ console.log(fileName); console.log(e.target.result); }; })(file); reader.readAsArrayBuffer(file); }); //return names ? names.join(", "): "No files currently added."; } To get the Files: this.ng2FileInputService.getCurrentFiles(this.myFileInputIdentifier) You can see this in action here: I used to have this problem because of the lifecycle hooks. Instead of using ngOnInit() or the constructor to process the params, I use: ngAfterViewInit(){ //code with id } Instead of using ionViewWillEnter(), I use: ionViewDidEnter(){ //code with id } @trevaun23 thanks for your answer . I have watched vedio on youtube use input type file for implementing the uploading . what do you think of this way ? I tried that too. Longer process. (I’m a lazy programmer, I go for the easiest and asthetically pleasing solution) In ng2-file-input docs they say that i should install bootstrap . so how did you install it ? I didn’t put in bootstrap until a few weeks after adding in the file input. But you can use the CDN to get bootstrap. A vote of thanks no errors appears if the file is not in my extensions … what I should do ? @Morad-Abdo did you get this to work with the method that @trevaun23 proposed i.e using ngAfterViewInit() and ionViewWillEnter() ? I’m looking into this area at the moment and keen to know the best way to go. Thanks! Thanks for this. I’m looking into webifying my mobile app right now. I’m interested in the segment area. In Ionic’s Conference App they list their segments in app.module.ts (under Links within IonicModule) and they don’t have the segment entry in each Page component like you do. Why is that? Are the two approaches achieving the same thing? NO , it doesn’t work . when I refresh the page from the browser I got the same error . I do not know how to handle this . I’m thinking of using model to view the detail page and provide it with a refresher in the header of the model to be a replacement , but it is not the best solution for this . Do you have any Idea ? my code is : ngAfterViewInit() { this.catId = this.navParams.get('cat').id } everything is working as expected but when I refresh page using chrome refresher there is error TypeError: Cannot read property 'id' of undefined Are you using segments? Like in the post above (or - as I mentioned - the way they do it in in the Conference app) ? I didn’t use segment . really I’m a junior . what’s the importance of segment ? Take a look at app.module in the conference app and you’ll see a list of links with segments (which in some cases have paramaters passed). And also see the docs here: see the bit under Dynamic Links This would be of importance aswell.
https://forum.ionicframework.com/t/making-a-website-using-ionic-firebase-hosting/96178/22
CC-MAIN-2020-45
refinedweb
856
53.07
:> . :Yes, that is the main difference indeed, essentially "log everything" vs :"commit" style versioning. The main similarity is the lifespan oriented :version control at the btree leaves. Reading this and a little more that you describe later let me make sure I understand the forward-logging methodology you are using. You would have multiple individually-tracked transactions in progress due to parallelism in operations initiated by userland and each would be considered committed when the forward-log logs the completion of that particular operation? If the forward log entries are not (all) cached in-memory that would mean that accesses to the filesystem would have to be run against the log first (scanning backwards), and then through to the B-Tree? You would solve the need for having an atomic commit ('flush groups' in HAMMER), but it sounds like the algorithmic complexity would be very high for accessing the log. And even though you wouldn't have to group transactions into larger commits the crash recovery code would still have to implement those algorithms to resolve directory and file visibility issues. The problem with namespace visibility is that it is possible to create a virtually unending chain of separate but inter-dependant transactions which either all must go, or none of them. e.g. creating a, a/b, a/b/c, a/b/x, a/b/c/d, etc etc. At some point you have to be able to commit so the whole mess does not get undone by a crash, and many completed mini-transactions (file or directory creates) actually cannot be considered complete until their governing parent directories (when creating) or children (when deleting) have been committed. The problem can become very complex.? . I think you can get away with this as long as you don't have too many snapshots, and even if you do I noticed with HAMMER that only a small percentage of inodes have a large number of versions associated with them from normal production operation. /var/log/messages is an excellent example of that. Log files were effected the most though I also noticed that very large files also wind up with multiple versions of the inode, such as when writing out a terrabyte-sized file. Even with a direct bypass for data blocks (but not their meta-data, clearly), HAMMER could only cache so much meta-data in memory before it had to finalize the topology and flush the inode out. A terrabyte-sized file wound up with about 1000 copies of the inode prior to pruning (one had to be written out about every gigabyte or so). . How are you dealing with expansion of the logical inode block(s) as new versions are added? I'm assuming you are intending to pack the inodes on the media so e.g. a 128-byte inode would only take up 128 bytes of media space in the best case. Multiple inodes would be laid out next to each other logically (I assume), but since the physical blocks are larger they would also have to be laid out next to each other physically within any given backing block. Now what happens when one has to be expanded? I'm sure this ties into the forward-log but even with the best algorithms you are going to hit limited cases where you have to expand the inode. Are you just copying the inode block(s) into a new physical allocation. :. :> : Yes, it makes sense. If the snapshot is explicitly taken then you can store direct references and chain, and you wouldn't need a delete id in that case. From that article though the chain looks fairly linear. Historical access could wind up being rather costly. . When truncating to 0 I would agree with your assessment. For the topology you are using you would definitely want to use different file data sets. You also have to deal with truncations that are not to 0, that might be to the middle of a file. Certainly not a common case, but still a case that has to be coded for. If you treat truncation to 0 as a special case you will be adding considerable complexity to the algorithm. With HAMMER I chose to keep everything in one B-Tree, whether historical or current. That way one set of algorithms handles both cases and code complexity is greatly reduced. It isn't optimal... large amounts of built up history still slow things down (though in a bounded fashion). In that regard creating a separate topology for snapshots is a good idea. :>. This could wind up being a sticky issue for your implementation. I like the concept of using the forward-log but if you actually have to do a version copy of the directory at all you will have to update the link (or some sort of) count for all the related inodes to keep track of inode visibility, and to determine when the inode can be freed and its storage space recovered. Directories in HAMMER are just B-Tree elements. One element per directory-entry. There are no directory blocks. You may want to consider using a similar mechanism. For one thing, it makes lookups utterly trivial... the file name is hashed and a lookup is performed based on the hash key, then B-Tree elements with the same hash key are iterated until a match is found (usually the first element is the match). Also, when adding or removing directory entries only the directory inode's mtime field needs to be updated. It's size does not. Your current directory block method could also represent a problem for your directory inodes... adding and removing directory entries causing size expansion or contraction could require rolling new versions of the directory inode to update the size field. You can't hold too much in the forward-log without some seriously indexing. Another case to consider along with terrabyte-sized files and log. Yes, I see. Can you explain the versioned pointer algorithm a bit more, it looks almost like a linear chain (say when someone is doing a daily snapshot). It looks great for optimal access to the HEAD but it doesn't look very optimal if you want to dive into an old snapshot. For informational purposes: HAMMER has one B-Tree, organized using a strict key comparison. The key is made up of several fields which are compared in priority order: localization - used to localize certain data types together and to separate pseudo filesystems created within the filesystem. obj_id - the object id the record is associated with. Basically the inode number the record is associated with. rec_type - the type of record, e.g. INODE, DATA, SYMLINK-DATA, DIRECTORY-ENTRY, etc. key - e.g. file offset create_tid - the creation transaction id Inodes are grouped together using the localization field so if you have a million inodes and are just stat()ing files, the stat information is localized relative to other inodes and doesn't have to skip file contents or data, resulting in highly localized accesses on the storage media. Beyond that the B-Tree is organized by inode number and file offset. In the case of a directory inode, the 'offset' is the hash key, so directory entries are organized by hash key (part of the hash key is an iterator to deal with namespace collisions). The structure seems to work well for both large and small files, for ls -lR (stat()ing everything in sight) style traversals as well as tar-like traversals where the file contents for each file is read. The create_tid is the creation transaction id. Historical accesses are always 'ASOF' a particular TID, and will access the highest create_tid that is still <= the ASOF TID. The 'current' version of the filesystem uses an asof TID of 0xFFFFFFFFFFFFFFFF and hence accesses the highest create_tid. There is also a delete_tid which is used to filter out elements that were deleted prior to the ASOF TID. There is currently an issue with HAMMER where the fact that the delete_tid is *not* part of the B-Tree compare can lead to iterations for strictly deleted elements, verses replaced elements which will have a new element with a higher create_tid. . Are you scanning the entire B-Tree to locate the differences? It sounds you would have to as a fall-back, but that you could use the forward-log to quickly locate differences if the first version is fairly recent. HAMMER's mirroring basically works like this: The master has synchronized up to transaction id C, the slave has synchronized up to transaction id A. The mirroring code does an optimized scan of the B-Tree to supply all B-Tree elements that have been modified between transaction A and C. Any number of mirroring targets can be synchronized to varying degrees, and can be out of date by varying amounts (even years, frankly). I decided to use the B-Tree to optimize the scan. The B-Tree is scanned and any element with either a creation or deletion transaction id >= the slave's last synchronization point is then serialized and piped to the slave. To avoid having to scan the entire B-Tree I perform an optimization whereby the highest transaction id laid down at a leaf is propagated up the B-Tree all the way to the root. This also occurs if a B-Tree node is physically deleted (due to pruning), even if no elements are actually present at the leaf within the transaction range. Thus the mirroring scan is able to skip any internal node (and its entire sub-tree) which has not been modified after the synchronization point, and is able to identify any leaf for which real, physical deletions have occured (in addition to logical deletions which simply set the delete_tid field in the B-Tree element) and pass along the key range and any remaining elements in that leaf for the target to do a comparative scan with. This allows incremental mirroring, multiple slaves, and also allows a mirror to go offline for months and then pop back online again and optimally pick up where it left off. The incremental mirroring is important, the last thing I want to do is have to scan 2 billion B-Tree elements to do an incremental mirroring batch. The advantage is all the cool features I got by doing things that way. The disadvantage is that the highest transaction id must be propagated up the tree (though it isn't quite that bad because in HAMMER an entire flush group uses the same transaction id, so we aren't constantly repropagating new transaction id's up the same B-Tree nodes when flushing a particular flush group). You may want to consider something similar. I think using the forward-log to optimize incremental mirroring operations is also fine as long as you are willing to take the 'hit' of having to scan (though not have to transfer) the entire B-Tree if the mirror is too far out of date. . Yes. The reason I don't is because while it is really easy to lay down a forward-log, intergrating it into lookup operations (if you don't keep all the references cached in-memory) is really complex code. I mean, you can always scan it backwards linearly and that certainly is easy to do, but the filesystem's performance would be terrible. So you have to index the log somehow to allow lookups on it in reverse to occur reasonably optimally. Have you figured out how you are going to do that? With HAMMER I have an in-memory cache and the on-disk B-Tree. Just writing the merged lookup code (merging the in-memory cache with the on-disk B-Tree for the purposes of doing a lookup) was fairly complex. I would hate to have to do a three-way merge.... in-memory cache, on-disk log, AND on-disk B-Tree. Yowzer! .. The only sychronization point is fsync(), the filesystem syncer, and of course if too much in-memory cache is built up. To improve performance, raw data blocks are not included... space for raw data writes is reserved by the frontend (without modifying the storage allocation layer) and those data buffers are written to disk by the frontend directly, just without any meta-data on-disk to reference them so who cares if you crash then! It would be as if those blocks were never allocated in the first place. When the backend decides to flush the cached meta-data ops it breaks the meta-data ops into flush-groups whos dirty meta-data fits in the system's buffer cache. The meta-data ops are executed, building the UNDO, updating the B-Tree, allocating or finalizing the storage, and modifying the meta-data buffers in the buffer cache. BUT the dirty meta-data buffers are locked into memory and NOT yet flushed to the media. The UNDO *is* flushed to the media, so the flush groups can build a lot of UNDO up and flush it as they go if necessary. When the flush group has completed any remaining UNDO is flushed to the media, we wait for I/O to complete, the volume header's UNDO FIFO index is updated and written out, we wait for THAT I/O to complete, *then* the dirty meta-data buffers are flushed to the media. The flushes at the end are done asynchronously (unless fsync()ing) and can overlap with the flushes done at the beginning of the next flush group. So there are exactly two physical synchronization points for each flush. If a crash occurs at any point, upon remounting after a reboot HAMMER only needs to run the UNDOs to undo any partially committed meta-data. That's it. It is fairly straight forward. For your forward-log approach you would have to log the operations as they occur, which is fine since that can be cached in-memory. However, you will still need to synchronize the log entries with a volume header update to update the log's index, so the recovery code knows how far the log extends. Plus you would also have to log UNDO records when making actual changes to the permanent media structures (your B-Trees), which is independant of the forward-log entries you made representing high level filesystem operations, and would also have to lock the related meta-data in memory until the related log entries can be synchronized. Then you would be able to flush the meta-data buffers. The forward-log approach is definitely more fine-grained, particularly don't know how you can make them that small. I spent months just getting my elements down to 64 bytes. The data reference alone for data blocks is 12 bytes (64 bit media storage offset and 32 bit length). :>? :>. For uncacheable data sets the cpu overhead is almost irrelevant. But for cached data sets, watch out! The cpu overhead of your B-Tree lookups is going to be 50% of your cpu time, with the other 50% being the memory copy or memory mapping operation and buffer cache operations. It is really horrendous. When someone is read()ing or write()ing a large file the last thing you want to do is traverse the same 4 nodes and do four binary searches in each of those nodes for every read(). For large fully cached data sets not caching B-Tree cursors will strip away 20-30% of your performance once your B-Tree depth exceeds 4 or 5. Also, the fan-out does not necessarily help there because the search within the B-Tree node costs almost as much as moving between B-Tree nodes. I found this out when I started comparing HAMMER performance with UFS. For the fully cached case UFS was 30% faster until I started caching B-Tree cursors. It was definitely noticable once my B-Tree grew past a million elements or so. It disappeared completely when I started caching cursors into the B-Tree. :> think it will be an issue for people trying to port HAMMER. I'm trying to think of ways to deal with it. Anyone doing an initial port can just drop all the blocks down to 16K, removing the problem but increasing the overhead when working with large files. :> I'd love to do something like that. I think radix compression would :> remove much of the topological bloat the B-Tree creates verses using :> blockmaps, generally speaking. : :Topological bloat? Bytes per record. e.g. the cost of creating a small file in HAMMER is 3 B-Tree records (directory entry + inode record + one data record), plus the inode data, plus the file data. For HAMMER that is 64*3 + 128 + 112 (say the file is 100 bytes long, round up to a 16 byte boundary)... so that is 432 bytes. The bigger cost is when creating and managing a large file. A 1 gigabyte file in HAMMER requires 1G/65536 = 16384 B-Tree elements, which comes to 1 megabyte of meta-data. If I were to radix-compress those elements the meta-data overhead would probably be cut to 300KB, possibly even less. Where this matters is that it directly effects the meta-data footprint in the system caches which in turn directly effects the filesystem's ability to cache information without having to go to disk. It can be a big deal. :. . Orphan inodes in HAMMER will always be committed to disk with a 0 link count. The pruner deals with them after a crash. Orphan inodes can also be commited due to directory entry dependancies. :>. Yes, I see. The budding operations is very interesting to me... well, the ability to fork the filesystem and effectively write to a snapshot. I'd love to be able to do that, it is a far superior mechanism to taking a snapshot and then performing a rollback later. Hmm. I could definitely manage more then one B-Tree if I wanted to. That might be the ticket for HAMMER... use the existing snapshot mechanic as backing store and a separate B-Tree to hold all changes made to the snapshot, then do a merged lookup between the new B-Tree and the old B-Tree. That would indeed work. :>.. : :.... :>! I can tell you've been thinking about Tux for a long time. If I had one worry about your proposed implementation it would be in the area of algorithmic complexity. You have to deal with the in-memory cache, the log, the B-Tree, plus secondary indexing for snapshotted elements and a ton of special cases all over the place. Your general lookup code is going to be very, very complex. My original design for HAMMER was a lot more complex (if you can believe it!) then the end result. A good chunk of what I had to do going from concept to reality was deflate a lot of that complexity. When it got down to brass tacks I couldn't stick with using the delete_tid as a B-Tree search key field, I had to use create_tid. I couldn't use my fine-grained storage model concept because the performance was terrible (too many random writes interfering with streaming I/O). I couldn't use a hybrid B-Tree, where a B-Tree element could hold the base of an entirely new B-Tree (it complicated the pruning and reblocking code so much that I just gave up trying to do it in frustration). I couldn't implement file extents other then 16K and 64K blocks (it really complicated historical lookups and the buffer cache couldn't handle it) <--- that one really annoyed me. I had overly optimized the storage model to try to get block pointers down to 32 bits by localizing B-Tree elements in the same 'super clusters' as the data they referenced. It was a disaster and I ripped it out. The list goes on :-) I do wish we had something like LVM on BSD systems. You guys are very lucky in that regard. LVM is really nice. BTW it took all day to write this! -Matt Matthew Dillon <dillon@backplane
https://www.dragonflybsd.org/mailarchive/kernel/2008-07/msg00116.html
CC-MAIN-2018-13
refinedweb
3,388
60.35
how convert .vcg to .rviz if I have .vcg file? where tell us .vcg format file and .rviz format ? add a comment where tell us .vcg format file and .rviz format ? Please start posting anonymously - your entry will be published after you log in or create a new account. Asked: 2015-12-11 03:07:52 -0500 Seen: 270 times Last updated: Dec 11 '15 "node name cannot contain namespace" How to set Rviz to 60 Hz? Rviz moveit plugin show current robot state odometry Tutorial and Rviz Fixed frame does not exist [rospack] Error: package 'rviz' not found rviz qtCore missing in melodic How to display CV_32FC2 images in ROS
https://answers.ros.org/question/222333/how-convert-vcg-to-rviz-if-i-have-vcg-file/
CC-MAIN-2020-16
refinedweb
111
83.25
Common integer types. More... #include <sys/cdefs.h> #include <stddef.h> #include <sys/_types.h> Go to the source code of this file. Common integer types. This file contains typedefs for some common/useful integer types. These types include ones that tell you exactly how long they are, as well as some BSD-isms. Endianness definition – Little Endian. Generic "handle" type. 16-bit signed integer 32-bit signed integer 64-bit signed integer 8-bit signed integer Priority value type. Pointer arithmetic type. Thread ID type. BSD-style unsigned char. BSD-style unsigned integer. BSD-style unsigned long. BSD-style unsigned short. BSD-style unsigned integer. 16-bit unsigned integer 32-bit unsigned integer 64-bit unsigned integer 8-bit unsigned integer BSD-style unsigned short. 16-bit volatile signed type 32-bit volatile signed type 64-bit volatile signed type 8-bit volatile signed type 16-bit volatile unsigned type 32-bit volatile unsigned type 64-bit volatile unsigned type 8-bit volatile unsigned type
http://cadcdev.sourceforge.net/docs/kos-2.0.0/types_8h.html
CC-MAIN-2018-05
refinedweb
166
64.17
. Your best bet for running a program from within sublime is to write a simple plugin to launch your application, perhaps by using the python subprocess module. It's possible to use the exec command to do this without using a plugin, but it's pretty tedious to get all the escaping done correctly, it's simpler to just write a plugin. mhmm ok well the problem is that i dont know nothing about python.... so i would need some help... can somebody show me something simple and very detailed on how to do it!? ive seen the plugin devellopment page but it doesnt help help pl0x? You'll want a plugin along these lines: import sublime, sublimeplugin import subprocess class RunApplicationCommand(sublimeplugin.ApplicationCommand): def run(self, args): subprocess.Popen("C:\\path\\to\\myapp.exe", "argument1"]) This will run "C:\path\to\myapp.exe argument1" To bind this to a key, use the command name "runApplication", eg: <binding key="f5" command="runApplication"/> Ok so I tried it... and since Im not good at python I dont know what to change in order to make it work. I dont know what to replace argument1 for This is my run.py file import sublime, sublimeplugin import subprocess # This simple plugin will add 'Hello, World!' to the end of the buffer when run. # To run it, save it within the User/ directory, then open the console (Ctrl+~), # and type: view.runCommand('sample') # # See for more information class RunApplicationCommand(sublimeplugin.ApplicationCommand): def run(self, args): subprocess.Popen("C:\Program Files\Java\jdk1.6.0_16\bin\java.exe", "$File"]) I dont know what to do from here In order to run a java file you need to compile it (which works)and then run in cmd the run command Ex: javac test.java java test (without the .java extension) So can anybody help? anybody? try adding print str(args) the args you get are from extra words you add to your key binding. 'somehow' you should have the file name to compile, it could be from the args, it could be by calling view's API (see sublimetext.com/docs/api-reference) and getting the current opened file. this is up to you, and how you want the plugin to work. Hi, hope this isn't too late. I stumbled into this problem myself just now, and the 10-second solution is to go to: Preferences > Default Key Bindings and enter the following line: <binding key="f5" command="exec '' 'java $BaseName'"/> This will run the program when you press F5. Be sure to compile first! oh my god... redandwhite... thank you very much!!!! its freaking aweosme! like seriously thank you mhmm i have a new problem.... I can now run the program but lets say I ask somebody to input somehting.... it doesnt work I cant write anything.... anyway around this? nobody? you may want to give more details about your problem. yes actually thank you sublimator, that is what im talking about I will try it out later when I have the time... thnx
https://forum.sublimetext.com/t/compile-and-run-java-in-sublimetext/409/6
CC-MAIN-2016-18
refinedweb
510
66.84
Perfect...thanks... Perfect...thanks... I'm using Teensy 3.2; typically, I only access very simple I2C devices like RTC modules (DS1307, DS1338 and the likes). Most of the time, I just have a single I2C device, wired to the Teensy (short wires). I'd like to get rid of (external) resistors and only use Teensy 3.2 integrated pullups, to simplify the circuit. How should I call i2c_t3 functions, in order to accomplish this? A short example would be great! Many thanks! Indications on the forum is that you cannot expect the internal pullups to work. Teensy 3.1/3.2 need external pullup on the line somewhere. The pullups can work, depending on situation. The Teensy 3.x pullups are low resistance (~200 ohms), but while this value is low it can still work in most cases. I've used these pullups many times on quick breadboard setups. Where it might have problems is on long resistive bus lines if the Slave cannot pull down strong enough (cannot establish low voltage due to strong pullup). The LC pullups on the other hand are nearly useless. They are the opposite, very resistive ~44k. They are so resistive that only the lowest signals speeds might work, if at all. Still it costs nothing to try out either of these, just a line of code. It can be set in a couple ways, either on the initial begin() call: Or via pin reconfiguration command:Or via pin reconfiguration command:Code:Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_INT, I2C_RATE_400); Code:Wire.pinConfigure(I2C_PINS_18_19, I2C_PULLUP_INT); Thanks a lot guys! nox771: I big THANK YOU for putting this library together. It just saved my life .. By the way - in my setup I do use the internal pullups since I literally only have 1" distance to cover to feed into a P82B715TD I2C driver chip. From there I have about 15 feet to my system and on the system side I have another driver to bring the signal back down to "normal" level. Today I ran a test with a 30 foot non-shielded line between the two driver chips and still was able to securely communicate between the two stations. Mind you - I had to limit the rate setting to 600 (with the Teensy 3.1 running at 72 MHz), but that is still fast enough to get my data across in time. Again, thanks a lot for putting this work into this library. Wolfie Always good to hear when things work. I'm glad it helped you out Hi All, My first project with my new Teensy 3.1 is to use I2C to read a temperature sensor. I constructed the code below based on the examples, and using the library provided by nox771 (thank you!). I checked the SDA and SCL lines with an oscilloscope. After reset they are in high imp, and after 1 sec they both go high and stay high. The serial monitor says: Error - Set mode: I2C timeout Any suggestions welcome. Thanks Andras The full code: #include <i2c_t3.h> void setup() { Serial.begin(9600); ledBlink(1000); // Setup for Master mode, pins 18/19, internal pullups, 400kHz Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_INT, I2C_RATE_400); Wire.setDefaultTimeout(1000); } void loop() { readTemp(0x48); ledBlink(500); } void readTemp(uint8_t sensor_addr) { uint16_t temp =0; Wire.beginTransmission(sensor_addr); // slave addr Wire.write(0); //Write 0 to config register means read will return temperature value Wire.endTransmission(); if (Wire.status()!=I2C_WAITING) { print_i2c_status("Error - Set mode: "); Wire.resetBus(); return; } Wire.requestFrom(sensor_addr,2,I2C_STOP); // blocking read (request 2 bytes) if (Wire.status()!=I2C_WAITING) { print_i2c_status("Error - Read temp: "); Wire.resetBus(); return; } temp=Wire.readByte()<<8; temp|=Wire.readByte(); temp>>=7; Serial.printf("Temperature: %.1f \n",temp,(float)(temp) / 2); } void print_i2c_status(char * s) { Serial.print(s); switch(Wire.status()) { case I2C_WAITING: Serial.print("I2C waiting, no errors\n"); break; case I2C_ADDR_NAK: Serial.print("Slave addr not acknowledged\n"); break; case I2C_DATA_NAK: Serial.print("Slave data not acknowledged\n"); break; case I2C_ARB_LOST: Serial.print("Bus Error: Arbitration Lost\n"); break; case I2C_TIMEOUT: Serial.print("I2C timeout\n"); break; case I2C_BUF_OVF: Serial.print("I2C buffer overflow\n"); break; default: Serial.print("I2C busy\n"); break; } } void ledBlink(uint16_t ms) { pinMode(LED_BUILTIN,OUTPUT); // LED digitalWrite(LED_BUILTIN,HIGH); // LED on delay(ms); digitalWrite(LED_BUILTIN,LOW); // LED off delay(ms); } Do you have external pullup resistors on the SDA and SCL lines? You will need them. No, I don't have external resistors. I activated the internal ones in Wire.begin, and I could also see on the scope that they are actively pulled high. I can give it a try, though I don't expect much. Thanks Cross wired! Yesss! Dang, I forgot to check that earlier (I measured everything else in terms of connectivity and shortcuts...) Thank you, now it works! Hi, I am having problems running the i2c_t3 library with the following problem: Code:Arduino: 1.6.7 (Windows 7), TD: 1.27, Board: "Teensy 3.0, Serial, 48 MHz, US English" C:\Users\...\Documents\Arduino\libraries\i2c_t3\i2c_t3.cpp: In static member function 'static uint8_t i2c_t3::setOpMode_(i2cStruct*, uint8_t, i2c_op_mode)': C:\Users\...\Documents\Arduino\libraries\i2c_t3\i2c_t3.cpp:289:84: error: 'DMAMUX_SOURCE_I2C1' was not declared in this scope i2c->DMA->triggerAtHardwareEvent((bus == 0) ? DMAMUX_SOURCE_I2C0 : DMAMUX_SOURCE_I2C1); ^ exit status 1 Error compiling. Thanks, Dylan Last edited by Dylan144GT; 01-17-2016 at 03:23 PM. Sorry about that. It got pushed to the bottom of the list and forgotten (last 6 months have been hard for unrelated reasons). I'll take a look at it. What it means is that version 3.0 of the die has no I2C1 bus (it only has I2C0), so any line referring to an I2C1 bus should be skipped (or otherwise routed around) using macro checks. Give me a little bit of time, I'll see if I can figure it out. FWIW, the defines for the specific Teensy 3.x/LC's are: - If __MK20DX128__ is defined, it is a Teensy 3.0 (without i2c1); - If __MK20DX256__ is defined, it is a Teensy 3.1 or Teensy 3.2; - If __MKL26Z64__ is defined, it is a Teensy LC. I wasn't able to see this error when I compiled. Although trying to work with I2C1 will fail on a T3.0, the defines exist in the kinetis.h file, so I'm not sure how you got the compile to fail (although I'm not running the newest stuff, so that might explain it). Hi, I've got an ongoing project that keeps evolving. I tried using the fast TFT for my display but it wasn't working out so now I'm experimenting with OpenVG and HDMI on a Pi A+ for the display. But my project requires hard real time too so I'm using a Teensy 3.x and my plan is to communicate by using the Pi as an i2c master and the Teensy as both an i2c master (to communicate with sensors) and as an i2c slave to the Pi. Looking at your example code in I see that it says: // ************************************************** ******************************************** // ** Note: This is a Teensy 3.1/LC ONLY sketch since it requires a device with two I2C buses. ** // ************************************************** ******************************************** // but in another place I found: Can you elaborate on this? I've got several different Teensies and if I need to I can purchase an LC and see if I can shoehorn my code into 8k. But I'm surprised that the 3.x Teensies might be providind a subset of the LC functionality, i.e. the dual i2c bus. Thanks! The 3.1 and 3.2 devices have two I2C buses (Wire on SDA0/SCL0, and Wire1 on SDA1/SCL1), however Wire1 connections are only available on the backside surface mount pads. The LC device also has two buses (Wire on SDA0/SCL0, and Wire1 on SDA1/SCL1), but they are both accessible on the main thru-hole connections. However LC runs at a lower internal bus frequency, so this limits the top speed you can use on I2C (still overclocked with respect to I2C spec, but not quite as fast as 3.2 device). This is described in more detail in the "Description" and "Clocking" sections of the 1st post in this thread. On a Teensy 3.1 or 3.2 with a single TMP102 temp sensor, with 10K pullups I measure about 5 usec risetime, and less than 20 nsec fall time. This is way too slow. The standard Wire library often fails, leaving SCL and/or SDA low. I wonder if it is partly because of the slow rise on clock contributing to missed data bits? With 2k2 pullups, risetime is about 500 nsec - 10X faster. This is in a white breadboard with 24" of 100-mil ribbon cable between Teensy and TMP102. I also get I2C lockups with much shorter prototype wires between a Teensy and Adafruit 14- or 7-segment display using the HT16K33 backpack. These lockups are what led me here to a hopefully more robust library. Last edited by bboyes; 03-10-2016 at 06:30 PM. Reason: clarify pullups The only thing to check there is if your low-levels are low enough to register as logic-low, which is more a problem with long wires between pullup and slave (or weak slave pulldown) - essentially since pulldowns are active, you are weighting your effective pulldown strength against your pullup strength to obtain your resulting voltage. If you have a scope or logic analyzer that would be best for verifying communication, otherwise you will just have to gauge lockups/corruption with respect to different pullup values. If your program checks return values and such for errors that can also help isolate problems. Amen to the checking return values. It's amazing how much open source driver and demo app code does not do that! Astonishingly, the Adafruit 7- and 14-segment display example code never checks anything. If the display is completely missing, the demo application runs fine and reports no errors! My mind is boggled.
https://forum.pjrc.com/threads/21680-New-I2C-library-for-Teensy3?s=12e30b97b3fbc3d21a83db4ab1847fc5&p=88932&viewfull=1
CC-MAIN-2019-47
refinedweb
1,676
67.76
Suppose, my global variable and local variables has same name, how can i access the global variable value in subroutine? #! /usr/bin/perl $name = "Krishna"; sub printName{ my $name = "Sankalp"; print ("Local name : ", $name, "\n"); # How to print global variable here } &printName; print("Global name : ", $name, "\n"); If your global variable is in fact a package variable, you can access it through the package namespace. The default package is main. print "Local name : $main::name\n"; Since you're staying in the same namespace, you can omit the main, so $::name works, too. Both solutions do not work if your outside variable was also defined using my. You can define a package variable with our or via use names qw($name). That said, you should never do that. Always use lexical variables, and put them in the smallest scope possible. use strict and use warnings will help you, and there is a Perl::Critic rules that complains if you define a variable with the same name as an existing one in a smaller scope.
https://codedump.io/share/az2pITLsKOOW/1/how-to-access-global-variable-in-subroutine
CC-MAIN-2017-09
refinedweb
174
69.72
2 AnswersNew Answer def insertion_sort(ar): for i in range(len(ar)): for j in range(i-1): if ar[i] < ar[j]: ar[i],ar[j] =ar[j], ar[i] print(ar) insertion_sort([10,12,1,7,8,6,5]) 2/14/2021 12:51:03 AMLabib Hasan 2 AnswersNew Answer Trace your code with the print of the array after if conditions, and you will see how on the fourth exchange pass your 7 will fly to the end of the array, but should done have been inserted at the sort order. That makes sense. Yes , thank you . I was trying to implement insertion sort with just the basic understanding of how it works . Don't know what type of sorting it has become now though it is sorting correctly . Do you know ? Sololearn Inc.535 Mission Street, Suite 1591
https://www.sololearn.com/Discuss/2695899/can-i-claim-this-code-as-one-of-the-methods-of-insertion-sort
CC-MAIN-2022-21
refinedweb
142
71.55
Closed Bug 1376910 Opened 3 years ago Closed 3 years ago Remove Sys V IPC access from content processes Categories (Core :: Security: Process Sandboxing, enhancement, P1) Tracking () mozilla60 People (Reporter: jld, Assigned: jld) References Details (Whiteboard: sblc4) Attachments (1 file, 1 obsolete file) This turns out to be easier than I thought: * SysV message queues were used only by the ESET antivirus injected library, and bug 1362601 took care of that. * SysV semaphores are used by ALSA (probably for dmix), which is disabled by default as configure time. * SysV shared memory is more complicated, but we don't seem to be using it in content processes anymore. The fix/workaround for bug 1271100 prevents GTK from using it, but we don't seem to be having GTK draw directly to the X server in any case. There's also nsShmImage, but that seems to be used only in the parent process. Running `ipcs -p` shows child processes as the “last operation pid” for shm segments, but this seems to be an artifact of the parent doing fork/exec with SHM mappings (i.e., the exec acts like a shmdt() or something like that). And, indeed, blocking all the syscalls and unsharing the IPC namespace yields a browser that still works in local testing. Whiteboard: sblc4 Try: I should also mention that I tested this locally with both DRI-based and NVidia GL drivers, so hopefully we won't have too many surprised when this ships in Nightly. Comment on attachment 8887700 [details] Bug 1376910 - Remove SysV IPC access from Linux content sandbox when possible. Comment on attachment 8887701 [details] Bug 1376910 - Unshare the SysV IPC namespace in content processes. Attachment #8887701 - Flags: review?(gpascutto) → review+ Pushed by jedavis@mozilla.com: Block syscalls for SysV IPC in content processes. r=gcp Unshare the SysV IPC namespace in content processes. r=gcp Status: NEW → RESOLVED Closed: 3 years ago status-firefox56: --- → fixed Resolution: --- → FIXED Target Milestone: --- → mozilla56 Things that are broken and being fixed: * ALSA using --enable-alsa: bug 1384439. Things that seem to be broken and need more investigation: * fglrx (“AMD Catalyst”), the proprietary driver for ATi/AMD GPUs * Something about graphics that causes Cairo to be used to draw directly to X for GTk widgets, and doesn't happen in my testing or in Mozilla's automation. Additionally: * Using ALSA via a shim library that pretends to be PulseAudio was already broken by sandboxing but now it's even more broken. This isn't supported, and until bug 1362220 happens the workarounds are to disable sandboxing or build with --enable-alsa. I've backed this out while I deal with the graphics regressions: Status: RESOLVED → REOPENED Resolution: FIXED → --- Do you have some info on the 2 graphics regressions? (other bugs etc?) Comment on attachment 8887700 [details] Bug 1376910 - Remove SysV IPC access from Linux content sandbox when possible. ::: security/sandbox/linux/SandboxFilter.cpp (Diff revision 1) > - // access. But the graphics layer might not be using them > +#ifdef MOZ_ALSA > - // anymore; this needs to be studied. > - case SHMGET: > - case SHMCTL: > - case SHMAT: > - case SHMDT: Note to self: the ALSA `dmix` plugin uses shared memory as well as semaphores, so these need to be moved under `#ifdef MOZ_ALSA` rather than deleted. Priority: -- → P1 (In reply to Jed Davis [:jld] (⏰UTC-6) from comment #9) > * Something about graphics that causes Cairo to be used to draw directly to > X for GTk widgets, and doesn't happen in my testing or in Mozilla's > automation. I have a theory: libXext is being preloaded, probably indirectly via something like libGL, which defeats the XShmQueryExtension shim in libmozgtk[1]. If I do this kind of preload locally, it causes crashes that look like the ones we saw before this was backed out. [1] So we'll need: 1. Something to detect fglrx and communicate that to content processes in an environment variable so that the information is available early enough to skip unsharing the IPC namespace. And, of course, adjust the seccomp-bpf policy as well. (If this happens after bug 1151624 we can skip the env var dance steps, because I plan to move all the unsharing to when we clone() the child process.) 2. Either preload libmozgtk itself, or copy the shim into libmozsandbox, which is already preloaded. Fortunately, LD_PRELOAD is handled before /etc/ld.so.preload, so our preload will win — assuming that that's really what's going on. (Side note: bug 624422 suggests that libmozgtk might become unnecessary once NPAPI is gone. The other approach is to make semget() and shmget() non-fatal on Nightly, but that might still break things with fglrx. Priority: P2 → P1 Comment on attachment 8887700 [details] Bug 1376910 - Remove SysV IPC access from Linux content sandbox when possible. This is a completely different patch (and has a different MozReview ID, no less), but MozReview is confused again. It needs re-review. Attachment #8887700 - Flags: review+ → review?(gpascutto) Comment on attachment 8887700 [details] Bug 1376910 - Remove SysV IPC access from Linux content sandbox when possible. ::: security/sandbox/linux/SandboxFilter.cpp:599 (Diff revision 2) > public: > ContentSandboxPolicy(SandboxBrokerClient* aBroker, > ContentProcessSandboxParams&& aParams) > : mBroker(aBroker) > , mParams(Move(aParams)) > + , mAllowSysV(PR_GetEnv("MOZ_SANDBOX_ALLOW_SYSV") != nullptr) Counterintuitive that MOZ_SANDBOX_ALLOW_SYSV=0 does not do what you'd think. (Of course no user is *supposed* to specify that, though...) ::: security/sandbox/linux/launch/SandboxLaunch.cpp:124 (Diff revision 2) > + &nsIGfxInfo::GetAdapterVendorID, > + &nsIGfxInfo::GetAdapterVendorID2, > + }; > + for (const auto method : kMethods) { > + if (NS_SUCCEEDED((gfxInfo->*method)(vendorID))) { > + if (vendorID.EqualsLiteral("ATI Technologies Inc.")) { Ok this is a clever way to not catch newer drivers :-) (In reply to Gian-Carlo Pascutto [:gcp] from comment #18) > > + if (vendorID.EqualsLiteral("ATI Technologies Inc.")) { > > Ok this is a clever way to not catch newer drivers :-) I added a comment about this, because it's not quite what it looks like: Post-merger AMD-branded devices also have that ATI vendor string if they're using the Catalyst/fglrx drivers, but the open-source drivers integrated into Mesa identify their vendor as "X.Org". Pushed by jedavis@mozilla.com: Remove SysV IPC access from Linux content sandbox when possible. r=gcp Status: REOPENED → RESOLVED Closed: 3 years ago → 3 years ago status-firefox60: --- → fixed Resolution: --- → FIXED Target Milestone: mozilla56 → mozilla60 Because I never actually wrote out the rationale for this in comment #0: SysV IPC authorization is all uid-based, so anything running as the right uid that can obtain or guess the correct small-integer “key” can get access. This is a problem for sandboxing, where we're trying to draw finer-grained security boundaries than “same uid” — it's like a mini-filesystem that we can't restrict or broker access to, only block completely.
https://bugzilla.mozilla.org/show_bug.cgi?id=1376910
CC-MAIN-2020-34
refinedweb
1,111
52.19
> > . I have no problem with this - indeed, I fully agree that we shouldn't extend the FFI to deal with C's strange promotion rules. Nevertheless, we need to say that we're taking this approach. Similar problems occur with foreign exports: if you declare a foreign export with Float arguments (eg. see addFloat in section 3.4 of the FFI doc), does that correspond to a C function defined like this float addFloat(a,b) float a,b; { return (a+b); } or this float addFloat(float a, float b) { return (a+b); } Clearly the latter form is the desired one, but the FFI addendum should note that, and say that in order to correctly call the function from C you must have a visible prototype. Cheers, Simon
http://www.haskell.org/pipermail/ffi/2002-March/000454.html
CC-MAIN-2014-41
refinedweb
128
64.44
@PostConstruct method not getting fired in Spring @RepositoryPeter Hinds Feb 28, 2014 2:24 PM I am having trouble after updating an application that runs in WebSphere and Netweaver to run in JBoss6.2 EAP. I have found that a spring-managed @Repository (org.springframework.stereotype.Repository) with an init() method annotated with @PostConstruct (javax.annotation.PostConstruct) is does not have the init() method run when deployed in JBossEAP 6.2.0. The class looks something like the following: package com.company.productname.api.dao.impl; // ... imports removed .... @Repository public class UserRoleDao extends AbstractBaseDao { private static final Log LOG = LogFactory.getLog(UserRoleDao.class); private boolean testInitInvoked = false; // .... some code removed .... /** * Prepare the caches used to lookup market roles */ @PostConstruct protected void init() { testInitInvoked = true; if (LOG.isDebugEnabled())LOG.debug("UserRoleDao.init() method called"); // .. . . . some code removed ...... } @Override public Mask getMask(final String aMaskName) { LOG.debug("getRoleMask entered, testInitInvoked = [" + testInitInvoked + "]- aMaskName = " + aMaskName); Mask myMask = masksByName.map().get(aMaskName); if (myMask != null) { myMask.setMembers(this.getMembersForMaskId(myMask.getId())); } LOG.debug("getRoleMask returning - myMask = " + myMask); return myMask; } } (sorry, I submitted before I had finished typing, continuing now) What I can see from the logging is that the logging in the init method is not getting logged, and the value of the testInitInvoked boolean stays as false when the class is used by the application (a good length of time after startup). The class above is in a jar bundled into the war/WEB-INF/lib. I can see from the spring logging that the UserRoleDao class is being autowired into the class where it is referenced with an @Autowired annotation. The spring jars are installed in JBoss at JBOSS_HOME\modules\com\company\thirdparty\main and are referenced by the module.xml file correctly (as most of the app is spring managed I know they are referenced correctly). The spring context uses class scanning as shown in the following excerpt from the spring context xml file: <context:component-scan So, the strange thing is that spring is able to autowire the UserRoleDao class into the Service class that uses it, but the @PostConstruct seems to be ignored. I have tried moving the spring jars into the WEB-INF\lib directory (I found with previous issues around Hibernate that annotations weren't getting scanned if jars were referenced in the JBOSS_HOME\modules and moving them into the WEB-INF\lib directory fixed that). Has anybody else noticed a similar problem before? (and found a solution!) The @PostConstruct init method does get fired when deployed in WebSphere & Netweaver using the same spring version jars. Apologies if I have posted this in the wrong area, please let me know and I will move it. Thanks, Versions: JBoss: EAP 6.2.0.GA (built on AS 7.3.0) Spring: 3.1.1 1. Re: @PostConstruct method not getting fired in Spring @RepositoryPeter Hinds Mar 7, 2014 6:35 AM (in response to Peter Hinds) Thanks to 'M. Deinum' on stackoverflow.com (see ) I was able to resolve this by moving the spring jars into the WEB-INF/lib directory and removing them from the modules directory.
https://developer.jboss.org/thread/237597
CC-MAIN-2018-39
refinedweb
519
56.55