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
Opened 4 years ago Closed 4 years ago Last modified 4 years ago #19519 closed Bug (fixed) Django fails to close db connections at end of request-response cycle Description Under some circumstances (I'll get to guesses about this in the end), the db connection isn't closed at the end of the request, and resurfaces later on to service another request. Thus, one request writes to the database, and then the next request tries to look for that data and fails, because it uses an outdated connection that hasn't yet been notified of the db change (per pep-249, different connections aren't required to see the same data.) The workaround solution for this is to add a django.db.connection.close() before that query, which brings to mind bug #13533. Similarly, This bug manifests on mysql innodb; but I haven't checked other databases, so this might just be coincidence. It is also possible that the non-closing connection bug exists for all back-ends, but that auto-commit isn't enough to prevent the damage only on mysql innodb. The situation under which I've seen these connections retained is when sending an HttpResponse with a generator for content. It might be that when sending such content, the following lines (django.db:44-47) def close_connection(**kwargs): for conn in connections.all(): conn.close() signals.request_finished.connect(close_connection) which are supposed to make sure the connection closes, don't work, because the signal isn't raised. It is, however, still a riddle how the old connection gets attached to a new request. Bug #19117 might also be related to this. Attachments (3) Change History (28) comment:1 Changed 4 years ago by aaugustin - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 4 years ago by apollo13 Raising this issue to "release blocker" since streaming responses are new in 1.5 and somewhat broken in that regard! I attached a project which demonstrates the issue, see the following server log: <sqlite3.Connection object at 0x17234b8> ------------------------ () {'signal': <django.dispatch.dispatcher.Signal object at 0x149e1d0>, 'sender': <class 'django.core.handlers.wsgi.WSGIHandler'>} ------------------------ [29/Dec/2012 03:54:12] "GET /testing/ HTTP/1.1" 200 15 <sqlite3.Connection object at 0x17234b8> ------------------------ () {'signal': <django.dispatch.dispatcher.Signal object at 0x149e1d0>, 'sender': <class 'django.core.handlers.wsgi.WSGIHandler'>} ------------------------ None request already finished: True [29/Dec/2012 03:54:16] "GET /testing_generator/ HTTP/1.1" 200 18 What does this mean? When using StreamingHttpResponse the request_finished signal is sent before the response is actually generated, meaning database connections are already closed and a new query inside the iterator would cause a new connection to open. A fix might be something along the lines of -- eg returning the response and issuing the request_finished signal after the upstream wsgi gateway exhausted the iterator. Changed 4 years ago by apollo13 comment:3 Changed 4 years ago by apollo13 - Cc apollo13 added - Severity changed from Normal to Release blocker - Triage Stage changed from Unreviewed to Accepted - Version changed from 1.4 to master comment:4 Changed 4 years ago by amosonn@… It is probably best to make sure this works for iterators passed to regular HttpResponse objects as well, even though it is deprecated. comment:5 Changed 4 years ago by aaugustin The request_finished signal should be hooked on the close() method of the WSGI iterable. As pointed out in comment 4 this was already broken in the old-style streaming responses. comment:6 follow-up: ↓ 10 Changed 4 years ago by akaariai Do we have a problem with transactions here? The transaction used for the request could be closed before the request is actually generated. If this is the case, then documenting this with "if using transaction middleware the transaction used for the request will be closed before the request is generated" seems like the easy way out. Another option is to add hooks for request finished with success/exception, but this is out of scope for 1.5. comment:7 Changed 4 years ago by apollo13 Yes, the transaction middleware will also commit the transaction before the response is generated. Same goes for decorators like commit_on_success. But independent of that, the whole connection is closed before the response is generated. comment:8 Changed 4 years ago by apollo13 Ok, so I attached an initial patch. Anssi provided some valuable feedback: He suggested that we only do the .close dance if we are actually working with a StreamingResponse to keep the patch backwards-compatible (although we don't know if it is backwards-incompatible yet). I somewhat agree with that, but on the other hand I'd like to handle both cases in the same way. Next question is how to handle streaming responses in the test client. Currently they are not consumed at all and Anssi suggested to consume them always (probably add a flag later on to prevent consuming them, but that's probably not needed for 1.5). Last thing: I am still thinking how to test that since the TestClient uses it's own WSGI handler which does stuff a bit different (it actually disconnects the close_connections receiver before it fires request_finished ;)). Any thoughts from someone with more knowledge of the WSGI protocol than me would be appreciated :) EDIT:// Forgot to attach the patch, see below comment:9 follow-up: ↓ 11 Changed 4 years ago by apollo13 Related: -- We either have to raise the required python versions or fix it in our wsgiref subclass (probably the later since Python didn't fix it in 2.6, unless it wasn't broken which I doubt). comment:10 in reply to: ↑ 6 Changed 4 years ago by aaugustin Do we have a problem with transactions here? The transaction used for the request could be closed before the request is actually generated. This is less likely to bite people in real life. There are obvious uses cases for reading from the database while generating a streaming response (eg. huge CSV exports); I don't see writing to the database as being as common. It's tracked by #5241, and I don't think it is a release blocker. comment:11 in reply to: ↑ 9 Changed 4 years ago by aaugustin Related: -- We either have to raise the required python versions or fix it in our wsgiref subclass (probably the later since Python didn't fix it in 2.6, unless it wasn't broken which I doubt). This fix will be available in Python 2.7.4, which isn't released yet. If we want to fix this by triggering request_finished in the WSGI iterable's close() method we must ensure it's reliably closed. Changed 4 years ago by apollo13 comment:12 Changed 4 years ago by aaugustin - Has patch set - Needs tests set - Owner changed from nobody to aaugustin - Status changed from new to assigned comment:13 Changed 4 years ago by aaugustin - Needs tests unset - Triage Stage changed from Accepted to Ready for checkin This isn't testable within Django's test framework because the test client explicitly disables closing the database connection at the end of each request (since #8138). I've used Florian's test project to validate manually that the pull request fixes the issue. Per PEP 3333, "the close() method requirement is to support resource release by the application". Currently, Django uses the request_finished signal to close the connections to the databases and caches. That's exactly the purpose of close(), and therefore I think it's a good idea to send the signal from there. comment:14 follow-up: ↓ 15 Changed 4 years ago by akaariai I am wondering if pushing the request_finished signal to late stages is actually safe to do. Question no. 2 from pep 3333 says that:. To me this suggest it is possible a different thread will finish the request and/or there is another request processed at the same time by the same thread. This would mean that we could be closing connections for different threads or different requests. I hope I am 100% wrong here. If the above is the case, this is going to get a lot more complex. The connection handling is bound to threads, not requests. What we could do is detach the connection from the thread at the old request_finished point, and then when the request is actually finished (the new request_finished point) we could close the connection. comment:15 in reply to: ↑ 14 Changed 4 years ago by aaugustin The real question is: does any WSGI server actually used to serve real websites sport this behavior? comment:16 Changed 4 years ago by aaugustin Summary of an IRC discussion: - We believe that current implementations of this idea (eg. gunicorn's async workers) use green threads that honor Python's threading API; the database connection is a green thread local. - If that weren't true, Django would break horribly anyway, independently of streaming responses. - The way gevent solves blocking I/O makes the PEP's point moot; it makes the write() API just as "pseudo-non-blocking" as the iterator API. comment:17 Changed 4 years ago by aaugustin If we want to avoid changing the semantic of request_finished we can also introduce a new signal. We'd have to find a not-too-confusing name. comment:18 Changed 4 years ago by apollo13 -1 on a new signal, I'd say ship it as is. comment:19 Changed 4 years ago by Aymeric Augustin <aymeric.augustin@…> - Resolution set to fixed - Status changed from assigned to closed comment:20 Changed 4 years ago by Aymeric Augustin <aymeric.augustin@…> comment:21 Changed 4 years ago by aaugustin - Resolution fixed deleted - Status changed from closed to new My fix makes servers.LiveServerDatabase.test_fixtures_loaded hang under PostgreSQL. comment:22 Changed 4 years ago by aaugustin LiveServerTestCase needs request_finished to close connections; disabling it globally for tests was wrong. I'm attaching a patch that's supposed to fix the problem... Changed 4 years ago by aaugustin comment:23 Changed 4 years ago by apollo13 That's at least here not the case: Installed 0 object(s) from 0 fixture(s) test_test_test (regressiontests.servers.tests.LiveServerAddress) ... ok test_database_writes (regressiontests.servers.tests.LiveServerDatabase) ... ok test_fixtures_loaded (regressiontests.servers.tests.LiveServerDatabase) ... ok test_404 (regressiontests.servers.tests.LiveServerViews) ... ok test_environ (regressiontests.servers.tests.LiveServerViews) ... ok test_media_files (regressiontests.servers.tests.LiveServerViews) ... ok test_static_files (regressiontests.servers.tests.LiveServerViews) ... ok test_view (regressiontests.servers.tests.LiveServerViews) ... ok ---------------------------------------------------------------------- Ran 8 tests in 2.356s comment:24 Changed 4 years ago by apollo13 - Resolution set to fixed - Status changed from new to closed So the tests did work for me cause I already had the fix which github fails to display in the history *rage* and Did I already say that this is absolutely githubs fault? :þ comment:25 Changed 4 years ago by apollo13 Note: This also broke MySQL but the tests never got this far since the Postgres builds blocked the queue. I remember making some fixes in this area when I introduced explicit support for streaming responses. If this is indeed related to streaming responses it's most likely fixed in master.
https://code.djangoproject.com/ticket/19519?cversion=0&cnum_hist=2
CC-MAIN-2016-36
refinedweb
1,860
61.97
Ops, the first patch was introducing a bug in the nevow:invisible rendering, please ignore it and use the new one [1] Sorry about that, ciao ste [1] > Hello, > I just submitted a couple of patches to the Nevow issue tracker. > > The first one [1] is to make flatsax.ToStan use the namespace prefix of elements that are not in the default namespace. I also added a new testcase for it. > > The patch also fixes an already existing flatsax testcase which is now in TODO mode (test_switchns), at least as far as correct XML namespace usage is concerned, even if it would still fail because the input and output strings are not exactly the same. That testcase is probably superfluous if the new one gets checked in. > > The second one [2] is a trivial change to the default 404 page so that it is wellformed XML. > > Thanks, ciao > ste > > [1] > [2]
http://twistedmatrix.com/pipermail/twisted-web/2005-April/001421.html
CC-MAIN-2016-40
refinedweb
151
69.52
Ever tried to use a your camera memory card in your laptop. You cannot use it directly simply because there is no port in laptop which accept it. You must use a compatible card reader. You put your memory card into the card reader and then inject the card reader into the laptop. This card reader can be called the adapter. A similar example is your mobile charger or your laptop charger which can be used with any power supply without fear of the variance power supply in different locations. That is also called power “adapter”. In programming as well, adapter pattern is used for similar purposes. It enables two incompatible interfaces to work smoothly with each other. Going by definition: The definition of Adapter provided in the original Gang of Four book on Design Patterns states: “Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.” An adapter pattern is also known as Wrapper pattern as well. Adapter Design is very useful for the system integration when some other existing components have to be adopted by the existing system without sourcecode modifications. A typical interaction happen like this: Where to use Adapter Design Pattern? The main use of this pattern is when a class that you need to use doesn’t meet the requirements of an interface. e.g. If you want to read the system input through command prompt in java then given below code is common way to do it: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter String"); String s = br.readLine(); System.out.print("Enter input: " + s); Now observe the above code carefully. 1) System.in is static instance of InputStream declared as: public final static InputStream in = null; This input stream natively reads the data from the console in bytes stream. 2) BufferedReader as java docs define, reads a character stream. //Reads text from a character-input stream, buffering characters so as to //provide for the efficient reading of characters, arrays, and lines. public class BufferedReader extends Reader{..} Now here is the problem. System.in provides byte stream where BufferedReader expects character stream. How they will work together? This is the ideal situation to put a adapter in between two incompatible interfaces. InputStreamReader does exactly this thing and works adapter between System.in and BufferedReader. /**. */ public class InputStreamReader extends Reader {...} I hope the above usecase makes sense to all of you. Now, the next question is how much work adapter should do to make two incompatible interfaces work together? How much work the Adapter Pattern should do? Answer is really simple, it should do only that much work so that both incompatible interfaces can adapt each other and that’s it. e.g. in our above case study, A InputStreamReader simply wraps the InputStream and nothing else. Then BufferedReader is capable of using underlying Reader to read the characters in stream. /** * Creates an InputStreamReader that uses the default charset. * @param in An InputStream */ public InputStreamReader(InputStream in) { super(in); try { sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object } catch (UnsupportedEncodingException e) { // The default encoding should always be available throw new Error(e); } } Now when we have a good understanding of what’s an adapter looks like, let’s identify the actors used into adapter design pattern: Participants of Adapter Design Pattern The classes and/or objects participating in this pattern are listed as below: - Target (BufferedReader): It defines the application-specific interface that Client uses directly. - Adapter (InputStreamReader): It adapts the interface Adaptee to the Target interface. It’s middle man. - Adaptee (System.in): It defines an existing incompatible interface that needs adapting before using in application. - Client: It is your application that works with Target interface. Other example implementations of Adapter Design Pattern Some other examples worth noticing is as below: 1) java.util.Arrays#asList() This method accepts multiple strings and return a list of input strings. Though it’s very basic usage, but it’s what an adapter does, right? 2) java.io.OutputStreamWriter(OutputStream) It’s similar to above usecase we discussed in this post: Writer writer = new OutputStreamWriter(new FileOutputStream("c:\\data\\output.txt")); writer.write("Hello World"); 3) javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal() Adapts a Java type for custom marshaling. Convert a bound type to a value type. That’s all for this simple and easy topic. Happy Learning !! 10 thoughts on “Adapter Design Pattern in Java” Adapter class is a good example of object composition. Adapter class “has a” instance of the adaptee class. Very good explanation Lokesh, thank you. Diff between facade and factory pattern? Can we say Hibernate is a real time example of Adaptor design pattern? It converts RDBMS specific query. Thanks Lokesh. This was of great help!!!! Dear Lokesh, Adapter pattern is simple and powerful. Could you please post for Facade pattern as well would be appreciated, Thanks, Bala I will post soon. Hi Lokesh , I liked your simple and straight explanation about concept and you wont eat time in telling big story, that’s really made me crazy to read your articles as and when I get time from my Job. Please do you have real time examples to focus on real time entities on Design pattern planned in future..awaiting for those:) Singleton : Per JVM one object Example: Helper, Utility classes and Service classes using spring Strategy Pattern : WE wanted to display price and based on rule defined by the Author , through UI he switch the price pattern then Spring I used to inject respective. Factory : Used this one scenario for payment gateway Integration, when command pattern asked me to care an object , then Factory will give back the Objects Builder pattern : DB and Front end data compatibility issue, DB stored in Interger and Fromt end need Integer or Front end want with formatting price bla bla … Thanks for your Adptor design pattern. Best Regards Vinod Thanks for the above suggestions. They are really quit interesting. I have added them in my TODO list. Thanks Lokesh!
https://howtodoinjava.com/design-patterns/structural/adapter-design-pattern-in-java/
CC-MAIN-2022-27
refinedweb
1,019
56.66
GUALYN C. WILLIAMS AND MELONEEBRYANT, APPELLANTS,v.UNITED STATES, APPELLEE. Appeals from the Superior Court of the District of Columbia (F-265-06, F-266-06) (Hon. Harold L. Cushenberry, Jr., Trial Judge). The opinion of the court was delivered by: Farrell, Senior Judge Argued December 12, 2008 Before WASHINGTON, Chief Judge, KRAMER, Associate Judge, and FARRELL, Senior Judge.*fn1 A jury found both appellants guilty of distributing cocaine to an undercover police officer. On appeal, their primary argument (indeed, Williams' sole contention) is that the admission of a DEA-7 chemist's report identifying the recovered substance as cocaine, without corresponding testimony by the chemist, violated Crawford v. Washington, 541 U.S. 36 (2004), as applied in Howard v. United States, 929 A.2d 839 (D.C. 2007), and Thomas v. United States, 914 A.2d 1 (D.C. 2006). The government concedes error on the point but argues that Williams has not preserved the error nor shown "plain error," United States v. Olano, 507 U.S. 725 (1993), justifying reversal. As to Bryant, the government agrees that her distribution conviction must be reversed, but contends that the error in admitting the chemist's report was harmless as to the (implicitly tried) lesser-included offense of attempted distribution, which required no proof of the specific identity of the controlled substance. See Thompson v. United States, 678 A.2d 24, 27 (D.C. 1996).*fn2 In light of Howard and Thomas, supra, we agree with the government's concession of error, but reject its argument of non-preservation as to Williams. On the other hand, we conclude that on the facts of this case the error in admitting the DEA-7 report was harmless beyond a reasonable doubt, see Chapman v. California, 386 U.S. 18, 24 (1967), as to the included charge of attempted distribution, leaving the government free on remand to accept entry of convictions of each defendant for that crime. We reject Bryant's remaining claim for reversal. I. MPD Officer Ellerbee, acting undercover, was approached on a street corner by a woman, appellant Bryant, who asked him "what's up" or "what's wrong?" When he replied that he was "trying to get some stones" (a common street name for crack cocaine), Bryant told him she could "take him to it," and she led him to a nearby courtyard. As they walked, she instructed him that if anyone asked, he should say he was her cousin, and she gave him a fake "street name." Ellerbee gave Bryant $25 in pre-recorded police funds and asked her for "three for 25," knowing that drug dealers would often give a five dollar discount for three $10 bags of crack cocaine. Bryant took the money and walked into the courtyard, approaching a man, appellant Williams, who was standing by a set of mailboxes. From his position at the edge of the courtyard, Ellerbee saw Bryant hand Williams the pre-recorded funds and receive something from him in return (a "hand-to-hand" exchange). Bryant then rejoined Ellerbee and, after they had walked away together, produced three ziplock bags of a white rock-like substance, giving him two and keeping one.*fn3 Leaving Bryant, Ellerbee returned to an unmarked police car where MPD Officer Brooks had been watching the undercover purchase. Ellerbee broadcast a lookout for Bryant and Williams and performed a field-test of the white substance,*fn4 which was positive for crack cocaine. An arrest team then located both defendants and arrested them. At trial, Ellerbee testified that he was "very sure" that Bryant was the "person who took [him] to the courtyard and brought [him] the drugs" and that Williams was "the person who [handed] Bryant the drugs that she . . . then . . . brought back to [Ellerbee]." MPD Detective Washington, the government's drug expert at trial, explained that drug transactions often involve two layers of distributors, the person "in charge of the drugs" and a "buffer[], . . . go between[,] or . . . freelancer[]." "Go-betweens" get "the money from the buyer, go to the seller, and get the drugs from the seller, and . . . take the drugs back to the buyer and give it to the buyer." A freelancer is a particular type of go-between who, rather than working directly with the seller, acts independently. A freelancer - "is . . . [an] opportunist"; unlike other go-betweens, freelancers . . . go into these areas and look for individuals who are looking to buy drugs . . . - - that's their sole purpose. . . . [T]hey'll make contact with . . . people [looking to buy drugs] because [the freelancers] know the area, they know who belong and don't belong in these areas, they'll . . . find out what they want, get the money from them, and then go and get the drugs from a person who is selling . . . . And from that point [the freelancers] take the drugs back to the [buyer], and usually what they'll try to do is get rewarded from the buyer . . . they'll try to get part of the drugs or they'll try to get a few dollars for their services rendered. Freelancers who are "from [an] area," Washington further explained, "know everything about that area."*fn5 They "take the big risk," as they "go a little bit beyond to solicit customers because they have a purpose for that . . . to get money or to get drugs." Their success depends on "how . . . the seller feels in allowing these people to work for him," since "these drug dealers . . . will not let outsiders come into the area to work their area." Bryant's defense was that she had been arrested innocently in the courtyard area while walking to visit friends. Williams, by contrast, offered the testimony of a friend that she and Williams were passing through the courtyard when Bryant, whom she knew, tried to solicit drugs (in vain) from Williams, then approached another person and walked away together with him, leading to Williams' mistaken arrest. II. The government's primary evidence that the substance appellants sold was cocaine was the DEA-7 report confirming the laboratory analysis. Appellants both argue that, by not calling as a witness the chemist who did the analysis, the government denied them the opportunity to cross-examine him and thus "confront" the testimonial report. Given our decisions in Howard and Thomas, the government agrees with this in principle but argues, first, that Williams' failure to object on constitutional grounds at trial requires him to show plain error, Olano, supra, something he cannot do in light of our repeated rejection of similar claims. See Thomas, 914 A.2d at 22-24; accord, e.g., Otts v. United States, 952 A.2d 156, 162-163 (D.C. 2008). We are not persuaded, however, that Williams must overcome the plain-error hurdle, given Bryant's objection squarely placing the confrontation issue before the trial court. Normally, a defendant's failure to object on a point subjects his related claim of error on appeal to plain error review. But, "at least in some circumstances, an objection may be preserved when made by a co-defendant." Johnson v. United States, 756 A.2d 458, 462 n.2 (D.C. 2000); see also Bayer v. United States, 651 A.2d 308, 311 n.1 (D.C. 1994) ("[w]hen one co-defendant makes an objection at trial which the other co-defendant does not join, the latter can nonetheless benefit from the objection, on appeal, when it applies equally to his or her own situation."). The reason for this, as we explained in Williams v. United States, 382 A.2d 1 (D.C. 1978), is that the plain error rule is not meant to be "punitive"; instead its purpose is to allow the trial judge "fully to consider issues and thereby avoid potential error, and to afford prosecutors the opportunity to present evidence on the issue raised." Id. at 7 n.12. The government cites other decisions of ours seemingly to the contrary, e.g., Thacker v. United States, 599 A.2d 52, 59 (D.C. 1991) (failure to "poseany objection at trial and [to] join in the motion of" co-defendant subjects belated claim to plain error review). Rather than insist that we resolve the conflict here, however, it limits itself to arguing that Williams should not be allowed to ride "Bryant's coattails" because his failure to join the objection "fairly can be viewed as a tactical choice" - i.e., a desire not to obscure his chosen defense of misidentification. Bryant's defense, however, was also misidentification, and the government all but concedes that it is surmising ("[c]counsel may have reasoned") that Williams was thinking tactically, and was not just asleep
http://dc.findacase.com/research/wfrmDocViewer.aspx/xq/fac.20090226_0000034.DC.htm/qx
CC-MAIN-2017-51
refinedweb
1,444
64
The goal of a C/C++ compiler is to turn every sequence of ASCII characters into executable instructions. OK, not really — though it does seem that way sometimes. The real goal of a C/C++ compiler is to map every conforming input into executable instructions that correspond to a legal interpretation of that input. The qualifiers “conforming” and “legal interpretation” are very important. First, the compiler has extremely weak requirements about what it should do with non-conforming inputs, such as programs that contain undefined behaviors (array bounds violations, etc.). Second, all realistic C/C++ programs have a large number of possible interpretations, for example corresponding to different integer sizes, different orders of evaluation for function arguments, etc. The compiler chooses a convenient or efficient one, and the remaining interpretations are latent. They may emerge later on if the compiler options are changed, if the compiler is upgraded, or if a different compiler is used. The point is that the compiler has no obligation to tell us whether the input is conforming or not, nor how many possible interpretations it has. Thus, while C/C++ compilers are very good at turning conforming programs into efficient executables, they are just about useless for other answering other kinds of questions: - Does the program ever execute undefined behaviors, causing it (in principle) to have no meaning and (in practice) to execute attack code or crash? - Does the program rely on unspecified behaviors, making it non-portable across compilers, compiler versions, and changes in compiler options? - Does the program rely on implementation-defined behaviors, affecting its portability to other compilers and platforms? - Why does the program behave in a certain way? In other words, what part of the standard forced that interpretation? To answer these questions, a wide variety of static analyzers, model checkers, runtime verifiers, and related tools have been developed. These tools are great. However, even taken all together, they are incomplete: there exist plenty of bad (or interesting) program behaviors that few or none of them can find. For example: - Very few tools exist that can reliably detect uses of uninitialized storage. - Few, if any, tools can correctly diagnose problems resulting from C/C++’s unspecified order of evaluation of function arguments. - An lvalue must not be modified multiple times, or be both read and written, in between sequence points. I’m not aware of many tools that can correctly detect that evaluating this function results in undefined behavior when p1 and p2 are aliases: int foo (int *p1, int *p2) { return (*p1)++ % (*p2)++; } - There exists C code subtle enough that multiple independent compiler teams get it wrong. Miscompilations are, by definition, out of reach for source-level analysis tools. The Missing Tool The missing tool (or one of them, at any rate) is an executable semantics for C. An executable semantics is an extremely careful kind of interpreter where every action it takes directly corresponds to some part of the language standard. Moreover, an executable semantics can be designed to tell us whether the standard assigns any meaning at all to the program being interpreted. In other words, it can explicitly check for all (or at least most) undefined, unspecified, and implementation-defined behaviors. For example, when an executable semantics evaluates (*p1)++ % (*p2)++, it won’t assign a meaning to the expression until it has checked that: - both pointers are valid - neither addition overflows (if the promoted types are signed) - p1 and p2 are not aliases - *p2 is not 0 - either *p1 is not INT_MIN or *p2 is not -1 Moreover, the tool should make explicit all of the implicit casts that are part of the “usual arithmetic conversions.” And it needs to do about 500 other things that we usually don’t think about when dealing with C code. Who Needs an Executable Semantics? Regular programmers won’t need it very often, but they will occasionally find it useful for settling the kinds of annoying arguments that happen when people don’t know how to read the all-too-ambiguous English text in the standard. Of course, the executable semantics can only settle arguments if we agree that it has captured the sense of the standard. Better yet, we would treat the executable semantics as definitive and the document as a derivative work. Compiler developers need an executable semantics. It would provide a simple, automated filter to apply to programs that purportedly trigger compiler bugs. A web page at Keil states that “Fewer than 1% of the bug reports we receive are actually bugs.” An executable semantics would rapidly find code fragments that contain undefined or unspecified behaviors — these are a common source of bogus bug reports. Currently, compiler developers do this checking by hand. The GCC bug database contains 4966 bug reports that have been marked as INVALID. Not all of these could be automatically detected, but some of them certainly could be. People developing safety-critical software may get some benefit from an executable semantics. Consider CompCert, a verified compiler that provably preserves the meaning of C code when translating it into assembly. CompCert’s guarantee, however, is conditional on the C code containing no undefined behaviors. How are we supposed to verify the absence of undefined behaviors when existing tools don’t reliably check for initialization and multiple updates to lvalues? Moreover, CompCert is free to choose any legitimate interpretation of a C program that relies on unspecified behaviors, and it does not need to tell us which one it has chosen. We need to verify up-front that (under some set of implementation-defined behaviors) our safety-critical C program has a single interpretation. My students and I need an executable semantics, because we are constantly trying to figure out whether random C functions are well-defined or not. This is surprisingly hard. We also need a reliable, automated way to detect undefined behavior because this enables automated test case reduction. An Executable Semantics for C Exists I spent a few years lamenting the non-existence of an executable C semantics, but no longer: as of recently, the tool exists. It was created by Chucky Ellison, a PhD student at the University of Illinois working under the supervision of Grigore Rosu. They have written a TR about it and also the tool can be downloaded. Hopefully Chucky does not mind if I provide this link — the tool is very much a research prototype (mainly, it is not very fast). But it works: regehr@home:~/svn/code$ cat lval.c int foo (int *p1, int *p2) { return (*p1)++ % (*p2)++; } int main (void) { int a = 1; return foo (&a, &a); } regehr@home:~/svn/code$ kcc lval.c regehr@home:~/svn/code$ ./a.out ============================================================= ERROR! KCC encountered an error while executing this program. ============================================================= Error: 00003 Description: Unsequenced side effect on scalar object with value computation of same object. ============================================================= File: /mnt/z/svn/code/lval.c Function: foo Line: 2 ============================================================ As I mentioned earlier, very few tools for analyzing C code find this error. Chucky’s tool can also perform a state space exploration to find order of evaluation problems and problems in concurrent C codes. Finally, it can run in profile mode. Unlike a regular profiler, this one profiles the rules from the C semantics that fire when the program is interpreted. This is really cool and we plan to use it to figure out what parts of the C standard are not exercised by Csmith. Chucky’s tool is already an integral part of one of our test case reducers. This reducer takes as input a huge, ugly, bug-triggering C program generated by Csmith. It then uses Delta debugging to output a much smaller bug-triggering program that (ideally) can be included in a compiler bug report without further manual simplification. Before Chucky’s tool arrived, we had spent several years trying to deal with the fact that Delta always introduces undefined behavior. We now seem to have a bulletproof solution to that problem. The benefits of executable semantics have long been recognized in the PL community. The new thing here is a tool that actually works, for the C language. Hopefully, as Chucky’s tool matures people will find more uses for it, and perhaps it can even evolve into a sort of de facto litmus test for ascertaining the meaning — or lack thereof — of difficult C programs. * both pointers are non-NULL * neither addition overflows (if the promoted types are signed) * p1 and p2 are not aliases * *p2 is not 0 * either *p1 is not INT_MIN or *p2 is not -1 Since the standard allows to compute t+n for an array t of size n, which it then forbids to dereference, I would argue that the first condition should be “both pointers are valid”. But this is only one way a pointer can be invalid. Another is to point to a local variable that has gone out of scope. In Frama-C’s value analysis, this check used to require in the first implementation a pass on the entire state, to see which variable was pointing to variables that had gone out of scope. The current implementation spends some time tracking who contains addresses of locals to save time when a block is exited. Do you know how KCC does this? Note that Frama-C’s value analysis does check all the conditions above and emit an alarm each time one of them seems not to be verified (it may stop propagation at the first one, like a KCC-compiled program does, but reserves the right not to do so). For historical reasons, you need to activate signed arithmetic overflow detection with -val-signed-overflow-alarms in order to get a warning for the last condition (there is no option to activate the detection only for division). Option -unspecified-access must be set to detect interfering side-effects caused by pre/post-decrement operators. Side effects of function calls are only taken into account in a separate, undistributed plug-in. Hi Pascal. Here is an example of your first question. int main(void){ int* p; { int x; p = &x; } *p; } [celliso2@fsl3 c-semantics]$ kcc cuoq.c [celliso2@fsl3 c-semantics]$ ./a.out ============================================================= ERROR! KCC encountered an error while executing this program. ============================================================= Error: 00007 Description: Referring to an object outside of its lifetime. ============================================================= File: /home/grosu/celliso2/c-semantics/cuoq.c Function: main Line: 7 ============================================================= The way that this is handled is pretty straightforward. The lifetime of variables is enforced in the semantics by deleting (marking the block dead) that memory as soon as its life is over. Then, if in the future the program tries to dereference this memory, the semantics sees that the memory no longer exists. Actually, the standard is even more strict than that. It says “The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime” (n1548 6.2.4:2). This means it’s possible just reading the pointer (p; instead of *p; above) is undefined. My semantics can do this, but I have it turned off because it’s annoying. It should be an option available to the user in the future. The “or just past” clause is because you are actually allowed to create a pointer that points to t+n+1 for array t an length 1, in order to make loops over arrays easy to write. Of course, you still can’t dereference t+n+1. Incidentally, you are not allowed to create a pointer t-1, even though you see decrementing loops over arrays a lot. Finally, the memory itself is being handled symbolically, so that this program emits an error: int main(void){ int x, y; return &x < &y; } and this program succeeds: int main(void){ int a[3]; return &a[0] < &a[2]; } As John said, we don't want to allow users to write code that relies on unspecified behavior. Ah, obviously I can’t count. You’re right, it’s just t+n for array t of length n. E.g, for int a[3]; a[3] is a valid pointer, but not dereferencable. My point was that it’s one past what you’re allowed to dereference, although I messed up the arithmetic. It’s a good thing we have computers to do this for us! Pascal, of course you’re right about the valid pointers vs. non-null. Is it possible to invoke Frama-C in interpreter mode? One of the things that’s really nice about Chucky’s tool is its complete lack of false positives. Hello John, we have just discussed this a bit with Chucky by e-mail. I do not think that you will get either interesting new features or speed from doing so, but Csmith-generated programs can be “interpreted” by the value analysis with options -no-results -slevel 999999 -val. I have been doing this in the background for a while. As you say, there aren’t supposed to be false positives in this mode, so this is good for looking for “loss of precision” bugs, whereas the first technique we had discussed is only good for finding correctness bugs. In the development version you have access to, there are no known issues that would cause a completely unrolled analysis of a Csmith-generated program not to remain precise until the end, with both -machdep x86_64 and the default -machdep x86_32. The only alarms that very rarely pop up are related to addresses of locals being used out of scope, considering that the value analysis considers “passing as an argument to a function” as “using” (which it wouldn’t have to do, but when the called function’s code is unavailable, you can’t hope to postpone the alarm until the dangling pointer is actually used because the actual use may be in the missing code, and then for consistency it was easier to warn when a dangling pointer is passed to a function even when that function’s code is available). Do you want me to send in a bug report against the official Csmith 2.0.0 version? John, The Model Implementation C Checker was written over 20 years ago and detects all undefined, implementation defined and unspecified behaviors. It is essentially a compiler, linker and interpreter. Some description of what it does here,. There was never a commercially significant market for the runtime checks (it did all the uninitialised variable and pointer must point at an object {it even checked that two compared pointers pointed at the same object}). The front end morphed in OSPC,, and also got licensed to a static analysis vendor. Derek, Is it possible to obtain a copy of the Model Implementation C Checker, or any documentation, TR, whitepaper, or paper about it? I’m interested in knowing how that tool works. I’ve been unable to find essentially anything except for your link you posted above. From your description, it sounds like my tool is entirely redundant! Derek this is very interesting. I echo Chucky’s request for more information. I’m curious why you say there was never a market for the runtime checks: Purify and related tools have enjoyed a reasonable degree of success, right? Valgrind, while not a commercial product, is heavily used. Pascal, thanks for the details. Yes, if you have found a bug in Csmith 2.0.0 we’d certainly like to hear about it. Of course, in the meantime, Xuejun is busily hacking new features into Csmith. We’re working on getting Csmith into github, at which point you’ll be able to run the latest version, which of course is where we’re most interested in bug reports. Chucky, Your tool is not redundant there are all sorts of things that could be done with it; also it is C99 while the Model implementation is C90 and you could look for inconsistencies in the specification, ie bugs in the C Standard). I was rather discouraged by the response to the Model Implementation and never wrote anything up for publication. Very few people understand the benefits of runtime checking, even Boundschecker,, whose executables run an order of magnitude faster than the Model Implementation has few users. The Model Implementation was written by three guys, it used the compiler/linker/interpreter approach, who tried real hard to follow the exact wording of the C Standard. The runtime checking worked at the byte level and so if two bit-fields occupied the same byte and initialization of one of them would cause the other to be treated as initialized, also it would not detect unspecified behavior caused by pointer aliasing (considered to have too high an overhead for the likely benefit; we were aiming for real world use). A good test of the quality of a ‘checking’ implementation is how many bugs it finds in the language standard. The US members of WG14 got rather tired of lists,, of what they considered nit picking problems in the C Standard and some suggested improvements have only just made it into the latest standard, You ought to try and find at least one ambiguity in the C Standard. I was interested to see that your tool will print out a profile of the appropriate C semantics as it processes code. We cross referenced if statements in the Model Implementation to requirements in the C Standard as method of checking that all requirements were covered and somebody suggested that there ought to be an option to print these out as code was processed. One possible use for this profiling ability is to be able to warn developers when they are making use of obscure corners of the language; obscure might be measured in terms of frequency of use, which as this experiment suggests, is a possible cause of developer misunderstanding. Have yo tried some of the more obscure examples from my C book? You might be interested in this paper on forms of language specification: John, You might like to look at Coccinelle as a very useful tool for matching fragments of C source: Grrr, you are still referring to CompCert as a verified compiler. I saw somebody repeat your claim on a mailing list the other day. CompCert is a great achievement and including Chucky’s tool as a front end it would be a step closer to it becoming a verified compiler.
https://blog.regehr.org/archives/523
CC-MAIN-2021-43
refinedweb
3,075
50.57
On 9/27/2010 11:37 AM, Michael Albinus wrote: Jan Djärv<address@hidden> writes:* dbus_fd_cb calls only xd_read_queued_messages. Couldn't both functions be merged? Or, since we have the file descriptor in the callback, shouldn't we call only xd_read_message for that socket?Yes and yes. I was lazy, I saw that xd_read_queued_messages wasn't static and kept it just in case. I wasn't sure how to get the DbusConnection from a fd so I skipped that. But feel free to make any changes you think appropriate. I don't think xd_get_dispatch_status and xd_pending_messages are used for example.I've tried to adapt it as much as possible. I've kept xd_read_queued_messages in order to be able to catch errors from xd_read_message.* We assume that communication is socket base. This must not be true; see the comment in <>. If xd_find_watch_fd returns -1, we shall raise an error at least.I'm not sure what you mean. If you look at the code, the functions dbus_watch_get_fd, dbus_watch_get_unix_fd and dbus_watch_get_socket all return the same thing, watch->fd. We don't really assume socket, any fd that can be passed to select will do. In practice on Unix-like systems, we can't get -1 (minus dbus-bugs of course).Yes, you are right. If dbus_watch_get* returns something less than zero, we silently return as well. This might be sufficient.? === modified file 'src/keyboard.c' --- src/keyboard.c 2010-07-05 17:16:59 +0000 +++ src/keyboard.c 2010-09-27 19:33:05 +0000 @@ -4107,7 +4107,7 @@ interrupt handlers have not read it, read it now. */ /* Note SIGIO has been undef'd if FIONREAD is missing. */ -#ifdef SIGIO +#if defined (SIGIO) || defined (CYGWIN) gobble_input (0); #endif /* SIGIO */ if (kbd_fetch_ptr != kbd_store_ptr)If this is OK, I have one more question: How do I guarantee that the patch doesn't propagate to the trunk? Is it enough to say in the log message that it's for emacs-23 only? Ken
http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01478.html
CC-MAIN-2016-50
refinedweb
330
77.64
> I would ask everybody who has an opinion to vote. This issue has > implications which effect all Apache developers. I will tally the votes > and report them on Monday morning. This gives everybody plenty of time > to vote on this issue. > I would like to see the prefix for apr functions to be: > > [ ] ap_ [X] apr_ [ ] I don't care. I think it would be better to have more prefixes ( like apr_thread_, apr_io_, apr_mutex_) More information in the function name -> easier to use the function. 2 "categories" ( specified in method name ) are better than 1 category. In C++ and java the class name helps a lot. A flat namespace may be harder to use. Costin
http://mail-archives.apache.org/mod_mbox/httpd-dev/199905.mbox/%3CPine.LNX.4.10.9905191027150.5860-100000@simonam.pacbell.net%3E
CC-MAIN-2014-52
refinedweb
115
75.5
GarethJ's WebLog - Code generation and abstraction. With the pre-processed templates and winforms binding of model, do you see the enabling of VS 2010 scenarios where the models can be re-used outside of VS for interrogation, modification and transformation. In other words, will similar de-coupling from VS core be occurring in the modeling namespaces? I guess you could say that the equivalent decoupling has always been there for modeling. If you look at this work as an exercise in using the pieces without any reference to the VS product assemblies, then the equivalent is the fact that the models serialize as easily parseable XML that can be read with regular .Net XML code. Now T4 will also spit out code that only relies on regular .net code too.
http://blogs.msdn.com/garethj/archive/2008/11/12/dsl-2010-feature-dives-t4-preprocessing-part-two-basic-design.aspx
crawl-002
refinedweb
131
63.8
From: Randy Kramer (rhkramer@fast.net) Date: Sat Aug 30 2003 - 13:34:50 EDT Martin, Thanks for the response -- some comments below! On Saturday 30 August 2003 10:20 am, msevior@physics.unimelb.edu.au wrote: > This got me thinking thinking for a post 2.0 feature. Alt-S Selects style > drop down box, naviagte it with up/down arrows, select with return. > > We'd need to define a simple way to escape this if a user accidently > enabled the feature since it would basically steal the keyboard focus. > > Maybe clicking anywhere witht eh mouse would put the focus back in abiword. That sounds ok (trying to sound unenthusiastic), but I'd really rather have the ability to assign styles directly using keyboard shortcuts (assignable by me) -- in Word I had pretty much (muscle) memorized (not that it takes much effort) <ctrl><alt><shift> (with one hand) and n (for normal), 1 thru 9 (for headings 1 thru 9), etc. (with the other hand). (The <ctrl><alt><shift> was an aberration, but it was the only combination key "namespace" that Word hadn't used at least a little bit of for one thing or another. Today I'd look seriously at the <windows> key (forget what it's called in Linux) -- works well for my Nedit macros.) > >> What are AbiWord's macro capabilities? > > > > I'm not at all clear on that myself, so can offer no response. > > Write them in perl, python or C as a plugin. Sorry we don't record > keyboard strokers for replay. > > It would be simple enough to do but we've just had too many other things > to do. I searched bugzilla and couldn't find it, so I created bug (RFE) 5681 () -- will add a few votes shortly. regards, Randy Kramer ----------------------------------------------- To unsubscribe from this list, send a message to abiword-user-request@abisource.com with the word unsubscribe in the message body. This archive was generated by hypermail 2.1.4 : Sat Aug 30 2003 - 13:38:44 EDT
http://www.abisource.com/mailinglists/abiword-user/2003/Aug/0151.html
CC-MAIN-2014-35
refinedweb
337
73.78
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards A number in VMD is a preprocessing 'pp-number', limited to a Boost PP number. This is an integral literal between 0 and 256. The form of the number does not contain leading zeros. Acceptable as numbers are: 0 127 33 254 18 but not: 033 06 009 00 As can be seen from the explanation of an identifier, a number is merely a small subset of all possible identifiers, for which VMD internally provides registration macros for its use and pre-detection macros for its use. Therefore any number in VMD is called BOOST_VMD_IS_NUMBER. The macro takes a single parameter, the input to test against. The macro returns 1 if the parameter is a Boost PP number, otherwise the macro returns 0. The Boost PP library has a great amount of functionality for working with numbers, so once you use VMD to parse/test for a number you can use Boost PP to work with that number in various ways. The VMD makes no attempt to duplicate the functionality of numbers that in the Boost PP library. Any number is also an identifier, which has been registered and pre-detected, so you can also use the VMD functionality which works with identifiers to work with a number as an identifier if you like. Let us look at an example of how to use BOOST_VMD_IS_NUMBER. #include <boost/vmd/is_number.hpp> BOOST_VMD_IS_NUMBER(input) returns: if input = 0, 1 if input = 44, 1 if input = SQUARE, 0 if input = 44 DATA, 0 since there are tokens after the number if input = 044, 0 since no leading zeros are allowed for our Boost PP numbers if input = 256, 1 if input = 257, 0 since it falls outside the Boost PP number range of 0-256 if input = %44, does not meet the constraint therefore undefined behavior if input = 44.0, does not meet the constraint therefore undefined behavior if input = ( 44 ), 0 since the macro begins with a tuple and this can be tested for To use the BOOST_VMD_IS_NUMBER macro either include the general header: #include <boost/vmd/vmd.hpp> or include the specific header: #include <boost/vmd/is_number.hpp>
http://www.boost.org/doc/libs/1_61_0/libs/vmd/doc/html/variadic_macro_data/vmd_specific/vmd_number.html
CC-MAIN-2017-43
refinedweb
380
55.27
I want to take any user input integer between 1 and 9999 and return that number with its digits reversed. The problem with my code is it's returning the sum of the entered integer and I have no idea how to fix it. This is the code that that I came up with so far: import java.util.Scanner; class Reverse{ public static void main(String []args){ Scanner input = new Scanner(System.in); System.out.print("Enter a number between 1 and 9999: "); int user = input.nextInt(); if(user>1 && user<9999){ System.out.println("The number with its digits reversed is : " + reverseDigit(user)); }else{ System.out.println("Invalid Input"); } } public static int reverseDigit(int num){ return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000); //This is the problem } } You could replace : return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000); with: return ((num%10)*1000 + ((num%100)/10 )*100+ ((num%1000)/100)*10 + num/1000); The reason that the first was wrong is because you get: last digit:num%10 third digit:num%100)/10 second digit:(num%1000)/100 first digit:num/1000 so you was just adding all the digits before But the Above works only for numbers from 1000-9999 .So you could replace the reverseDigit method with this simple method that works for every number: public static int reverseDigit(int num){ int reverse=0; while( num != 0 ) { reverse = reverse * 10; reverse = reverse + num%10; num = num/10; } return reverse; }
https://codedump.io/share/USz7GWav2IY2/1/reversing-a-user-input-digit-using-methods
CC-MAIN-2017-13
refinedweb
249
60.35
View Report Button in workspaceJohn Haddad Nov 16, 2018 2:31 PM Hi why there is no view report in workspace ! is it possible to add print button using crystal report ?! thanks 1. Re: View Report Button in workspaceMotazAlqaissi Nov 19, 2018 2:03 PM (in response to John Haddad) By design there is *still* no print button as the one available in Webacess. However, I always tend to use a calculation field which points into a pre-designed report similar to the ones used in Webaccess and use it in Workspace. The below article shall guide you through the needed steps to achieve that: Replacing the standard print function in Web Access with a Print Icon Motaz Tjdeed Technology 2. Re: View Report Button in workspaceMotazAlqaissi Nov 19, 2018 2:05 PM (in response to John Haddad) By the way, you can always raise new ideas/enhancement requests for such unavilable features Motaz 3. Re: View Report Button in workspaceJohn Haddad Dec 5, 2018 2:48 AM (in response to MotazAlqaissi)1 of 1 people found this helpful Motaz i can use the existing reports and landesk engine to generate the report , with no need to upload report files into crystal server the issue is only that when i create new process the "Printer icon" will appear . import System static def GetAttributeValue(Request): Image = '' Item = Request.Guid if Request.Status.Title != null: return String.Format("<a href='{0}'><img title='Print' src='{1}' height='40px' width='40px'></a>", Item, Image) and it can be used on workspace 4. Re: View Report Button in workspaceJulian Wigman Dec 5, 2018 10:50 PM (in response to John Haddad)
https://community.ivanti.com/thread/68503
CC-MAIN-2019-13
refinedweb
277
58.32
11464/how-is-a-transaction-public-key-related-to-original-public Contrary to the popular belief, it is ...READ MORE Blockchain relies on the number of nodes ...READ MORE Technically, it's not difficult at all, all ...READ MORE You can try the following: you can only ...READ MORE Summary: Both should provide similar reliability of ...READ MORE This will solve your problem import org.apache.commons.codec.binary.Hex; Transaction txn ...READ MORE This was a bug. They've fixed it. ...READ MORE You can do this by developing a ...READ MORE You can not use configtxlator tool for ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/11464/how-is-a-transaction-public-key-related-to-original-public
CC-MAIN-2019-47
refinedweb
109
63.66
WCF makes it easy to call the SharePoint web services using WCF. In this post, I’ll show how to call the Lists.asmx web service and show the few things you need to take into account. Just like if you were using ASMX web services, the place to start is to create a reference to the SharePoint Lists.asmx web service. This is done by appending “/_vti_bin/Lists.asmx” to the end of a site name. This is the first important thing to realize: the Lists.asmx web service is relative to a specific site. If I have a site collection with a top-level site at, and a child site, you will run into issues if you use and try to retrieve data from a list on the child site. Now that you know how to choose the appropriate URL, pop open a Visual Studio 2008 project and use the Add Service Reference dialog. Enter the URL into the Address box, and click Go. That will query the WSDL for the Lists.asmx service, the representation of which is shown below. You’ve now created the proxy, but you’re not done yet. Next step… authentication. Once you’ve created the proxy, the next step is to configure the security to be able to call the service methods. By default, SharePoint uses NTLM for authentication. There’s not really a way for the WSDL to express the fact that the web application requires Windows Integrated Authentication using NTLM or Kerberos, so we need to fill in that detail. We can do this by altering the bindingConfiguration to indicate the transport uses NTLM authentication. 1: <?xml version="1.0" encoding="utf-8" ?> 2: <configuration> 3: <system.serviceModel> 4: <bindings> 5: <basicHttpBinding> 6: <binding name="ListsSoap"> 7: <security mode="TransportCredentialOnly"> 8: <transport clientCredentialType="Ntlm" /> 9: </security> 10: </binding> 11: </basicHttpBinding> 12: </bindings> 13: <client> 14: <endpoint 15: address="" 16: binding="basicHttpBinding" 17: bindingConfiguration="ListsSoap" 18: contract="ServiceReference1.ListsSoap" 19: 20: </client> 21: </system.serviceModel> 22: </configuration> The biggest point to note is represented on lines 7 and 8, where we specify the security mode (TransportCredentialOnly) and the type of credential (Ntlm). This tells WCF to use integrated authentication using NTLM. Since we’ve specified NTLM as the security mechanism, we need to supply the correct credentials to WCF. To use the credentials of the user running the client application, the following works fine. ServiceReference1.ListsSoapClient proxy = new ConsoleApplication4.ServiceReference1.ListsSoapClient(); proxy.ClientCredentials.Windows.ClientCredential = new NetworkCredential(); XmlElement lists = proxy.GetListCollection(); Now that we’ve successfully created a proxy and configured the security correctly, the next step is to start calling methods on the server... which leads to our next configuration item. When you call the services for SharePoint, they can return a very large amount of data. This amount of data can represent the schema for a list that contains many columns, a list with many columns that contains a lot of data, or any combination. There are 2 things you need to configure. The first is the potential size of the entire message. WCF throttles this way down to help protect you against denial of service attacks caused by enormous payloads. You can increase the maxReceivedMessageSize to some number. I have it exorbitantly high here only for illustration… the recommendation is to throttle it to some sensible number. Similarly, the data returned from the ASMX service can contain really long attribute names, causing WCF to reject the message because it exceeds the default policy. Again, I have the readerQuotas set ridiculously high for illustration, you should set it to something more reasonable. Change the app.config to look like this: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> </configSections> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="ListsSoap" maxReceivedMessageSize="9999999"> <readerQuotas maxBytesPerRead="9999999" /> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Ntlm" /> </security> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="ListsSoap" contract="ServiceReference1.ListsSoap" name="ListsSoap" /> </client> </system.serviceModel> </configuration> OK, we’ve configured for security and potentially huge messages. Now, let’s look at the data that comes back from one of these services. The return formats for methods in the Lists service are documented in the MSDN online SDK, but let’s take a look at one of them. Go to the Visual Studio 2008 Tools directory in your programs start menu, and look for the Visual Studio 2008 Command Prompt. Open that up and type “svcconfigeditor.exe”, and then open up the app.config file for your application. This is an incredibly handy utility to set properties of your WCF client or service. I find it especially handy to configure logging. Go to the Diagnostics node, and you’ll see a screen that looks like this. Turn on “Log Auto Flush” and “Message Logging” as shown in the picture. Now, go to the child node in the treeview called “Message Logging”, we’ll configure WCF to log the entire message so we can have a peek at it. You should be at a point where you can simply run the 3 lines of code that we wrote earlier in this post. Once it runs without errors, you should be able to see a new file called app_messages.svclog. Open that file using the utility “svctraceviewer.exe” (run the Visual Studio 2008 Command Prompt again). You should see 2 messages, the request and the response. The complete XML payload for mine looks like: I couldn’t post the actual payload, because it’s pretty huge even for the few number of lists that we have here. Hence why we needed to increase the readerQuotas and maxReceivedMessageSize earlier in the post. The returned data is XML, and some of it is downright unfriendly to work with (a lot of it uses the old ADODB.Recordset XML format). Second, the returned data is represented as an XmlElement (you all know my thoughts on this one, but it’s there nonetheless). So, you need to learn how to coerce the XML out of the XmlElement type into something useful. The first way is to simply query it using XPath and iterate over it. Here’s where the XPathNavigator type comes in handy. void DumpListCollection(ServiceReference1.ListsSoapClient proxy, System.IO.TextWriter writer) { XmlNode node = proxy.GetListCollection(); XPathNavigator nav = node.CreateNavigator(); XPathNodeIterator iter = nav.SelectDescendants("List", "", false); while (iter.MoveNext()) { string title = iter.Current.GetAttribute("Title", string.Empty); string id = iter.Current.GetAttribute("ID", string.Empty); writer.WriteLine("{0}\t\t{1}", title, id); } writer.Flush(); } It’s simple, really. Create an XPathNavigator and choose the XPath statement that you want to work with. The XPathNavigator also exposes helpful methods (SelectChildren, SelectAncestors, SelectDescendants, etc) that make the XPath a little easier if you’re not one of those who well up with pride at convoluted XPath queries. OK, that’s easy enough, just iterate over the nodes. Now, let’s look at the return data for one of those old ADODB.Recordset schema methods that I mentioned before, which is what the GetListItems method returns. <?xml version="1.0" encoding="utf-8" ?> <listitems xmlns=""> <rs:data <z:row ows_ContentTypeId="0x010400FC18B450FF380C439C2CDDF2ED7A29F1" ows_Title="Get Started with Windows SharePoint Services!" ows_LinkTitleNoMenu="Get Started with Windows SharePoint Services!" ows_LinkTitle="Get Started with Windows SharePoint Services!" ows_Body="<div class=ExternalClass6C9D36A90B784F649E081ED819ED11F4>Microsoft Windows SharePoint Services helps you to be more effective by connecting people, information, and documents. For information on getting started, see Help.</div>" ows_Expires="2009-03-07 06:47:57" ows_ID="1" ows_ContentType="Announcement" ows_Modified="2009-03-07 06:47:57" ows_Created="2009-03-07 06:47:57" ... xmlns: </rs:data> </listitems> I elided quite a bit for brevity’s sake here. When confronted with this XML that only it’s author could possibly love (and that is even questionable), how are you expected to work with this data? Turns out to be incredibly easy if you use a System.Data.DataTable that reads from an XmlNodeReader. void DumpListItems(ServiceReference1.ListsSoapClient proxy, System.IO.TextWriter writer) { XmlDocument xmlDoc = new System.Xml.XmlDocument(); XmlElement ndQuery = xmlDoc.CreateElement("Query"); XmlElement ndViewFields = xmlDoc.CreateElement("ViewFields"); XmlElement ndQueryOptions = xmlDoc.CreateElement("QueryOptions"); XmlElement items = proxy.GetListItems("Announcements", null, ndQuery, ndViewFields, null, ndQueryOptions, null); using (DataSet ds = new DataSet()) { ds.ReadXml(new XmlNodeReader(items)); ds.WriteXml(writer); } } This is cool because it makes data binding incredibly easy using the resulting DataSet. You could, for instance, bind the DataSet to a grid and display the data. You could also limit the number of fields that are returned to make the payload smaller and more relevant. See the example for the GetListItems method to understand the query, viewfields, and queryoptions parameters. It’s also helpful to see my example above because you don’t have to provide extensive CAML for the 3 parameters, you only need to pass in an XmlElement with the correct element name. I agree, LINQ to XML is hotness, and makes XML programming incredibly easy. However, getting to the XML data using LINQ to XML can be frustrating because there’s not an IEnumerable collection to iterate over. Instead of building integration into the existing System.Xml datatypes, the LINQ to XML folks left that as an exercise to the reader. Suppose you want to query the returned data and stuff it into a generic list. Turns out to be pretty easy, you just have to get creative with the LINQ syntax. public IEnumerable<SPList> GetLists(ServiceReference1.ListsSoapClient proxy) { XmlElement listNodes = proxy.GetListCollection(); var q = from c in listNodes.ChildNodes.Cast<XmlNode>() select new SPList() { ListID = c.Attributes["ID"].Value, Title = c.Attributes["Title"].Value }; return q; } public class SPList { public string ListID { get; set; } public string Title { get; set; } public override string ToString() { return string.Format("{0} - {1}", Title, ListID); } } In order to access the XmlNode type using LINQ, you can cast the XmlNodeList type, allowing you to query it! Pretty slick little trick, and enables you to use LINQ over the boring ol’ System.Xml namespace. Methods for the Lists service in SharePoint Using LINQ to XML (ScottGu’s blog) WCF Developer Center Super Easy Way to Add WCF to SharePoint 2007 (Sahil Malik has done a tremendous job fighting WCF and SharePoint and has written some great articles and code to help us mere mortals) SharePoint and Web Services (one of the first articles I ever read on SharePoint’s web services, and still a great read on the topic) Example for the GetListItems method (help you understand the CAML that *can* be sent, but don’t have to). PingBack from Hey Kirk, Thanks for the linkage. I feel WCF makes SharePoint a tonne much more flexible and better. Would love to have a multi-beer conversation with you on this at some point. Regards, Sahil Introduction Integrating external applications with SharePoint data and functionality is pretty easy, So this is a great blog post and it answers a lot of the questions I had. However, tried to apply this to custom list in my farm and I am having a hard time getting the linq statement to work. Is the syntax different when you are pull information from a particular list using GetListItems? Part 4 of the SharePoint for Developers screencast series has been posted to Channel9… this one focusing
http://blogs.msdn.com/b/kaevans/archive/2009/03/10/calling-sharepoint-lists-web-service-using-wcf.aspx
CC-MAIN-2015-11
refinedweb
1,872
58.08
Steve Langasek writes... > That's a fine goal, but I believe it's out of scope for the LSB, and I don't > want to see the ability of distros to conform to the LSB compromised by some > poorly designed attempt to enforce common init script names. As I pointed out in another mail, the LSB can't mandate this due to it's trailing edge nature. If someone could accomplish this goal *then* it would be in the scope of the LSB and could be added. > The issue isn't even that the LSB mandates that distros use common init > script names for particular services (it doesn't); the issue is that the LSB > says that LSB packages are allowed to use any init script names that haven't > previously been registered with LANANA. There is no sane reason why a > Debian packager should have to contact LANANA first for clearance before > adding a new init script to his or her package; this is useless bureaucracy, > offering no real advantages over requiring *only* LSB packagers to register > with LANANA (which they'll have to do anyway). Hmm, I just re-read FHS-NAME-RULES and I see the problem you are pointing out. I had assumed LANANA just dealt with the "lsb-" and "domainname-" but the above says it owns "[a-z0-9]" too, yuck. Could we count on LANANA to not issue names that would conflict with existing distros in sort of a "prior art" manner? This would require a way to query all distro namespaces I guess (at least it's easier than a patent prior art search). I still don't like that though. It only fixes the problem of LANANA issuing something we're already using, and not the converse case, all new distro packages would need to check with LANANA to ensure they didn't conflict with something LANANA had handed out. > >. > > Frankly, I couldn't care less about cross-distro administration frameworks. This isn't the LSB charter anyway. In the past I've considered the idea of an LSB-sysadmin standard. LSB = binary application portibility LSB-sysadmin = sysadmin portibility :) -- Matt Taggart taggart@debian.org
https://lists.debian.org/debian-project/2005/10/msg00013.html
CC-MAIN-2015-48
refinedweb
362
67.08
Writing Applications in the Cloud with Visual Studio Online Introduction With the move to cloud-based services, even project development has gone to the "clouds". Microsoft now offers Visual Studio Online, which supports all aspects of project development in the cloud. In earlier articles and, we got some insights into the offering. In this article, we will explore how we can actually code and build using the new "Visual Studio Online" offering. Hands On Figure 1: Creating a new project Click the "Create Project" button to create the project. Next, if you have not installed the Visual Studio 2013 Update 2, please install it now. Next, we will create a demo application in Visual Studio 2013 and configure it to have our source code hosted at Visual Studio Online. Fire up Visual Studio 2013, and create a new Windows Desktop console project titled "DemoConsoleApp". Make sure you have the "Add to source control" checkbox checked and click OK. Figure 2: Creating a new DemoConsole app Select Team Foundation Version Control when prompted to select the source control system for the new project. Figure 3: Choosing the source control Select the Project we created in Visual Studio Online and click OK. If the mapping of the project hasn't been done before, you will be asked to map the Visual Studio Online project to a local workspace. Figure 4: Adding the app to the demo Our project is now created locally. At this time, we should, as a best practice, commit the project to the source control. To do that, go to Team Explorer. Figure 5: In Team Explorer Your team explorer window will appear as shown in Figure 6. Figure 6: The Team Explorer screen Click the Pending Changes link to view the open changes that need to be committed. Figure 7: The Pending Changes screen To commit the code, we have the option to get a code review or skip and commit it directly. For our demo, we will commit directly. Enter a comment and click the "Check In" button. You will be asked to confirm the commit. Figure 8: The Check-in Confirmation screen Click Yes to proceed with the commit. Once the commit is successful, you will not see any open changes. Next, we will set up "building our changes" in the cloud. Building in the Cloud Go to Team Explorer Home and click Builds. Figure 9: The Builds button is available You will see the Build view. Figure 10: The Build view Click "New Build Definition" to start creating a build definition. We will see the workflow step to creating a new build definition. Figure 11: Creating a new build definition We can define the trigger for auto builds, but select "Trigger" now. For our case, we will make this "Continuous integration" to build the changes after each check-in. Figure 12: Defining the trigger for auto builds Click the Save button to save the build definition. Next, we will make code changes and commit it to see the automated build step in action. We will intentionally cause a build-break by missing a ";" at the end of the statement. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoConsoleApp { class Program { static void Main(string[] args) { Console.Write("hello") } } } Check in the new change. Open the Pending changes view on Team Explorer and click "Check in". Figure 13: The Pending Changes window Next, we will visit the Builds view on Team Explorer to check the status of the build. Figure 14: Checking the status of the build After a few minutes, we can see that the build failed. Figure 15: The build has failed Double-click on the build to see the details. Figure 16: Viewing the details We can see that the error is due to a missing ";" at the end of the statement. We also can see that a new bug 36 was created because of the build failure. Figure 17: Observing the error message generated by the build failure Now, let us fix the build break. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoConsoleApp { class Program { static void Main(string[] args) { Console.Write("hello"); } } } And Commit the changes. When commiting, make sure to associate the change with the bug # as shown below. Figure 18: Committing to the changes Click Check In to commit the code. We can monitor the progress by double-clicking the build. Figure 19: Monitoring the progress After a few minutes, we can see the progress of the build and see that it completed successfully. Figure 20: A successful build Summary In this article, we learned about building applications in the cloud using Visual Studio Online. About the Author Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at.
http://www.developer.com/cloud/writing-applications-in-the-cloud-with-visual-studio-online.html
CC-MAIN-2015-06
refinedweb
823
66.44
I am building a model to calculate geometric mean for each shape file in model builder. How to do write Expression and Code Block which would: Take in shapefile "City_1" and use all the values in Field "Area" and calculate n√a*b*c*d. ..... where n are number of values in field "Area" and a,b,c,d are all the value in field "Area" the first example is a code block (def gm(a) ), just substitute your field name in the expression call …. gm(!YourFieldName!) … using a python parser. The last one can be turned into a code block import scipy.stats as st def gm(a): """scipy version""" areas = st.gmean(areas) return areas gm(!YourFieldName!) This is the link to Calculate values to show you where to put stuff Calculate Value—Tools | ArcGIS Desktop
https://community.esri.com/thread/222420-how-to-write-python-expression-and-code-block-for-geometric-mean
CC-MAIN-2018-51
refinedweb
138
72.76
// zoomkat 11-14-11 serial servo test// type servo position 1f, 1r, xx, etc. in serial monitor and enter// Powering a servo from the arduino usually DOES NOT WORK.String readString;#include <Servo.h> Servo myservo1; // create servo object to control a servo Servo myservo2;void setup() { Serial.begin(9600); myservo1.writeMicroseconds(1500); //set initial servo position if desired myservo2.writeMicroseconds(1500); //set initial servo position if desired myservo1.attach(6); //the pin for the servo control myservo2.attach(7); Serial.println("servo-test if (readString == "1f") myservo1.writeMicroseconds(2000); if (readString == "1r") myservo1.writeMicroseconds(1000); if (readString == "1x") myservo1.writeMicroseconds(1500); if (readString == "2f") myservo2.writeMicroseconds(2000); if (readString == "2r") myservo2.writeMicroseconds(1000); if (readString == "2x") myservo2.writeMicroseconds(1500); if (readString == "xx"){ myservo1.writeMicroseconds(1500); myservo2.writeMicroseconds(1500); } if (readString == "ff"){ myservo1.writeMicroseconds(2000); myservo2.writeMicroseconds(2000); } if (readString == "rr"){ myservo1.writeMicroseconds(1000); myservo2.writeMicroseconds(1000); } readString=""; //empty for next input } } wait is it possible for me to soft code the position I want it to go to? and of course by this I mean how would I do so int pos = 78;myServo.write(pos); Quoteand of course by this I mean how would I do soWhat do you mean by soft-code? To me, this means that you want to change, at run time, the servo position. That's what zoomkat's code does.If you want to send the servo to a specific position, that is hard-coding the position.Code: [Select]int pos = 78;myServo.write(pos); I would like to take the current location of the servo, and change the position, then be able to do this again, so that I can hit one key to make it move forward, and one key to make it move backward. (I want to have it move in degrees, not over a certain period of time like the code zoomkat gave me.) Servo myServo;int pos = 90;void setup(){ // set serial option and attach the servo}void loop(){ if(Serial.available() > 0) { char aChar = Serial.read(); if(aChar == 'p') val += 5; else if(aChar == 'm') val -= 5; myServo.write(val);} I already tried to declare an int and and have serial read the current angle of the servo. Then add one to the angle when a certain String was read in the Serial Monitor. I hope that clears up what that means. (I am still getting used to the syntax sorry) #include <Servo.h> #include <string.h>int rx_pos=0;char rx_char='0';char rx_string[50]="";Servo myservo;int pos=0;boolean oneTime=true;void setup() { Serial.begin(9600); Serial.println("READY: "); myservo.attach(9);}void loop() { if(Serial.available()){ if( (rx_char=Serial.read()) !='\n'){ rx_string[rx_pos++]=rx_char; //put rx char in the string } else{ rx_string[rx_pos]='\0'; //add string delimiter rx_pos=0; //reset string pointer Serial.println(rx_string); //for debug, print cmd received oneTime=true; //new string received, so new command possible } } if(oneTime && (strcmp(rx_string,"more")==0) && pos<180) pos+=10; else if(oneTime && (strcmp(rx_string,"less")==0) && pos>0) pos-=10; myservo.write(pos); oneTime=false; //command has already been executed delay(10); } Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=91218.0
CC-MAIN-2016-30
refinedweb
554
60.61
I've tried every way I can possibly see to try and convert the value from the numctrl to a decimal but the problem lies with the retrieved value being a float. I cant covert the float to a string first because it looses the trailing 0 in values such as 1.30 which I need because I am trying to represent currency. Does anyone know the way forward or what I am doing wrong please? import wx from wx.lib.masked import NumCtrl from decimal import * class MyFrame(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, 'Quick Silver', size = (180, 100)) context = Context(prec = 2) setcontext(context) panel = wx.Panel(self) lolinput = wx.lib.masked.NumCtrl(panel, pos = (20,20), fractionWidth = 2) # for 2 decimal places. lolinput.SetValue(1.30) x = Decimal(lolinput.GetValue(), 2) context.create_decimal(x) print x app = wx.App(redirect = False) frame = MyFrame(parent = None, id = -1) frame.Show() app.MainLoop()
https://www.daniweb.com/programming/software-development/threads/350333/float-to-decimal-with-precision-applied
CC-MAIN-2019-35
refinedweb
161
62.04
When using EF Core Migrations the tooling isn't picking up all my properties, only the "Id" and some (not all) of the FK's (navigation properties). It also seems to understand the "Table Per Hierarchy" very well - as it has set up a discriminator where I wanted it to, but the migration file itself doesn't reflect the properties I have in my Model namespace (see github code). My DbContext are located here: My Model classes here: You can look at the generated "Initial Migration" at [ ]. There you'll see that it detected all the Id properties (defined in the base class [Entity][1]), but none of the other properties I of my Model classes. I used the approach of adding a Console App to run migrations (otherwise it won't work - see Julie Lerman's tips on getting started with EF Core). Thus when running migrations I do it this way: dotnet ef --startup-project ../../TheConference.Infrastructure.ConsoleApp migrations add Initial. Do I have to use annotations or modelBuilder or a form of EntityTypeConfiguration in EFCore to let EF know what I want to take?. All of your class properties are like this public string Title { get; } i.e. read only auto properties. EF Core does not support (map) such properties. In order to get them mapped, you need to provide property setters public string Title { get; set; } The access level does not really matter - private, protected or internal will work. The only requirement is to have a setter. EF Core also allows mapping properties and using backing fields, but all that requires fluent API configuration and also most likely will not work with get only auto properties because they are backed with readonly fields.
https://entityframeworkcore.com/knowledge-base/44354561/ef-core-migrations-doesn-t-pick-up-all-properties
CC-MAIN-2020-40
refinedweb
287
51.48
Your Account by Tim O'Brien This) informative one to get started learning JavaFX. nice post.. import javafx.ui.*; Frame { title: "Test Application" width: 300 height: 100 visible: true menubar: MenuBar { menus: Menu { text:"File" items: MenuItem { text:"Open" } } } } Why wrap JavaFX code (which uses Java) in another java program? I'm also having issues because I'm an Eclipse user, and I'm still trying to figure out NetBeans. also its interesting to see how html code is used in the Java FX. it will be more useful for developing the complex screens. i realy liked it. @Josh, thanks for the note, I'm sure I'm doing *something* wrong in NetBeans. Glad to hear it works for you. package com.oreilly.onjava.feedticker; import javafx.ui.*; import javafx.ui.canvas.*; import javax.swing.JComponent; import com.oreilly.onjava.feedticker.FeedReader; import javafx.ui.filter.*; import java.net.URL; //var reader:FeedReader = READER; // Added these lines: var reader:FeedReader = new FeedReader(new URL("")); reader.read(); // -- var canvas = Canvas { height: 500 width: 445 content: VBox { content: foreach (i in reader.entries) Group { content: [Rect { x: 5 y: 5 height: 40 width: 435 arcHeight: 20 arcWidth: 20 fill: lightgrey stroke: black strokeWidth: 1 filter: [ShadowFilter] }, Text { content: bind i.title font: Font {face: VERDANA, style: [ITALIC, BOLD], size: 14} transform: translate(10, 10) }, Text { content: bind i.author, font: Font {face: VERDANA, size: 12} transform: translate(310, 30) }] } } }; // -- Create a frame in JavaFX, instead of the java code: Frame { width: 500 height: 800 content: canvas visible: true } //-- //MY_CONTAINER:JComponent.add(canvas.getComponent()); I created a main because I'm taking the application in a different direction. Stay tuned. Next steps include integrating this with an existing backend (using Spring Framework). But i have a question about Ticker.fx code. I'm using eclipse and writing "var reader:FeedReader = READER;" gave me "undefined variable READER in reader:FeedReader=READER" error. I couldn't find why. I am hard-trying to achieve this, but it seems impossible :) ** Not JavaAPI and Swing classes, I mean real third party APIs © 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://archive.oreilly.com/pub/post/javafx_first_steps_hello_onjav_1.html
CC-MAIN-2017-04
refinedweb
372
57.87
My first piece of learning from the experience just reconfirms something I already knew - games development is hard! Pygame Zero takes some of the pain and is certainly a lot easier to get started with than Pygame, but there is still a lot of work to do for game like Pong. The second thing I learnt is that I didn't know how Pong worked! This page which describes how the balls reacts when it hits a paddle is really useful. You will find all the code on github. You control the paddles with Q A (player 1) and K M (player 2). Its very much unfinished and is missing features like: - Time limit - the game continues forever - Scores - the score should be displayed on the screen - 1 player mode - artificial intelligent 2nd player Does anyone fancy picking it up? Code from math import sin, cos, radians from time import sleep #setup the constants WIDTH = 500 HEIGHT = 300 BALLSPEED = 10 PADDLESPEED = 5 MAXBOUNCEANGLE = 75 def reset_game(angle): #setup ball properties ball.pos = WIDTH / 2, HEIGHT / 2 ball.x_float = float(ball.x) ball.y_float = float(ball.y) ball.angle = angle ball.x_vel = BALLSPEED * cos(radians(ball.angle)) ball.y_vel = BALLSPEED * sin(radians(ball.angle)) #position the paddles pad1.pos = 10, HEIGHT / 2 pad2.pos = WIDTH - 10, HEIGHT / 2 #create a rectangle of the playing area screenRect = Rect(10,0,WIDTH - 10,HEIGHT) #create ball ball = Actor('ball') #create paddles pad1 = Actor('paddle') pad2 = Actor('paddle') #reset the game reset_game(180) #setup the goals goals = [0, 0] def draw(): screen.clear() ball.draw() pad1.draw() pad2.draw() def update(): #move the paddles if keyboard.q: pad1.top -= PADDLESPEED if keyboard.a: pad1.top += PADDLESPEED if keyboard.k: pad2.top -= PADDLESPEED if keyboard.m: pad2.top += PADDLESPEED #move the ball ball_old_x = ball.x_float ball_old_y = ball.y_float ball.x_float = ball.x_float + ball.x_vel ball.y_float = ball.y_float + ball.y_vel ball.x = int(round(ball.x_float)) ball.y = int(round(ball.y_float)) #move the ball back to where it was? reset_ball = False #has the ball left the screen? if not screenRect.contains(ball): #did it hit the top or bottom? if ball.top < 0 or ball.bottom > HEIGHT: ball.y_vel *= -1 reset_ball = True #it must have hit the side else: if ball.left < 10: print("Player 2 goal") goals[1] += 1 reset_game(180) sleep(2) print("Score {} : {}".format(goals[0], goals[1])) elif ball.right > WIDTH - 10: print("player 1 goal") goals[1] += 1 reset_game(0) sleep(2) print("Score {} : {}".format(goals[0], goals[1])) #has the ball hit a paddle if pad1.colliderect(ball): #work out the bounce angle bounce_angle = ((ball.y - pad1.y) / (pad1.height / 2)) * MAXBOUNCEANGLE ball.angle = max(0 - MAXBOUNCEANGLE, min(MAXBOUNCEANGLE, bounce_angle)) #work out the ball velocity ball.x_vel = BALLSPEED * cos(radians(ball.angle)) ball.y_vel = BALLSPEED * sin(radians(ball.angle)) reset_ball = True elif pad2.colliderect(ball): bounce_angle = 180 - (((ball.y - pad2.y) / (pad2.height / 2)) * MAXBOUNCEANGLE) ball.angle = max(180 - MAXBOUNCEANGLE, min(180 + MAXBOUNCEANGLE, bounce_angle)) ball.x_vel = BALLSPEED * cos(radians(ball.angle)) ball.y_vel = BALLSPEED * sin(radians(ball.angle)) reset_ball = True if reset_ball: ball.x_float = ball_old_x ball.y_float = ball_old_y ball.x = int(round(ball.x_float)) ball.y = int(round(ball.y_float)) Hi Trevor Appleton has code for the AI paddle on his page, using Pygame. I'm working on adding a second player to his code. Thanks for the game code Martin. I am a teacher trying to use it with my Python class. As a non-programmer I am puzzled by the fact that you set properties such as x_vel and y_vel that do not seem to be defined anywhere. Does the Actor class have such properties built-in? I appeared as "unknown" so have replied this time properly logged in :-) I am using a feature of Python which allows you to create properties of an object at run time, this is a convenient way for me to associate data which relates to the ball (i.e. its velocity in x and y) to the object itself rather than using global variables which are 'a bit dirty' (imho). Properties you can define at runtime! Fantastic! Loving discovering Python. Thanks (Thanks also for your Minecraft book which I own)
https://www.stuffaboutcode.com/2015/09/pygame-zero-pong.html
CC-MAIN-2019-35
refinedweb
700
61.22
Redux: Wrapping dispatch() to Recognize Promises We will learn how to teach dispatch() to recognize Promises so that we can move the async logic out of the components into asynchronous action creators. We will learn how to teach dispatch() to recognize Promises so that we can move the async logic out of the components into asynchronous action creators. Access all courses and lessons, track your progress, gain confidence and expertise. 00:01 The receive todo action creator is not very useful by itself because anytime we call it, we want to fetch the todos first. Also, they accept the same argument so it would be great if we could group this code into a single action creator. 00:17 I'm opening the file where I define the action creators and I'm adding a new import there. It will make all functions in the API module available on the API namespace import object. 00:31 I'm adding a special kind of action creator that I'm going to call in an asynchronous action creator. It takes filter as an argument and it calls the API fetch todos method with it. I'm using the promise the method to transform the result of the promise from the response to the action object generated by received todos given the filter and the response. 00:58 Received todos return an action object synchronously but fetch todos returns a promise that resolves through the action object. I can stop exporting receive todos because I'll change the components to sue fetch todos directly. 01:15 I'm going back to my component file and I can use the fetch todos prop injected by connect which corresponds to the new asynchronous fetch todos action creator. I'm removing the direct import of fetch todos function from API because from now on I'll be using the fetch todos action creator, which is injected into the props by connect. 01:40 Let's take another look at what happens in the action creators. The fetch todos action creator calls the fetch todos function from the API but then it transforms its result into a Redux action generated by receive todos. 01:57 However, by default, Redux only allows dispatch in plain objects rather than promises. We can teach it to recognize promises by using the same trick that we use for login every dispatch. 02:11 A login into dispatch is the function we wrote before that creates the dispatch from the store and returns a new version of dispatch that logs every action and the state. In a similar fashion, I can create a function called at promise support the dispatch that takes the store and returns a version of dispatch that supports promises. 02:35 First, we will write the raw dispatch function at it is defined on the store so that we can call it later. We return a function that has the same API as a dispatch function that is, it takes an action. 02:51 We don't know if the action is a real action or a promise of action, which hack if it has a then method that is a function, which is a way to tell if something is a promise. If it is a promise, we wait for it to resolve to an action object that we pass through raw dispatch. 03:11 Otherwise, we'll just call raw dispatch right away with the action object we received. Now, we can dispatch both actions and promises that resolve to actions. Finally, I need to use the function I just wrote to write the dispatch function one more time before returning the store to the app. 03:32 If I run the app now, I will still see the receive todos action being dispatch when the response is ready. However, the component uses a more convenient API that encapsulates the asynchronous logic in the asynchronous action creator. 03:49 One thing to remember is that the order in which we override the dispatch function is important. If we change it, the action will first be printed and then the promise will be processed so action type is undefined and we see the promise instead of the action, which is not very useful. 04:08 This is why I'm changing the auto back so that the promises are resolved before the action is locked. Let's recap how we added the promise support to the dispatch function. 04:20 We override store dispatch two times. Once to add the login and second time to add the promise support. The function that adds the promise support accepts the store an argument and it reaches the previous value of the dispatch function. 04:37 It returns a function that looks like a dispatch function because it accepts the action but if the action is not really an action but a promise, we're going to wait for that promise to resolve to the real action, which will pass through raw dispatch. 04:53 Finally, if the action is not a promise, we'll just dispatch it right away by calling raw dispatch. Let's see what happens when we try to dispatch the result of call and fetch todos asynchronous action creator. 05:08 First of all, it calls the fetch todos function from the API module, which I import as a namespace import. It waits for the promise to resolve with the response and rather than return the response, it returns the result of calling receive todos action creator, which returns an action object. 05:31 This is why fetch todos, itself, returns a promise that resolves through the action returned by receive todos. The wrap dispatch function recognizes that this is a promise and not an action so it waits for the promise to resolve and passes it on through the raw dispatch function with dispatches the action object returned by receive todos. 05:56 I remove the export from receive todos because it is only used as part of the asynchronous fetch todos action creator. Being a named expert, it becomes available as part of the actions object, which is the namespace import invisible todo list. 06:14 The actions object gets passed as a second argument through the connect function. This has me call these props fetch todos from my component without thinking whether it is backed by a synchronous and an asynchronous action creator.
https://egghead.io/lessons/javascript-redux-wrapping-dispatch-to-recognize-promises
CC-MAIN-2018-39
refinedweb
1,081
65.86
The problem Decompress Run-Length Encoded List Leetcode Solution states that you are given an array or vector containing a sequence. The sequence has some specific representation. The input sequence is formed from another sequence. We will call that another sequence as the original sequence. As per which the input sequence has been created. We are asked to find the original sequence. Each odd (ith) index in the sequence represents the number of times the following (i+1th) index is repeated in the original sequence. So, as always before diving into the solution let’s take a look at a few examples. nums = [1,2,3,4] [2,4,4,4] Explanation: Let us verify if the output is correct? 2 is repeated 1 time in the original statement. So in the input sequence, it should be 1, 2. Afterward, 4 is repeated 3 times, which is also shown in the input sequence So, this proves that the output is correct. nums = [1,1,2,3] [1,3,3] Explanation: Again if we verify the output. 1 has a single copy and 3 is repeated twice. Once again the output is correct. Approach for Decompress Run-Length Encoded List Leetcode Solution The problem Decompress Run-Length Encoded List Leetcode Solution is a standard one. And is asked frequently in several coding rounds conducted by various companies. The approach is very simple since we need to create a new array to store the original sequence. We simply use either array or a vector and keep on adding elements in the back. We can run a for loop that jumps 2 units after each iteration. This confirms that we deal only with (frequency, value) pairs. Now again with a nested for loop, we add the element at the ith index to vector. We run the nested for loop as per the element at i+1th index in the given input sequence. Code for Decompress Run-Length Encoded List Leetcode Solution C++ code #include <bits/stdc++.h> using namespace std; vector<int> decompressRLElist(vector<int>& nums) { vector<int> tmp; for(int i=0;i<nums.size();i+=2){ for(int j=0;j<nums[i];j++) tmp.push_back(nums[i+1]); } return tmp; } int main(){ vector<int> input = {1,2,3,4}; vector<int> output = decompressRLElist(input); for(auto x: output)cout<<x<<" "; } 2 4 4 4 Java code import java.util.*; import java.lang.*; import java.io.*; class Main { public static int[] decompressRLElist(int[] nums) { int size = 0, k = 0; for(int i=0;i<nums.length;i+=2) size += nums[i]; int[] tmp = new int[size]; for(int i=0;i<nums.length;i+=2){ for(int j=0;j<nums[i];j++) tmp[k++] = nums[i+1]; } return tmp; } public static void main (String[] args) throws java.lang.Exception{ int[] input = {1,2,3,4}; int[] output = decompressRLElist(input); for(Integer x: output)System.out.print(x+" "); } } 2 4 4 4 Complexity Analysis Time Complexity O(N), where N is the length of the output. Here the time complexity does not depends on the input. Instead of input, the time complexity is dependent on the output or result obtained. Space Complexity O(N), where N is the length of the output. Since we store the output because we are returning it. Space is also occupied by it.
https://www.tutorialcup.com/leetcode-solutions/decompress-run-length-encoded-list-leetcode-solution.htm
CC-MAIN-2021-25
refinedweb
557
58.69
On May 30, 2008, at 2:23 PM, James Carman wrote: > On Fri, May 30, 2008 at 5:17 PM, Janne Jalkanen > <Janne.Jalkanen@ecyrd.com> wrote: >>> As an end user, I would _hate_ to have to change all of my code to >>> reference a totally new package structure after the podling >>> graduates. >>> That's a major pain... >> >> With JSPWiki we have plenty of plugins and other extensions donated >> by >> people over the years. Every binary break means that we obsolete >> most of >> this stuff (unless we can take the responsibility of recompiling >> everything). Every binary break means that we will have to answer >> questions >> from people running obsolete software because they can't afford the >> cost of >> the upgrade because they have money invested in the customizations. >> >> So it's not only the pain of upgrading the package definitions; >> changing >> packages issues a damaging blow to the ecosystem nurtured in the >> incubator. >> Sometimes the impact can be minimal; sometimes it could be rather >> bad. > > The package names have to change when a podling comes into the > incubator (to the org.apache namespace). So, the "blow" has to happen > anyway. I'm not suggesting we enforce this for existing podlings > necessarily, but future ones should probably do it. Once the podling > graduates, the plugins would need to change the package name they use > because they are now based on an official ASF library. Is > find/replace really that difficult? Yes, it is. When your entire community and the communities that rely on them have to do it, yes it is. Remember, some podlings incubate for years and so these roots can go way out. Frankly, I am really, really, surprised that this is being entertained at all. Regards, Alan --------------------------------------------------------------------- To unsubscribe, e-mail: general-unsubscribe@incubator.apache.org For additional commands, e-mail: general-help@incubator.apache.org
http://mail-archives.apache.org/mod_mbox/incubator-general/200805.mbox/%3C9F0C74A0-B89D-4DDF-9C9B-5B6634CD1A49@toolazydogs.com%3E
CC-MAIN-2015-32
refinedweb
308
56.15
A short Python class puzzle Here’s a short Python puzzle that I use in many of my on-site courses, which I have found to be useful and instructive: Given the following short snippet of Python, which letters will be printed, and in which order? print("A") class Person(object): print("B") def __init__(self, name): print("C") self.name = name print("D") print("E") p1 = Person('name1') p2 = Person('name2') Think about this for a little bit before looking at the answer, or executing it on your computer. Let’s start with the answer, then: A B D E C C Let’s go through these one by one, to understand what’s happening. The initial “A” is printed because… well, because it’s the first line of the program. And in a Python program, the lines are executed in order — starting with the first, then the second, and so forth, until we reach the end. So it shouldn’t come as a surprise that the “A” line is printed first. But what is surprising to many people — indeed, the majority of people who take my courses — is that we next see “B” printed out. They are almost always convinced that the “B” won’t be printed when the class is defined, but rather when… well, they’re really sure when “B” will be printed. Part of the problem is that Python’s keywords “class” and “def” look very similar. The former defines a new class, and the latter defines a new function. And both start with a keyword, and take a block of code. They should work the same, right? Except that “class” and “def” actually work quite differently: The “def” keyword creates a new function, that’s true. However, the body of the function doesn’t get executed right away. Instead, the function body is byte compiled, and we end up with a function object. This means that so long as the function body doesn’t contain any syntax errors (including indentation errors), the function object will be created. Indeed, the following function will produce an error when run, but won’t cause a problem when being defined: def foo(): asdfafsafasfsafavasdvadsvas This is not at all the case for the “class” keyword, which creates a new class. And if we think about it a bit, it stands to reason that “class” cannot work this way. Consider this: Immediately after I’ve defined a class, the methods that I’ve defined are already available. This means that the “def” keyword inside of the class must have executed. And if “def” executed inside of a class, then everything else executes inside of a class, also. Now, under most normal circumstances, you’re not going to be invoking “print” from within your class definition. Rather, you’ll be using “def” to define methods, and assignment to create class attributes. But both “def” and assignment need to execute if they are to create those methods and attributes! Their execution cannot wait until after the class is already defined. I should also add that in Python, a class definition operates like a module: What would looks like an assignment to a global variable inside of the class definition is actually the creation of an attribute on the class (module) itself. And of course, the fact that the body of a class definition executes line by line makes it possible to use decorators such as @staticmethod and @property. In short, “def” inside of a class definition creates a new function object, and then creates a class-level attribute with the same name as your function. So, when you define a class, Python executes each line, in sequence, at the time of definition. That’s why “B” is printed next. Why is “C” not printed next? Because the body of a function isn’t executed when the function is defined. So when we define our __init__ method, “print” doesn’t run right away. It does, however, run one time for each of the two instances of “Person” we create at the end of the program, which is why “C” is printed twice. However, before “C” is printed, the class definition still needs to finish running. So we first see “D” (inside of the class definition), and then “E” (just after the class is defined). Over the years, I’ve found that understanding what goes on inside of a class definition helps to understand many of the fundamental principles of Python, and how the language is implemented. At the same time, I’ve found that even in my advanced Python classes, a large number of developers don’t answer this puzzle correctly, which means that even if you work with Python for a long time, you might not have grasped the difference between “class” and “def”. […] post A short Python class puzzle appeared first on Lerner Consulting […]
https://lerner.co.il/2017/01/30/short-python-class-puzzle/
CC-MAIN-2019-35
refinedweb
813
68.6
Start a hosting plan from $3.92/mo and get a free year on Tuts+ (normally $180) By integrating your Android apps with the Google Play Services, you can access Google services, such as Maps, Drive, and Google+. Once you have your apps set up to use these services, accessing them is typically straightforward. The setup process does require a few steps, but you only need to carry them out once. In this tutorial we will go through the process of integrating Google Play Services with Android apps. Introduction Throughout the tutorial, we will outline what you need to do to integrate apps with Play Services in both Eclipse and Android Studio. You will need access to the Google Developer Console and to the Keytool utility. Once you are set up with Play Services, the development process itself will be determined by what you want your apps to do. The the setup procedure, however, remains the same. By using the client library to access platform services, your apps will benefit from automatic updates through the Play Store. 1. Install Play Services in your IDE Step 1 Open your IDE and start the Android SDK Manager. In Eclipse, choose Window > Android > SDK Manager. In Android Studio, click the SDK Manager toolbar button. Scroll through the list, expand the Extras folder and select Google Play Services. Click to install the package and accept the license when you are prompted. If you are developing in Android Studio, you will also need to install the Google Repository. Step 2 When you test apps in which you use the Google Play Services APIs, ideally, you should run them on physical devices. However, it is possible to test in the emulator. To do this, you will need to install the Google APIs Platform. You will find this inside the directory for any of the API levels 17 and up. Find the platform in your SDK Manager, install it, and accept the license. When you create an AVD (Android Virtual Device) to test an app using Google Play Services, choose Google APIs as the target. Step 3 If you are developing in Eclipse, you will also need to copy the Play Services library into your workspace. First, browse to it on your computer using a file explorer. You will find it in the folder you downloaded your Android SDK into, at /extras/google/google_play_services/libproject/google-play-services_lib/. Copy it to a location on your computer that you use for Android development files. Once you have copied the library (you must copy it rather than using the version in the SDK directory), go back to Eclipse. Choose Import from the File menu. Expand the Android folder, select Existing Android Code Into Workspace, and click Next. Click the Browse button and navigate to the location you copied the Play Services library into. Select the folder you copied and click Finish to import it. The package will appear in your Package Explorer. 2. Create an Android Project Step 1 You can now start developing with the Play Services resources. Create a new Android project in your IDE. Once you have a project in your workspace, you need to reference the Play Services resources within it. In Android Studio, you will need to add a build rule to the build.gradle file in the module for your application project. In the dependencies section, use the following syntax: compile 'com.google.android.gms:play-services:4.1.32' Make sure you use the number for the most recent version of Play Services. You will need to update this as the library is updated. Save the file and click the Sync Project with Gradle Files button. In Eclipse, select the project in your Package Explorer, right-click or select the Project menu, and choose Properties. Select the Android option on the left and click Add in the Library section. Select the Google Play Services library from the pop-up window and click OK to add it. Click Apply and the OK. Step 2Whichever IDE you are using, you will need to add Play Services meta-data to your manifest file. Open the project's manifest file and add the meta-data element inside the applicationelement: <meta-data android: If you are using Proguard, you will need to create an exception. See the Developer Guide for more details. For an overview of the Google Play Services APIs, check out the Package Index. 3. Connecting with Play Services in your Apps Step 1 The processing steps you need to take within your application code will depend on what functionality you want to implement with Play Services. The following sections outline some general considerations and steps. Although updates are pushed through the Google Play Store, it is still advisable to check what version the user device has installed before you attempt to carry out any processing with Google Play Services. See the Implementing GCM Client example code in the Developer Guide for an overview of how to implement these checks within an Activity class. The method call to look for is isGooglePlayServicesAvailable, which you can add to a helper method as in the following excerpt: private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); //... } You could call the method in onCreate, before attempting to create the GoogleAPIClient instance through which you access the Play Services resources, and within onResume. If the user device does not have the required resources installed, they will be prompted to do so through the Google Play Store. Step 2 After checking the level of support on the user device, you can create an instance of the GoogleAPIClient class to call on the Google Play resources. The following example code demonstrates this and could be included in onCreate: GoogleApiClient myClient = new GoogleApiClient.Builder(this) .addApi(Plus.API) .addScope(Plus.SCOPE_PLUS_PROFILE) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); This would prepare your application for accessing Google+ services, as you can see from the Plus.API excerpt. The addScope line will vary depending on what your app does. This code also sets up callbacks for the connection process. Your class can implement the following interfaces: public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener The class can then implement the onConnected and onConnectionSuspended callbacks for handling changes in connection to Play Services. To handle failures in connecting to Play Services, such as in cases where user sign-in is required, your class can also implement onConnectionFailed , for accessing various standard methods for resolving typical errors. Some of these methods will cause the onActivityResult method to execute when the user returns to the app, so you can reattempt to connect there. In general, your Activity class should connect to Play Services in onStart and disconnect in onStop via the GoogleAPIClient class as in the following excerpt: myClient.connect(); 4. Using Play Services Resources Step 1 For certain Play Services, including Google+, you need to register for access. To do so, log into the Google APIs Console, click Create Project, and enter a name. After creating the project, you should be redirected to the project in the console. Select the APIs menu item, find Google+ API in the list, and click the button to enable it. The status should change to ON after accepting the license. Clicking the API listing will give you an overview of what you can do with it. Step 2 Next, select Credentials and click Create New Client ID. Select the Installed application radio button, select Android as the type, and enter your app details. Now you need to use the Keytool resource to generate a SHA1 certificate. During development, you can use the debug keystore, entering the following code in a terminal: keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v You'll need to make sure this is the correct location for your debug keystore, alter the path if it isn't. When you execute this command, you'll be prompted for the password. Enter android for the debug keystore and the fingerprint should be output to the terminal. Copy the SHA1 line and paste it into the Signing certificate fingerprint box in the APIs Console. Enable deep linking if necessary and then click the button to create the ID. A section will appear entitled Client ID for Android Application. You do not actually need to use the ID in your app code, but you may wish to keep a copy of it for your own records. Step 3 Before you can call on the Play Services APIs in your application code, you will need to add the appropriate permissions to your project's manifest file. The following examples demonstrate a few typical use cases, but you will need to choose the appropriate permissions for your own project: <uses-permission android: <uses-permission android: <uses-permission android: Your project should now be configured to call the Play Services APIs that you need. You will need to structure your Activity classes differently depending on what your apps do. Take a look at the Developer Guide for more information about this. Don't forget to check out the following guides to get started with some of the available Play Services: If the Google services you wish to access are not part of the Play Services library, you can access them using Google's REST API. Conclusion There are a lot of possibilities with Google Play Services in Android apps. From gaming to location and mapping services, your apps can take advantage of the existing platform features within the context of your own user interfaces and functionality. The setup process may seem a little laborious, but once you're set up, you can focus on bringing these services to your users.
http://code.tutsplus.com/tutorials/integrating-google-play-services-on-android--cms-19828
CC-MAIN-2015-06
refinedweb
1,616
62.27
I need help with trying to determine why my array is being overwritten. The problem is that when I run this code and then print out the results, array Var[m] gets filled from beginning to end with the last value that sscanf got from the data file "Data.txt". If you look at the code the sscanf puts the last field of data into a variable called t5. Therefore I only see "S2_536" from the data file in all 15 array elements. When I ran the code through the debugger I saw the first element get the correct value ("S2_632" from the data file), then the second time through the loop the first and second elements both had the second elements value (or "S2_627" from the data file)... and so on until all 15 elements contained the last or 15th elements value. Each element for Var[m] should have it's respective data from line one through line 15. All other arrays that I print out look good except this one. Why is it doing this? What am I doing wrong? Please run this code below to see exactly what I'm saying. Thanks for your help! #include <ctype.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXCHARS 80 int m; FILE *infp; char line1[MAXCHARS]; char t1[20], t2[20], t3[20], t4[20], t5[20]; int int Index[25], Pos[25][11], int Var[25]; int main() { fp = fopen("Data.txt", "r"); if(fp == NULL) { fprintf(stderr, "can't open %s\n", "Data.txt"); exit(EXIT_FAILURE); } for (m=0; m<15; m++) { if(fgets(line1, MAXCHARS, infp) != NULL) { sscanf (line1, "%s %s %s %s %s", t1, t2, t3, t4, t5); Index[m] = atoi(t1); Pos[m][1] = atoi(t2); Pos[m][2] = atoi(t3); Pos[m][3] = atoi(t4); Var[m] = t5; } } for (m=0; m<15; m++) { printf("Index = %i\n",Index); printf("Index = %i\n",Pos[m][1]); printf("Index = %i\n",Pos[m][2]); printf("Index = %i\n",Pos[m][3]); printf("Index = %s\n",Var[m]); } // Done reading input file at this point fclose(infp); return(0); } Data.txt is a text file, 15 lines long, each field separated by a space and looks exactly like this: 1 0 0 1 S2_632 2 21 21 2 S2_627 3 30 51 2 S2_621 4 18 69 0 S2_613 5 18 87 0 S2_606 6 19 106 0 S2_599 7 57 163 1 S2_595 8 14 177 0 S2_589 9 18 195 0 S2_587 10 15 210 0 S2_579 11 14 224 0 S2_572 12 21 245 0 S2_566 13 21 266 0 S2_554 14 14 280 0 S2_542 15 13 293 0 S2_536
http://cboard.cprogramming.com/c-programming/19399-trouble-string-output-help.html
CC-MAIN-2015-18
refinedweb
455
78.28
django-object-tools 0.0.3 Django app enabling painless creation of additional admin object tools. Django Object Tools Django app enabling painless creation of additional admin object tools. Contents This packages is part of the larger Jmbo project. Installation Install or add django-object-tools to your python path. Add object_tools to your INSTALLED_APPS setting. django-object-tools overrides certain admin templates so you have to add it before django.contrib.admin. Call object tool's autodiscover method. This works in a similar fashion as Django's admin; discovering which tools to render in admin. You can do this in any module that is called during initialization but we recommend doing it in urls.py, as illustrated in the next point. Hook up URLConf. Do this by pointing a given URL at the tools.urls method. In this example, we register the default Tools instance object_tools.tools at the URL /object-tools/: # urls.py from django.conf.urls.defaults import * import object_tools object_tools.autodiscover() urlpatterns = patterns('', (r'^object-tools/', include(object_tools.tools.urls)), ) Obviously Django Admin itself needs to be installed, as described here. Remember to run syncdb whenever you install new tools to setup permissions. Usage django-object-tools itself doesn't do much in terms of providing useful tools. Its purpose is to simplify creation and integration of custom tools delivered by other Django applications. To that end it takes care of the messy details like permissions and admin template integration so you can focus on the fun stuff. As an example lets create a tool allowing you to delete all objects. Yes this is a bit convoluted but it's a good toy example for illustration purposes. Have a look at django-export and django-order for examples of real world tools leveraging django-object-tools. Firstly create a Django app folder structure as per usual, with the root directory named delete, including a file called tools.py. It should look as follows: delete/ __init__.py tools.py Edit tools.py to look like this: from django.contrib.admin.actions import delete_selected import object_tools class Delete(object_tools.ObjectTool): name = 'delete' label = 'Delete all' def view(self, request, extra_context=None): queryset = self.model.objects.all() response = delete_selected(self.modeladmin, request, queryset) if response: return response else: return self.modeladmin.changelist_view(request) object_tools.tools.register(Delete) Let's go through that line by line: - object_tools behaves similarly to Django's admin allowing you to explicitly register tools, see line 17. It also provides the ObjectTool base class. - import delete_selected method provided by Django. This method will do all the heavy lifting. - Create a tool class inheriting from object_tools.ObjectTool. All object tools have to inherit from object_tools.ObjectTool. ObjectTool provides various methods to simplify creation of tools. See object_tools.options.py for more details. - Set tool name to delete. This has to be a unique name identifying the tool. This is used to uniquely identify the tool internally and for instance to setup permissions. - Set label to Delete all. The label is displayed within admin and not the name, thus allowing you to specify a more verbose, user friendly label. - Implement view method. This is the brains of your tool. The view method is called when the user executes your tool, so your tool logic would go here. This can be any view like code, as long as it returns an HttpResponse object. In this case we wrap Django's built-in delete_selected to provide the form, logic and template code to perform the actual delete. - Register the tool with object_tools, thus enabling its display in admin. To enable the tool add delete to your INSTALLED_APPS setting. Now when you navigate to the change list view of any model you'll find the delete all object tool in the upper right hand corner. Clicking on the Delete all tool fires of the view and proceeds with deleting objects as per usual. Note: django-object-tools adds per tool permissions to the built-in set of default Django permissions. So in this example only superusers or users who have the the Can delete <model> permission will be able to see and use the tool. If you can't see or use a particular tool make sure the authenticated user has the required permissions to do so. Changelog 0.0.3 (2011-09-15) - Correctly resolve title. 0.0.1 (2011-07-22) - Initial release. - Author: Praekelt Foundation - Categories - Package Index Owner: Shaun.Sephton, Praekelt, hedley - DOAP record: django-object-tools-0.0.3.xml
http://pypi.python.org/pypi/django-object-tools/0.0.3
crawl-003
refinedweb
755
52.05
It feels like ages since part 2 was out. Meanwhile, the movie Man of Steel has actually been released. So there is really no need to check for rumors about what that movie is all about. Probably the industry is now abuzz with rumours about its sequel instead. In this tutorial, I would be showing how to use features like comments and CRUD views which are integral to a social site. You can choose to watch the video or read the step by step description below or follow both. The goodies pack which was introduced in the last part has been updated and would be used again to save time to create templates. This video would be a continuation of the previous video and I recommend watching it. Click on the image below to watch the screencast or scroll down to read the steps. Enjoyed this tutorial? Then you should sign up for my upcoming book “Building a Social News Site in Django”. It tries to explain in a learn-from-a-friend style how websites are built and gradually tackles advanced topics like testing, security, database migrations and debugging. Step-by-step Instructions Here is the text version of the video for people who prefer to read. In part 2, we showed you how to create a beta-like site to publish rumors about “Man of Steel” where users can sign-up and create their own profiles. The outline of Part 3 of the screencast is: - Create/Read/Update/Delete of a Link - Pagination Get the goodies pack again The goodies pack has changed since the last tutorial, so I would recommend downloading it again. Download sr-goodies-master.zip to any convenient location. On Linux, you can use the following commands to extract it to the /tmpdirectory. cd /tmp wget unzip master.zip Explore the extracted files in /tmp/sr-goodies-master Pagination So far we have been seeing just the first page of the list of links. But we are using Django’s ListView which provides pagination. Let’s implement a simple ‘Next’ link to visit the next page. Add the following snippet to steelrumors/templates/links/link_list.htmljust before {% endblock %}: {% if is_paginated %} <div class="pagination"> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">More »</a> {% endif %} </div> {% endif %} In the same template file we’ll need to change the first <ol>tag to ensure that the line numbers in page 2 and later appear correctly. Replace that line with <ol>with these lines: {% if is_paginated %} <ol start="{{ page_obj.start_index }}"> {% else %} <ol> {% endif %} Now you can visit every page and read every submitted link! CRUD - Create and Read Links We have been using the admin interface to create/update/delete links. But this is only accessible to staff members. To allow users to submit links, we will need a new form, a new view class (generic CBV) and a new template with a form. Add this new ModelForm to links/forms.py: from .models import Link ... class LinkForm(forms.ModelForm): class Meta: model = Link exclude = ("submitter", "rank_score") Time to implement the “C” of CRUD by importing CreateViewand the form you just created: Add the LinkCreateViewclass to links/views.py: from django.views.generic.edit import CreateView from .forms import LinkForm ... class LinkCreateView(CreateView): model = Link form_class = LinkForm def form_valid(self, form): f = form.save(commit=False) f.rank_score = 0.0 f.submitter = self.request.user f.save() return super(CreateView, self).form_valid(form) Copy link_form.htmlfrom goodies to steelrumors/templates/links/link_form.html: cp /tmp/sr-goodies-master/templates/links/link_form.html \ ~/proj/steelrumors/steelrumors/templates/links/ Add this view in steelrumours/urls.py: from links.views import LinkCreateView url(r'^link/create/$', auth(LinkCreateView.as_view()), name='link_create'), Visit and submit a new link. Remember, you’ll need to be logged in to submit links. If you try to submit a link, you will see an error message asking you to “Either provide a url or define a get_absolute_urlmethod on the Model.” So let’s define the get_absolute_urlmethod. Add the following method in the Linkclass: from django.core.urlresolvers import reverse ... def get_absolute_url(self): return reverse("link_detail", kwargs={"pk": str(self.id)}) Create a DetailView in links/views.py. This is the “R” of CRUD. from django.views.generic import DetailView ... class LinkDetailView(DetailView): model = Link Copy link_detail.htmlfrom goodies to steelrumors/templates/links/link_detail.html: cp /tmp/sr-goodies-master/templates/links/link_detail.html \ ~/proj/steelrumors/templates/links/ Add this detail view in steelrumours/urls.py: from links.views import LinkDetailView url(r'^link/(?P<pk>\d+)/$', LinkDetailView.as_view(), name='link_detail'), Try submitting the add link form again and it should take you to the detail page, without error. For convenience, let’s add the urls to these new views in our template so that users can easily find them. Add only the line with a + sign to base.html(remove the + sign): {% if user.is_authenticated %} + <a href="{% url 'link_create' %}">Submit Link</a> | <a href="{% url 'logout' %}">Logout</a> | Make the following change (changed line starts with a + sign) to steelrumors/templates/links/link_list.html: {% for link in object_list %} <li> [{{ link.votes }}] + <a href="{% url 'link_detail' pk=link.pk %}"> <b>{{ link.title }}</b> Refresh the steelrumours site on your browser and check if all the links work correctly. CRUD - Update and The remaining two views for Update and Delete are straight forward and we can add them together. We are going to reuse the LinkForm, so let’s start with views. Add these view classes to links/views.py: from django.core.urlresolvers import reverse_lazy from django.views.generic.edit import UpdateView from django.views.generic.edit import DeleteView ... class LinkUpdateView(UpdateView): model = Link form_class = LinkForm class LinkDeleteView(DeleteView): model = Link success_url = reverse_lazy("home") Copy link_confirm_delete.htmlfrom goodies to steelrumors/templates/links/link_confirm_delete.html: cp /tmp/sr-goodies-master/templates/links/link_confirm_delete.html \ ~/proj/steelrumors/templates/links/ Add these views in steelrumours/urls.py: from links.views import LinkUpdateView from links.views import LinkDeleteView url(r'^link/update/(?P<pk>\d+)/$', auth(LinkUpdateView.as_view()), name='link_update'), url(r'^link/delete/(?P<pk>\d+)/$', auth(LinkDeleteView.as_view()), name='link_delete'), Finally, for convenience, add these lines (with + sign) to steelrumors/templates/links/link_detail.html: <h2><a href="{{ object.link }}">{{ object.title }}</a></h2> + {% if object.submitter == user %} + <a href="{% url 'link_update' pk=object.pk %}">Edit</a> | + <a href="{% url 'link_delete' pk=object.pk %}">Delete</a> + {% endif %} Now, you can create, read, update and delete Link objects. Try it! Enabling Comments We are going to add comments to the link detail pages using the built-in Django comments framework. First add this applications in steelrumors/settings.py: INSTALLED_APPS = ( 'django.contrib.admin', + 'django.contrib.comments', Run syndb to create the tables required by the comments app: ./manage.py syncdb Copy the new link_detail.htmlpage from the goodies pack: cp /tmp/sr-goodies-master/templates/links/link_detail2.html \ ~/proj/steelrumors/templates/links/link_detail.html We need to show comment counts in the front page itself. So add the following lines to steelrumors/templates/links/link_list.htmlat the beginning and middle of the template: {% extends "base.html" %} + {% load comments %} ... <a href="{% url 'link_detail' pk=link.pk %}"> <b>{{ link.title }}</b> + {% get_comment_count for link as comment_count %} + {{ comment_count }} comment{{ comment_count|pluralize }} </a> Add this line to steelrumours/urls.pyfor wiring up the comments app: url(r'^comments/', include('django.contrib.comments.urls')), Now, open any link detail page and have fun writing comments! Fun with Random Gossip Add a mixin class called RandomGossipMixin in links/views.py before LinkListView class: from django.contrib.comments.models import Comment ... class RandomGossipMixin(object): def get_context_data(self, **kwargs): context = super(RandomGossipMixin, self).get_context_data(**kwargs) context[u"randomquip"] = Comment.objects.order_by('?')[0] return context Change the class declaration of LinkListView to include this mixin as a base class: class LinkListView(RandomGossipMixin, ListView): Add the following lines to steelrumors/templates/links/link_list.html before the endblock line: <blockquote style="background-color: #ddd; padding: 4px; border-radius: 10px; margin: 10px 0; color: #666; font-size: smaller; text-shadow: rgba(255,255,255,0.8) 1px 1px 0;"> {{ randomquip.comment|truncatechars:140 }} </blockquote> Now refresh the home page and enjoy a random comment appear at the bottom of the page. Final Comments We have a lot more feature-complete social news site at this point. Users can actually submit links and comment about them. In the next and concluding part, we will cover writing mixins and ranking algorithms in Django. With this users will be able to vote and influence the ranking of links. That concludes Part 3. Follow me on Twitter at @arocks to get updates about upcoming parts. Resources - Full Source on Github - Goodies pack on Github
http://arunrocks.com/building-a-hacker-news-clone-in-django-part-3/?src=reddit
CC-MAIN-2015-27
refinedweb
1,447
53.17
0 so all i want to do is roll 1 die repeatedly and add it to a total until the total is equal to or greater than 31 this is what i have got to so far import java.io.*; import java.util.*; public class comp { public static void main(String[] args) throws FileNotFoundException { Scanner user = new Scanner(System.in); Random r = new Random(); int roll; int comptotal = 0; do{ roll = r.nextInt(6) + 1; comptotal = comptotal + roll; }while (comptotal >= 31); System.out.println(comptotal); }} it only rolls the die once i can't think of another way to roll the die again and keep rolling it until the total is equal to or greater than 31
https://www.daniweb.com/programming/software-development/threads/277008/die-roll-repeat
CC-MAIN-2017-17
refinedweb
117
66.88
info_outline Solutions will be available when this assignment is resolved, or after a few failing attempts. Time is over! You can keep submitting you assignments, but they won't compute for the score of this quiz. Subtract Reversed Using a while loop, write a function subtract_reversed that receives a list and subtracts all the numbers, starting from the end. Example: subtract_reversed([3, 7, 18]) # Result: 8 (18 - 7 - 3) subtract_reversed([9]) # Result: 9 (9 - 0....) Special case: If the list is empty, should return 0. Check the tests for details. Test Cases test list with many elements - Run Test def test_list_with_many_elements(): assert subtract_reversed([2, 7, 9, 32]) == (32 - 9 - 7 - 2)
https://learn.rmotr.com/python/base-python-track/advanced-control-flow/subtract-reversed
CC-MAIN-2018-22
refinedweb
111
66.33
Akka Actor Thread Utilization and Optimization Akka Actor Thread Utilization and Optimization Join the DZone community and get the full member experience.Join For Free I am working on a project where we have http requests from an IVR Voice browser making VXML requests. Each request is a phone caller and each new caller in our application will spawn 6 Akka actor requests for various account look-ups. The issue I had was the concurrent new caller volume of ~20 was backing up the Akka queues and then timing out the akka requests. This was puzzling as the Dispatcher thread pool was set to a core size of 10 which seemed to spawn off 50 akka threads total. Then we used JMeter to simulate new callers and as we started increasing up the number of callers, we noticed that Akk was not using the new threads. The JMEter tests simulated 120 new callers with a 60 second ramp-up time and would loop for forever for a total of 300 seconds. Here is the result of that test showing only 1 thread used. When I look at the threads that are being used, I noticed only 1 thread is active, thus why the performance is so slow. We would fill up each Actors queue around 50-60 concurrent callers so the numbers where quite small. Not enough for our target traffic which needs be in excess of 300 concurrent callers per machine. We could just get many more machines, bu that is not the best approach. Here is the akka configuration we had <akka:typed-actor <akka:dispatcher <property name="appointmentServiceClient" ref="appointmentServiceClient"/> </akka:typed-actor> Maybe I missed this in the documentation, but it seems that even though we created the actor as prototype, there was still only 1 instance of the Actor created, and then only 1 thread was being used because an Actor is bound to a queue. You can see that 1 thread per actor is working while the others are waiting. In order to be able to use multiple threads per typed actor we needed to create an ActorRegistry and create multiple Actors per type. Right now we created the actors individually. We are going to refactor this to be dynamic instead of static, but for our proof of concept, this is what we are going use: <akka:typed-actor id="appointmentActor> <akka:typed-actor id="appointmentActor> ... more actors omitted ... This is the initial Actor Load balance Registry. import java.util.Random; import static akka.actor.Actors.registry; public class ActorLoadBalancer { // TODO: Implement proper load balancing algorithm using CyclicIterator @SuppressWarnings("unchecked") public static T actor(Class targetClass) { Object[] workers = registry().typedActorsFor(targetClass); // Routing.loadBalancerActor(new CyclicIterator(Arrays.asList(workers)); int actorNumber = new Random().nextInt(workers.length); return (T) workers[actorNumber]; } } We started with 4 actors for each registry at first then ran the same JMeter test with 120 callers and our numbers where an order of magnitude better Wen I looked at the thread usage, I was able to see better thread utilization for the actor threads: But I noticed there where still some threads that where backing up so I created 3 of the actors with 10 instances, and the others stayed with 4. I can to this numbering with trial-and-error to see how many I could use. But I was still able to get another large improvement Here is the test I ran and noticed this thread activity By creating more Actors, I noticed more of the threads where actually running verse wait state. This was the most actors in most any combination I could get without 1 of 2 things happening. 1. If I increased all actors evenly, the slow Actors where backing up while the faster actors where more idol so there where many threads that where not running waiting for the other actors to free up. 2. I then wanted to increase the number of slow actors to get more through-put but then after the exact number I had above, I started getting HTTP transport errors like this: Caused by: com.sun.xml.internal.ws.client.ClientTransportException: HTTP transport error: java.net.BindException: Address already in use: connect at com.sun.xml.internal.ws.transport.http.client.HttpClientTransport.getOutput(Unknown Source) at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.process(Unknown Source) at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.processRequest(Unknown Source) at com.sun.xml.internal.ws.transport.DeferredTrans138.lookupApplicationConfigurationProperties(Unknown Source) at sun.reflect.GeneratedMethodAccessor163.invoke(Unknown Source) I found this reference to the error: But I still need to research if the Spring-ws implementation, which is the web service each of these Actors is calling has a keep-alive set or not. I know Akka has the keep-alive set to 60000/ms. Some observations 1. When I set core-pool-size=”1″ each actor spawned only 1 thread and each thread was used more. 2. When I set core-pool-size=”2″ I noticed each actor spawned 2 threads, and each of the threads sometimes where used interchangeably, but not always. Conclusion All-in-all I was able to get a good amount of traffic through-put. I feel there is more that I can achieve, but I might be limited by the operation teams choice of Windows 2003 running a 32-bit client mode jvm. I think I can do further research to see if netstat -anop tcp will show that connections are indeed kept alive, and if not, look into the Spring-ws to see why this would not be the case. I found further reading on testing the keep-alive From Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/akka-actor-thread-utilization
CC-MAIN-2018-43
refinedweb
967
51.28
I presented an "in the brain" session at Skills Matter on Monday night as a follow-up to my post called Mapping software architecture to code that discussed how the mapping between the abstractions we talk about as software architects (e.g. components and services) are often never reflected in the code. The slides are available to view online and there's also a video that you can watch, although this was an "in the brain" session so don't expect a polished conference presentation. :-) Packaging code by layer The basic premise of the session is that many software teams structure their code by layer. In other words, if you open up a codebase, you'll see a package for domain classes, one for UI stuff, one for "business services", one for data access, another for integration points and so on. The reason for this is very simple. We know that architectural layering is good and many of the tutorials out there teach this packaging style as a way to structure code. If you do a Google search for tutorials related to Spring or ASP.NET MVC, for example, you'll see this in the sample code. I spent 10+ years in London building software systems in Java and I too used the same packaging approach for the majority of the projects that I worked on. Although there's nothing particularly wrong with packaging code in this way, this code structure never quite reflects the abstractions that we think about when we view the system from an architecture perspective. If you're using an OO programming language, do you talk about "objects" when you're having architecture discussions? In my experience, the answer is no. I typically hear people referring to concepts like components and services instead. The result is that a "component" on an architecture diagram is actually implemented by a combination of classes across a number of different layers. For example, you may find *part* of the component in a "services" package and the rest of the component inside the "data access" package. In order to make this possible, the code in the lower layers (e.g. that "data access" package) often has public visibility, which means that it can be called directly from any other layer in the architecture. So what? The driver for having this discussion is that a good software architecture enables agility. For example, there's a growing trend for building software systems from loosely coupled micro-services, which are basically very small applications that do one thing and do one thing well. While the benefits are easy to see, in my experience, many (most?) teams are still building systems that are monolithic in nature. In my view, both architectural styles have their advantages and disadvantages, with the decision to build a monolithic system vs one composed of micro-systems coming back to the trade-offs that you are willing to make. A major disadvantage of building a monolithic system is that it requires some major architectural refactoring in order to reshape it so that parts of the system can be deployed and evolved separately. As with all things in the IT industry, there's a middle ground between these extremes. There's nothing stopping you from building a monolithic system but structured in a way that allows you to migrate to a micro-service architecture more easily at a later date. This is what component-based development is all about and although many people *talk* about their software systems in terms of components, that structure isn't usually reflected in the code. This is one of the reasons why there is a disconnect between software architecture and coding as disciplines - the architecture diagrams on the wall say one thing, but the code says another. Here's an example of a codebase that I've built where much of the code has been packaged by component. I'll write a separate blog post on the details later but the architectural components and code structure have a one-to-one mapping. There are some trade-offs, but I do quite like it as an approach. Perhaps bringing the software architecture and coding worlds closer together would prevent teams getting nervous whenever somebody mentions the phrase "architectural refactoring"? * I'm using the Java terminology of a "package" here, but the same is applicable to namespaces in C#, etc.
http://java.dzone.com/articles/aligning-software-architecture
CC-MAIN-2014-42
refinedweb
732
58.21
This article takes off from an earlier one on constant pointers. Here, the focus is on dangling pointershow they occur and how to prevent them. The article is a great guide for C newbies. Dangling pointers are those in the C programming language that do not point to valid objects. Pointers are like sharp knives that have tremendous power in C programming. When used properly, they reduce the complexity of the programs to a great extent. But when not used properly, they result in adverse effects and, in the worst case scenario, may crash the system. In this article, I mainly focus on dangling pointers and what causes them by looking at several different situations in which they occur. I also suggest simple methods to avoid them. Note: Code snippets provided here are tested with the GCC compiler [gcc version 4.7.3] running under the Linux environment. Lets now look at three different cases that give rise to dangling pointers. Case 1: When a function returns the address of the auto variables Consider the simple code snippet given below (Code 1): 1 #include <stdio.h> 2 3 int *fun(void); 4 5 int main() 6 { 7 int *int_ptr = fun(); 8 printf(The value at address %p : %d\n, int_ptr, *int_ptr); 9 return 0; 10 } 11 12 int *fun(void) 13 { 14 int auto_var = 10; 15 return (&auto_var); 16 } When we run the program shown in Code 1 in the GCC compiler, we get the warning shown in Figure 1. What is wrong when the address of the auto/local variables is returned? Let us examine this in detail: - We know that whenever there is a function call, a new stack frame will be created automatically, where auto variable auto_var is local in our example. Its scope and lifetime is within the function call. - When the control returns from the function call, all the memory allocated for that function will be freed automatically. - In our example program, we are returning the address of the auto variable and collecting this in the int_ptr pointer in the main function. So, int_ptr is still pointing to the memory, which is freed as mentioned in Point 2. - One can observe allocation and deallocation of the stack frame (let us called this fun frame) for the fun() in Figure 2 for better understanding. - Now, int_ptr becomes a dangling pointer. Dereferencing this pointer results in unexpected output. - So, always take extra care while playing with pointers and local variables. Any attempt to dereference the pointer that is already dangling may still print the correct value after the control returning from a function call, but any functions called thereafter will overwrite the stack storage allocated for the auto_var variable with other values, and the pointer will no longer work correctly. How to prevent a pointer from becoming a dangling pointer in this case: If a pointer to auto_var is to be returned, auto_var must have scope beyond the function so that it may be declared as static in order to avoid the pointer from dangling. This is because the memory allocated to the static variables is from the data segment, where the lifetime will be throughout the program. Case 2: When the variable goes out of scope Consider the sample code (Code 2) given below for analysis: 1 #include <stdio.h> 2 3 int main() 4 { 5 int *iptr; 6 //Block started 7 { 8 int var = 10; 9 iptr = &var; 10 } //After this block iptr is dangling 11 //Some code goes here 12 return 0; 13 } Running the program shown in Code 2 in the GCC compiler with the -Wall option results in the warning shown in Figure 3. Since the variable var is invisible for the outer block shown in Code 2, iptr is still pointing to the same object even when the control comes out of the inner block. Hence, the pointer iptr becomes a dangling pointer after Line 10 in the example shown in Code 2. Case 3: When, in dynamic memory allocation, the block of memory that is already freed is used Consider the sample code given below: 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 5 int main() 6 { 7 int *block_ptr = (int *) malloc(sizeof(int)); 8 9 //Do something with allocated memory 10 11 free(block_ptr); 12 13 //Some statements 14 15 *block_ptr = 20; 16 //Pointer becomes dangling, since the memory 17 //block to which it is pointing is already freed 18 19 return 0; 20 } In the code snippet shown above, Line 5: Memory allocation by malloc(). Line 9: Memory allocated is freed by free() manually. Line 13: Reusing the pointer, which is still pointing to the memory that is already freed. In our example, block_ptr is now the dangling pointer. Note: In Case 1: Memory is freed automatically.In Case 3: Memory is freed manually. This is one of the key differences between stack and heap. In the C programming language, deleting an object from memory explicitly or by destroying the stack frame on the return of the control does not alter associated pointers as seen in Case 1 and Case 3. The pointer still points to the same location in memory, even though the reference has since been deleted and may now be used for other purposes. Solution for the problem in Case 3: In Case 3, the dangling pointer can be avoided by initialising it to NULL immediately after freeing it, if the OS is capable of detecting the runtime references as shown below: 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int main() 5 { 6 int *block_ptr = (int *) malloc(sizeof(int)); 7 8 //Do something with allocated memory 9 free(block_ptr); 10 //Initialising the block pointer to NULL 11 block_ptr = NULL; 12 //Now, block_ptr is no more dangling 13 //Some statements 14 15 *block_ptr = 20; 16 //Error: Dereferencing the NULL pointer, gives segmentation fault 17 return 0; 18 } Dangling pointers are very harmful and have adverse effects in embedded systems programming. So, they should be strictly avoided. Connect With Us
http://opensourceforu.com/2015/04/dangling-pointers-avoid-them-strictly/
CC-MAIN-2017-26
refinedweb
1,008
58.62
Generics¶ Defining generic classes¶ The built-in collection classes are generic classes. Generic types have one or more type parameters, which can be arbitrary types. For example, Dict[int, str] has the type parameters int and str, and List[int] has a type parameter int. Programs can also define new generic classes. Here is a very simple generic class that represents a stack: from typing import TypeVar, Generic T = TypeVar('T') class Stack(Generic[T]): def __init__(self) -> None: # Create an empty list with items of type T self.items = [] # type: List[T] def push(self, item: T) -> None: self.items.append(item) def pop(self) -> T: return self.items.pop() def empty(self) -> bool: return not self.items The Stack class can be used to represent a stack of any type: Stack[int], Stack[Tuple[int, str]], etc. Using Stack is similar to built-in container types: # Construct an empty Stack[int] instance stack = Stack[int]() stack.push(2) stack.pop() stack.push('x') # Type error Type inference works for user-defined generic types as well: def process(stack: Stack[int]) -> None: ... process(Stack()) # Argument has inferred type Stack[int] Construction of instances of generic types is also type checked: class Box(Generic[T]): def __init__(self, content: T) -> None: self.content = content Box(1) # OK, inferred type is Box[int] Box[int](1) # Also OK s = 'some string' Box[int](s) # Type error Generic class internals¶ You may wonder what happens at runtime when you index Stack. Actually, indexing Stack returns essentially a copy of Stack that returns instances of the original class on instantiation: >>> print(Stack) __main__.Stack >>> print(Stack[int]) __main__.Stack[int] >>> print(Stack[int]().__class__) __main__.Stack Note that built-in types list, dict and so on do not support indexing in Python. This is why we have the aliases List, Dict and so on in the typing module. Indexing these aliases gives you a class that directly inherits from the target class in Python: >>> from typing import List >>> List[int] typing.List[int] >>> List[int].__bases__ (<class 'list'>, typing.MutableSequence) Generic types could be instantiated or subclassed as usual classes, but the above examples illustrate that type variables are erased at runtime. Generic Stack instances are just ordinary Python objects, and they have no extra runtime overhead or magic due to being generic, other than a metaclass that overloads the indexing operator. Defining sub-classes of generic classes¶ User-defined generic classes and generic classes defined in typing can be used as base classes for another classes, both generic and non-generic. For example: from typing import Generic, TypeVar, Iterable T = TypeVar('T') class Stream(Iterable[T]): # This is a generic subclass of Iterable def __iter__(self) -> Iterator[T]: ... input: Stream[int] # Okay class Codes(Iterable[int]): # This is a non-generic subclass of Iterable def __iter__(self) -> Iterator[int]: ... output: Codes[int] # Error! Codes is not generic class Receiver(Generic[T]): def accept(self, value: T) -> None: ... class AdvancedReceiver(Receiver[T]): ... Note You have to add an explicit Iterable (or Iterator) base class if you want mypy to consider a user-defined class as iterable (and Sequence for sequences, etc.). This is because mypy doesn’t support structural subtyping and just having an __iter__ method defined is not sufficient to make mypy treat a class as iterable. Generic[...] can be omitted from bases if there are other base classes that include type variables, such as Iterable[T] in the above example. If you include Generic[...] in bases, then it should list all type variables present in other bases (or more, if needed). The order of type variables is defined by the following rules: - If Generic[...]is present, then the order of variables is always determined by their order in Generic[...]. - If there are no Generic[...]in bases, then all type variables are collected in the lexicographic order (i.e. by first appearance). For example: from typing import Generic, TypeVar, Any T = TypeVar('T') S = TypeVar('S') U = TypeVar('U') class One(Generic[T]): ... class Another(Generic[T]): ... class First(One[T], Another[S]): ... class Second(One[T], Another[S], Generic[S, U, T]): ... x: First[int, str] # Here T is bound to int, S is bound to str y: Second[int, str, Any] # Here T is Any, S is int, and U is str Generic functions¶ Generic type variables can also be used to define generic functions: from typing import TypeVar, Sequence T = TypeVar('T') # Declare type variable def first(seq: Sequence[T]) -> T: # Generic function return seq[0] As with generic classes, the type variable can be replaced with any type. That means first can be used with any sequence type, and the return type is derived from the sequence item type. For example: # Assume first defined as above. s = first('foo') # s has type str. n = first([1, 2, 3]) # n has type int. Note also that a single definition of a type variable (such as T above) can be used in multiple generic functions or classes. In this example we use the same type variable in two generic functions: from typing import TypeVar, Sequence T = TypeVar('T') # Declare type variable def first(seq: Sequence[T]) -> T: return seq[0] def last(seq: Sequence[T]) -> T: return seq[-1] Generic methods and generic self¶ You can also define generic methods — just use a type variable in the method signature that is different from class type variables. In particular, self may also be generic, allowing a method to return the most precise type known at the point of access. Note This feature is experimental. Checking code with type annotations for self arguments is still not fully implemented. Mypy may disallow valid code or allow unsafe code. In this way, for example, you can typecheck chaining of setter methods: Without using generic self, the last two lines could not be type-checked properly. Other uses are factory methods, such as copy and deserialization. For class methods, you can also define generic cls, using Type[T]: from typing import TypeVar, Tuple, Type T = TypeVar('T', bound='Friend') class Friend: other = None # type: Friend @classmethod def make_pair(cls: Type[T]) -> Tuple[T, T]: a, b = cls(), cls() a.other = b b.other = a return a, b class SuperFriend(Friend): pass a, b = SuperFriend.make_pair() Note that when overriding a method with generic self, you must either return a generic self too, or return an instance of the current class. In the latter case, you must implement this method in all future subclasses. Note also that mypy cannot always verify that the implementation of a copy or a deserialization method returns the actual type of self. Therefore you may need to silence mypy inside these methods (but not at the call site), possibly by making use of the Any type. Variance of generic types¶ There are three main kinds of generic types with respect to subtype relations between them: invariant, covariant, and contravariant. Assuming that we have a pair of types types A and B and B is a subtype of A, these are defined as follows: - A generic class MyCovGen[T, ...]is called covariant in type variable Tif MyCovGen[B, ...]is always a subtype of MyCovGen[A, ...]. - A generic class MyContraGen[T, ...]is called contravariant in type variable Tif MyContraGen[A, ...]is always a subtype of MyContraGen[B, ...]. - A generic class MyInvGen[T, ...]is called invariant in Tif neither of the above is true. Let us illustrate this by few simple examples: Unionis covariant in all variables: Union[Cat, int]is a subtype of Union[Animal, int], Union[Dog, int]is also a subtype of Union[Animal, int], etc. Most immutable containers such as Sequenceand FrozenSetare also covariant. Callableis an example of type that behaves contravariant in types of arguments, namely Callable[[Employee], int]is a subtype of Callable[[Manager], int]. To understand this, consider a function: def salaries(staff: List[Manager], accountant: Callable[[Manager], int]) -> List[int]: ... this function needs a callable that can calculate a salary for managers, and if we give it a callable that can calculate a salary for an arbitrary employee, then it is still safe. Listis an invariant generic type. Naively, one would think that it is covariant, but let us consider this code: class Shape: pass class Circle(Shape): def rotate(self): ... def add_one(things: List[Shape]) -> None: things.append(Shape()) my_things: List[Circle] = [] add_one(my_things) # This may appear safe, but... my_things[0].rotate() # ...this will fail Another example of invariant type is Dict, most mutable containers are invariant. By default, mypy assumes that all user-defined generics are invariant. To declare a given generic class as covariant or contravariant use type variables defined with special keyword arguments covariant or contravariant. For example: from typing import Generic, TypeVar T_co = TypeVar('T_co', covariant=True) class Box(Generic[T_co]): # this type is declared covariant def __init__(self, content: T_co) -> None: self._content = content def get_content(self) -> T_co: return self._content def look_into(box: Box[Animal]): ... my_box = Box(Cat()) look_into(my_box) # OK, but mypy would complain here for an invariant type Type variables with value restriction¶ By default, a type variable can be replaced with any type. However, sometimes it’s useful to have a type variable that can only have some specific types as its value. A typical example is a type variable that can only have values str and bytes: from typing import TypeVar AnyStr = TypeVar('AnyStr', str, bytes) This is actually such a common type variable that AnyStr is defined in typing and we don’t need to define it ourselves. We can use AnyStr to define a function that can concatenate two strings or bytes objects, but it can’t be called with other argument types: from typing import AnyStr def concat(x: AnyStr, y: AnyStr) -> AnyStr: return x + y concat('a', 'b') # Okay concat(b'a', b'b') # Okay concat(1, 2) # Error! Note that this is different from a union type, since combinations of str and bytes are not accepted: concat('string', b'bytes') # Error! In this case, this is exactly what we want, since it’s not possible to concatenate a string and a bytes object! The type checker will reject this function: def union_concat(x: Union[str, bytes], y: Union[str, bytes]) -> Union[str, bytes]: return x + y # Error: can't concatenate str and bytes Another interesting special case is calling concat() with a subtype of str: class S(str): pass ss = concat(S('foo'), S('bar'))) You may expect that the type of ss is S, but the type is actually str: a subtype gets promoted to one of the valid values for the type variable, which in this case is str. This is thus subtly different from bounded quantification in languages such as Java, where the return type would be S. The way mypy implements this is correct for concat, since concat actually returns a str instance in the above example: >>> print(type(ss)) <class 'str'> You can also use a TypeVar with a restricted set of possible values when defining a generic class. For example, mypy uses the type typing.Pattern[AnyStr] for the return value of re.compile, since regular expressions can be based on a string or a bytes pattern. Type variables with upper bounds¶ A type variable can also be restricted to having values that are subtypes of a specific type. This type is called the upper bound of the type variable, and is specified with the bound=... keyword argument to TypeVar. from typing import TypeVar, SupportsAbs T = TypeVar('T', bound=SupportsAbs[float]) In the definition of a generic function that uses such a type variable T, the type represented by T is assumed to be a subtype of its upper bound, so the function can use methods of the upper bound on values of type T. def largest_in_absolute_value(*xs: T) -> T: return max(xs, key=abs) # Okay, because T is a subtype of SupportsAbs[float]. In a call to such a function, the type T must be replaced by a type that is a subtype of its upper bound. Continuing the example above, largest_in_absolute_value(-3.5, 2) # Okay, has type float. largest_in_absolute_value(5+6j, 7) # Okay, has type complex. largest_in_absolute_value('a', 'b') # Error: 'str' is not a subtype of SupportsAbs[float]. Type parameters of generic classes may also have upper bounds, which restrict the valid values for the type parameter in the same way. A type variable may not have both a value restriction (see Type variables with value restriction) and an upper bound. Declaring decorators¶ One common application of type variable upper bounds is in declaring a decorator that preserves the signature of the function it decorates, regardless of that signature. Here’s a complete example: from typing import Any, Callable, TypeVar, Tuple, cast FuncType = Callable[..., Any] F = TypeVar('F', bound=FuncType) # A decorator that preserves the signature. def my_decorator(func: F) -> F: def wrapper(*args, **kwds): print("Calling", func) return func(*args, **kwds) return cast(F, wrapper) # A decorated function. @my_decorator def foo(a: int) -> str: return str(a) # Another. @my_decorator def bar(x: float, y: float) -> Tuple[float, float, bool]: return (x, y, x > y) a = foo(12) reveal_type(a) # str b = bar(3.14, 0) reveal_type(b) # Tuple[float, float, bool] foo('x') # Type check error: incompatible type "str"; expected "int" From the final block we see that the signatures of the decorated functions foo() and bar() are the same as those of the original functions (before the decorator is applied). The bound on F is used so that calling the decorator on a non-function (e.g. my_decorator(1)) will be rejected. Also note that the wrapper() function is not type-checked. Wrapper functions are typically small enough that this is not a big problem. This is also the reason for the cast() call in the return statement in my_decorator(). See Casts.
http://mypy.readthedocs.io/en/latest/generics.html
CC-MAIN-2017-13
refinedweb
2,312
53.71
Everyone wants to get their apps in front of the largest possible audience, and as mobile app stores are global, your app should be too. That makes localization into a vital marketing expense. New development tools make it easy to support multiple languages and cultures, and you’ll find that the hardest part is the language translation itself.. In this article, I’m going to build the same application on Android, iOS, and Windows Phone 8. To do this, I’ll use Xamarin’s Android and iOS tools (formerly known as MonoDroid and MonoTouch). Xamarin’s iOS and Android products use the native localization mechanisms on each platform. So although the iOS and Android information in this article has a definite .NET flavor, the core concepts also apply if you were doing Objective-C and Java development on each platform. Know Your Localization Problem What are the localization needs for your app? Have you been given any localization requirements? If you have, then you already have your marching orders. If you haven’t been given any requirements for localization, think about your target markets. There are global app stores and you don’t want to limit the marketability of your app if you don’t have to. How many languages do you need to support? If your app targets Canadian government employees, you need both English and French. If your app displays public transit information for cities in California, you want English and Spanish at minimum, Chinese and other languages if you can get translation resources. Know who your target audience is for your app. Don’t limit your app sales to a single market. The Basic Terminology There are some common terms used when you talk about localization. I’ll cover the basic ones here. Language: This is the language chosen by the user. The same language in different countries can have different spelling and grammar rules. Locale: The culture for the user. This is the language matched to the country. Locale can be used to differentiate between different dialects of a language. For example American English (en-US) and UK English (en-UK) have different spellings for the same word (such as color and colour) and also different terms for the same items (like hood versus bonnet). It also includes how dates, numbers, and currency are displayed. The locale is usually defined with a lower-case two-character language code and an uppercase two-character county code, separated by a hyphen. The language codes are defined by the ISO 639 standard, using the two-letter codes defined as ISO 639-1. The country codes are defined by the ISO 3166 standard, with ISO 3166-1 alpha-2 defining the two-letter country codes. A locale can be defined by only the language code, but it is more accurate to use language and country to account for regional differences. For example fr-CA represents the French language as it is used in Canada. This can be different than the French used in France with the locale code fr-FR. It’s mostly the same language, but with minor spelling differences and very different idioms. The language resource files used by the applications are selected based on the locale. This is handled by the runtime code; you don’t have to set this manually. Culture/UICulture: The .NET representation of a locale. For the most part, you don’t need to think about this part. The language resource should be selected by the app based on the locale. Right to Left (RTL) Support Do you need to support right-to-left (RTL) languages like Arabic, Hebrew, or Persian? This impacts how you layout out controls on the screen. The latest versions of mobile platforms have good support for RTL layout. If you’re writing an Android app, consider targeting Android 4.2 or later if you need RTL support. Full native support for RTL layout was added to 4.2. You can do RTL in older versions, but it’s much easier in 4.2. To add RTL support in Android 4.2, you’ll need to do the following: - Add the android:supportsRtl attribute to the <application> element in your manifest file and set it to true. This enables the RTL support in Android 4.2 (API level 17) and is ignored in older versions. - Convert “left” and “right” layout properties to “start” and “end.” For example, android:paddingLeft becomes android:paddingStart. RTL layouts do not have the same level of support in iOS. The UILabel control displays the text in RTL if the text starts with the Unicode character 0x200F. Unicode has two characters that are invisible and set the direction of the text. The 0x200F character indicates RTL and 0x200E indicates LTR. If you’re writing an iPhone app, the narrow width of the screen limits you to one text item per row. If you’re displaying multiple items horizontally, you need to detect the language and arrange the controls for the RTL layout. Windows Phone uses a property named FlowDirection to set RTL and LTR. This is set by the current Culture of the phone; you don’t need to do anything to support it. You can override the direction by adding a FlowDirection attribute to a control and setting it to LeftToRight or RightToLeft. Building the Localized Cross Platform The sample app is a basic note-taking app. It doesn’t do a lot, but it does enough to show language and culture localization on each platform. A complete solution containing projects for Android, iOS, and Windows Phone 8 can be downloaded from. Windows Phone 8 First I’m building the app on Windows Phone first because Microsoft has the best tools for writing and testing code; when you add the Xamarin tools, you can stay with a single language. Plus you gain a level of code reuse across the platforms. For localization, you have a secret weapon called the Multilingual App Toolkit. The Multilingual App Toolkit is a Visual Studio extension that handles the grunt work of adding language resource files. It can even use Microsoft Translator to machine translate some of the common language. For localization, you have a secret weapon called the Multilingual App Toolkit. The Multilingual App Toolkit is a Visual Studio extension that handles the grunt work of adding language resource files. You’ll also use the T4 feature in Visual Studio to generate the Android and iOS string resource files from the Windows string resource files. Creating the Windows Phone 8 App I’ll skip how to create a Windows Phone App because you can look at the sample solution or create an app of your own. What you need to do is to make sure that all of the text strings come from a resource file. The standard templates for a new Windows Phone app create the initial AppResources.resx file and wire it up for declarative binding in the XAML. Instead of having embedded text strings like this: <TextBlock Text="Hello World" /> You have something like this: <TextBlock Text="{Binding Path= LocalizedResources.HelloWorld, Source={StaticResource LocalizedStrings}}"/> If you need to set any text properties in the code-behind file, you just add the .NET resource syntax like this: appBarButton.Text = AppResources.Save Once you have the Windows Phone app working and with strings properly placed in the AppResources file, you’ll add some languages and do a rough translation of the text Create the Android App A sample Xamarin.Android app is included with this project (), and you can use that project or create one of your own. The code for using string resources is nearly identical between Xamarin.Android and Google’s Java-based development toolkit. The design of the app should be the Android equivalent of the Windows Phone app. The Android layout files are a rough approximation for the Windows Phone XAML views. Create the app, but don’t worry about localizing the string resources. You’ll want the resources that are generated from the Windows project. The reason for creating the project now is to create the project resource folder so that the tools have a destination folder for their output. Create the iOS App As with the Android app, a sample iPhone app that was created with Xamarin.iOS is included with this project at. If you use Objective-C, the resource files are the same but the source code is different. The UI for this app is code-based; it doesn’t use the .xib files generated by the Xcode Interface Builder tool. It takes a little more to localize an iOS app than it does for Windows or Android, but it’s pretty straight-forward and you’ll use a String Extension method to help out. As with the Android app, you don’t have to worry about localization yet. You just want to get the folders set up for the automated transforms. Install the Multilingual Toolkit Now it’s time to install the Multilingual App Toolkit for Visual Studio 2012. Follow these steps to get the Multilingual App Toolkit installed and usable with the sample project: - Make sure that Visual Studio has all of the latest service packs and critical updates installed. - Install the Multilingual App Toolkit from the language appropriate download link at. - Restart Visual Studio. - Open the solution containing the Windows Phone app and select the Windows Phone app project. - From the TOOLS menu, select “Enable Multilingual App Toolkit.” This enables the Multilingual App Toolkit to the project and adds a pseudo language (that you can ignore). - From the PROJECT menu, select “Add Translation Languages…” This invokes the Translation Languages dialog box, as seen in Figure 1. - Select French and Spanish and press the OK button. This adds the files AppResources.es.xlf and AppResources.fr.xlf to the project in the Resources folder. The xlf files are XLIFF (XML Localization Interchange File Format) files, which is standard XML format for storing localizable data that can be shared with external tools and third-party services. Double-click on the AppResources.fr.xlf file. This opens up the file in the Multilingual Editor, as displayed in Figure 2. Select all of the strings with the state of New (red icon) and click the Translate button. This does a machine translation of each string and is going to be a rough approximation of the translated text. You will get a translation, but translated without any context. A language expert should validate the translation to make sure it’s accurate. The Multilingual Editor sets the state of machine-translated text from “New” to “Needs Review.” This makes it easier for the language expert to know which items need to be reviewed. An alternative way of using auto translate is to right-click on the .xlf files that were just added and select “Generate Machine Translations.” The Multilingual App Toolkit uses the Microsoft Translator service to translate all of the new string resources in the files. Rebuild the project to generate the localized .resx files from the .xlf files. To test the localized string resources, you need to deploy the app to the Windows Phone Emulator and change the country and language. Windows Phone 8 does not differentiate between US Spanish and Spain’s Spanish. This is why, when you did the “es” locale, Windows Phone didn’t recognize “es-US” when you selected Spanish as the language and US as the country. It's a little cumbersome to test localization on Windows Phones because you have to run the Settings app on the Emulator (or device) and change the language (and region). This requires a reboot. There is a shortcut that that requires a couple of lines of code. Instead of having the app pick up the current language and region from the operating system, you can force a specific language. In the constructor method of the main page, add two lines to set CurrentCulture and CurrentUICulture to the locale you want to test. That code will look something like this: public MainPage() { InitializeComponent(); // Force the app to use a specific style Thread.CurrentThread.CurrentCulture = new CultureInfo("es-US"); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture; DataContext = App.ViewModel; BuildLocalizedApplicationBar(); } This can save a lot time during debugging, as opposed to changing the settings in the emulator each time, as that change reboots the emulator. Just remember to comment out or remove that before submitting the app. Otherwise, you’ll have locked every user into one language. One way around this is to put the code inside a #ifdef DEBUG/#endif block. When you compile the code for release, the debug code won’t be in the app. If you set the language in the code, remove that code before you submit the app to the app store. Using the sample Windows Phone project, the English page in English (US) appears in Figure 3. Changing the language to Spanish and the Region to Spain generates the Edit Notes page, as in Figure 4. You can generate the Android and iOS string resource files from the Windows RESX files, but first you need to add the Android and iOS versions of this app to the solution. Generate the Android and iOS Resource Files from the Windows Phone With the Android and iOS apps using string resource files, it’s time to transform the Windows string resource files into string resources for the other platforms. Install the T4 Tools A good programmer uses a tool for the grunt work. For this project, the tool is the T4 feature of Visual Studio, with a free extension from the Visual Studio Gallery called “T4 Toolbox.” T4, which stands for Text Template Transformation Toolkit, is a template-based text generation framework that comes with Visual Studio. It’s used by the Entity Framework to generate entities from database schema and by ASP.NET MVC to generate views and controllers. You’re going to generate language resource files from language .resx files. Among other things, T4 Toolbox makes it easier to generate multiple output files from a single source file. Install T4 Toolbox from within Visual Studio via the Extension Manager. From the main menu, select TOOLS, then Extension and Updates. Then select Visual Studio Gallery for T4 Toolbox and click the Download button, as shown in Figure 5. Add the T4 Scripts I wrote a T4 template that has the classes for transforming the Windows string resource files to the formats needed for Android and for iOS. This T4 file is named Resx2AndroidTemplate.tt and is included in Listing 1. This script defines two classes, Resx2AndroidTemplate and Resx2iOSTemplate. The bulk of the code is in Resx2AndroidTemplate; it loads in a specified .resx file and creates a Dictionary<string, string> list from the string resources in the .resx file. I’ve added properties that let you specify the output folder. With multiple platforms as separate projects within a single solution, being able to specify the paths allows the T4 code to update the .csproj projects files correctly. The TransformText() method takes the Dictionary of resource values and renders an XML file in the format of the Android string resource file. The following is an excerpt from the AppResources.resx resource file for the Windows Phone app: <?xml version="1.0" encoding="utf-8"?> <root> <data name="ApplicationTitle" xml: <value>Notes Demo</value> </data> <data name="Save" xml: <value>Save</value> </data> </root> The TransformText() method renders the following for Android: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="ApplicationTitle"> Notes Demo</string> <string name="Save">Save</string> </resources> The Android and Windows string resources have a very similar format and it’s easy to generate Android from Windows. For iOS, the Resx2iOSTemplate class is based on the Resx2AndroidTemplate class. The TransformText() method renders a string resource file in the format that iOS compiler recognizes. Based on the same AppResources.resx snippet, the rendered for iOS looks like this: "ApplicationTitle"="Notes Demo"; "Save"="Save"; Another T4 script, Res2Others.tt in Listing 2, is the code that collects the resource files and runs the transformations on them. It executes in the Resources folder of the Windows Phone project and uses wild-card matching on the file name to process the .resx file for each language. This script has hard-coded paths to the resource folders for the Android and iOS apps, based on each app being a project in the same solution. This is easy to change to meet your needs. If you aren’t already using the Xamarin tools or the other projects in a different solution, create the folders outside the solution and let the T4 transform output to those folders. To run the transformation, right-click on Res2Others and select Run Custom Tool. The T4 engine runs the script and generates the transformed resource files. The code in Res2Others generates the platform folder names, based on the locale. Android uses specially named folders in the project Resources folder. The folder Values is the default folder and usually contains the English (en) string resources. If only the language is localized, the folder is named Values-xx where “xx” is the two-character language code. If a country code is also used, the name is Values-xx-rYY, with “xx” as the language. The “r” meaning regions and “YY” as the country or region. The “r” is an Android quirk, just having the country/region code should be enough to indicate that there is a region. But, as that is what Android requires, it needs to include that “r.” When Android needs to locate a string resource, it goes from most specific resource to most generic. For example, if you had Spanish language support and included both a generic Spanish resource and a US Spanish resource, it reads the resources in the following order: - Values-es-rUS - Values-es - Values The reason for this is so you don’t need to translate every string for every language. If your app has 90% of the terms as the same translation for Spain and for the US, you put the country-specific terms in the Values-es-rUS and Values-es-rES folders. In iOS, the folders are located off the root folder of the project and are named xx.lproj, where “xx” is the language. Apple does not support region-specific resource files for iOS projects. The first time that iOS resource files are generated, you’ll need to set the Build Action to Content, under the file properties tab. Localizing the Android App After generating the resource files for Android from the Windows Phone project, rebuild the Android project. This generates the symbols for the resource strings so that you can use them in the layout designer and in the code. With the layout files, it’s pretty easy. You set the android:text property to @string/ResourceStringName. It doesn’t matter how many string resource files you have or how they are named, Android references them all as @string. So a TextView control looks like this: <TextView android: You’ll be able to see the value of the NoteTitle resource at design time. You can select the displayed language in the designer to see the other languages. That’s a handy feature that would also be useful with the Windows Phone XAML designer. If you change the language and country in the emulator, remember to restart the app. Otherwise the settings may not be completely localized. If you change the language and country in the emulator, remember to restart the app or the settings may not be completely localized. To reference the resource string in code, use the GetString() method in C# (Xamarin) or in Java. You pass in the resource ID for the string, which is generated when you build the app. In C#, it looks like this: SomeButton.Text = Resources.GetString(Resource.String.SomeText); And in Java, it’s just slightly different: SomeButton.Text = Resources.GetString(R.String.SomeText); In addition to localizing the text in a layout file, you can have different layout files for different locales. As with string resource files, you can add localized layout folders by following the same naming conventions that were used for the string resource files. Localizing the iSO App With iOS, resources get compiled into what Apple calls bundles. To get a string resource, use the LocalizedString() method of the main bundle for the app. It looks something like this: myLabel.Text = NSBundle.MainBundle.LocalizedString("Save", "", ""); This returns the resource value for Save. If the resource does not exist, the value Save is returned. That’s a lot of code to use for every string resource to be assigned. With C#, you can make it much simpler with an extension method. Add this extension to your iOS project: using System; using MonoTouch.Foundation; namespace notes.iPhone { public static class LocalizationExtensions { public static string t(this string translate) { return NSBundle.MainBundle. LocalizedString(translate, "", ""); } } } With that extension, the code to set the Text property of the UILabel control becomes: myLabel.Text = "Save".t(); That extension was posted by Thomas Rosenstein on the Stack Overflow site. This is very handy for catching misspelled string resource keys. Unlike Android and Windows, iOS does not generate resource IDs; if you misspell the key string, you’ll get that back as the translated value. The second parameter of the LocalizedString method is the optional default value. If you do not pass in a value, you get the key string returned. If you set that to something that should not appear in app (like “!!TILT!!!”), it makes it easier to catch misspelled or missing resource keys. Other Concerns There are a few additional considerations to keep in mind. Dates, Numbers, and Currency There’s some additional work besides the language translation that you need to do. Part of the localization process is making sure that dates, times, and numbers are displayed correctly. Always use the .ToString() methods to display the values. If you use the .ToShortDateString() method for a DateTime variable, you’ll always get the right text for the locale. Currency is a different concern. You can’t automatically convert a currency value to the current locale. How you handle currency depends entirely on the needs of the application. Be careful how you localize the currency symbol. The value €10.00 does not have the same value as $10.00. Gender While translated terminology on mobile apps is usually terse, it’s something that you will need to watch out for. In English, the definite article “the” is gender neutral. Many languages, such as French and Spanish, assign a gender to a noun and their equivalent of “the” depends on the gender of that noun. For example, take the following two sentence fragments as they appear in English: - Press the button. - Edit the photo. In French, they could be translated as: - Pressez le bouton - Modifier la photo For these examples, you translate the entire sentence. If you’re creating the sentence at runtime and the noun is selected by the users, you need a way of determining the gender of the noun. Plural forms Handling plural forms can be tricky as the rules vary depending on the language. The most common pattern in English is the singular/plural rule. That’s represented like this: - You have 1 new message. - You have 4 new messages. In your code, you have two resource strings with a placeholder for the quantity; the string is selected by the quantity. Although many languages follow the singular/plural rule, it’s not universal. Asian languages (Chinese, Japanese, Korean, Vietnamese), only use the plural form. The Polish language has two forms (if the number is 1 or ends with 2 or 4-except 12 and 14-and everything else). To get an idea of the number of plural forms, see the list published on the Mozilla Developer site:. If you can avoid having to use plural forms, your code will be simpler. Instead of using the singular and plural forms for the number of emails, put the number at the end like this: - New messages: 1 That works for any quantity, including 0. Another reason to use this method is that it uses less screen real estate, which is always a premium on a mobile phone. Localization is More than Text If your app has images, consider whether there need to be localized versions. If you use an icon or an image that has context in your culture, use a generic version or culture-specific versions. The Stop Sign is often used as an icon to indicate a button to stop a process or an action. Many countries use a variation of the word “Stop” in a red octagon shape, as shown in Figure 6. Other countries use a local word and can even change the shape. Japan uses a triangle shape and the Japanese characters for “Stop” on their stop sign (Figure 7). When in doubt, use culture-specific icons. Avoid using the flag of a country as a symbol to represent the language being used. This can be viewed as offensive to countries with populations that speak different languages. French-speaking Canadians are particularly sensitive to this. This is less of an issue with mobile apps than with browser apps. I have seen many sites that use a flag as way of displaying or changing the language that it’s rendered with. Use the Right Resources for the Text Translation Although I used machine translation for this article, I wouldn’t put out an app without having a language expert review the translations. Machine translation gives you a rough approximation and has value for checking layout and making sure that the text has been moved to a resource file. If you’re fluent in multiple languages, you are the first source for translation for those languages. Remember, localization is a marketing expense. If you know the language well enough to translate it, it’s a cost savings for you. If you really want to reach a global audience, you’ll want to contract the translation work to a company that specializes in app localization. They can also translate the content that you submit to the app stores. Apple has a good list of resources for this work at. Make sure that localization vender can work with the resource file formats that you’re using. Use the Multilingual App Toolkit with its industry-standard XLIFF files. If you use third-party components in your code, make sure that they can be localized and that they respect the locale settings. Summary When designing a mobile application, you want to localize that application so that it reaches more users than an app built just for the default language. If you plan to support multiple platforms, you can get away with only having to have the text resources translated once. With the tools available for Visual Studio and some custom T4 scripting, you can translate once and get resource files for each platform.
https://www.codemag.com/Article/1401081
CC-MAIN-2019-47
refinedweb
4,513
64.71
On 12/11/18, Christian Grothoff <address@hidden> wrote: > e13c79ee..273a6df9 #ifdef's the VLA logic as discussed, but would be > nice if someone with VS could confirm that the compiler is now happy, > especially as my VLA_ARRAY_LEN_DIGEST macro generates stuff like > > char array[((n<4)?1:abort()),4]; > > which I'm not 100% sure will be read as an obviously constant-size > array by some compilers ;-). It wouldn't be a constant expression for any compiler, the C standard says it's not. You're calling a function and using a global variable and a local variable in there. The fact that the _result_ of the expression is a constant expression doesn't make the whole expression constant. > Also, I might have overlooked a VLA somewhere... Line 1324, nonce in MHD_queue_auth_fail_response2(). Since you're willing to use C99 features, here's what I'm thinking. In w32/common/MHD_config.h, you want an exception for the clang toolset, which does support VLAs: /* MS VC doesn't support VLAs, but the clang toolset does */ #ifndef __clang__ #define __STDC_NO_VLA__ 1 #endif and change your macro to something like this: #if __STDC_NO_VLA__ #define MAKE_VLA(TYPE, NAME, REAL_SIZE, MAX_SIZE) \ TYPE NAME[(MAX_SIZE)]; \ if ((REAL_SIZE) > (MAX_SIZE)) \ mhd_panic(mhd_panic_cls, __FILE__, __LINE__, "VLA too big"); #else #define MAKE_VLA(TYPE, NAME, REAL_SIZE, MAX_SIZE) \ TYPE NAME[(REAL_SIZE)]; #endif Use it like this: MAKE_VLA(uint8_t, dig, da->digest_size, MAX_DIGEST); There are a few definitions that have a complicated size, with a combination of the digest size and NONCE_STD_LEN, I'd pay special attention to those, they might not work with my macro. I would again urge you to reconsider going the VLA route and change this all back to constant sizes for all compilers. -- Jonathan McDougall
https://lists.gnu.org/archive/html/libmicrohttpd/2018-12/msg00025.html
CC-MAIN-2019-30
refinedweb
287
56.29
A Character Is Vowel Or Consonant Character is a Vowel or a Consonant Five alphabets out of the 26 alphabets are known as Vowels. These are A, E, I, O, and U. The remaining 21 alphabets are known as the consonants. A computer program can test whether the entered character is a vowel or a consonant. This can be done by comparing the entered character with a set of vowels and consonants. If the character matches with a, e, i, o, or u, or A, E, I, O, or U, it is a vowel. Otherwise, if it matches with any other character, it is consonant. Algorithm to Check Whether a Character is a Vowel or a Consonant Step 1. Start Step 2. Enter the character Step 3. Compare the character with lowercase vowels, return true in a condition of the match. Step 4. Compare the character with uppercase vowels, return true in a condition of the match. Step 5. Stop Read Also: A Number Is Even Or Odd C Program to Check Whether a Character is a Vowel or a Consonant #include <stdio.h> #include <conio.h> int main() { char a; int Lowercase, Uppercase; printf("Enter an alphabet: "); scanf("%c",&a); // returns 1 if a is a lowercase vowel Lowercase = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); // returns 1 if a is an uppercase vowel Uppercase = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); // returns 1 if either of Lowercase or Uppercase is true if (Lowercase || Uppercase) printf("%a is a vowel.", c); else printf("%a is a consonant.", c); return 0; } Output Enter an alphabet: A A is a vowel.
https://prepinsta.com/temporary-c-programming/a-character-is-vowel-or-consonant/
CC-MAIN-2021-43
refinedweb
276
63.9
all class HighlightStopWordsCommand(sublime_plugin.TextCommand): def __init__(self, view): self.view = view stopWords = ['word1', 'word2', 'word3'] self.view.add_regions("inset", ???, "comment") but I don't know how to finish it. How can I highlight all the stopWords on running this command? Also -- how can I make a distinction between checking the entire file and only the part of the file that the user currently sees (so that the command will be run again when the user scrolls to a different portion of the text)? I understand both of these things are simple for those who know them... hence your tips will be greatly appreciated. All best, Tench
http://www.sublimetext.com/forum/viewtopic.php?p=52233
CC-MAIN-2014-10
refinedweb
107
68.77
In a radical and terrifying experiment, I’m going to document what happens when I try to extend the Silverlight Media Framework (SMF) for the Silverlight HyperVideo Player as I do it. This article is part of the Mini-Tutorial Series This article is part of the Silverlight HVP Documentation My plan is to follow along with this video (part of the SMF documentation) and adapt it to extending the SMF player already embedded in the HVP source code so as to add a pseudo-links window to the right of the video player. Adding the SMF Player I begin by checking out (updating) my copy of the Silverlight HVP source code (available here) to version 52279 Opened the project and added a new view named Player Added the DLLs required by the SMF (see Image) Added the namespace for the Media Player to the top of the Player.xaml file Added the code to create a player that begins playing immediately, using the URL provided by the SMF project, as shown in the code block: xmlns:p="clr-namespace:Microsoft.SilverlightMediaFramework.Player; assembly=Microsoft.SilverlightMediaFramework.Player" <p:Player> <p:CoreSmoothStreamingMediaElement </p:Player> 6. Added a block to MainPage.xaml to navigate to the new page: <HyperlinkButton x:Name="PlayerLink" Style="{StaticResource LinkStyle}" NavigateUri="/Player" TargetName="ContentFrame" Content="{Binding Path=ApplicationStrings.PlayerPageTitle, Source={StaticResource ResourceWrapper}}" /> 7. Opened Assets –> Resources –> ApplicationStrings.resx and added a string for the new page title and fixed up any detritus from previous updates. While I was at it, I removed the link to home.xaml and set About.xaml as the default page. Running the application brings you to the About page, clicking on the player page brings up the SMF player and starts the movie. Adding A Custom Player I’m now ready to begin the process covered in the SMF video Extending The Video Player Create a new class: SlhvpPlayer and add these attributes: [TemplatePart(Name="TOCToggle", Type=typeof(ButtonBase))] [TemplateVisualState(Name="ShowTOC", GroupName = "TOCVisibility")] [TemplateVisualState(Name="HideTOC", GroupName = "TOCVisibility")] Indicating that the class will have a template part of type Button that will toggle between the Show and Hide visual states. The new class extends Player, and thus needs a using statement: using Microsoft.SilverlightMediaFramework.Player; We’ll also give the class a private member variable to track whether the Table of Contents (toc) is visible, private bool tocIsVisible; The custom class also overrides OnApplyTemplate, calling the base method but retrieving a reference to the Button that (will be) in the templated player and setting a handler for the click event on that button. The click event toggles between the two visual states. public override void OnApplyTemplate() { base.OnApplyTemplate(); var btn = GetTemplateChild("TOCToggle") as ButtonBase; if (btn != null) { btn.Click += BtnClick; } } private void BtnClick(object sender, RoutedEventArgs e) { tocIsVisible = !tocIsVisible; string whichState = tocIsVisible ? "ShowTOC" : "HideTOC"; VisualStateManager.GoToState(this, whichState, true); } Returning to the Player.xaml file, you’ll need an alias to the project itself, xmlns:hvp="clr-namespace:SilverlightHVP" That will allow you to swap out the SMF player for your derived player: <hvp:SlhvpPlayer> <p:CoreSmoothStreamingMediaElement </hvp:SlhvpPlayer> Templating in Blend All of this is well and good, but nothing will change with the new player unless we open the project in Blend and set some form of behavior for the two Visual States we created. I’ll start by checking in what I have so far (always nice to have a working copy checked in). [Version 52355]. Next Best Practice: I’ll stop for the night and get a good night’s sleep! — Next Day — My goal now is to modify the template to have a place for the links to the right of the video, and a button at the bottom that will make this appear and disappear. Adding the pseudo-links list Returning to the project, I’ll open it in Blend, double click on Player.xaml file and right click on the Player in Objects and Timeline and click on Edit Template –> Copy. I’ve named the template SlhvpPlayerToggleButtonTemplate. I’ll select the radio button to place the new template into a Resource dictionary and name that dictionary SLHvpPlayer.xaml. Click on the layout controls in the toolbox and choose StackPanel. Double click to add a StackPanel to the template, and then right click on the StackPanel in the Objects and Timeline window and use the Order context menu to send it to the back. In the properties window, set its size to Auto/Auto and both alignments to Stretch. Finally, set its orientation to horizontal. Click on the MediaPresenterElement (which displays the video) and drag and drop it onto the StackPanel, causing it to be a child of the StackPanel. Set its width to Auto. To stand in for the links, add a TextBlock to the StackPanel, Set its font to Goergia, 12 and its vertical alignment to center, horizontal alignment to stretch and its height and width to auto. Adding the Toggle Button In the Ojbects and Timeline window, click on the ControllerContainer, and then in properties set its height to Auto. Expand the Layout section and click on the elipses button for the RowDefinition collection (as shown, cropped) . Add two rows to the ControllerContainer, setting the height of each to Auto. In Objects and TimeLine click on the ControllerContainer to make it the selected object and then in the toolbox double click on the button, causing it to be added to the ControllerContainer. Click on the button in either Objects and Timeline or the designer and turn to the properties window where you can set the button’s ColumnSpan to 1, its Row to 1 (second row) and its margins to 0. Set its content to “Toggle.” We want the name of the button to match the name we set up in the TemplatePart attribute for the derived player: TOCToggle. Toggling the View State Click on the States tab to open the States window and notice that the TOCVisibility states are available for you to modify. Click on the ListBox and then on ShowTOC and set visibility to Visible. Then click on HideTOC and set visibility to collapsed. Finally, set the default transition time to 0.3s. Click on the ShowTOC state and then click on the TextBox that holds our pseudo-links and set its Visibility property to visible. Then click on the red circle in the design frame to stop recording state changes. Repeat for HideTOC setting Visibility to collapsed, and then save the project. Return to Visual Studio, click Yes to accept the changes that were made by Expression Blend and run the application. Click on the Player button and the movie starts playing. Click the toggle button to display or hide the “list of links” There is much more to be done, but we’ve extended the SMF player within a view of the HVP project and it is quite clear that we can add both a links and a TOC window based on this work. This is checked in as 52454 Pingback: SMF – How to Install | Host Rage
http://jesseliberty.com/2009/12/17/extending-the-smf-for-the-hvp/
CC-MAIN-2021-17
refinedweb
1,180
60.14
isprint, iswprint, _ismbcprint Remonter à Ctype.h - Index Header File ctype.h, wctype.h, mbstring.h Category Classification Routines Prototype int isprint(int c); int iswprint(wint_t c); int _ismbcprint(unsigned int c); Description Tests for printing character. isprint is a macro that classifies ASCII-coded integer values by table lookup. The macro is affected by the current locale’s LC_CTYPE category. For the default C locale, c is a printing character including the blank space (‘ ‘). You can make this macro available as a function by undefining (#undef) it. Return Value isprint returns nonzero if c is a printing character. Example #include <stdio.h> #include <ctype.h> int main(void) { char c = 'C'; if (isprint(c)) printf("%c is a printable character\n",c); else printf("%c is not a printable character\n",c); return 0; } Portability
https://docwiki.embarcadero.com/RADStudio/Alexandria/fr/Isprint,_iswprint,_ismbcprint
CC-MAIN-2021-39
refinedweb
137
52.15
NAME device_add_child, device_add_child_ordered - add a new device as a child of an existing device SYNOPSIS #include <sys/param.h> #include <sys/bus.h> device_t device_add_child(device_t dev, const char *name, int unit); device_t device_add_child_ordered(device_t dev, int order, const char *name, int unit); DESCRIPTION Create a new child device of dev. The name and unit arguments specify the name and unit number of the device. If the name is unknown then the caller should pass NULL. If the unit is unknown then the caller should pass -1 and the system will choose the next available unit number. The name of the device is used to determine which drivers might be. This allows busses which can uniquely identify device instances (such as PCI) to allow each driver to check each device instance for a match. For busses which rely on supplied probe hints where only one driver can have a chance of probing the device, the driver name should be specified as the device name. Normally unit numbers will be chosen automatically by the system and a unit number of -1 should be given. When a specific unit number is desired (e.g. for wiring a particular piece of hardware to a pre- configured unit number), that unit should be passed. If the specified unit number is already allocated, a new unit will be allocated and a diagnostic message printed. If the devices attached to a bus must be probed in a specific order (e.g. for the ISA bus some devices are sensitive to failed probe attempts of unrelated drivers and therefore must be probed first), the order argument of device_add_child_ordered().
http://manpages.ubuntu.com/manpages/intrepid/man9/device_add_child.9freebsd.html
CC-MAIN-2015-27
refinedweb
271
62.17
Query writing: common performance issues¶ This topic offers some simple tips on how to avoid common problems that can affect the performance of your queries. Before reading the tips below, it is worth reiterating a few important points about CodeQL and the QL language: - CodeQL predicates and classes are evaluated to database tables. Large predicates generate large tables with many rows, and are therefore expensive to compute. - The QL language is implemented using standard database operations and relational algebra (such as join, projection, and union). For further information about query languages and databases, see About QL. - Queries are evaluated bottom-up, which means that a predicate is not evaluated until all of the predicates that it depends on are evaluated. For more information on query evaluation, see Evaluation of QL programs in the QL handbook. Performance tips¶ Follow the guidelines below to ensure that you don’t get tripped up by the most common CodeQL performance pitfalls. Eliminate cartesian products¶ The performance of a predicate can often be judged by considering roughly how many results it has. One way of creating badly performing predicates is by using two variables without relating them in any way, or only relating them using a negation. This leads to computing the Cartesian product between the sets of possible values for each variable, potentially generating a huge table of results. This can occur if you don’t specify restrictions on your variables. For instance, consider the following predicate that checks whether a Java method m may access a field f: predicate mayAccess(Method m, Field f) { f.getAnAccess().getEnclosingCallable() = m or not exists(m.getBody()) } The predicate holds if m contains an access to f, but also conservatively assumes that methods without bodies (for example, native methods) may access any field. However, if m is a native method, the table computed by mayAccess will contain a row m, f for all fields f in the codebase, making it potentially very large. This example shows a similar mistake in a member predicate: class Foo extends Class { ... // BAD! Does not use ‘this’ Method getToString() { result.getName() = "ToString" } ... } Note that while getToString() does not declare any parameters, it has two implicit parameters, result and this, which it fails to relate. Therefore, the table computed by getToString() contains a row for every combination of result and this. That is, a row for every combination of a method named "ToString" and an instance of Foo. To avoid making this mistake, this should be restricted in the member predicate getToString() on the class Foo. Use specific types¶ Types provide an upper bound on the size of a relation. This helps the query optimizer be more effective, so it’s generally good to use the most specific types possible. For example: predicate foo(LoggingCall e) is preferred over: predicate foo(Expr e) From the type context, the query optimizer deduces that some parts of the program are redundant and removes them, or specializes them. Determine the most specific types of a variable¶ If you are unfamiliar with the library used in a query, you can use CodeQL to determine what types an entity has. There is a predicate called getAQlClass(), which returns the most specific QL types of the entity that it is called on. For example, if you were working with a Java database, you might use getAQlClass() on every Expr in a callable called c: import java from Expr e, Callable c where c.getDeclaringType().hasQualifiedName("my.namespace.name", "MyClass") and c.getName() = "c" and e.getEnclosingCallable() = c select e, e.getAQlClass() The result of this query is a list of the most specific types of every Expr in that function. You will see multiple results for expressions that are represented by more than one type, so it will likely return a very large table of results. Use getAQlClass() as a debugging tool, but don’t include it in the final version of your query, as it slows down performance. Avoid complex recursion¶ Recursion is about self-referencing definitions. It can be extremely powerful as long as it is used appropriately. On the whole, you should try to make recursive predicates as simple as possible. That is, you should define a base case that allows the predicate to bottom out, along with a single recursive call: int depth(Stmt s) { exists(Callable c | c.getBody() = s | result = 0) // base case or result = depth(s.getParent()) + 1 // recursive call } Note The query optimizer has special data structures for dealing with transitive closures. If possible, use a transitive closure over a simple recursive predicate, as it is likely to be computed faster. Fold predicates¶ Sometimes you can assist the query optimizer by “folding” parts of large predicates out into smaller predicates. The general principle is to split off chunks of work that are: - linear, so that there is not too much branching. - tightly bound, so that the chunks join with each other on as many variables as possible. In the following example, we explore some lookups on two Elements: predicate similar(Element e1, Element e2) { e1.getName() = e2.getName() and e1.getFile() = e2.getFile() and e1.getLocation().getStartLine() = e2.getLocation().getStartLine() } Going from Element -> File and Element -> Location -> StartLine is linear–that is, there is only one File, Location, etc. for each Element. However, as written it is difficult for the optimizer to pick out the best ordering. Joining first and then doing the linear lookups later would likely result in poor performance. Generally, we want to do the quick, linear parts first, and then join on the resultant larger tables. We can initiate this kind of ordering by splitting the above predicate as follows: predicate locInfo(Element e, string name, File f, int startLine) { name = e.getName() and f = e.getFile() and startLine = e.getLocation().getStartLine() } predicate sameLoc(Element e1, Element e2) { exists(string name, File f, int startLine | locInfo(e1, name, f, startLine) and locInfo(e2, name, f, startLine) ) } Now the structure we want is clearer. We’ve separated out the easy part into its own predicate locInfo, and the main predicate sameLoc is just a larger join. Further information¶ - Find out more about QL in the QL language handbook and QL language specification.
https://help.semmle.com/QL/learn-ql/writing-queries/debugging-queries.html
CC-MAIN-2020-24
refinedweb
1,034
54.22
CMS preview Overview With the addition of side-by-side editing, the preview has the ability to appear within the CMS window when editing content in the Pages section of the CMS. The site is rendered into an iframe. It will update itself whenever the content is saved, and relevant pages will be loaded for editing when the user navigates around in the preview. The root element for preview is .cms-preview which maintains the internal states necessary for rendering within the entwine properties. It provides function calls for transitioning between these states and has the ability to update the appearance of the option selectors. In terms of backend support, it relies on SilverStripeNavigator to be rendered into the .cms-edit-form. LeftAndMain will automatically take care of generating it as long as the *_SilverStripeNavigator template is found - first segment has to match current LeftAndMain-derived class (e.g. LeftAndMain_SilverStripeNavigator). We use ss.preview entwine namespace for all preview-related entwines. SilverStripeNavigatorand CMSPreviewableinterface currently only support SiteTree objects that are Versioned. They are not general enough for using on any other DataObject. That pretty much limits the extendability of the feature. Configuration and Defaults Like most of the CMS, the preview UI is powered by jQuery entwine. This means its defaults are configured through JavaScript, by setting entwine properties. In order to achieve this, create a new file mysite/javascript/MyLeftAndMain.Preview.js. In the following example we configure three aspects: - Set the default mode from "split view" to a full "edit view" - Make a wider mobile preview - Increase minimum space required by preview before auto-hiding Note how the configuration happens in different entwine namespaces ("ss.preview" and "ss"), as well as applies to different selectors (".cms-preview" and ".cms-container"). (function($) { $.entwine('ss.preview', function($){ $('.cms-preview').entwine({ DefaultMode: 'content', getSizes: function() { var sizes = this._super(); sizes.mobile.width = '400px'; return sizes; } }); }); $.entwine('ss', function($){ $('.cms-container').entwine({ getLayoutOptions: function() { var opts = this._super(); opts.minPreviewWidth = 600; return opts; } }); }); }(jQuery)); to the LeftAndMain.extra_requirements_javascript configuration value LeftAndMain: extra_requirements_javascript: - mysite/javascript/MyLeftAndMain.Preview.js is your best reference at the moment - have a look in framework/admin/javascript/LeftAndMain.Preview.js. To understand how layouts are handled in the CMS UI, have a look at the CMS Architecture guide. Enabling preview The frontend decides on the preview being enabled or disabled based on the presence of the .cms-previewable class. If this class is not found the preview will remain hidden, and the layout will stay in the content mode. If the class is found, frontend looks for the SilverStripeNavigator structure and moves it to the .cms-preview-control panel at the bottom of the preview. This structure supplies preview options such as state selector. If the navigator is not found, the preview appears in the GUI, but is shown as "blocked" - i.e. displaying the "preview unavailable" overlay. The preview can be affected by calling enablePreview and disablePreview. You can check if the preview is active by inspecting the IsPreviewEnabled entwine property. Preview states States are the site stages: live, stage etc. Preview states are picked up from the SilverStripeNavigator. You can invoke the state change by calling: ``` the Link in their names. This call will also redraw the state selector to fit with the internal state. See AllowedStates in .cms-preview entwine for the list of supported states. You can get the current state by calling: ``` This selector defines how the preview iframe is rendered, and try to emulate different device sizes. The options are hardcoded. The option names map directly to CSS classes applied to the .cms-preview and are as follows: - auto: responsive layout - desktop - tablet - mobile You can switch between different types of display sizes programmatically, which has the benefit of redrawing the related selector and maintaining a consistent internal state: ``` ``` Preview modes map to the modes supported by the threeColumnCompressor layout algorithm, see layout reference for more details. You can change modes by calling: ``` internal states of the layout. You can reach it by calling: ``` Caveat: the .preview-mode-selector appears twice, once in the preview and second time in the CMS actions area as #preview-mode-dropdown-in-cms. This is done because the user should still have access to the mode selector even if preview is not visible. Currently CMS Actions are a separate area to the preview option selectors, even if they try to appear as one horizontal bar. [/notice] Preview API Namespace ss.preview, selector .cms-preview: - getCurrentStateName: get the name of the current state (e.g. LiveLink or StageLink). - getCurrentSizeName: get the name of the current device size. - getIsPreviewEnabled: check if the preview is enabled. - changeState: one of the AllowedStates. - changeSize: one of auto, desktop, tablet, mobile. - changeMode: maps to threeColumnLayout modes - split, preview, content. - enablePreview: activate the preview and switch to the split mode. Try to load the relevant URL from the content. - disablePreview: deactivate the preview and switch to the content mode. Preview will re-enable itself when new previewable content is loaded.
https://docs.silverstripe.org/en/3/developer_guides/customising_the_admin_interface/preview/
CC-MAIN-2020-10
refinedweb
837
50.02
Created on 2016-04-27 03:34 by xiang.zhang, last changed 2017-03-24 23:31 by xiang.zhang. This issue is now closed. test_options in test_ssl fails on Ubuntu 16.04. I don't know this is due to the newest ubuntu or a recent code change. But I checkout revision 90000 and then rebuild and test, test_option still fails. The traceback is: FAIL: test_options (test.test_ssl.ContextTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/angwer/cpython/Lib/test/test_ssl.py", line 847, in test_options self.assertEqual(0, ctx.options) AssertionError: 0 != 33554432 After some test, I think the reason causing this error is due to SSL_CTX_clear_options. With OPENSSL_VERSION_NUMBER 268443775, SSL_CTX_clear_options(self->ctx, 2248147967) returns 33554432, where SSL_CTX_get_options returns 2248147967. From the manpage of SSL_CTX_clear_options, it seems it should return 0. From the source code (get from apt-get source) of openssl-1.0.2g, I find SSL_CTX_clear_options(ctx, op): op &= ~SSL_OP_NO_SSLv3 return (ctx->options &= ~op) SSL_CTX_set_options(ctx, op): op |= SSL_OP_NO_SSLv3 return (ctx->options |= op) which differs from the official code repos: SSL_CTX_clear_options(ctx, op): return (ctx->options &= ~op) SSL_CTX_set_options(ctx, op): return (ctx->options |= op) This difference is introduced by debian-specific patch: case SSL_CTRL_OPTIONS: + larg|=SSL_OP_NO_SSLv3; return (ctx->options |= larg); case SSL_CTRL_CLEAR_OPTIONS: + larg&=~SSL_OP_NO_SSLv3; return (ctx->options &= ~larg); Can we close this as an Ubuntu-specific problem? This test is already decorated with @skip_if_broken_ubuntu_ssl. I’m not sure Python should go too far out of its way to handle downstream patches, but it seems there is a precedent here. I just spoke with @doko about this here at PyCon. I think we came to the conclusion it might be time to consider removing the old @skip_if_broken_ubuntu_ssl decorator and focus on making the tests work with the most recent releases since pretty much every distributor and current Python releases have moved to disabling the old compromised ssl/tls versions. @skip_if_broken_ubuntu_ssl doesn't work in this case. `hasattr(ssl, 'PROTOCOL_SSLv2')` returns False. I got this when testing 3.5.2rc1 on my Ubuntu 16.04 machine. CAs Xiang Zhang showed, this is Ubuntu doing something crazy. I ignored the failure and shipped 3.5.2rc1, however I would be interested in suppressing the test for 3.5.2 final. That way it has a chance of passing the whole test suite on user's Linux machines...! ubuntu doesn't do anything crazy, but just disables oldish, deprecated und probably now unsecure ssl protocols. This is done by other vendors as well. From my point of of view this skip_if_ubuntu stuff should be replaced by proper feature tests. I'll see if I can come up with another work around. This still affects 3.4 and 3.5. It'd be lovely if it could be fixed in all the still-alive versions. (Yes, this is technically a "bug fix", but I'd still like it fixed in 3.4.) Description: properly handle Ubuntu's openssl having OP_NO_SSLv3 forced on by default Author: Marc Deslauriers <marc.deslauriers@canonical.com> Forwarded: yes, Index: b/Lib/test/test_ssl.py =================================================================== --- a/Lib/test/test_ssl.py +++ b/Lib/test/test_ssl.py @@ -821,7 +821,8 @@ class ContextTests(unittest.TestCase): self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3, ctx.options) ctx.options = 0 - self.assertEqual(0, ctx.options) + # Ubuntu has OP_NO_SSLv3 forced on by default + self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3) else: with self.assertRaises(ValueError): ctx.options = 0 That does seem like it'd make the test failure go away. But the fix seems a little Ubuntu-specific. Is it reasonable to do that when testing on every platform? FWIW I imagine Ubuntu overriding the option will break the example code in the documentation of clearing SSL_OP_NO_SSLv3: <>. If we keep that documentation, I think we should continue to test that clearing the option works, which conflicts with the proposed patch. Well, I want this fixed in 3.5.2 final. If nobody can propose a better patch in the next 24 hours then I'm going with Matthias's patch. FWIW I had a quick look at ways to detect if you are running on Ubuntu. But platform.linux_distribution() seems to be deprecated and looks like it might have trouble differentiating Debian and Ubuntu. So it may be easier to just go with the current patch on all platforms, at least for the moment. Maybe if someone that uses Ubuntu could suggest a specific file or config the test can check for. Well, as Donald Rumsfeld said in 2008: "As you know, you go to war with the army you have, not the army you might want or wish to have at a later time." 3.5.2 final and 3.4.5 final will ship with Matthias's patch as proposed. FWIW I'd accept an improved patch in both versions for the next release. New changeset 4d04aca4afb0 by Matthias Klose in branch '3.5': Issue #26867: Ubuntu's openssl OP_NO_SSLv3 is forced on by default; fix test. New changeset 8f028d04df11 by Matthias Klose in branch '3.4': Issue #26867: Ubuntu's openssl OP_NO_SSLv3 is forced on by default; fix test. Does this need to be backport to py2.7? It suffers from the same problem. This test still fails with lastest Py2.7 on Ubuntu 16.10. Could we backport the patch to silence the failure? ./python -m test.regrtest test_ssl [1/1] test_ssl test test_ssl failed -- Traceback (most recent call last): File "/home/angwer/py2.7/Lib/test/test_ssl.py", line 780, in test_options self.assertEqual(0, ctx.options) AssertionError: 0 != 33554432L 1 test failed: test_ssl New changeset c9ba1862222bcbb309278db028d33a57f039d587 by Xiang Zhang in branch '2.7': bpo-26867: Ubuntu's openssl OP_NO_SSLv3 is forced on by default; fix test. (GH-374)
https://bugs.python.org/issue26867
CC-MAIN-2021-39
refinedweb
952
68.26
On Fri, Jun 17, 2011 at 7:45 AM, Geert Uytterhoeven<geert@linux-m68k.org> wrote:Hi Geert,> This is the WARN_ONCE(!irqs_disabled()) check.>> static inline bool arch_irqs_disabled_flags(unsigned long flags)> {> return (flags & ~ALLOWINT) != 0;> }>> with flags = 0x2300. Due to the "special" value of ALLOWINT on Atari:>> #if defined(MACH_ATARI_ONLY)> /* block out HSYNC on the atari */> #define ALLOWINT (~0x400)> #define MAX_NOINT_IPL 3> #else> /* portable version */> #define ALLOWINT (~0x700)> #define MAX_NOINT_IPL 0> #endif /* machine compilation types */>> the test fails.>> Would it harm to always use the "portable" version?> That one is used on multi-platform kernels anyway?> Or would it cause too many HBLANK interrupts?I'd say it would cause too many unnecessary interrupts. At least withthe original Falcon hardware that was a problem (haven't ever triedthis on the CT60). Not sure I tried multi platform kernels in a longtime, either. For these, it would probably required to male ALLOWINT aruntime optiion in order to avoid this problem (I seem to recall weused the corresponding hbl interrrupt handler for this originallysince it only was a problem on Falcon, not on TT. Does the TT use IPL1 and 2, Andreas?).MAX_NOINT_IPL may not needed any longer because all interrupt andsignal return is now done from assembler code in entry.S, I guess.Probably best to ignore the two lowest IRQ bits on Atari for thepurpose of this test since these are always going to be disabled.Cheers, Michael> BTW, MAX_NOINT_IPL is no longer
https://lkml.org/lkml/2011/6/16/805
CC-MAIN-2015-22
refinedweb
243
66.44
Windows Server 2008, Visual Studio 2008 and .NET 3.5 are exciting new releases for Microsoft. I am responsible for developer and ITPRO excitement and adoption of this platform at Microsoft and want to show a view of the excitement and challenges of the role. People seem to have got overly excited about what we are going to announce at Mix. Nicholas Carr posts Rumor: Microsoft about to unveil web-apps strategy and Robert on “Wait until you see what Ray Ozzie is doing”. The fact is that we have been running a number of services in the cloud for a while such as Biztalk Services which today offers an Identity and Relay service. This is in beta form, but shows our direction. However today at Mix we announced another service offering called SQLServer Data Services ( SSDS ).. Some of the capabilities are a Flexible Entity Model, where no schema required and you can update name/value pairs (which is the smallest unit of storage). You can also store unique ID's within the parent container, for tracking user type information and their is an update timestamp on each operation. Finally the properties are pretty flexible. You can change instance type information on the fly or add additional properties. We support simple types such as decimal, string, bool, etc and all the properties are indexed. There is also the concept of a Container. This defines a unit of consistency and is the boundary for a single search or operation and has a unique name within parent container (and a size limit). Above that you have something called an Authority. This is a collection of containers(from above), analogous to a namespace ( with a DNS) and is the unit of billing and potential geo-location. From an data update and access point of view, there are many choices. You could use the Microsoft Sync Framework for offline data, ADO.Net Data Services Framework or just plain old REST. Its really flexible and this provides a huge advantage. You can find out a whole lot more at the following site or download the following SSDS document on the subject. Cool things are coming out of Mix08 ! There's even something there for we database people: SQL Server Wow! Just....WOW! I can't wait to get stuck into this! Good product but what a complicated and difficult to remember name! I don't care what any of you say, by far the most exciting announcement from today's MIX08 keynote was I've asked this already in a comment posted to another blog... Does anyone know if there is (or will be) an ADO.NET provider for SSDS? As in, something that will make it look like a regular SQL Server from above but doing all the REST or SOAP stuff under the hood. I ask because many there is a big world beyond Ajax and mash-ups. There are scores of ISVs with desktop apps that run on SQL Server who would love to be able to offer a version that stores data in the cloud. This model is ideal when pitching an SQL-based product to smaller prospective customers, many of whom lack a proper IT infrastructure and are slow to take on the responsibility of managing a traditional RDBMS.
http://blogs.msdn.com/neilhut/archive/2008/03/05/microsoft-announces-sqlserver-data-services-ssds-structured-storage-in-the-cloud.aspx
crawl-002
refinedweb
549
63.49
The Universal super class in java - The Object Class, why object class is known as Universal super class, what are key features in it The Object Class is known as universal super class of Java. This is so because Every class you create in Java automatically inherits the Object class. The Object class is super class of all the classes in Java either directly or Indirectly. You don't need to extend it manually. All the properties of Object class are already in your class. You can find the definition of the Object class in java.lang package And there are a few useful methods in this class which you can override in your class. Following program shows a few method with the examples. public class ObjectClass { public static void main(String[] args){ ObjectClass oc = new ObjectClass(); System.out.println(oc.hashCode()); System.out.println(oc.toString()); System.out.println(oc.getClass()); ObjectClass oc1 = new ObjectClass(); System.out.println(oc.equals(oc1)); System.out.println(oc1.hashCode()); System.out.println(oc1.toString()); ObjectClass oc2 = oc; System.out.println(oc.equals(oc2)); } } the output is 1680090029 ObjectClass@642423ad class ObjectClass false 1386102722 ObjectClass@529e3fc2 true Note: the output could be slightly different when you run this program because its up to JVM what hash code it generates for object on your system. In the output you will see that when I used the equals() to compare two object of same class oc and oc1 it returns false, this is because every Object has a different hash code, as you can see in the next like of the boolean result. shows that its is a different object. However if you try to match an object with its reference it will always return the true. I guess there is no need to explain every single bit in the program but here is a small overview of all the methods I have used in this small program. hasCode() - this returns the hash code associated with the Object toString() - returns any object in the form of string getClass() - returns the class Name of the Object equals() - check if two objects are equal or not. along with these main and commonly used methods there is another one which is less used but is very useful and powerful. clone() this is used to clone the object. NOTE: If you have JDK installed you may check the complete definition of Object using command: javap java.lang.Object.
http://www.examsmyantra.com/article/45/java/the-universal-super-class-the-object-class
CC-MAIN-2019-09
refinedweb
409
61.06
I'm working on a certain program and I need to have it do different things if the file in question is a flac file, or an mp3 file. Could I just use this? if m == *.mp3 .... elif m == *.flac .... I'm not sure whether it will work. EDIT: When I use that, it tells me invalid syntax. So what do I do? Assuming m is a string, you can use endswith: if m.endswith('.mp3'): ... elif m.endswith('.flac'): ... To be case-insensitive, and to eliminate a potentially large else-if chain: m.lower().endswith(('.png', '.jpg', '.jpeg')) (Thanks to Wilhem Murdoch for the list of args to endswith) os.path provides many functions for manipulating paths/filenames. (docs) os.path.splitext takes a path and splits the file extension from the end of it. import os filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"] for fp in filepaths: # Split the extension from the path and normalise it to lowercase. ext = os.path.splitext(fp)[-1].lower() # Now we can simply use == to check for equality, no need for wildcards. if ext == ".mp3": print fp, "is an mp3!" elif ext == ".flac": print fp, "is a flac file!" else: print fp, "is an unknown file format." Gives: /folder/soundfile.mp3 is an mp3! folder1/folder/soundfile.flac is a flac file!
https://pythonpedia.com/en/knowledge-base/5899497/checking-file-extension
CC-MAIN-2020-40
refinedweb
221
77.64
in reply to Re: use CGI qw(:standard) vs. use CGIin thread use CGI qw(:standard) vs. use CGI I have heard this before, but I am unclear as to exactly why this is better or what types of problems might be encountered if it was done the other way. Why is it better to call an objects new method like this... $q = CGI->new(); [download] $q = new CGI; [download] Any help is much appreciated. A long time ago i read some material here at the Monastery that disuaded using "indirect object syntax" (thanks Corion). After reading your question, which is a good one ... i did a Google Search Gone Wrong (notice the first hit) and found the result so funny that i just had to share it in the CB. This led to both bart and Corion correcting my search parameters, and bart went searching for material. From one of runrig's journal entries, bart posted this link in the CB. I invite you to copy that code and run it on your own. Done so yet? Good. :) The only difference in the two versions is that the second declares package X::Y before it is used in package X. Had the code not used indirect object syntax, it would not have mattered which package was declared first. That is, new X::Y (@_); should have been X::Y->new(@_);. Using direct object syntax, in essence, is just a Good Habit™ to get into. For your example, it doesn't really matter. But the day may come when you, like Simon Cozens, will get bitten in the butt from using indirect object syntax (or notation). To add some more insight to your original question (and yes, your understanding is correct) i only instantiate a CGI object (via my $cgi = CGI->new;) if i have to reuse that CGI object. Otherwise i just import the functions into my namespace for ease of typing. Check this out: perl -MCGI=foo -le'print foo{bar=>baz}=>qux' [download] Thanks to bart (who should get all the credit for this node), Corion, and of course, yourself and Zaxo. :) jeffa L-LL-L--L-LL-L--L-LL-L-- -R--R-RR-R--R-RR-R--R-RR B--B--B--B--B--B--B--B-- H---H---H---H---H---H--- (the triplet paradiddle with high.
http://www.perlmonks.org/?node_id=462396
CC-MAIN-2017-17
refinedweb
394
72.26
Svelte Native is a community-led integration that extends NativeScript into the popular new framework known as Svelte. These are exciting times for NativeScript, as today the core team directly supports Angular and Vue.js, with the community offering early support for React and Svelte. Curious about Svelte? Svelte was created by Rich Harris to build fast apps. Read more about Svelte and Svelte Native in this intro blog post by Rob Lauer. What follows is a brief interview with Svelte Native creator, David Pershouse: Always been a fan of programming after learning on the Commodore 64. I enjoy all types of programming. I have built games, databases, windows line of business applications. For the last ten or so years I have moved into web and mobile development, mainly C# and whatever flavour of the day front-end Javascript framework is doing the rounds (angular, backbone, prototype, jquery, ractive, riot, react, extjs). I was a late comer to Svelte, getting interested in it only when 3.0.0 was in the works. I had used Rich Harris's RactiveJS for a couple of large customer projects and enjoyed the experience, so I knew that Svelte would be well designed, especially v3. The major version bump would allow those rough edges to be removed that require breaking changes. I had recently used React/Preact and wanted something that had a smoother developer experience, looking at Vue reminded me very much of Ractivejs and prompted me to look at what Rich was up to. Svelte 3 with its compiler approach and unique handling of reactivity seemed like a step into the next generation of frameworks, so I hopped on board. I had recently released a mobile game written in preact and PhoneGap/Capacitor and was looking for a "native" mobile framework that would be as easy to deploy to multiple platforms as the PhoneGap solution, but with native speed/features. I wanted the ease and reactivity of modern JS frontend development, but with the cross platform native capability of something like Xamarin/Xamarin Forms. I tried React Native and Flutter before stumbling upon Nativescript-Vue, and through that I was introduced to Nativescript. Having used Xamarin for previous projects, I am aware how powerful it is to have the full mobile SDK available to your application framework and language runtime. NativeScript manages to achieve the same goal as Xamarin, but for Javascript/Typescript instead of .Net. The fact that it is open source, and maintained/developed by a company (Progress) already highly regarded in the .Net ecosystem, ticked some more boxes for me. Having found Nativescript-Vue, I wanted a similar environment but for Svelte 3. It would also be a good project to teach myself NativeScript and Svelte. The nice things about Svelte Native are the nice things about Svelte. Svelte Native doesn't require a special build of the Svelte compiler. It is a small DOM abstraction that the compiled svelte components interface with, and is based on the DOM code found in Nativescript-Vue. Interestingly, due to Svelte's compiler nature, in the future we could remove the dependency on the DOM abstraction by writing a custom compile target for svelte that would emit Nativescript-core code directly. Svelte Native also provides an implementation of Svelte's awesome transition/intro outro system backed by NativeScript's native transition infrastructure (where possible). They are definitely supportive. There was mentioned a possible future move to under the svelte namespace and domain for the project site and source. Rich Harris helped out with with the REPL and allowed me to pinch the Svelte site design, and has been quick to fix any svelte bugs/behaviours that impacted svelte-native. They also setup a #nativedev channel on the official Svelte discord server. Near term is to get compatibility with the professional NativeScript UI components and the new Tab feature of NativeScript 6.0. I would also like to enable HMR support in the default svelte native template. Medium term is a showcase/examples page to show off apps people have made, and encourage more development. Long term is to maintain the library to keep it supporting the latest NativeScript and Svelte versions. Take it for a spin and report back any problems. Once you have written a mobile app in svelte, it is hard to go back to any other way of doing it. The code and documentation are all open source and available on Github. Pull requests and/or issues are most welcome, or jump onto #nativedev on the Svelte discord if you need a hand.
https://blog.nativescript.org/an-interview-with-svelte-native-creator-david-pershouse/index.html
CC-MAIN-2021-21
refinedweb
764
62.07
Sentiment analysis is a useful tool for gathering information on emotions relayed through text. It relies on text analysis systems to interpret the polarity of the opinions expressed in text — positive, negative or neutral — as well as emotions or interest level. Sentiment analysis programs optimize data comprehension by automatically iterating through text and providing a general conclusion of the sentiment behind a piece of text. A typical use of sentiment analysis is to collect information on customer satisfaction. Thousands of words can be used in a written review of something, so text processing with sentiment analysis is an efficient way to aggregate relevant information about a product to determine the overall opinion of it. This tutorial will teach you how to code an effective sentiment analysis program that looks at the data from customer reviews of Amazon products. In Part 1, you will convert data formats to organize the data and make it easier to work with. Part 2 is the sentiment analysis portion, where you will create word clouds that show the most commonly used words in the reviews of a product. Lastly, you will check the performance of your model through training and testing, and produce a confusion matrix that visualizes your model’s accuracy. By the end of the tutorial, you should be able to: - Import and properly call several programs to use in your code - Convert data from a json gzip format into a more readable chart-style dataframe from Pandas - Use the asin, or Amazon standard identification number, to decipher how many reviews correlate to a product - Use the “worldcloud” Python library to create diagrams showing common words in reviews - Train and test your model by splitting up your data - Use scikit learn to perform logistic regression, vectorization, and other programs to test the model’s accuracy Let’s get started! Tutorial Getting Started For this tutorial, you will need to download this dataset. All of our outcomes will be drawn from this dataset, which holds reviews for Amazon's most and least reviewed Sports and Outdoor products. First, import the necessary Python libraries and packages. import gzip import itertools import string import wordcloud import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt import pylab as pl from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from collections import Counter from sklearn import svm from sklearn.pipeline import Pipeline, make_pipeline from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer %matplotlib inline Part 1: EDA and Preprocessing The dataset you downloaded comes in a json gzip format, so we first have to convert it into something more visual and easy to extract from. gzip is a compression and decompression file format. A Pandas dataframe is like a chart, which is a great alternative since it organizes information into rows and columns, making it easier to read and extract data from. We’re going to create some of our own functions to help ourselves out in the process. - parse_gz opens a .gz formatted file using the gzip library so we can start reading the data. - convert_to_DF converts an opened gzip file into a Pandas dataframe for organization through parsing #Code provided via def parse_gz(path): g = gzip.open(path, 'rb') for l in g: yield eval(l) def convert_to_DF(path): i = 0 df = {} for d in parse_gz(path): df[i] = d i += 1 return pd.DataFrame.from_dict(df, orient='index') Next, we convert from a dataset to a dataframe. It should be downloaded and in the same folder as where this code file is: sports_outdoors = convert_to_DF('reviews_Sports_and_Outdoors_5.json.gz') If you want to see how many words are in this dataframe: print('Dataset size: {:,} words'.format(len(sports_outdoors))) To print out first 3 results of dataframe: sports_outdoors[:3] # note: replace number for more or less results We can see that the review time right now is a date. We want a clock time, so we can use Pandas .to_datetime function: sports_outdoors["reviewTime"] = pd.to_datetime(sports_outdoors["reviewTime"]) We also want to organize the columns according to their relevance sports_outdoors = sports_outdoors[['asin', 'summary', 'reviewText', 'overall', 'reviewerID', 'reviewerName', 'helpful', 'reviewTime', 'unixReviewTime']] Note: asins (Amazon Standard Identification Number) unique to each product and the corresponding number of reviews for each product. Let's check the first 3 results again to see our changes: sports_outdoors.head(3) We can see more columns are organized in the topics we set above and the time column isn't a date anymore. We can also check out the last 3 results: sports_outdoors.tail(3) Finding the Number of Reviews of Unique Products [asin] Continuing to use the Pandas library to explore our dataframe, we're going to get the number of unique items that are in this dataframe. products = sports_outdoors['overall'].groupby(sports_outdoors['asin']).count() print("Number of Unique Products in the Sports & Outdoors Category = {}".format(products.count())) Most and Least Reviewed Products First, we’re going to sort our dataframe so that it’s ordered from most reviewed to least reviewed. sorted_products = products.sort_values(ascending=False) Let’s take a look at the top 20 most reviewed products. From the sorted_products dataframe, we’re going to display the first 20 items, and after printing each one, we’re going to enter the next line for the next print. When results are out, we’re going to print how many reviews the most reviewed product has. print("Top 20 Reviewed Products:\n") print(sorted_products[:20], end='\n\n') print('Most Reviewed Product, B001HBHNHE - has {} reviews.'.format(products.max())) If you save your code and run it, you should see this printed: Turns out, the most reviewed product is this 9mm Pistol Magazine Loader. Now let’s get the least reviewed product. The code is pretty much the same. Return to your code. You can comment out the code that prints the top 20 products but keep the sorting element. print("Bottom 20 Reviewed Products:\n") print(sorted_products[18337:], end='\n\n') print('Least Reviewed Product (Sorted), B003Z6HUZE - has {} reviews.'.format(products.min())) Save and run. This will return in the same format as the most reviewed products. The least reviewed product is a 2-Position Web Nylon Knife Sheath. Preprocessing Now, we have to process our dateset before modeling. Below are our top 11 results. Here, we have punctuation and words that might not matter. Let’s clean it up! sports_outdoors['reviewText'][:11] We’ll start with stopwords. Stopwords are common words that have no definition/not too much meaning (e.g. “the,” “a,” “and”). These words show up way too often and will disrupt our data if they aren’t taken out. Luckily, there is a function stopwords() from NLTK (Natural Learning Toolkit) that helps us remove all of them! There are many languages compatible with this function, but we’re going to use English since the reviews are mainly in English . stops = stopwords.words('english') Tokenize in Python means to split up large amounts of text into smaller parts, and it sometimes can create words that might not be in English. Lemmatize in Python means to group together the different tenses of a word (e.g. “-ed,” “-ing”) so that they can fall under one word. This is important because we don’t want similar words to take up critical space where other words could be. The 2 functions below will help us do this. def tokenize(text): tokenized = word_tokenize(text) no_punc = [] for review in tokenized: line = "".join(char for char in review if char not in string.punctuation) no_punc.append(line) tokens = lemmatize(no_punc) return tokens def lemmatize(tokens): lmtzr = WordNetLemmatizer() lemma = [lmtzr.lemmatize(t) for t in tokens] return lemma Now we’re going to apply these changes to finish cleaning our dataset. reviews = reviews.apply(lambda x: tokenize(x)) reviews[:11] You can see that the reviews have now been split into a list form. Using a list will give us easy access when modeling. Part 2: Modeling Classification / Sentiment Analysis (LogReg, Multinomial) We’re going to make a word cloud with the top words that appear in the written reviews. This will show the most commonly used words in all the reviews of a product, so we can determine if the overall sentiment is positive or negative for a product. Creating a word cloud is made easy thanks to the wordcloud library that we imported from the beginning. Background_color will indicate the background color behind the words. max_font_size sets the largest font size for the most common word, and as the count of other words goes down, relative_scaling will indicate how much the font size will decrease by each time. This is how we will tell visually how often a word is used in comparison to others. There are many more features included that you’re welcome to explore! cloud = wordcloud.WordCloud(background_color='gray', max_font_size=60, relative_scaling=1).generate(''.join(sports_outdoors.reviewText)) fig = plt.figure(figsize=(20, 10)) plt.axis('off') plt.imshow(cloud); Let’s print the top 3 results again: sports_outdoors[:3] We also want to figure out the star rating of a product. We will do this by assuming that negative reviews are rated 1-3 stars, which we will label as 0, and that positive reviews are rated 4-5 stars, labeled as 1. These labels (0 or 1) will go in a new column that we will add so it’s clear what has a positive star value and what has a negative one. sports_outdoors['pos_neg'] = [1 if x > 3 else 0 for x in sports_outdoors.overall] sports_outdoors.head(3) Run the result. review_text = sports_outdoors["reviewText"] Using both methods to determine a review’s rating, we can check to see if the star value corresponds to the sentiment in the text reviews for products. This will show us how accurately the stars represent the actual opinion of a product. Train/Test Split Training data is used to help the machine learn with a dataset, while test data will be used to test the accuracy of the model. Training is how the machine learns how to work with the data, and also gives us an opportunity to check for holes in the program. Testing is where we put our model to work with new data, and check how well it works. We want to keep the data used for training and testing separate. Since the training data was used to train the model, if it were also used in testing, the testing process would be redundant. The model will also appear more accurate than it actually is if the data is reused, since it will easily predict the results for the data it was trained with. The model learned from the training data, so using it again will inaccurately reflect a ‘smarter’ system. x_train, x_test, y_train, y_test = train_test_split(sports_outdoors.reviewText, sports_outdoors.pos_neg, random_state=0) print("x_train shape: {}".format(x_train.shape), end='\n') print("y_train shape: {}".format(y_train.shape), end='\n\n') print("x_test shape: {}".format(x_test.shape), end='\n') print("y_test shape: {}".format(y_test.shape), end='\n\n') Run result: x_train shape: (222252,) y_train shape: (222252,) x_test shape: (74085,) y_test shape: (74085,) Logistic Regression We are going to be using scikit-learn for logistic regression. Logistic regression will compute the probability of an event’s occurrence. In our case, we want to look at the occurrence of words in the reviews for each product. CountVectorizer Vectorization is the process turning text into a numeric representation. CountVectorizer will tokenize and count the occurances of words in our training data. fit() is the function that will take our document name. #Vectorize X_train vectorizer = CountVectorizer(min_df=5).fit(x_train) X_train = vectorizer.transform(x_train) print("X_train:\n{}".format(repr(X_train))) Run result: X_train: <222252x28733 sparse matrix of type '<class 'numpy.int64'>' with 12428687 stored elements in Compressed Sparse Row format> The number of features is how many terms are selected from the original (raw) document. The feature names list is sorted. The number of featured names is the length of the feature names list. feature_names = vectorizer.get_feature_names() print("Number of features: {}".format(len(feature_names))) Run result: Number of features: 28733 Training Data We also want to test our model’s accuracy, so we can make sure that we can trust it. Cross_val_score gives an estimate of the accuracy of our model with the training data. scores = cross_val_score(LogisticRegression(), X_train, y_train, cv=5) print("Mean cross-validation accuracy: {:.3f}".format(np.mean(scores))) Run result: Mean cross-validation accuracy: 0.888 Our accuracy is 0.888. That means the model will be pretty reliable, which is good news! We’re also going to do accuracy estimations on our testing data. logreg = LogisticRegression(C=0.1).fit(X_train, y_train) X_test = vectorizer.transform(x_test) log_y_pred = logreg.predict(X_test) logreg_score = accuracy_score(y_test, log_y_pred) print("Accuracy: {:.3f}".format(logreg_score)) Run result: Accuracy: 0.890 print("Training set score: {:.3f}".format(logreg.score(X_train, y_train))) print("Test set score: {:.3f}".format(logreg.score(X_test, y_test))) Run result: Training set score: 0.907 Test set score: 0.890 A confusion matrix is a visualized summary of the predicted results. Most importantly, it can tell us the type of errors that are being made. This is your standard confusion matrix: - True Positive (TP) : Observation is positive, and was predicted to be positive. - False Negative (FN) : Observation is positive, but was predicted to be negative. - True Negative (TN) : Observation is negative, and was predicted to be negative. - False Positive (FP) : Observation is negative, but was predicted to be positive. log_cfm = confusion_matrix(y_test, log_y_pred) print("Confusion matrix:") print(log_cfm, end='\n\n') print('-'*15) print(np.array([['TN', 'FP'],[ 'FN' , 'TP']])) Run the result. Confusion matrix: [[ 4645 6289] [ 1831 61320]] --------------- [['TN' 'FP'] ['FN' 'TP']] We will now plot our data into an actual matrix. We’re going to use matplotlib.pyplot, which is a library that makes plotting simple (plt). imshow()from matplotlib creates the 2D image you see in the results. The number of boxes that the chart is going to split up into is the number of elements there are. The background color of each box depends on where the number is on the scale used by imshow(). plt.imshow(log_cfm, interpolation='nearest') for i, j in itertools.product(range(log_cfm.shape[0]), range(log_cfm.shape[1])): plt.text(j, i, log_cfm[i, j],horizontalalignment="center",color="white") plt.ylabel('True label (Recall)') plt.xlabel('Predicted label (Precision)') plt.title('Logistic Reg | Confusion Matrix') plt.colorbar(); Run the result. The F1 score measures a test’s accuracy. It usually helps for retrieving information. The F1 score is best at 1 and worst at 0. log_f1 = f1_score(y_test, log_y_pred) print("Logistic Reg - F1 score: {:.3f}".format(log_f1)) Run the result. Logistic Reg - F1 score: 0.938 Our F1 score is pretty close to 1. This means our model is accurate. Success! Conclusion In this tutorial, we walked through how to format usable data for analysis, how to efficiently gather the sentiments behind text reviews and the proper way to train and test the model in order to determine the accuracy of the results. With the help of sentiment analysis, we can optimize the way we understand opinion and emotion in text, and draw valuable conclusions about the products discussed in written reviews. This method of customer review analysis can be very useful in the real world. Paired with additional data, sentiment analysis can give insight for marketing strategies and business models. For example, people’s shopping patterns can be collected and compared to the sentiment analysis, illuminating how trustworthy or valuable certain reviews are. The sentiments can also be checked against the star ratings, like we did in this tutorial, to see how accurately the star values represent what the customers are saying. Sentiment analysis offers an innovative intersection of programming and psychology, where we can efficiently analyze customer/ reviewer needs and opinions through coding. Rather than gather customer surveys or use other feedback methods, we can use computer systems to detect how a group perceives something, and quickly make necessary changes to promote satisfaction. Thus, sentiment analysis programs are very powerful tools in data analysis and marketing.
https://hq.bitproject.org/using-sentiment-analysis-to-draw-conclusions-from-written-product-reviews/
CC-MAIN-2020-29
refinedweb
2,697
56.76
XML::RSS::Parser - A liberal object-oriented parser for RSS feeds. #!. rssor RDFin the tree. Namespace declaration information is still extracted. channeland iteminto a parent-child relationship. In versions 0.9 and 1.0, channeland itemtags are siblings. Two significant changes were made with the release of version 4.0. This change should be transparent in most cases, but deemed necessary for the error handling and special handling of RSS data. This change is inherited from recent changes in XML::Elemental. The previous system was flawed and not widely adopted. Clarkian notation is the form used by XML::SAX and XML::Simple to name a few. Use the process_name in XML::Elemental::Util to parse element and attribute names intoo their namespace URI and local name parts. The following objects and methods are provided in this package. Constructor. Returns a reference to a new XML::RSS::Parser object. method inherited from Class::ErrorHandler. Once the markup has been parsed it is automatically passed through the rss_normalize method before the parse tree is returned to the caller. Registers the given path with namespace URI for XPath lookups. Both parameters are required. An simple utility implemented as an abstract method that will return a fully namespace qualified string for the supplied element. Return values are now in Clarkian notation. Returns the prefix to the given namespace URI. Returns undef if the prefix is not known. Returns the namespace URI to the given prefix. Returns undef if the namespace is not registered. Sets an error message for later retreival and returns undef. Inherited from Class::ErrorHandler. Returns the last error message set by error. Inherited from Class:ErrorHandler. XML::SAX, XML::Elemental, Class::ErrorHandler, Class::XPath 1.4* Versions up to 1.4 have a design flaw that would cause it to choke on feeds with the / character in an attribute value. For example the Yahoo! feeds. The Feed Validator What is RSS? Raising the Bar on RSS Feed Quality "/ rssfeedquality.html" in http: The myth of RSS compatibility "/diveintomark.org/archives/2004/02/04/incompatible- rss" in http: Except where otherwise noted, XML::RSS::Parser is Copyright 2003-2005, Timothy Appnel, cpan@timaoutloud.org. All rights reserved.
http://search.cpan.org/~tima/XML-RSS-Parser-4.0/lib/XML/RSS/Parser.pm
CC-MAIN-2017-04
refinedweb
365
54.18
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Hi, I have written a code for Merge Script in Bitbucket. Its working in Admin but in Admin to repository it showing the following error. [Static type checking] - You tried to call a method which is not allowed: groovy.json.JsonSlurper#() @ line 18, column 20. def JSON_slurper = new groovy.json.JsonSlurper(). These are the import packages i have used for JSON. import groovy.json.JsonOutput import groovyx.net.http.HttpResponseException import groovy.json.JsonSlurper Thanks, please stop forwarding me questions just because you've asked them, it's really annoying and I ignore.
https://community.atlassian.com/t5/Bitbucket-questions/Bitbucket-Merge-script-working-in-Gobal-Admin-but-not-in-Admin/qaq-p/93886
CC-MAIN-2018-47
refinedweb
115
52.76
Groovy, Sometimes You Still Need a Semicolon. Groovy, Sometimes You Still Need a Semicolon. Join the DZone community and get the full member experience.Join For Free Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now. Example the first: Generics at the end of a line: def list = [1,2,3] as List<Integer> println list If you try to compile this in Groovy it will give you the error message: 'unexpected token: println', however this: def list = [1,2,3] as List<Integer>; println listGives the expected output. Example the second: Ambiguous Closures {-> assert GroovyClosureTest == owner.getClass() }() {-> assert GroovyClosureTest == delegate.getClass() }() I don't think you'd really ever need to do something like this, but a closure can be defined and called on a single line. Because of Groovy's special closure parameter syntax ( e.g. list.each() {} being synonomous with list.each({})) the compiler thinks I'm passing the second closure into the first as an argument. Again a semicolon is needed to seperate the two lines: {-> assert GroovyClosureTest == owner.getClass() }(); {-> assert GroovyClosureTest == delegate.getClass() }() From Connect any Java based application to your SaaS data. Over 100+ Java-based data source connectors. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/groovy-sometimes-you-still
CC-MAIN-2018-39
refinedweb
219
50.84
"We are floating in oil and gas but unable to explore it" Under fire on the gas pricing issue, Petroleum and Natural Gas Minister Veerappa Moily on Friday took everyone by surprise by claiming that India was “floating in oil and gas” and every successive Petroleum Minister stood threatened by “import lobbies” not to take decisions aimed at cutting down import of petroleum products. Interestingly, Mr. Moily refrained from naming the lobbies. India, which imports around 80 per cent of oil and gas needs, has been constantly trying to seek investments from domestic and foreign investors in the oil and gas sector. Public sector oil marketing companies are major importers of oil and gas. Bureaucratic delays “I am telling you with all sense of responsibility that we are floating in oil and gas in this country. We are not exploring it; instead we are putting every obstruction to it. There are delays caused by bureaucrats in decision-making and there are lobbies which don’t want us to stop imports. There are some lobbies which threaten every successive Petroleum Minister against taking decisions to cut down imports,” he told reporters in New Delhi. On being repeatedly asked about the lobbies, he said: “history will speak about it. It is for you to judge.” “Oil and gas imports will keep on rising if domestic production is not incentivised through the right pricing policy. We are challenged by the vagaries of international price,” he said. Revision of gas price was aimed at reviving investor sentiment. the sentiment was quite low for the last four to five years and the government had to find the right price to attract investments. Interestingly, even before the Cabinet has discussed the matter, which is confidential in nature, Mr. Moily went public stating that he had proposed to the Cabinet Committee on Economic Affairs (CCEA) the raising of domestic gas price from the current $4.2 per million British thermal unit to $6.775. Asked about CPI MP Gurudas Dasgupta’s allegations that gas price hike was meant to benefit Reliance Industries Ltd (RIL), he said the Petroleum Ministry was open to any solution that would help unshackle the present grid of non-investment-no-production and increased imports. “I had called Mr. Dasgupta but he is not prepared to come for a discussion. But I can reassure him or whosoever is there in the market — all the criticism should be there, but it should not get personal. I am open to all suggestions.” Keywords: Veerappa Moily, import lobbies, Gurudas Dasgupta, oil imports, natural gas pricing, petroleum products, oil and gas sector The right pricing policy must be a variable one. The gas price increase must lead to higher production and thereby reduce the imports cost.But the revision of gas price will not revive the investor sentiment. The investors, whether domestic or foreign,are selfish and donot have any national interest.If their production is increased by 20% , they may be paid extra ,say 20% etc. If their production become less by 20%, they must be paid less by 20%. The government should prepare a MASTER PLAN and ACTION PLAN to reduce the import cost of our oil and gas by 50%, within 5 years by raising the production through all means including foreign investment like CAIRN, PETRONET ,SHELL BPS It seems he is not in a position to initiate any action against them then why the he is continuing as minister? Fantastic statements like Minister Moily's without any credible evidence to support them make people question the basis of how Cabinet members think or what they believe. What kind of decisions one can expect from people who say whatever comes to their mind? One hopes the country's incentives and regime for exploration of oil and gas is competitive and fair. May be Minister Moily can show us why he thinks it is not so. That is a very irresponsible statement by a Union minister with out giving any details of his remarks. he needs to tell the nation is that why Jaipal was replaced by him and who has the authority to control this menace in oil imports. to explore the resources required millions of dollars investments..who believes in our corrupt politicians and system to come forward to invest. god alone can save us... why will someone make an allegation and not offer credence to it? Blow the whistle Mr.minister. India has been always full of natural resources. The only un-useful product produced by India is Humans and their mentality. If a team which is prepared to find the truth and full authority , they will find that even our independence was received with hell of an amount to be paid to lot of people. Forget about the oil fields, there are other natural resources which have been and will be sold at throw away prices so that the richer would become more richer. Moily sir, i praise you for being so daring to say this in front of the media though i wouldn't say that you aren't corrupt. If Mr.Moily is striving for finding and exploring for oil wells and sources within the country it is good for the people and the economy of the nation.Mr.Moily will be lauded for his effort by the entire nation. This is a dangerous trend. Private lobbies who obstruct the Nation's development should be exposed and dealt with, firmly. Government has got the muscle power to take strong steps against such lobbies. Lobbies should never be allowed to even exist since they are extremely harmful. India has abundant natural resources : Rivers, forests, mines, minerals, and now this latest and emphatic acknowledgement by Mr. Moily that India is ' floating in oil and gas' .But, we are struggling to attain the status of a developed nation and are' tied ' to hefty oil import bills with their far reaching implications on our economy and our standard of life. It has again been proved, that our economic ills are manufactured by those at the helm, entrusted with the responsibility to keep the economy robust . What a sad irony that things have come to such a pause,when we have as our PM, an internationally acclaimed economist ! What Mr.Moily has pointed out calls for a national debate and appropriate policy prescriptions to conserve our precious foreign exchange to shore up our balance of payments, instead of spending it by pampering and yoelding to the unnamed import lobbies, besides sparing the aam aadmi from the cascading effects of imported oil and gas price volatilty. “Oil and gas imports will keep on rising if domestic production is not incentivised through right pricing policy. This will be detriment to the interests of the country. We are challenged by the vagaries of international price,” he remarked. This makes sense. We Indians know our Bureaucrats and the 'honest' Public Sector Officials all too well. Now, about the lobby - uh! If you want to paint it black, it is a conscious choice! Petroleum&gas ministry is a gold mine for who ever be the minister in charge except a few like Mani Shankar Iyer and may be Jaipal Reddy who could not oblige the corporate big wigs.It is a natural need to support Reliance Industries and in the proces make them richer,who cares for consumer India.All the best Moily and Ambanis. If India is floating on oil and gas, then Moily must answer why Reliance Industry/Mukesh Ambani said output at the KG-6 acreage fell due to low gas reserves and they had initially overstated the reserve. Citing this reason, Reliance sought clearance from the government for more investments, a fraud that is known as 'gold-plating' of costs in accounting parlance. The former CAG Vinod Rai had red-flagged Reliance's claim and had sought access to the firm's books. Reliance dragged its feet to cause inordinate delays and Shri Rai finally retired. Finally, Gurudas Dasgupta is a well respected leftist trade union leader. I'm no supporter of the communists, but even to imply that Shri Dasgupta is speaking on behalf of the import-lobby is blasphemous. It's an utter disgrace that Moily, whose party Congress has been involved in some of independent India's biggest scams, is making such juvenile allegations. Bold statement by the minister. Good at last somebody is talking about domestic oil resources. High time India explores the domestic oil resources which would help to develop our economy bigway. The Honorable minister should quit and start an oil & gas exploration company. As a public service he does not want to be the new billionairepathy to ensure the citizens of India gets his wise counsel. This is to be understood that the business and industrial environment is not in good position in our country,tough decisions has to be taken by the ministries and government with equal provisions for check on financial irregularities,violations of legal norms and frauds by corporate groups transparency in functioning and yes,investors need to be attracted towards our market as to bring back economy of India on road to progress but what is more important is socio-economic progress. Very well spoken. The minister has come out plainly and put it out very transparently over the price issue. His openness to debate it in worthy manner, without prejudice is truly appreciated. A very shocking revelation by oil minister. Indeed we should not relent to any pressure, oil is a commodity which can derail indian economy completely, should be taken on priority. A very candid statement indeed from a very important Union Minister, which paints a very worrying picture for the nation. Coming from the Petroleum ministry, this is shocking indeed. I hope the Minister has referred the matter to the CBI and / or the Intelligence Bureau. By refusing to name names, he gives the impression of being scared of the import lobby. I find that surprising, since India is not a weak nation. We have strong investigative agencies, and a strong army & police force. It seems incongruous that any lobby that dares to threaten a cabinet minster cannot be dealt with and face the strong arm of the law. I hope this is not just another emotional outburst as our politicians are all too fond of exhibiting. Threatening a minister, any minister, to unwillingly tow a certain policy line is a national security issue of the highest magnitude. I hope the PM, Parliament or the NSA will take action to get to the bottom of this issue. Please Email the Editor
http://www.thehindu.com/business/Economy/import-lobbies-threaten-petroleum-ministers-moily/article4814393.ece
CC-MAIN-2013-48
refinedweb
1,770
61.67
Predicting cricket match scores with machine learning and T-20 cricket, many factors play a key role in deciding what the final score will be. Let’s look at some of the key factors: - Number of wickets left - Number of balls left - On how much scores are the current batsman batting? - How much the team had scored in last 5 overs? - How much the team had lost wickets in last 5 overs? - The nature of the pitch - How strong is the batting and bowling team? I will use some of these factors to predict score using machine learning algorithms. We use regression analysis in machine learning to predict the final score of an ODI or T-20 match. Preparing the dataset I have not scrapped the web pages to prepare the dataset. I have downloaded the dataset from cricsheet. The site gives us ball by ball details of matches. I then wrote a custom code to only include some of the features which I will be using. The dataset contains ball by ball coverage of: - 1188 ODI matches: data/odi.csv - 1474 T-20 matches: data/t20.csv - 617 IPL matches: data/ipl.csv Each dataset consists of following columns(features): - mid: Each match is given a unique number - date: When the match happened - venue: Stadium where match is being played - bat_team: Batting team name - bowl_team: Bowling team name - batsman: Batsman name who faced that ball - bowler: Bowler who bowled that ball - runs: Total runs scored by team at that instance - wickets: Total wickets fallen at that instance - overs: Total overs bowled at that instance - runs_last_5: Total runs scored in last 5 overs - wickets_last_5: Total wickets that fell in last 5 overs - striker: max(runs scored by striker, runs scored by non-striker) - non-striker: min(runs scored by striker, runs scored by non-striker) - total: Total runs scored by batting team after first innings Importing the dataset import pandas as pd dataset = pd.read_csv('data/odi.csv') X = dataset.iloc[:,[7,8,9,12,13]].values #Input features y = dataset.iloc[:, 14].values #Label I have used ‘odi.csv’ datafile here for predicting scores in ODI cricket. One can use ‘t20.csv’ or ‘ipl.csv’ if they want to predict scores of T-20 matches or IPL matches respectively. Features Used: - runs - wickets - overs - striker - non-striker Why didn’t I use other features? While experimenting, all the other features didn’t make much difference in results. You can use a different combination of features and test the code on them. Label Used: total Splitting data into training and testing set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) We will train our model on 75 percent of the dataset and test the model on remaining dataset. Feature Scaling the data from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) Feature scaling is a very important part of machine learning. You can read more about it here Training the dataset Using Linear Regression Algorithm from sklearn.linear_model import LinearRegression lin = LinearRegression() lin.fit(X_train,y_train) Using Random Forest Regression Algorithm from sklearn.ensemble import RandomForestRegressor lin = RandomForestRegressor(n_estimators=100,max_features=None) lin.fit(X_train,y_train) You can use any one of these algorithms but as you will see later random forest regression gives us better accuracy. Testing the dataset on trained model y_pred = lin.predict(X_test) score = lin.score(X_test,y_test)*100 print("R-squared value:" , score) print("Custom accuracy:" , custom_accuracy(y_test,y_pred,20)) R-squared value R-sqaured is a statistic that will give some information about the goodness of fit of a model. In regression, the R-squared coefficient of determination is a statistical measure of how well the regression predictions approximate the real data points. An R-squared value of 1 indicates that the regression predictions perfectly fit the data. Custom accuracy I have defined my own function to measure accuracy of model. Custom Accuracy is defined on the basis of difference between the predicted score and actual score. If this difference falls below a particular thresold, we count it as a correct prediction. def custom_accuracy(y_test,y_pred,thresold): right = 0 l = len(y_pred) for i in range(0,l): if(abs(y_pred[i]-y_test[i]) <= thresold): right += 1 return ((right/l)*100) I have kept thresold as 20 for ODI matches and 10 for T-20 matches. Testing with a custom input import numpy as np new_prediction = lin.predict(sc.transform(np.array([[100,0,13,50,50]]))) print("Prediction score:" , new_prediction) Results Linear Regression Random Forest Regression Code and dataset
https://shivammitra.com/python/predicting-cricket-score/
CC-MAIN-2019-35
refinedweb
771
57.27
On 06/24/2011 09:18 PM, Daniel P. Berrange wrote: > On Fri, Jun 24, 2011 at 02:33:29PM +0800, Lai Jiangshan wrote: >> Add virtkey lib for usage-improvment and keycode translating. >> Add 4 internal API for the aim >> >> const char *virKeycodeSetName(virKeycodeSet codeset); >> virKeycodeSet virParseKeycodeSet(const char *name); > > These should just be done using the standard VIR_ENUM_DECL/IMPL macros. > >> diff --git a/include/libvirt/libvirt.h.in b/include/libvirt/libvirt.h.in >> index 3f634e6..2f2efe7 100644 >> --- a/include/libvirt/libvirt.h.in >> +++ b/include/libvirt/libvirt.h.in >> @@ -1815,6 +1815,12 @@ typedef enum { >> VIR_KEYCODE_SET_ATSET1 = 2, >> VIR_KEYCODE_SET_ATSET2 = 3, >> VIR_KEYCODE_SET_ATSET3 = 4, >> + VIR_KEYCODE_SET_OSX = 5, >> + VIR_KEYCODE_SET_XT_KBD = 6, >> + VIR_KEYCODE_SET_USB = 7, >> + VIR_KEYCODE_SET_WIN32 = 8, >> + VIR_KEYCODE_SET_XWIN_XT = 9, >> + VIR_KEYCODE_SET_XFREE86_KBD_XT = 10, >> } virKeycodeSet; > > IMHO, we don't really need to include the XT_KBD, XWIN_XT or > XFREE86_KBD_XT codesets, since these are all special purpose > sets which are just derived from the based XT set. Lets just > stick to the core interesting sets. So add OSX, USB and WIN32 > only. I found qemu monitor just accept XT_KBD, not XT, maybe I'm wrong. > >> diff --git a/src/util/virtkey.c b/src/util/virtkey.c >> new file mode 100644 >> index 0000000..48fbfcc >> --- /dev/null >> +++ b/src/util/virtkey.c >> @@ -0,0 +1,633 @@ >> + >> +/* >> + * Copyright (c) 2011 Lai Jiangshan >> + * >> + * This program is free software; you can redistribute it and/or modify it >> + * under the terms of the GNU General Public License version 2 as published by >> + * the Free Software Foundation. >> + */ >> + >> +#include <config.h> >> +#include <string.h> >> +#include <stddef.h> >> +#include <libvirt/libvirt.h> >> +#include "virtkey.h" >> + >> +#define ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0])) >> +#define getfield(object, field_type, field_offset) \ >> + (*(typeof(field_type) *)((char *)(object) + field_offset)) >> + >> +struct keycode { >> + const char *linux_name; >> + const char *os_x_name; >> + const char *win32_name; >> + unsigned short linux_keycode; >> + unsigned short xt; >> + unsigned short atset1; >> + unsigned short atset2; >> + unsigned short atset3; >> + unsigned short os_x; >> + unsigned short xt_kbd; >> + unsigned short usb; >> + unsigned short win32; >> + unsigned short xwin_xt; >> + unsigned short xfree86_kbd_xt; >> +}; >> + >> +/* >> + * generated from >> + * script: >> + * >> + * #!/bin/python >> + * import sys >> + * import re >> + * >> + * for line in sys.stdin.xreadlines(): >> + * a = re.match("([^,]*)," * 13 + "([^,]*)$", line[0:-1]).groups() >> + *> + * for i in (0,2,10,1,7,4,5,6,3,8,9,11,12,13): >> + * if i in (0, 2, 10): >> + * b = b + (a[i] and ('"' + a[i] + '"') or 'NULL') + ',' >> + * else: >> + * b = b + (a[i] or '0') + ',' >> + * print " { " + b + "}," >> + */ > > One of the goals of having the keymap data in the CSV file was that > it makes it trivially updatable across apps using it, without making > code changes. In fact my goal is to actually put 'keymaps.csv' and > 'keymaps.pl' into a separate shared package at some point. So rather > than hardcoding this giant array in libvirt, just include the GTK-VNC > keymaps.csv and keymaps.pl file as-is, and run them to generate the > mapping tables for combinations we need. > > NB, keymaps.pl will need to be updated to be able to output a > table for doing "string->keycode" mapping since it doesn't > do that yet. For the plain keycode->keycode mappings though > just use its currently functionality. I didn't find separate git repository for keymaps.csv. Should I copy keymaps.csv to libvirt? keymaps.pl need to be run O(N*N) times and it will generate O(N*N) tables for different translating, I think that 1 table is the best, even the table are bigger. > >> +const char *virKeycodeSetName(virKeycodeSet codeset) >> +{ >> + int i = (int)codeset; >> + >> + if (i < 0 || i >= ARRAY_SIZE(codesetInfo)) >> + return "UNKNOWN"; >> + >> + return codesetInfo[i].name; >> +} >> + >> +virKeycodeSet virParseKeycodeSet(const char *name) >> +{ >> + int i; >> + >> + for (i = 0; i < ARRAY_SIZE(codesetInfo); i++) { >> + if (!strcmp(codesetInfo[i].name, name)) >> + return (virKeycodeSet)i; >> + } >> + >> + return (virKeycodeSet)-1; >> +} > > These just get replaced by VIR_ENUM_IMPL Will do, thanks, > >> +static int virParseKeyNameOffset(unsigned int name_offset, >> + unsigned int code_offset, >> + const char *keyname) >> +{ >> + int i; >> + >> + for (i = 0; i < ARRAY_SIZE(keycodes); i++) { >> + const char *name = getfield(keycodes + i, const char *, name_offset); >> + >> + if (name && !strcmp(name, keyname)) >> + return getfield(keycodes + i, unsigned short, code_offset); >> + } >> + >> + return -1; >> +} > > This will want to use a number table that keymaps.pl will > need to generate for name -> code mapping. > >> +static int virTranslateKeyCodeOffset(unsigned int from_offset, >> + unsigned int to_offset, >> + int key_value) >> +{ >> + int i; >> + >> + for (i = 0; i < ARRAY_SIZE(keycodes); i++) { >> + if (getfield(keycodes + i, unsigned short, from_offset) == key_value) >> + return getfield(keycodes + i, unsigned short, to_offset); >> + } >> + >> + return -1; >> +} > > This is not nice because it is O(n) lookups. If you just use > the keymaps.pl script to generate all the conversion tables > we need, we get O(1) lookups & simpler code. I think O(n) lookups is OK for <=16 keycodes. Thank you very much. I need to investigate/think more Lai > >> diff --git a/tools/virsh.c b/tools/virsh.c >> index fcd254d..a1e2f83 100644 >> --- a/tools/virsh.c >> +++ b/tools/virsh.c >> @@ -58,6 +58,7 @@ >> #include "threads.h" >> #include "command.h" >> #include "count-one-bits.h" >> +#include "virtkey.h" >> >> static char *progname; > > This ought to be in the next patch, since this doesn't need it yet > > Regards, > Daniel
https://www.redhat.com/archives/libvir-list/2011-June/msg01334.html
CC-MAIN-2014-15
refinedweb
825
58.58
Greetings, fellow ethical hackers! Today I will be demonstrating the process by which one can create a polymorphic worm in python. As an aside, I shall explain each and every step of said process; I don't do this just to feed the skiddies. With that said, let's dive into the code. First, we will need to download a few things. Grab a copy of Python 3.5 and install, as well as the winshell module. Now, create a file entitled "morph.pyw". The ".pyw" means that the file will run silently, without displaying the GUI. Open the file (preferably in N++), then type: import os, winshell from win32com.client import Dispatch from random import choice from string import ascii_uppercase from distutils.dir(underscore)util import copy(underscore)tree Note: the (underscore)s should be replaced with actual underscores in your code. These are all of the libraries that we need to import. Next, we will define our vital variables: thisdir = os.getcwd() thatdir = (''.join(choice(ascii_uppercase) for i in range(15))) The first one means that we set a var thisdir equal to the directory containing morph.pyw. The second means that we define thatdir to be a random string of 15 uppercase ASCII characters. Next, type: if os.path.exists(thisdir): ----------if os.path.exists('C:'): --------------------if not os.path.exists(r'C:\\' + thatdir): ---------------------------os.mkdir(r'C:\\' + thatdir) ---------------------------copy_tree(thisdir, r'C:\\' + thatdir) Note: here, dashes represent spaces. This is stating that if there exists a directory thisdir (the superset of files containing morph.pyw), and a drive C: (usually the OS drive letter), and a directory C:\thatdir does not already exist, python will create a directory C:\thatdir and copy the contents of thisdir to C:\thatdir. \ is a reserved character, so we use two backslashes and convert the result to a raw string. Now, key in the following: startup = winshell.startup() path = os.path.join(startup, "Google Chrome.lnk") targ = r"C:\\" + thatdir + r"\\morph.pyw" dirin = r"C:\\" + thatdir ico = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" This defines a var startup to be the windows startup folder, as detected by winshell, a var path to be startup\Google Chrome.lnk (a faux shortcut to the eponymous web browser), a var targ to be C:\thatdir\morph.pyw, a var dirin to be C:\thatdir, and a var ico to be C:\Program Files (x86)\Google\Chrome\Application\chrome.exe (the location of the chrome icon). For this stage of the virus, type: shell = Dispatch('Wscript.Shell') shortcut = shell.CreateShortCut(path) shortcut.TargetPath = targ shortcut.WorkingDirectory = dirin shortcut.IconLocation = ico shortcut.save() We are using Wscript.Shell to create a shortcut, then setting the attributes TargetPath (what the shortcut will link to), WorkingDirectory (the dir of the target), and IconLocation (where the .ico file is) to targ, dirin, and ico, respectively. Now, we do the same for a desktop shortcut: desktop = winshell.desktop() path = os.path.join(startup, "Google Chrome.lnk") targ = r"C:\\" + thatdir + r"\\morph.pyw" dirin = r"C:\\" + thatdir ico = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" shell = Dispatch('Wscript.Shell') shortcut = shell.CreateShortCut(path) shortcut.TargetPath = targ shortcut.WorkingDirectory = dirin shortcut.IconLocation = ico shortcut.save() I already explained a similar process, so I won't go into detail delineating this one. Next, type: if os.path.exists(thisdir): ----------if os.path.exists('Drive:'): --------------------if not os.path.exists(r'Drive:\\' + thatdir): ---------------------------os.mkdir(r'Drive:\\' + thatdir) ---------------------------copy_tree(thisdir, r'Drive:\\' + thatdir) Note: replace the word 'Drive' with a letter in your code. Do this for each possible drive letter. We are copying thisdir to each and every drive in the system. Next, open up a new file in thisdir. This file will be named 'hideme.vbs'. We will use it to silently execute stuff. Inside this file, type: CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False This simply enables us to pass arguments to cmd without any visible GUI. Now, type into morph: if os.path.exists(r'C:\\' + thatdir): cmd = 'wscript.exe r"C:\\" + thatdir + r"\\hideme.vbs" r"C:\\" + thatdir + r"\\payload.file"' os.system(cmd) Note: replace 'payload.file' with the name of your payload (this assumes that payload.file is in the same folder as morph.pyw). This is stating that if our directory C:\thatdir exists, cmd will execute your payload silently. If you want to make it more virulent, use an email sender script as your payload. Create a .bat file called launcher.bat in thisdir. In it, enter: morph.pyw %* This will run morph.pyw Lastly, but perhaps most importantly, type into morph: if os.path.exists(r'C:\\' + thatdir): cmd = 'wscript.exe r"C:\\" + thatdir + r"\\hideme.vbs" r"C:\\" + thatdir + r"\\launcher.bat"' os.system(cmd) This will run the program in an infinite loop, exhausting hard-drive space and crashing the computer. You have finished my tutorial, bravo! Congratulation, a winrar is you! 3 Responses What exactly makes this polymorphic? I suppose that I should have instead said 'pseudo-polymorphic'. It does not exhibit true polymorphic behaviour, as it does not contain an encryption system that permutates each time the virus is run. However, part of its signature, thatdir, does. I will work on creating a dynamic encryption system that changes each time the file is copied. Seriously sorry about the misleading title, I've only recently started writing viruses. Share Your Thoughts
https://null-byte.wonderhowto.com/forum/polymorphic-worm-0172639/
CC-MAIN-2020-29
refinedweb
912
63.05
Parse::Eyapp::Driver - The LR parser This class has the method YYParse implementing the LR generic parsing algorithm plus the methods that give support to the generated parser. YYParseMETHOD The YYParse methods implements the generic LR parsing algorithm. It very much works Parse::Yapp::YYParse and as yacc/bison yyparse. It accepts almost the same arguments as Class->new (Being Class the name of the generated class). The parser uses two tables and a stack. The two tables are called the action table and the goto table. The stack is used to keep track of the states visited. At each step the generated parser consults the action table and takes one decision: To shift to a new state consuming one token (and pushing the current state in the stack) or to reduce by some production rule. In the last case the parser pops from its stack as many states as symbols are on the right hand side of the production rule. Here is a Perl/C like pseudocode summarizing the activity of YYParse: 1 my $parser = shift; # The parser object 2 push(@stack, $parser->{startstate}); 3 $b = $parser->YYLexer(); # Get the first token 4 FOREVER: { 5 $s = top(0); # Get the state on top of the stack 6 $a = $b; 7 switch ($parser->action[$s->state][$a]) { 8 case "shift t" : 9 my $t; 10 $t->{state} = t; 11 $t->{attr} = $a->{attr}; 12 push($t); 13 $b = $parser->YYLexer(); # Call the lexical analyzer 14 break; 15 case "reduce A->alpha" : 16 # Call the semantic action with the attributes of the rhs as args 17 my $semantic = $parser->Semantic{A ->alpha}; # The semantic action 18 my $r; 19 $r->{attr} = $semantic->($parser, top(|alpha|-1)->attr, ... , top(0)->attr); 20 21 # Pop as many states as symbols on the rhs of A->alpha 22 pop(|alpha|); 23 24 # Goto next state 25 $r->{state} = $parser->goto[top(0)][A]; 26 push($r); 27 break; 28 case "accept" : return (1); 29 default : $parser->YYError("syntax error"); 30 } 31 redo FOREVER; 32 } Here |alpha| stands for the length of alpha. Function top(k) returns the state in position k from the top of the stack, i.e. the state at depth k. Function pop(k) extracts k states from the stack. The call $state->attr returns the attribute associated with $state. The call $parser->Semantic{A ->alpha} returns the semantic action associated with production A ->alpha. Let us see a trace for the small grammar in examples/debuggingtut/aSb.yp: pl@nereida:~/LEyapp/examples$ /usr/local/bin/paste.pl aSb.yp aSb.output | head -5 %% | Rules: S: { print "S -> epsilon\n" } | ------ | 'a' S 'b' { print "S -> a S b\n" } | 0: $start -> S $end ; | 1: S -> /* empty */ %% | 2: S -> 'a' S 'b' The tables in file aSb.output describe the actions and transitions to take: pl@nereida:~/LEyapp/examples$ cat -n aSb.output . ......................................... 7 States: 8 ------- 9 State 0: 10 11 $start -> . S $end (Rule 0) 12 13 'a' shift, and go to state 2 14 15 $default reduce using rule 1 (S) 16 17 S go to state 1 18 19 State 1: 20 21 $start -> S . $end (Rule 0) 22 23 $end shift, and go to state 3 24 25 State 2: 26 27 S -> 'a' . S 'b' (Rule 2) 28 29 'a' shift, and go to state 2 30 31 $default reduce using rule 1 (S) 32 33 S go to state 4 34 35 State 3: 36 37 $start -> S $end . (Rule 0) 38 39 $default accept 40 41 State 4: 42 43 S -> 'a' S . 'b' (Rule 2) 44 45 'b' shift, and go to state 5 46 47 State 5: 48 49 S -> 'a' S 'b' . (Rule 2) 50 51 $default reduce using rule 2 (S) 52 53 54 Summary: 55 -------- 56 Number of rules : 3 57 Number of terminals : 3 58 Number of non-terminals : 2 59 Number of states : 6 When executed with yydebug set and input aabb we obtain the following output: pl@nereida:~/LEyapp/examples/debuggingtut$ eyapp -b '' -o use_aSb.pl aSb pl@nereida:~/LEyapp/examples/debuggingtut$ ./use_aSb.pl -d Provide a statement like "a a b b" and press <CR><CTRL-D>: aabb ---------------------------------------- In state 0: Stack:[0] Need token. Got >a< Shift and go to state 2. ---------------------------------------- In state 2: Stack:[0,2] Need token. Got >a< Shift and go to state 2. ---------------------------------------- In state 2: Stack:[0,2,2] Need token. Got >b< Reduce using rule 1 (S --> /* empty */): S -> epsilon Back to state 2, then go to state 4. ---------------------------------------- In state 4: Stack:[0,2,2,4] Shift and go to state 5. ---------------------------------------- In state 5: Stack:[0,2,2,4,5] Don't need token. Reduce using rule 2 (S --> a S b): S -> a S b Back to state 2, then go to state 4. ---------------------------------------- As a result of reducing by rule 2 the three last visited states are popped from the stack, and the stack becomes [0,2]. But that means that we are now in state 2 seeing a S. If you look at the table above being in state 2 and seeing a S we go to state 4. In state 4: Stack:[0,2,4] Need token. Got >b< Shift and go to state 5. ---------------------------------------- In state 5: Stack:[0,2,4,5] Don't need token. Reduce using rule 2 (S --> a S b): S -> a S b Back to state 0, then go to state 1. ---------------------------------------- In state 1: Stack:[0,1] Need token. Got >< Shift and go to state 3. ---------------------------------------- In state 3: Stack:[0,1,3] Don't need token. Accept. Parse::Eyapp::DriverMETHODS The class containing the parser generated by Parse::Eyapp inherits from Parse::Eyapp::Driver. Therefore all the methods in Parse::Eyapp::Driver are available in the generated class. This section describes the methods and objects belonging to the class generated either using eyapp or Parse::Eyapp->new_grammar. In the incoming paragraphs we will assume that Class was the value selected for the classname argument when Parse::Eyapp->new_grammar was called. Objects belonging to Class are the actual parsers for the input grammar. The method Class->new returns a new LALR parser object. Here Class stands for the name of the class containing the parser. See an example of call: my $parser = main->new(yyprefix => 'Parse::Eyapp::Node::', yylex => \&main::_Lexer, yyerror => \&main::_Error, yydebug => 0x1F, ); The meaning of the arguments used in the example are as follows: Used with %tree or %metatree. When used, the type names of the nodes of the syntax tree will be build prefixing the value associated to yyprefix to the name of the production rule. The name of the production rule is either explicitly given through a %name directive or the concatenation of the left hand side of the rule with the ordinal of the right hand side of the production. See section "Compiling with eyapp and treereg" in Parse::Eyapp for an example. Reference to the lexical analyzer subroutine Reference to the error subroutine. The error subroutine receives as first argument the reference to the Class parser object. This way it can take advantage of methods like YYCurval and YYExpect (see below): sub _Error { my($token)=$_[0]->YYCurval; my($what)= $token ? "input: '$token'" : "end of input"; my @expected = $_[0]->YYExpect(); local $" = ', '; die "Syntax error near $what. Expected one of these tokens: @expected\n"; } Controls the level of debugging. Must be a number. The package produced from the grammar has several methods. The parser object has the following methods that work at parsing time exactly as in Parse::Yapp. These methods can be found in the module Parse::Eyapp::Driver. Assume you have in $parser the reference to your parser object: Receives the name of a production and a subroutine reference implementing the new semantic action. If no subroutine reference is set returns the reference to the current semantic action. See the tutorial Parse::Eyapp::defaultaction and the examples in the examples/recycle/ directory Works as yacc/bison YYACCEPT. The parser finishes returning the current semantic value to indicate success. Works as yacc/bison YYABORT. The parser finishes returning undef to indicate failure. Is not a method. Receives as input a Class name. Introduces Parse::Eyapp::Node as an ancestor class of Class. To work correctly, objects belonging to Class must be hashes with a children key whose value must be a reference to the array of children. The children must be also Parse::Eyapp::Node nodes. Actually you can circumvent this call by directly introducing Parse::Eyapp::Node in the ancestors of Class: push @{$class."::ISA"}, "Parse::Eyapp::Node" Sometimes the best time to decorate a node with some attributes is just after being built. In such cases the programmer can take manual control building the node with YYBuildAST to immediately proceed to decorate it. The following example from the file lib/Simple/Types.eyp in the tarball in examples/typechecking/Simple-Types-XXX.tar.gz illustrates the idea: Variable: %name VARARRAY $ID ('[' binary ']') <%name INDEXSPEC +> { my $self = shift; my $node = $self->YYBuildAST(@_); $node->{line} = $ID->[1]; return $node; } Actually, the %tree directive is semantically equivalent to: %default action { goto &Parse::Eyapp::Driver::YYBuildAST } Influences the semantic of list operators. If true the action associated with X+ will be to build a Parse::Eyapp::Node node with all the attributes of the elements in the list as children. This is the appropriate semantic when working under the %tree directive. If set to false the semantic action will return an anonymous list with the attributes associated with the X in the plus list. Same thing with the operators * and ?. Similar to $parser->YYBuildAST but builds nodes for translation schemes. Returns TRUE if running under the %tree bypass clause Returns TRUE if the production being used for reduction was marked to be bypassed. Gives the current token Gives the attribute associated with the current token Use it as defaultaction if you want to recycle your grammar. It is equivalent to: sub YYDelegateaction { my $self = shift; my $action = $self->YYName; $self->$action(@_); } For a full example illustrating how to use it, see files examples/recycle/NoacInh.eyp and examples/recycle/icalcu_and_ipost.pl in the Parse::Eyapp distribution True if the pos() of the input being scanned in ${$parser->input} is at the end Works as yacc/bison yyerrok. Modifies the error status so that subsequent error messages will be emitted. Works as yacc/bison YYERROR. Pretends that a syntax error has been detected. Returns the list of tokens the parser expected when the failure occurred pl@nereida:~/src/perl/YappWithDefaultAction/examples$ \ sed -ne '26,33p' Postfix.eyp sub _Error { my($token)=$_[0]->YYCurval; my($what)= $token ? "input: '$token'" : "end of input"; my @expected = $_[0]->YYExpect(); local $" = ', '; die "Syntax error near $what. Expected one of these tokens: @expected\n"; } See the tutorial Parse::Eyapp::datagenerationtut and the section TOKENS DEPENDING ON THE SYNTACTIC CONTEXT in the tutorial Parse::Eyapp::debuggingtut for more detailed examples of use of YYExpect. First line of the input string describing the grammar Return the list of grammar items. Each item is an anonymous list containing If it receives an index as argument returns the corresponding item The following debugger session explain its use: pl@europa:~/LEyapp/examples/recycle$ perl -wd usepostfix.pl main::(usepostfix.pl:5): my $parser = new Postfix(); DB<1> n main::(usepostfix.pl:6): $parser->Run; DB<1> x $parser->YYGrammar 0 ARRAY(0xde5e20) 0 '_SUPERSTART' 1 '$start' 2 ARRAY(0xc85e80) 0 'line' 1 '$end' 3 0 1 ARRAY(0xe2b6b0) 0 'line_1' 1 'line' 2 ARRAY(0xe3abc0) 0 'exp' 3 0 2 ARRAY(0xa05530) 0 'exp_2' 1 'exp' 2 ARRAY(0x75bdc0) 0 'NUM' 3 0 ... etc, etc If an index is provided it returns the item for such number: DB<2> x $parser->YYGrammar(10) 0 'exp_10' 1 'exp' 2 ARRAY(0xa05f80) 0 '(' 1 'exp' 2 ')' 3 0 You can also use a production name as argument: DB<3> x $parser->YYGrammar('exp_7') 0 'exp_7' 1 'exp' 2 ARRAY(0xa05890) 0 'exp' 1 '*' 2 'exp' 3 0 Returns the shift-reduce action for state $state and token $token. A positive number must be interpreted as a shift to the state with that number. A negative number -m indicates a reduction by production with index m. Returns undef if no action is defined for such combination ($state, $token). See example DynamicallyChangingTheParser.eyp in the directory examples/debuggintut for an example of use. Returns TRUE if the terminal is semantic. Semantics token can be declared using the directive %semantic token. The opposite of a Semantic token is a Syntactic token. Syntactic tokens can be declared using the directive %syntactic token. When using the %tree directive all the nodes corresponding to syntactic tokens are pruned from the tree. Under this directive tokens in the text delimited by simple quotes (like '+') are, by default, considered syntactic tokens. When using the %metatree directive all the tokens are considered, by default, semantic tokens. Thus, no nodes will be - by default- pruned when construction the code augmented tree. The exception are string tokens used as separators in the definition of lists, like in S <* ';'>. If you want the separating string token to appear include an explicit semantic declaration for it (example %semantic token ';'). Receives the name of production (right hand side). Returns the index in the grammar of the production with such name. When called in a list context and without a name return the hash containing the relation production name => production index The following debugger session illustrates its use: pl@europa:~/LEyapp/examples/recycle$ perl -wd usepostfix.pl main::(usepostfix.pl:5): my $parser = new Postfix(); main::(usepostfix.pl:6): $parser->Run; DB<1> x $parser->YYIndex 0 'line_1' 1 1 2 'exp_3' 3 3 4 'exp_6' 5 6 6 'exp_4' 7 4 8 'exp_10' 9 10 10 'exp_8' 11 8 12 'exp_5' 13 5 14 'exp_7' 15 7 16 'exp_2' 17 2 18 '_SUPERSTART' 19 0 20 'exp_9' 21 9 We can specify a list of names: DB<2> x $parser->YYIndex(qw{exp_4 exp_7}) 0 4 1 7 DB<3> x $parser->YYIndex(qw{exp_4}) 0 4 Alias input. If an argument is provided, sets the input for the parser object. The argument is a string or a reference to a string. It returns a reference to the input string or undef if not set. Returns TRUE if the symbol given as argument is a terminal. Example: DB<0> x $self->YYIsterm('exp') 0 '' DB<1> x $self->YYIsterm('*') 0 1 An example of combined use of YYRightside, YYRuleindex, YYLhs and YYIsterm can be found examples/Eyapp/Rule3.yp: nereida:~/src/perl/YappWithDefaultAction/examples> sed -n -e '4,22p' Rule3.yp | cat -n 1 sub build_node { 2 my $self = shift; 3 my @children = @_; 4 my @right = $self->YYRightside(); 5 my $var = $self->YYLhs; 6 my $rule = $self->YYRuleindex(); 7 8 for(my $i = 0; $i < @right; $i++) { 9 $_ = $right[$i]; 10 if ($self->YYIsterm($_)) { 11 $children[$i] = bless { token => $_, attr => $children[$i] }, 12 __PACKAGE__.'::TERMINAL'; 13 } 14 } 15 bless { 16 children => \@children, 17 info => "$var -> @right" 18 }, __PACKAGE__."::${var}_$rule" 19 } when executed an output similar to this is produced: nereida:~/src/perl/YappWithDefaultAction/examples> userule3.pl 2*3 $VAR1 = bless( { 'info' => 'exp -> exp * exp', 'children' => [ bless( { 'info' => 'exp -> NUM', 'children' => [ bless( { 'attr' => '2', 'token' => 'NUM' }, 'Rule3::TERMINAL' ) ] }, 'Rule3::exp_6' ), bless( { 'attr' => '*', 'token' => '*' }, 'Rule3::TERMINAL' ), bless( { 'info' => 'exp -> NUM', 'children' => [ bless( { 'attr' => '3', 'token' => 'NUM' }, 'Rule3::TERMINAL' ) ] }, 'Rule3::exp_6' ) ] }, 'Rule3::exp_11' ); Returns a reference to the lexical analyzer Returns the identifier of the left hand side of the current production (the one that is being used for reduction/reverse derivation. An example of use can be found in examples/Eyapp/Lhs1.yp: %defaultaction { print $_[0]->YYLhs,"\n" } Alias is also main. Other than the package, it has as optional arguments the prompt (shown each time it ask for input), the name of the input file (if it wasn't specified in the command line using --file filename) and also the input string. This method provides a default main for testing the generated parser. It parses the commandline searching for a number of options. See an example of use: pl@nereida:~/LEyapp/examples/eyapplanguageref$ cat use_list2.pl #!/usr/bin/env perl use warnings; use strict; use List2; unshift @ARGV, '--noslurp'; List2->new->main("Try input 'aacbb': "); pl@nereida:~/LEyapp/examples/eyapplanguageref$ ./use_list2.pl --help) Returns the name of the current rule (The production whose reduction gave place to the execution of the current semantic action). DB<12> x $self->YYName 0 'exp_11' Return the list of production names. In a scalar context returns a reference to such list. pl@europa:~/LEyapp/examples/recycle$ eyapp Postfix pl@europa:~/LEyapp/examples/recycle$ perl -wd usepostfix.pl main::(usepostfix.pl:5): my $parser = new Postfix(); main::(usepostfix.pl:6): $parser->Run; DB<1> x $parser->YYNames 0 '_SUPERSTART' 1 'line_1' 2 'exp_2' 3 'exp_3' 4 'exp_4' 5 'exp_5' 6 'exp_6' 7 'exp_7' 8 'exp_8' 9 'exp_9' 10 'exp_10' The current number of errors If called inside a semantic action, returns the state after the reduction by the current production. Provide a token if called from any other side: $parser->YYNextState($token); It will return the state given by the action table for the state in the top of the stack and the given token. For an example, see the program DynamicallyChangingTheParser.eyp in the directory examples/debuggintut/. Return and/or sets the yyprefix attribute. This a string that will be concatenated as a prefix to any Parse::Eyapp::Node nodes in the syntax tree. It very much works Parse::Yapp::YYParse and as yacc/bison yyparse. It accepts almost the same arguments as Class->new with the exception of yyprefix which can be used only with new. Works as yacc/bison YYRECOVERING. Returns TRUE if the parser is recovering from a syntax error. This method has been designed to solve shift-reduce and reduce-reduce conflicts at parsing-time using the postponed conflict strategy. It has to be called inside the semantic action associated with the postponed conflict rule. The LALR table is changed so that the action in the presence of the token $token is restored the one before the last call to $parser->YYSetReduce($token, $productionname ) See the examples in examples/debuggingtut/ in files DynamicallyChangingTheParser2.eyp and Cplusplus.eyp. Also: $parser->YYRHSLength returns the length of the right hand side (the number of symbols) of $productionindex. The name of the production can be used instead of its index. If no index or name is provided and the method is called inside a semantic action, the length of the current production is returned. Also: $parser->YYRightside($index) Returns an array of strings describing the right hand side of the rule. The name of the production can be given instead of $index. If no $index is provided and the method is called inside a semantic action the right hand side of the current production is returned. To be called inside a semantic action. Returns the index of the current production rule, counting the super rule as rule 0. To know the numbers have a look at the .output file. To get a .output file use the option -v of eyapp or the outputfile parameter when using method new_grammar (see the documentation for eyapp). Return the list of rules. The following debugger session illustrates its use: pl@europa:~/LEyapp/examples/recycle$ perl -wd usepostfix.pl main::(usepostfix.pl:5): my $parser = new Postfix(); main::(usepostfix.pl:6): $parser->Run; 0 ARRAY(0xa068e0) 0 '$start' 1 2 2 undef 1 ARRAY(0xa06940) 0 'line' 1 1 2 CODE(0xc22360) -> &Postfix::__ANON__[Postfix.eyp:10] in Postfix.eyp:227-10 ... etc, etc. Each item has three components: the LHS of the production, the number of symbols in the RHS and the CODE reference to the semantic action. If an index is specified as argument it returns the corresponding item: DB<2> x $parser->YYRule(7) 0 'exp' 1 3 2 CODE(0xc1fce0) -> &Postfix::__ANON__[Postfix.eyp:7] in Postfix.eyp:276-7 To know to what production an item is associated we can use the YYGrammar method: DB<3> x $parser->YYGrammar('exp_7') 0 'exp_7' 1 'exp' 2 ARRAY(0xa05290) 0 'exp' 1 '*' 2 'exp' 3 0 We can also use the name of the rule to get the item: DB<4> x $parser->YYRule('exp_7') 0 'exp' 1 3 2 CODE(0xc1fce0) -> &Postfix::__ANON__[Postfix.eyp:7] in Postfix.eyp:276-7 Receives a hash with keys the names of the production rules (right hand sides) and values the new semantic actions. Used to reuse a grammar without overwriting all the semantic actions. See section Reusing Grammars by Dynamic Substitution of Semantic Actions in Parse::Eyapp::defaultactionsintro. It also accepts the syntax: $parser->YYSetLRAction($conflictstate, [$token1, ... ], $shiftreduceaction ) This method has been designed to solve shift-reduce and reduce-reduce conflicts at parsing-time (not at parser-generation time). The LR table is changed so that the action in state $conflictstate in the presence of the token $token will be given by $shiftreduceaction. The current shift-reduce action isn't saved. See an example in Cplusplus2.eyp in the directory examples/debuggintut. This method has been designed to solve shift-reduce and reduce-reduce conflicts reduce by $productionname. The current shift-reduce action is saved to be restored using $parser->YYRestoreLRAction('conflictname', $token) See the examples in examples/debuggingtut/ in files DynamicallyChangingTheParser2.eyp confusingsolveddynamic.eyp DebugDynamicResolution.eyp DynamicallyChangingTheParser2.eyp DynamicallyChangingTheParser3.eyp DynamicallyChangingTheParser.eyp DynamicvsTieIns.eyp nolr_k_grammarsolveddynamic.eyp pascalenumeratedvsrangesolvedviadyn.eyp Cplusplus.eyp. Also: $parser->YYSetShift([$token1, $token2, ... ]) This method has been designed to solve shift-reduce shift. See the examples in examples/debuggingtut/ in files DebugDynamicResolution.eyp DynamicallyChangingTheParser.eyp alias: $parser->slurp_file($filename[,$prompt[,$mode]]) Receives the name of the file, reads its contents and stores it in $parser->input. If the file does not exists, it proceeds to read from STDIN. If a prompt was set with $parser->YYPrompt, it will be shown. The additional optional parameter $mode is used in such case to set $/. It can also be used as a class method. YYState returns a reference to the list of states containing the LALR(1) tables: the action and GOTO tables. Each state is an anonymous hash: DB<4> x $parser->YYState(2) 0 HASH(0xfa7120) 'ACTIONS' => HASH(0xfa70f0) # token => state ':' => '-7' 'DEFAULT' => '-6' A negative number means reduction using the corresponding production rule (opposite) number. The former example tells to reduce by rule 7 when in state 2 and seeing token ':'. By default, the action when in state 2 is to reduce by rule number 6. There are three keys: ACTIONS, GOTOS and DEFAULT DB<7> x $parser->YYState(13) 0 HASH(0xfa8b50) 'ACTIONS' => HASH(0xfa7530) 'VAR' => 17 'GOTOS' => HASH(0xfa8b20) 'type' => 19 The GOTOS tables contains the DFA transition tables for the syntactic variables. The former example tells to move to state 19 when in state 13 after seeing the syntactic variable type (i.e. if after reducing by a rule of type we are in state 13). If $length is zero or not provided it returns the state on top of the stack. Otherwise, returns the state $length units deep in the stack..
http://search.cpan.org/~casiano/Parse-Eyapp/lib/Parse/Eyapp/Driver.pod
CC-MAIN-2016-44
refinedweb
3,885
55.03
Created on 2016-08-17 03:49 by steve.dower, last changed 2016-11-07 03:36 by python-dev. This issue is now closed. I. I personally hate ansi myself so +1 to UTF-8/UTF-16. Would it be acceptable for you to add a new option to switch to UTF-8 in Python 3.6, and discuss later if it's ok to enable it by default? In the python-ideas threed, you wrote that Windows allow surrogate characters in filenames, but not the UTF-8/strict Python codec. Would it make sense to use UTF-8/surrogatepass codec to avoid any unicode error? Steve Dower: Please don't use git format for diff, or the bug tracker is unable to create reviews. I regenerated the patch. By the way, you introduced a bug in posix_do_stat(): you added a new "else" in the !MS_WINDOWS path which leads to a compilation error. I fixed it. Thanks for the regen. I don't think git format is the problem as most of my patches are fine, it's probably because it was in a patch queue and so the parent isn't actually a known commit. I haven't tested whether this works without my other console patches but I think it should. Is there a surrogatepass option? If so, I'll definitely use that, as that'll fix the one remaining edge case. I suspect we'll have to go to Guido to get a ruling on the default, but I'll add an environment variable to switch. > Is there a surrogatepass option? I'm talking about error handlers of Python codecs: text.encode('utf8', 'surrogatepass') > I suspect we'll have to go to Guido to get a ruling on the default, but I'll add an environment variable to switch. If you go in this direction, I would like to follow you for the UNIX/BSD side to make the switch portable. I was thinking about "-X utf8" which avoids to change the command line parser. If we agree on a plan, I would like to write it down as a PEP since I expect a lot of complains and questions which I would prefer to only answer once (see for example the length of your thread on python-ideas where each people repeated the same things multiple times ;-)) By portable, do you mean not using an environment variable? Command line parsing is potentially affected by this on Windows - I'd have to look deeper - as command lines are provided as UTF-16. But we may not ever expose them as bytes. I don't even know that this matters on the UNIX/BSD side as the file system encoding provided there is correct, no? It's just Windows where the file system encoding used for bytes doesn't match what the file system actually uses. I was afraid a PEP would be necessary out of this, but I want to see how the python-dev discussion goes first. Steve Dower added the comment: > By portable, do you mean not using an environment variable? I mean that "python3 -X utf8" should force sys.getfilesystemencoding() to UTF-8 on UNIX/BSD, it would ignore the current locale setting. Ah I see, if we end up sticking with MBCS and offering a switch to enable UTF-8. In that case, we'll definitely ensure the flag is the same (but I'm hopeful we will just make the reliable behavior on Windows the default, so it won't matter). I belatedly remembered I've had this new test case hanging around for a while, and never got around to getting it into shape for inclusion in the standard library. With the prospect of reasonable cross-platform consistency in this area, it could be a good thing to add as part of this PEP. Also see PEP 529 for the latest updates there. This is likely to be accepted as experimental for 3.6.0b1-3, and we'll commit to either the new default or a compatible default for b4. PEP 529 has been accepted, so this really needs a review now. But since it's experimental and all the tests pass, I'll be committing it shortly anyway and will be tidying up issues during beta. One minor change - I removed the unused definition of Py_FileSystemDefaultDecodeErrors. Thanks for that review, Eryk, but I'm going to defer those to other issues (specifically issue27998 for scandir and we should file a new issue for the symlink concerns). I've got some more doc updates to do though, and then I'll check in if there are no other concerns. New changeset e20c7d8a8187 by Steve Dower in branch 'default': Issue #27781: Change file system encoding on Windows to UTF-8 (PEP 529) This is pushed now - let the bug fixing begin :) New changeset faca0730270b by Steve Dower in branch 'default': Fixes tests broken by issue #27781. It looks as though this change might have broken the compile on OS X. On my OS X 10.9 machine, building from a clean Git checkout of the master branch fails; the tail of the failed build looks like this: ./python.exe -E -S -m sysconfig --generate-posix-vars ;\ if test $? -ne 0 ; then \ echo "generate-posix-vars failed" ; \ rm -f ./pybuilddir.txt ; \ exit 1 ; \ fi Fatal Python error: Py_Initialize: unable to load the file system codec Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 962, in _find_and_load File "<frozen importlib._bootstrap>", line 951, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 656, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 668, in exec_module File "<frozen importlib._bootstrap_external>", line 782, in get_code File "<frozen importlib._bootstrap_external>", line 842, in _cache_bytecode File "<frozen importlib._bootstrap_external>", line 867, in set_data File "<frozen importlib._bootstrap_external>", line 117, in _write_atomic ValueError: negative file descriptor /bin/sh: line 1: 35829 Abort trap: 6 ./python.exe -E -S -m sysconfig --generate-posix-vars generate-posix-vars failed make: *** [pybuilddir.txt] Error 1 Full build output attached. It looks as though this change in posixmodule.c is the cause: #ifdef MS_WINDOWS - if (path->wide) - fd = _wopen(path->wide, flags, mode); - else + fd = _wopen(path->wide, flags, mode); #endif #ifdef HAVE_OPENAT if (dir_fd != DEFAULT_DIR_FD) fd = openat(dir_fd, path->narrow, flags, mode); else -#endif fd = open(path->narrow, flags, mode); +#endif The move of the final #endif means that `fd` is not defined on OS X. If I move the #endif back again, the compile succeeds. New changeset 801634d3c105 by Steve Dower in branch 'default': Issue #27781: Fixes uninitialized fd when !MS_WINDOWS and !HAVE_OPENAT That seems to have done the trick. Thanks! Before 3.6.0 beta 4 I need to make this change permanent. From memory, it's just an exception message that needs changing (and PEP 529 becomes final), but I'll review the changeset to be sure. New changeset b26c8104e54f by Steve Dower in branch '3.6': Closes #27781: Removes special cases for the experimental aspect of PEP 529 New changeset b8233c779ff7 by Steve Dower in branch 'default': Closes #27781: Removes special cases for the experimental aspect of PEP 529
https://bugs.python.org/issue27781
CC-MAIN-2017-13
refinedweb
1,191
72.97
The QAbstractXmlReceiver class provides a callback interface for transforming the output of a QXmlQuery. More... #include <QAbstractXmlReceiver> This class is not part of the Qt GUI Framework Edition. Inherited by QXmlSerializer. Note: All functions in this class are reentrant. This class was introduced in Qt 4.4.. An XQuery sequence is an ordered collection of zero, one, or many items. Each item is either an atomic value or a node. An atomic value is a simple data value. There are six kinds of nodes. The sequence of nodes and atomic values obeys the following rules. Note that Namespace Node refers to a special Attribute Node with name xmlns. The sequence of nodes and atomic values is sent to an QAbstractXmlReceiver (QXmlSerializer in the example above) as a sequence of calls to the receiver's callback functions. The mapping of callback functions to sequence items is as follows. For a complete explanation of XQuery sequences, visit XQuery Data Model. See also W3C XQuery 1.0 and XPath 2.0 Data Model (XDM), QXmlSerializer, and QXmlResultItems. Constructs an abstract xml receiver. Destroys the xml receiver. This callback is called when an atomic value appears in the sequence. The value is a simple data value. It is guaranteed to be valid. This callback is called when an attribute node appears in the sequence. name is the attribute name and the value string contains the attribute value. This callback is called when a text node appears in the sequence. The value contains the text. Adjacent text nodes may not occur in the sequence, i.e., this callback must not be called twice in a row. This callback is called when a comment node appears in the sequence. The value is the comment text, which must not contain the string "--". This callback is called when the end of a document node appears in the sequence. This callback is called when the end of an element node appears in the sequence. This callback is called once only, right after the sequence ends.. This callback is called when a document node appears in the sequence. This callback is called when a new element node appears in the sequence. name is the valid name of the node element. This callback is called once only, right before the sequence begins.
http://doc.trolltech.com/4.6-snapshot/qabstractxmlreceiver.html#atomicValue
crawl-003
refinedweb
381
69.58
JSP Tutorials Resource - Useful Jsp Tutorials Links and Resources on the exercises, these are designed to solidify your grasp of the material.  ... technology projects all the dynamic capabilities of Java Servlet technology..., the page is translated into a Java Servlet and compiled. At runtime, you execute Plz provide me all the material for Java Plz provide me all the material for Java Plz provide me all the material for Java Please go through the following link: Java Tutorials servlet servlet how to read a file from different folder using filereader in servlet Hello Friend, Please visit the following link: Here you will get an useful java - Servlet Interview Questions java servlet interview questions Hi friend, For Servlet interview Questions visit to : Thanks Electronic spreadsheets are useful in situation Electronic spreadsheets are useful in situation Electronic spreadsheets are useful in situation where relatively ---- data must be input.. 1. Small, 2.Large, 3. No, 4. All of the above 5. None is true Answer:1. Small Servlets - JSP-Servlet Servlets How can we differentiate the doGet() and doPost() methods in Servlets Hi friend, Difference between doGet() and doPost() Thanks Useful SEO Articles - 5 Killer Tips for Writing SEO Articles for Home-Based Online Business Ideas are typed by Internet users while searching for some material in search engines Constructor in Servlet. Constructor in Servlet. how to write a constructor in Java Servlet? Servlet is like a POJO .You can create constructor in servlet. You can also use constructor for initialising purpose but it is not a useful approach interview question - Servlet Interview Questions can visit here at question What is Servlet? Need interview questions on Java Servlet Servlet is one of the Java technologies which is used Useful Negotiation Tips on Outsourcing, Helpful Negotiation Tips requirements. This can be useful, as the third party can bring in a lot autentication & authorisation - JSP-Servlet /interviewquestions/corejava/null-marker-interfaces-in-java.shtml Thanks How is LBS useful? How is LBS useful? LBS is designed to provide valuable information to the users based... of LBS service is useful for users when they find themselves in an unfamiliar diff b/w applet and servlet to servlet. 5)Applets are useful to develop the static web pages whearas Servlets... and servlet? Difference between servlet and applet: 1)An applet is client side programming whereas servlet is server side programming. 2)Applets run Regarding a project in java - JSP-Servlet suggestions or material to follow. It is based on datawarehousing. Hi friend, Plz specify the technologies you have used like JSP/Servlet/Struts/J2EE Why PHP Is So Useful Know About Outsourcing, More About Outsourcing, Useful Information Outsourcing Servlet Servlet What is Servlet Servlet Servlet how to navigate one servlet page to another servlet page servlet servlet How many times the servlet is accessed servlet servlet is there any way to include pdf's in servlet servlet servlet what are the methods and interfaces in the servlet api ? Servlet Tutorials jsp - JSP-Servlet jsp it is possible to fire a java page from a jsp page through tag Hi Friend, Yes you can but it will show the java code. The standard and useful way of using the java file is through the tag. http styling jsp - JSP-Servlet these links very useful. Core Java JSP Servlet JDBC Hibernate...; } Our site contains several useful examples and applications of Java, JSP servlet servlet what are the all necessary configuration to run a servlet servlet servlet how to interact with a servlet from a swing program servlet servlet I designed 1 html form & a servlet but when I click on form I don't get output of servlet Please help servlet servlet i want to create a login page with servlet using database mysql? only in servlet not in jsp plzz help me out javascript-html - JSP-Servlet the following code. It may be useful for you. var numLinesAdded Servlet Servlet What must be implemented by all Servlets? The Servlet Interface must be implemented by all servlets servlet servlet i want a program for counting the no of times the servlet has been invoked servlet servlet how to create a login form using servlet using submit,edit delete button servlet servlet dear sir servlet and html not run on eclips plz help me servlet servlet can i stoar record in variable which selected from table in servlet servlet of the Servlet API. It contains the classes necessary for a standard, protocol-independent servlet. Every servlet must implement the Servlet interface in one Why Web Development with PHP Is Useful Servlet Servlet I want to know the steps to write a simple servlet program... . Hello Friend, Follow these steps: Put servlet-api.jar inside the lib folder of apache tomcat. 1)create a servlet. import java.io.*; import Servlet Servlet Why is Servlet so popular? Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web Servlet Servlet Can a user defined function be included in a servlet? I need information regarding servlet syntax and not JSP. Yes, you can create user defined function in Servlets. Have a look at the following link: http servlet servlet i want to use servlet application on my web page then what should i do. I have already webspace. Hi Friend, Please visit the following link: Servlet Tutorials Thanks Java - JSP-Servlet think it will be useful to u. see, while doing an web application we have Servlet Servlet Hi, Can any one please expalin me below topics SERVLET ENGINE 2.WHY SUPER.INIT(); Thanks alot in advance!! Regards: Akash servlet servlet Dear Deepak, is it compulsary to write the sevice() becoz i ve seen some example which does not ve sevice()..is it tue? plz replay me with thanks praveen servlet servlet plz can anyone give me the link of javax library jar file. i badly need that. thanks in advance Please visit the following link: Download Servlet API servlet servlet I want a fully readymade project on online voting system with code in java servlet and database backend as msaccess.can u plz send me as soon as possible Servlet the same error <web-app> <servlet> <servlet-name>InsertServlet</servlet-name> <servlet-class>InsertServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name> Outsourcing Guidelines,Successful Guidelines on Outsourcing,Useful Guidelines on Outsourcing servlet servlet file which prints out the user's inputs. I need to use the post method to pass the data from html to the java servlet and also use both doGet and doPost methods in the servlet. I think, but unfortunately I have a terrible teacher SERVLET to the servlet and if the user id is correct then a new page will be displayed with his... pass to the servlet and all the fields brlongs to that id will be appear... will be done by using jsp and servlet... Plz help me,im really tensed...........   servlet servlet hi sir,this is ashok.i installed tomcat 6.0 and jdk-150.i checked the server it's working but when execute servlet program for the .class file it shows the errors javax.servlet is not exist.what can i do,please tell me servlet to servlet. So, if anyone can help me so I can see how to connect the two I would servlet servlet How do we define an application level scope for servlet? Application scope uses a single namespace, which means all your pages should be careful not to duplicate the names of application scope objects servlet servlet how to jsp integer are type cast int servlet page Hi Friend, Try the following code: 1)form.jsp: <form method="post" action="../Data"> Enter Number:<input type="text" name="num" > <input servlet servlet try { con=DaoPack.createConnection(); } catch(Exception e) { e.printStackTrace(); } if(request.getParameter("addproduct")!=null) { ProductBean bean=new ProductBean servlet com.ilp.tsi.pm.services.StockService; /** * Servlet implementation class AddServlet1 */ //Servlet for Adding the stock public class AddStockServlet extends...; import com.ilp.tsi.utils.*; /** * Servlet implementation class Changepwd Why Offshore Outsourcing,Why Offshore Outsourcing Useful,Why Need of Offshore Outsourcing Services Offshore Outsourcing Tips,Useful Offshore Outsourcing Tips,Helpful Outsourcing Tips What is Static Website and products in simple manner and at low cost. This type of website is very useful.... A static website is just you write your material in any word processor code in single jsp - JSP-Servlet in single jsp it would be useful the code which u gave is 1)click.jsp servlet com.ilp.tsi.um.bean.BankBean; import com.ilp.tsi.um.service.BankService; /** * Servlet servlet ); } } } this is the code for .java servlet am able to run creating a feedback form - JSP-Servlet material sufficient? Poor Average Good Challenging SEO Tips,Latest SEO Tips,Free SEO Tips & Tricks,Useful Search Engine Optimization Tips Java Servlet : Http Request Headers in orignal URL User-Agent : type of browser, useful if servlet...Java Servlet : Http Request Headers In this tutorial, you will learn how to Http Request Headers works in java servlet. Http Request Headers : HTTP Servlet servlet SERVLET Insert Image into Database Using Servlet of inserting image into database table using Servlet. This type of program is useful... useful, which makes your program very attractive. How to Compile Servlet program... Insert Image into Database Using Servlet   Insert Image into Database Using Servlet image into database table using Servlet. This type of program is useful in social...Insert Image into Database Using Servlet  ... the image from database using Servlet. After retrieving the image from database Outsourcing Communication Tips,Useful Cultural Tips in Offshore Outsourcing,Communication and Culture Tips What is Struts? What is a Struts? Understand the Struts framework This article tells you "What is a Struts?". Tells you how Struts learning is useful in creating.... The Struts 2 version is based on the following Java Technologies: Servlet
http://www.roseindia.net/tutorialhelp/comment/94290
CC-MAIN-2013-48
refinedweb
1,651
63.19
FMOUTCHAR(3W) FMOUTCHAR(3W) fmoutchar - render a single glyph. #include <fmclient.h> long fmoutchar(fh, ch) fmfonthandle fh; unsigned int ch; fmoutchar renders a single glyph from the given font. It does not change the current font. If the glyph doesn't exist, it spaces forward the width of a space; if a space doesn't exist, it spaces forward the width of the font. The width used is returned. Note that 'ch' is declared as 'unsigned int' so that characters with code > 256 can be displayed. fminit(3W), fmfindfont(3W), fmscalefont(3W), fmsetfont(3W). This routine is available only in immediate mode. PPPPaaaaggggeeee 1111
https://nixdoc.net/man-pages/IRIX/man3w/fmoutchar.3w.html
CC-MAIN-2020-34
refinedweb
105
76.32
Important: Please read the Qt Code of Conduct - Position change when parent resizes How do I properly change the x, y of an object so that it changes its position when the parent is resized? There is, I will introduce that if I drag the rectangle to the middle, then when the window is resized, it should remain in the middle. (middle for example only, rectangle can be moved freely) import QtQuick 2.9 import QtQuick.Window 2.2 import QtQuick.Controls 2.3 Window { visible: true width: 640 height: 480 onWidthChanged: { block.x -= block.previousWidth - width block.previousWidth = width } onHeightChanged: { block.y -= block.previousHeight - height block.previousHeight = height } Rectangle { id: block color: "red" width: 50 height:50 x: 100 y: 50 property int previousWidth: 0 property int previousHeight:0 Component.onCompleted: { previousWidth = parent.width previousHeight = parent.height } MouseArea { anchors.fill: parent drag.target: block } } }
https://forum.qt.io/topic/120560/position-change-when-parent-resizes
CC-MAIN-2021-04
refinedweb
145
53.78
Hi, the code at post #21, which is here: Dust Sensor - PMS 5003/6003/7003 is good for me. It works! Did you try it? Dust Sensor - PMS 5003/6003/7003 Hi, the code at post #21, which is here: Dust Sensor - PMS 5003/6003/7003 Thanks for your reply. I’m sorry. Would it be possible for these questions: - For PMS 5003, I know it works that you say; but, In addition arduino,are there other? - Did you try for PMS5003ST with ST? Or stm32fxxx? Hi all. I just received 2x PMS7003 - trying to get one hooked up to my Electron. I have used a header to connect the PMS7003 to my breadboard, but now struggling to work out what/where I should connect to my Electron. Here is the pin details from data sheet from PMS5003 (can’t find 7003), I’m hoping that it has the same connections. I understand Pins 1, 2, 4, 5. But where should the others go? A couple of other quick questions: - @MartyMacGyver - using your code - does one need to define pins and/or IC2 address anywhere? - The data sheet seems to suggest power is 5V. Is it an issue to power by 3.5V through Photon? As you can see I’m new to electronics Cheers Matt There’s a pretty decent datasheet here (unlike the one I started with, this one even has a handy wiring diagram): (Yes, it’s in Chinese but you can put the URL through Google Translate to convert the whole doc.) I haven’t tried using 3.3V for VCC (since I can source the 5V from the Photon for the purpose of VCC< I do). I wouldn’t expect 3.3V to be enough though. The pins aren’t in the same configuration as the 5003. Refer to the datasheet for the pin ordering, but translated: PIN1 VCC Power is 5V PIN2 VCC Power is 5V PIN3 GND Power supply negative PIN4 GND Power supply negative PIN5 RESET Module reset signal / TTL level @ 3.3V, low reset PIN6 NC PIN7 RX Serial receive pin / TTL level @ 3.3V PIN8 NC PIN9 TX Serial transmission pin / TTL level @ 3.3V PIN10 SET Set the pin to TTL level @ 3.3V, high or floating Normal working state, low for the sleep state This device is serial-only (no I2C), so when you connect it up, you use the serial pins on your Photon/Electron. Float or pull SET high to let the device run all the time, and pull RESET high unless you want to directly reset it (which I’ve yet to need to do). 5V power, ground, and serial TXD/RXD (which are at 3.3V levels per the datasheet) should be all you really need. (Since it’s an Electron you might want to make your own code - mine would use a lot of data.) Thanks for your guidance. Here is what I’ve done so far, but not working… Any help diagnosing would be much appreciated: So on the connector that came with my PMS7003, the connections are a bit different to the data sheet. Goes from 10 pins down to 8 through the connector. See below: I’ve connected it up to my breadboard, Electron as follows. Pretend PMS7003 is connected to the generic header in diagram. In the Fritzing above, used a header where pins 1-8 align with pins 1-8 on the PMS7003 connector (as per first photo). I’ve then used @MartyMacGyver’s code - adding the following to try and pull SET high: pinMode(D3, OUTPUT); digitalWrite(D3, HIGH); I suspect this is completely wrong, and have no idea how to pull RESET high. Tried doing a quick search but couldn’t find much on how to do this. Should pulling have been done through hardware? Also, is there any code missing from @MartyMacGyver’s repository? I would have expected to see normal stuff like defining pins etc - like I’ve tried to do above? Am I missing something? When viewing serial output, I’m just getting: -- Initializing... -- Reading PMS7003 And nothing else. Thanks! Matt That’s my repo - it should be easier than all that. Looks like the breakout (oh how I wish that had come with mine!) simply omits/combines the two VCC and the two Gnd pins into one each. You likely need to only wire four things: VCC (5V), Gnd, TXD and RXD. That’s all. I suspect Set and Reset are already pulled to their appropriate states (Reset should be pulled high internally, and I think Set is internally pulled high too). Either way, the wiring looks OK to me in terms of pulling things up to 3.3V, though you’re going to need to do the same thing for D6 (reset) you’re doing for D3 (set). That said, I’d unplug those two for a moment and let the resistors do the work. What’s wrong here is that I don’t see VCC for the PMS7003 going to +5V… I see it going to 3.3V. While that’s fine for the pull-ups, the VCC must be 5V as far as I know (otherwise you’ll affect the fan speed, and that’s part of the measurement pathway - not to mention it might not even power up). On a Photon, when powered from USB, VIN will supply +5V. On the Electron I think the only option is VUSB (and that means having a USB supply… I don’t think the LiPo won’t suffice). Only wire +5V to VCC… never the other pins or pull-ups on the PMS7003! EDIT: Once you have the power thing sorted, you might have to reverse the TX and RX connections. I don’t recall which is which but try what you have first. EDIT2: and by the way… where did you get these? eBay, AliExpress, somewhere else? Would be good to know. Thanks - you’re right the fan wasn’t working at all under 3.3V - moving to 5V got the fan going for a while, but seems I killed it somehow - it’s not starting up at all now when powering it, perhaps I shorted it or something. I’ll try my second PMS7003. From AliExpress. Cheaper than eBay and included the connector. Thanks again. I’ll post my progress for other’s reference once I get it going. M If SET is low that would turn the fan off too: When the sleep function is applied, be aware that the fan stops working while the fan is inactive and requires at least 30 Sec settling time, so in order to obtain accurate data, the sleep sensor working time after wake-up should not be < [?] 30 seconds. Try giving the device VCC and GND only, and leave all the other wires completely unconnected. The fan ought to run. If not, pull the SET line up to 3.3v (I don’t think that’s necessary but it’s worth a try too). If that doesn’t work… maybe it really is dead. I have a hard time seeing how any of this would’ve killed it unless its power lines were reversed or something though..) Gave it another go. I had the connector/breakout supplied attached the wrong way around to the PMS7003 Anway’s it is now working! Receiving frames of data through serial as per your code, Marty. Any tips on how I can quickly convert these frames to something human readable to sense check readings?.) Can’t recall the vendor, and info isn’t in the email. I didn’t need to provide much info - just postal address, payment info. I didn’t register an AliExpress account - I just went through checkout process as a guest. Hi to all, This is my first post here. I’m starting to test the PMS7003 sensor with an Arduino. I have tried with at least 3 different softwares, and with all of them I’m getting consistent values, however looking at the readings and comparing them to the readings obtained by other Sharp dust sensors (just pm2.5), the readings from the PMS7003 appeared as multiplied by ten. Is this possible? Here is an example from the PMS7003 PM1.0cf: 369 ug/m3 PM2.5cf: 557 ug/m3 PM1 0cf: 601 ug/m3 PM1.0am: 245 ug/m3 PM2.5am: 371 ug/m3 PM1 0am: 400 ug/m3 From the Sharp sensor PM2.5 reading is now 39.8 ug/m3 If I increase the particles in the air by burning some incense near the sensors, both increase the readings, but the PMS7003 readings always seems 10 times the value of the Sharp sensor. Does anyone have already noted this, or I’m doing anything wrong. Which Sharp sensors are you using ? If it is a reference instrument then it would be more believable. The PM2.5 numbers you measured with the 7003 are really high. If you were regularly breathing this air you would be in big trouble. So without knowing anything more like seeing your code, it is possible that your 7003 readings are off by a factor of 10. OTOH if you are in Beijing or Delhi the readings are probably ok! it is best to check with aqicn.org - where is the nearest station that reports PM 2.5/pm10 readings and compare with it. 40 ug/m3 is generally clear air… you shouldn’t smell anything in it. 400 ug/m3 usually smells quite a lot on smoke, fire… you shouldn’t also be able to see more than 100m around you Thank you guys. All is working now, and the readings from my PMS7003 usually are inline with the values from the nearest (40Km away) aquicn.org station. Nice sensor. Hello, Thank your code share, current i sent code with PMS5003, but get PM2.5 PM1.0 and PM10 all value is 0.Any suggest? Neo Is there any reason you couldn’t split the data lines from a sensor (any of the PMS sensors) to feed two devices (an electron and another custom board)? I have a custom device that already has a PMS7003 in it but I want to datalog the PM values (something the custom device cannot do). An alternate idea I had was to feed the sensor serial lines to the Photon and then repeat them back to the custom device. Thoughts? Improvements to my initial ideas? HI ilak2k~ I run PMS5003 with the code you shared. However, I always get “zero” outcome. After I tried to debug, I found here: if( receiveSum == ((thebuf[leng-2]<<8)+thebuf[leng-1])) because the equation never achieve, so it doesn’t make the flag=1. Is there any solution about this problem? hello i have dust sensor SDS011 + USB adapter I connect the sensor to raspberry pi, basic to read a sensor I use command: od --endian=big -x -N10 < /dev/ttyUSB0 so it is giving me for example: 0000000 aac0 8c00 9400 bcf9 d5ab every packet of data begins “aac0” and rest of the data are converted to useful values (in bash script), basically everything work ok (for graphic representation of data I use RRDtool). But I want compare data from SDS011 with PMS7003. I don’t have any USB adapter so I connect PMS703 to raspberry pi pins. In PMS7003 datasheet I see that start of the packet of data should be “424d”. First I tryed this command: sudo od –endian=big -x -N10 < /dev/serial0 but this give me that kind of data: 3500 8200 0a54 008c 000a (first try) 8100 9f00 0a78 0094 000a (second try) 2900 6400 2900 6400 2900 (third try) I don’t see beginning the data packet “424d” I tried Python script: import serial from time import gmtime, strftime port = serial.Serial("/dev/serial0", baudrate=9600, timeout=1.5) data = port.read(32); PM01 = str(ord(data[5])*256+ord(data[6])) PM25 = str(ord(data[7])*256+ord(data[8])) PM10 = str(ord(data[9])*256+ord(data[10])) print(PM01) print(PM25) print(PM10) but this also give me strange no real value. Why data packet never start from “424d”? I ordered a PMS7003 and already wrote some software for it. The approach in the code is that it’s purely a state machine for interpreting the incoming serial bytes. So it will automatically sync to the start of a frame with measurement data, even if you start receiving data halfway inside a frame. It should be buffer-overflow-proof. The parsing code is also stand-alone, with no Arduino dependencies. This makes it easier to test. My code can be found at: in modules pms7003.cpp/.h I haven’t received the module yet, so I haven’t been able to test it with actual hardware, but I did write some unit tests. Hi folk, I use of Plantower pms 3003 with Teensy 3.2. It’s my code: But I see that I receive sometimes incorrect data. For example, PM2.5 — 50 PM10 — 65 PM2.5 — 50 PM10 — 65 … PM2.5 — 170 (once) PM10 — 500 … again PM2.5 — 50 PM10 — 65 … PM2.5 — 170 (once) PM10 — 500 Please help me.
https://community.particle.io/t/dust-sensor-pms-5003-6003-7003/24221/49
CC-MAIN-2019-22
refinedweb
2,211
82.04
import bb.cascades 1.0 Page { content: ListView { dataModel: GroupDataModel {} onCreationCompleted: { for (var a = 0; a < 20; a++) { dataModel.insert( {"exampleProperty" : a} ) } } } // end of ListView } // end of Page Sorted data models You can use a GroupDataModel to store data and sort it in a particular order. You can specify sorting keys for the data model, and items in the model are sorted based on the values of those keys. You can add simple item types to a GroupDataModel (such as strings or integers), or you can create and add your own item types by extending QObject. When you want to display the sorted data in your app, you can create a ListView and associate the GroupDataModel with it. The GroupDataModel class sorts your data automatically, in either ascending order or descending order, when you add the data to the model. This type of model also adds headers automatically to group the data, based on the sorting keys that you specify. This behavior can make this type of model ideal for information that you want to display in a certain order. For example, you can use a GroupDataModel for a list of contacts, and then sort the list based on the contact's first name or last name (or both). Sorting keys The sorting keys in a GroupDataModel determine how the data is sorted. Each key is a QString and represents the name of a property that you want to use to sort the data in the model. For items in the model to be sorted correctly, each item must contain a property with the same name as the key. For example, if you specify a key of lastName, each item that you add to the model must include a property called lastName. Then, the value of the lastName property in each item is used to sort the items. You can specify more than one key to use for sorting. The sortingKeys property in GroupDataModel represents the sorting keys for the model, and accepts a list of QString objects. If the items in your model represent contacts, you might want to sort them based on last name, then first name. You can specify the list of sorting keys as [lastName, firstName]. The items are first compared and sorted based on the lastName property. If the values of lastName are the same, then the items are compared and sorted based on the firstName property. Data items The items in a GroupDataModel are instances of either QVariantMap or QObject*. A QVariantMap represents a set of key-value pairs, making it a good choice when you want to store simple data (such as text or numbers) in a GroupDataModel. You can use keys in the QVariantMap that correspond to the keys of the GroupDataModel, which allows the QVariantMap items to be sorted according to these keys. The key in a QVariantMap needs to be a QString, but the value that's associated with the key doesn't. You can use various QVariant types for your values, including String, Double, and Date. For a complete list, see the API reference for GroupDataModel. For example, consider a GroupDataModel that represents a list of cities. Each item in the list has properties for the city name (cityName) and the corresponding country name (countryName). Here's how to populate QVariantMap objects with data for three cities. You can then add these QVariantMap objects to a GroupDataModel and sort them using the keys cityName and countryName. // Create QVariantMap objects for each city QVariantMap firstCity; QVariantMap secondCity; QVariantMap thirdCity; // Populate the QVariantMap objects firstCity["cityName"] = "Waterloo"; firstCity["countryName"] = "Canada"; secondCity["cityName"] = "Rome"; secondCity["countryName"] = "Italy"; thirdCity["cityName"] = "Barcelona"; thirdCity["countryName"] = "Spain"; You can also use a QObject pointer as an item in a GroupDataModel. This approach is effective if you want to create your own class to represent the data in your model. In the example of a GroupDataModel that represents a list of cities, you could create a City class that inherits from QObject and then add pointers to City objects to the model. When you use a QObject to represent data in your model, only the properties that you define in the class (that is, the properties that you define using Q_PROPERTY) are visible to the GroupDataModel. You can sort the data based only on values of these properties, and you can display only these properties in a ListView. Member variables and functions aren't visible, but can still be useful internally in your class implementation. Data hierarchy When you add data items to a GroupDataModel, all items are added at the same hierarchical level in the model. You can't specify that certain items are children of other items. This is an important difference between a GroupDataModel and other data models in Cascades, such as an XmlDataModel. In an XmlDataModel, you can arrange data in a hierarchy with multiple levels, and you can precisely define the relationships between the items. For example, you can create an item called "Fruit" and specify child items of "Bananas", "Apples", and "Oranges". This relationship is preserved in the XmlDataModel and is reflected when you display the data using a ListView. In a GroupDataModel, there are only two levels of items. Header items, which are created automatically, are on the first level of the model. Data items that you add to the model are on the second level. Header items are created based on the values of the properties that you specify as sorting keys. For example, if your data model represents a list of contacts and you choose to sort the items based on the lastName property, headers are created automatically based on the first character of each lastName property value (that is, all last names that start with A are placed under the "A" header, all last names that start with B are placed under the "B" header, and so on). You can choose to group items in different ways by using the grouping property. Several functions in GroupDataModel use index paths to specify items in the model. An index path is a list of integers that uniquely identifies a particular item in the model. Functions like GroupDataModel::data() (used to retrieve the data for an item in the model) and GroupDataModel::childCount() (used to determine how many children an item has in the model) use index paths as arguments to specify the appropriate item. To learn more about index paths, see Index paths. In a GroupDataModel, header items are always on the first level of the model, and so these items have index paths that contain a single integer. Data items that you add to the model are always on the second level, and so they have index paths that contain two integers. Creating a GroupDataModel You can create a GroupDataModel in QML and associate it with a ListView by using the ListView::dataModel property. This property specifies the data model that a ListView should use. In the simplest case, all you need to do is specify an empty GroupDataModel as the value of this property, and you can populate the data elsewhere in your app. Here's how to create a ListView that uses a GroupDataModel. After the ListView is created, data items are added to the model using DataModel::insert(). Each item includes a single property, exampleProperty, with a value. This model doesn't include any sorting keys, and so the items are displayed in the ListView in last-in, first-out (LIFO) order (the item that was added last is displayed first in the list). Not applicable This approach works well for simple data models when you don't really care about the order of the data. For more complicated data models, or for models that you want to reuse in multiple ListView objects, you can add the GroupDataModel as an attached object and reference it as the value of the dataModel property. Here's how to create a ListView that uses a GroupDataModel attached object. The model sorts data items according to the name property. After the ListView is created, several items are added to the model. import bb.cascades 1.0 Page { content: Container { attachedObjects: [ // Add a data model that sorts based on the name property GroupDataModel { id: groupDataModel sortingKeys: ["name"] } ] ListView { // Specify the data model from the attached objects list dataModel: groupDataModel // After the list is created, add the data items onCreationCompleted: { groupDataModel.insert( {"name" : "Charles"} ); groupDataModel.insert( {"name" : "Bob"} ); groupDataModel.insert( {"name" : "Karen"} ); groupDataModel.insert( {"name" : "Samantha"} ); } } } // end of Container } // end of Page Not applicable In some cases, you might want more control of how items are grouped and displayed in your list. Consider a GroupDataModel that represents a list of cities. You might want to display the cities grouped by country, with each country name as a heading in the list. The code samples below create the sorted list that you see to the right. Each country appears as a header item in the list, and the country names are sorted alphabetically. Within each country group, cities are sorted alphabetically according to the cityName property. Because the countryName values are the same in each country group, the GroupDataModel sorts based on the next key in the list of sorting keys (namely, cityName). If you don't want any headers to appear in your list, you can set the grouping property of GroupDataModel to ItemGrouping::None. The items in the data model are still sorted (based on the sorting keys that you specify), but the model doesn't create headers to group the items. Here's how to create the example above by using multiple sorting keys and the grouping property of GroupDataModel. import bb.cascades 1.0 Page { content: Container { attachedObjects: [ GroupDataModel { id: groupDataModel // Sort the data items based first on country name, // and then by city name (if the country names // are equal) sortingKeys: ["countryName", "cityName"] // Specify that headers should reflect the full value // of the sorting key property, instead of just the // first letter of the property grouping: ItemGrouping.ByFullValue } ] ListView { dataModel: groupDataModel // After the list is created, add the data items onCreationCompleted: { groupDataModel.insert( {"countryName" : "Italy", "cityName" : "Rome"} ); groupDataModel.insert( {"countryName" : "Spain", "cityName" : "Barcelona"} ); groupDataModel.insert( {"countryName" : "Canada", "cityName" : "Waterloo"} ); groupDataModel.insert( {"countryName" : "Canada", "cityName" : "Vancouver"} ); groupDataModel.insert( {"countryName" : "Italy", "cityName" : "Milan"} ); groupDataModel.insert( {"countryName" : "Canada", "cityName" : "Toronto"} ); groupDataModel.insert( {"countryName" : "Spain", "cityName" : "Madrid"} ); } } // end of ListView } // end of Container } // end of Page In many cases, it can be a good approach to populate a GroupDataModel in C++ instead of QML. By using C++, you can access data from various sources more easily, such as from a SQLite database or JSON data structure. You can also create your own class to represent your data, and then add objects of that class (as QObject pointers) to the model. This approach gives you more control over how you organize and store your data. In C++, you can specify the sorting keys that you want the GroupDataModel model to use. Then, you can create QVariantMap or QObject* objects and insert them into the model. You can also associate the data model with a ListView by calling ListView::setDataModel(). An easy way to specify the sorting keys is to use a QStringList, and pass this list (along with the keys to use) to the constructor of GroupDataModel. Each data item is a QVariantMap that contains the properties and values for each item. // Create the root Page and a top-level Container Page *root = new Page; Container *topContainer = new Container; // Create the data model and specify the sorting keys to use GroupDataModel *model = new GroupDataModel(QStringList() << "countryName" << "cityName"); // Specify the type of grouping to use for the headers in the list model->setGrouping(ItemGrouping::ByFullValue); // Create a QVariantMap and populate it with data for each item. // When the data for an item has been populated, add the item to // the data model and reuse the same QVariantMap for the next item. QVariantMap map; map["countryName"] = "Italy"; map["cityName"] = "Rome"; model->insert(map); map["countryName"] = "Spain"; map["cityName"] = "Barcelona"; model->insert(map); map["countryName"] = "Canada"; map["cityName"] = "Waterloo"; model->insert(map); map["countryName"] = "Canada"; map["cityName"] = "Vancouver"; model->insert(map); map["countryName"] = "Italy"; map["cityName"] = "Milan"; model->insert(map); map["countryName"] = "Canada"; map["cityName"] = "Toronto"; model->insert(map); map["countryName"] = "Spain"; map["cityName"] = "Madrid"; model->insert(map); // Create a ListView and associate the data model with it ListView *listView = new ListView(); listView->setDataModel(model); // Add the ListView to the top-level Container // and display the content topContainer->add(listView); root->setContent(topContainer); app->setScene(root); Not applicable Item types In the example above, the countryName properties appear as header items and the cityName properties appear as list items under the headers. The ListView class creates this arrangement automatically by selecting one of the properties of each item and creating a StandardListItem to display in the list for that property. In simple cases where each item in your model has only one or two properties, this approach can work well; indeed, it worked nicely in that example by arranging the country names as headers and the city names as list items. However, in more complicated cases where each item has multiple properties, the ListView might not choose the right property to display. When the data items in your model include more than one property, you should define the appearance of list items yourself. In QML, you do this by creating a ListItemComponent for each type of item in your list and then specifying which properties you want to display. To learn more about defining the appearance of list items, see List view. When you use this approach, you also need to tell the ListView the type of each item in the data model. For some data models, such as XmlDataModel, the type is included in the source of the data model. You can see an example of this in the list view documentation. In that document, an .xml file is used as the source of the data model, and the item types are included in the file itself as XML tags. Here's a section of the items.xml file that's used as an example in that document. The .xml file defines two types for items, "header" and "listItem", as XML tags. When you use XML tags to define item types, your ListView interprets the types automatically from the XML and lets you define the appearance for them using ListItemComponent objects. <header title="Fruits" subtitle="Generally sweet"/> <listItem title="Oranges" subtitle="Rich in vitamin C" status="Eaten" checked="1"/> <listItem title="Apples" subtitle="One a day keeps the doctor away" status="Not eaten" checked="0"/> ... For other data models, such as GroupDataModel, item types aren't defined and interpreted automatically; you need to explicitly state the type of each item in your data model. Fortunately, ListView includes a JavaScript function called itemType() that you can override to provide this information. The itemType() function returns the type of the item with the specified index path. Because a GroupDataModel includes only two levels of hierarchy for its data, you could implement itemType() to return either "header" for header items, or "listItem" for list items. Here's how you might do this by using the index path of the"; } } Not applicable Not applicable You can then create ListItemComponent objects to define the appearance of each type in your list. GroupDataModel example using QML and C++ You can create a list, associate it with a data model, and populate the model with data either entirely in QML, or entirely in C++. However, it's common to create your list in QML and then populate the data model for the list in C++. This approach lets you separate the UI component (the list, represented by a ListView) from the business logic component (the data model, represented by a GroupDataModel). You can change the implementation details of one component without affecting the other, which can be important for complex or large-scale apps that you develop. Here's how you could create a list and a data model that, when used together, represent a list of employees. Each employee has a first name, a last name, and an employee number, and this information is encapsulated in a custom Employee class. Instances of this class are created to represent each employee and are added to the data model as data items. The list is created and associated with a data model in QML, and the model is populated with data in C++. The following example combines many of the data model concepts with concepts from the list view documentation to create a more comprehensive and complete example. // If you want to use Employee objects in QML, you need to // register it as a type. You can include this C++ code in // the constructor for your app. qmlRegisterType<Employee>("myLibrary", 1, 0, "Employee"); // main.qml import bb.cascades 1.0 // Import the custom library that contains the Employee type, // so you can use this type in QML. For example, you might // need to use the Employee type in QML to respond to the // selection of an employee in the list. import myLibrary 1.0 Page { content: Container { attachedObjects: [ // Add the data model as an attached object. Make sure // to specify a value for the objectName property, // which is used to access the model from C++. GroupDataModel { id: groupDataModel objectName: "groupDataModel" // Sort the data first by last name, then by first // name sortingKeys: ["lastName", "firstName"] } ] ListView { id: listView // Associate the GroupDataModel from the attached // objects list with this ListView dataModel: groupDataModel listItemComponents: [ // Use a ListItemComponent to define the // appearance of list items (that is, those // with a type of "listItem") ListItemComponent { type: "listItem" // Each list item is represented by a // StandardListItem whose text fields are // populated with data from the item StandardListItem { title: ListItemData.lastName + ", " + ListItemData.firstName description: ListItemData.employeeNumber } } ] // Override the itemType() function to return the // proper type for each item in the list. Because a // GroupDataModel has only two levels, use the index // path to determine whether the item is a header item // or a list"; } } } // end of ListView } // end of Container } // end of Page // Employee.h // The implementation of these functions in Employee.cpp just sets // or returns the corresponding variables mFirstName, mLastName, // and mEmployeeNumber. // Remember that to be added to a GroupDataModel, your custom // class must inherit from QObject #include <QObject> using namespace bb::cascades; class Employee : public QObject { Q_OBJECT Q_PROPERTY(QString firstName READ firstName WRITE setFirstName FINAL) Q_PROPERTY(QString lastName READ lastName WRITE setLastName FINAL) Q_PROPERTY(int employeeNumber READ employeeNumber WRITE setEmployeeNumber FINAL) public: Employee(QObject *parent = 0); Employee(QString argLastName, QString argFirstName, int argEmployeeNumber); QString firstName() const; QString lastName() const; int employeeNumber() const; Q_SLOT void setFirstName(QString newName); Q_SLOT void setLastName(QString newName); Q_SLOT void setEmployeeNumber(int newNumber); private: QString mFirstName; QString mLastName; int mEmployeeNumber; }; // This is the C++ code that populates the data model. // You could include this code in the constructor for your app, // in an initialization function, or another location in your app. // Create the GroupDataModel by locating the corresponding // QML component GroupDataModel *pModel = root->findChild<GroupDataModel*>("groupDataModel"); // Insert the data as instances of the Employee class pModel->insert(new Employee("Barichak", "Westlee", 12596375)); pModel->insert(new Employee("Lambier", "Jamie", 53621479)); pModel->insert(new Employee("Chepesky", "Mike", 65523696)); pModel->insert(new Employee("Marshall", "Denise", 77553269)); pModel->insert(new Employee("Taylor", "Matthew", 51236712)); pModel->insert(new Employee("Tiegs", "Mark", 13112965)); pModel->insert(new Employee("Tetzel", "Karla", 99214732)); pModel->insert(new Employee("Dundas", "Ian", 64329841)); pModel->insert(new Employee("Cacciacarro", "Marco", 54575213)); Last modified: 2015-05-07 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/documentation/ui/lists/groupdatamodel.html
CC-MAIN-2017-04
refinedweb
3,277
50.36
This is a common issue. We have a file which was printed for human consumption. Consequently, it has many different kinds of lines. These are the two kinds of lines of interest: 900296268 4/9/16 Mobility, Data Mining, and Privacy Expired 900295204 4/1/16 Pro .NET Best Practices Expired The first is a single physical line. It has four data elements. The second is two physical lines. The first has three data elements. There are a number of other noise lines in the file which must be filtered out. The first "solution" pitched to me could be summarized with this: Move "Expired" on a line by itself to the previous line That was part of the email subject line. The body of the email was some whining about regular expressions. Which I mostly ignored. Multiline regular expressions are their own kind of challenge. We (should) all know this - see "Regular Expressions - Now You Have Two Problems". Let's do this without regular expressions. There are two things we need to know. One is buffering, and the other is the best way to split each line. It turns out that there are spaces as well as tabs, and by splitting on tabs we can make a lot of progress. Instead of the good approach, I'll pick the other approach that doesn't involve splitting on tabs. Here's the simulated file, with data lightly redacted. sample_text = ''' "Your eBooks" Show 200 Page: 1 Order # Date Title Formats Status Download ------- xxx315605 9/30/16 R for Cloud Computing Available xxx304790 6/21/16 Java XML and JSON Available xxx304790 6/21/16 Accelerated DOM Scripting with Ajax, APIs, and Libraries Available xxx291633 2/28/16 Practical Google Analytics and Google Tag Manager for Developers Expired ''' It's not perfectly obvious (because of line wrapping) but there are three examples of the "all-complete-in-one-line" records. There's one example of the "two-lines" record. Rather than mess with the file, we'll build a file-like object with our sample data. import io file_like_object = io.StringIO(sample_text) I like this because it lets me write proper unit test cases. The file has four kinds of lines: Complete Records Record Headers (without Available/Expired) Record Trailers (only Available/Expired) Noise We'll create some decision rules for the two obvious kinds of file lines: complete records and trailers. We can deduce the headers based on a simple adjacency rule: they precede a trailer. The fourth kind of lines are those which are possible headers but are not immediately prior to a trailer. def complete(words): return len(words) > 3 and words[-1] in ('Available', 'Expired') def trailer(words): return len(words) == 1 and words[0] in ('Available', 'Expired') We can spot these two kinds of lines easily. The other kinds require a Buffered Generator. def emit_clean(source): header = None for line in (line.strip() for line in source): words = [w.strip() for w in line.split()] if len(words) == 0: continue if complete(words): yield(line) header = None elif trailer(words) and header: yield(header + '\t\t' + line) header = None else: # Possible header # print('??', line) header = line The Buffered Generator is a way to implement a "look ahead one item" (LA1) algorithm. We do this by buffering rows. When we get to the next row we can use the buffered row and the current row to implement the look-ahead logic. The actual implementation uses a look-behind buffer, header. The (line.strip() for line in source) generator expression strips away leading and trailing spaces. This gets rid of the newline characters at the end of each input line. The default behavior of split() is to split on whitespace. In this case, it will create a number of words for complete records or header records, and a single word for a trailer record. If we had split on tab characters, some of this logic would be simplified. That's left as an exercise for the reader. If the len(words) is zero, the line is blank. If the line matches the complete() function, we can yield it as one of the iterable results of the generator function. We also clear out the look-behind buffer, header. If the line is a trailer and we have a buffered look-behind line, this is the two-physical-line case. We can assemble a complete record and emit it. Otherwise, we don't know what the line is. It's a possible header line, so we'll save it for later examination. This algorithm involves no regular expressions. With Regular Expressions An alternative would use three regular expressions to match the three kinds of lines. import re all_one_pat = re.compile("(.*)\t(.*)\t(.*)\t\t((?:Available)|(?:Expired))") header_pat = re.compile("(.*)\t(.*)\t(.*)") trailer_pat = re.compile("((?:Available)|(?:Expired))") This has the advantage that we can then use the groups() method of each successful match to emit useful data instead of text which needs subsequent parsing. This leads to a slightly more robust process. def emit_clean2(source): header = None for line in (line.strip() for line in source): if len(line) == 0: continue all_one_match = all_one_pat.match(line) header_match = header_pat.match(line) trailer_match = trailer_pat.match(line) if all_one_match: yield(all_one_match.groups()) header = None elif header_match and not header: header = header_match.groups() elif trailer_match and header: yield header + trailer_match.groups() header = None else: pass # noise The essential processing involves seeing which of the regular expressions match the line at hand. If it's all-in-one, this is good. We can yield the groups of meaningful data. If it's a header, we can save the groups. If it's a trailer, we can combine header and trailer groups and yield the composite. This has the advantage of explicitly rejecting noise lines instead of treating each noise line as a possible header. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/handling-irregular-file-formats
CC-MAIN-2017-04
refinedweb
987
67.04
<< // plugin.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } That's the main entry point of your DLL and you can leave that function unchanged. Copy all of the SDK files (except the Borland/Delphi subfolders of course) into the folder that is created by VC++. Now for compiling an A5 plugin DLL, you have to link the a5dll.lib (one of the files of the SDK) to the project (Project Properties -> Linker Input -> Additional Dependencies), and include the a5dll.h and a5funcs.h files to your main.cpp file. These 3 files are what you need for creating A5 DLLs. You can see in the ackdll.cpp example how it should look like. Now you can begin to add functions to the DLL that can then later be called by a script, or by the main function of your game. To be recognized by the engine, all such functions must be of type DLLFUNC fixed function(.), like this: // returns the value of x * 2n DLLFUNC fixed ldexp(fixed x,fixed n) { return (FLOAT2FIX(FIX2FLOAT(x)*pow(2.0,FIX2FLOAT(n)))); } This example function just returns an arithmetic expression of its arguments. DLLFUNC is not a part of C++ - it's just a convenience shortcut for declaring DLL export functions. fixed is the all-purpose numeric variable type of A5 and C-Script - a long integer that can be used either as 22.10 fixed point value, or as a pointer. Both are declared in the a5dll.h together with some conversion functions: #define DLLFUNC extern "C" __declspec(dllexport) typedef long fixed; // fixed inline fixed INT2FIX(int i) { inline int FIX2INT(fixed x) { inline double FIX2FLOAT(fixed inline fixed FLOAT2FIX(double point 22.10 number format used by C-Script return i<<10; } return x>>10; } x) { return ((double)x)/(1<<10); } f) { return (fixed)(f*(1<<10)); } The engine will pass and expect all numbers coordinates, variables, no matter what in fixed type. So convert any number to fixed before you return it to the engine, like in the example above. Ready? Now compile your DLL let's assume that you named it plugin.dll and copy it into your work folder. How can we now call our ldexp function by a script? We have to do two things: declare the function, and open the DLL. The first is achieved by a dllfunction prototype in the script: dllfunction ldexp(x,n); // declaration of a DLL function This makes our ldexp function known to C-Script. Before we can call it, we have to open the DLL. A good place to do this is the main() function of your script: function main() {. dll_open("plugin.dll"); and do not forget to close the DLL before exiting the game: . dll_close(dll_handle); exit; // just use the default handle as long as there's only one DLL After this is done, you can now enjoy that C-Script has gotten one extra instruction: . x = ldexp(y,n); // calculates x = y * 2n. For debugging your DLL in VC++, set the command in Project Properties -> Debug to the engine EXE path (like "C:\program files\gstudio\bin\acknex.exe"), the command arguments to your script and command line parameters (like "mygame.wdl -wnd") and the working directory to your game directory (like "C:\program files\gstudio\mygame"). In Project Properties -> General, set the output directory and the intermediate directory to. (a period, meaning the working directory) for the engine to find the intermediate files. Then you can compile and debug your DLL by setting breakpoints as usual. Ok, this was the basics of writing plugin DLLs. Of course, there's a lot more to learn. The methods for exchanging data with the engine are described in the following. All DLL functions can be declared and called in scripts just like each other C-Script function, after having activated the DLL through the dll_open and dll_close instructions described in the script manual. Using C-Script objects in a DLL We have learned how to add new C-Script instructions, but how can we access C-Script variables, objects and functions from within a DLL? We have some library functions to do that. All library functions provided by the SDK are preceded by a5dll_. The most often used function is long a5dll_getwdlobj(char *name); This function returns the address of the C-Script object or variable with the given name. It can be used to read or write any defined C-Script object from inside a DLL plugin. If the object does not exist, NULL is returned and an error message will pop up. Examples for DLL functions that access C-Script objects: // adds the given value to a C-Script vector fixed AddToVector(fixed value) { // get the address of the variable fixed *myvector = (fixed *)a5dll_getwdlobj("myvector"); // add the same value to the 3 components myvector[0] += value; myvector[1] += value; myvector[2] += value; return value; } // returns free distance in front of MY entity until next obstacle fixed DistAhead(long p_ent) { if (!my) return 0; // retrieve the pointer to the given entity A4_ENTITY *ent = (A4_ENTITY *)p_ent; // get the address of some script variables and functions fixed *tracemode = (fixed *)a5dll_getwdlobj("trace_mode"); wdlfunc2 vecrotate = (wdlfunc2)a5dll_getwdlfunc("vec_rotate"); wdlfunc2 trace = (wdlfunc2)a5dll_getwdlfunc("trace"); fixed target[3] = { FLOAT2FIX(1000.0),0,0 }; // trace target vector // rotate vector by entity engles, just as in C-Script (*vecrotate)((long)target,(long)&(ent->pan)); // add entity position to target target[0] += ent->x; target[1] += ent->y; target[2] += ent->z; // set trace_mode, then trace a line between entity and target, // and return the result *tracemode = INT2FIX(TRM_IGNORE_ME + TRM_IGNORE_PASSABLE + TRM_USE_BOX); return (*trace)((long)&(ent->x),(long)target); } Let's examine the important part of the code in detail: wdlfunc2 vecrotate = (wdlfunc2)a5dll_getwdlfunc("vec_rotate"); wdlfunc2 is a convenience typedef for a pointer to a C-Script instruction that takes 2 arguments. Because all C-Script instructions take either 1, 2, 3, or 4 arguments, there are 4 such typedefs in the a5dll.h: fixed fixed fixed fixed (*wdlfunc1)(long); (*wdlfunc2)(long,long); (*wdlfunc3)(long,long,long); (*wdlfunc4)(long,long,long,long); typedef typedef typedef typedef Once we've gotten the pointer to that instruction again, it's recommended to retrieve pointers to all used instructions in a startup function we can just call it: // rotate vector by entity engles, just as in C-Script (*vecrotate)((long)target,(long)&(ent->pan)); This looks a little different than you are used to call a function in C++! However, it's quite straightforward: We have a pointer to that function, so for calling the function itself we have to use the (*.). And the arguments passed are always fixed or long. We have casted them to long instead of fixed as a convention to indicate that we are passing pointers. All vector instructions expect pointers to fixed. All this pointer handling and typecasting may seem a little complicated at first, but because it's logical you'll fast get the grip of it. What if a C-Script instruction expects not a vector or value, but something more complicated like an entity? Well, we'll then just pass the A4_ENTITY pointer casted to long. And what if it expects a string must we really use a pointer to A4_STRING or can we just pass char*? We must use A4_STRING I'm afraid. But in the example ackdll.cpp you can find an easy way how to pass a string constant to a C-Script instruction: long pSTRING(char* chars) // convenience function to make string passing easy { static A4_STRING tempstring; static char tempname[256]; strncpy(tempname,chars,255); tempstring.chars = tempname; return (long)&tempstring; } // example for passing a string to create an entity DLLFUNC fixed create_warlock(long vec_pos) { wdlfunc3 ent_create = (wdlfunc3)a5dll_getwdlfunc("ent_create"); return (*ent_create)(pSTRING("warlock.mdl"),vec_pos,0); } Some special C-Script functions, like keyboard entry, can not be called directly from a DLL. However they can be executed indirectly by calling a script that executes that function. Scripts can be called from a DLL through the following functions: long a5dll_getscript(char *name); This function returns an addresss of the user-defined script function with the given name. It can be used to call user defined C-Script actions or functions from inside a DLL plugin. If the function is not found, NULL is returned and an error message will pop up. fixed a5dll_callscript(long script,long p1=0,long p2=0,long p3=0,long p4=0); fixed a5dll_callname(char *name,long p1=0,long p2=0,long p3=0,long p4=0); These functions call a user-defined script function with given address or given name. The 4 parameters can be a fixed point number, an array, or a pointer to a C-Script object. If the function expects less than 4 parameters, the superflous ones can just be set a 0. Example for a DLL function that calls a function that must be defined in the C-Script code: DLLFUNC fixed WDLBeep(fixed value) { // get the function long beeptwice = a5dll_getscript("beeptwice"); // call it return a5dll_callscript(beeptwice,0,0,0,0); } This DLL function expects the following function in the C-Script which is then called: function beeptwice() { beep; beep; } // in the script Now that we have learned to access every part of C-Script by a DLL and vice versa, let's continue with some special applications for DLL functions. Using Direct3D functions The following example shows how easy it is to use Direct3D functions for creating some effects on the screen. As all initialization is done by the engine, it is sufficient just to call the draw functions. All Direct3D functions are accessed through a LPDIRECT3DDEVICE8 pointer that is available through the DLL. For details refer to the DirectX documentation that is available, along with the DirectX 8.1 SDK, from the Microsoft site. The example paints a multicolored triangle onto the screen. You'll see the triangle briefly flashing in the upper left corner when you call PaintD3DTriangle() once. If you call it in a wait(1)-loop, the triangle will be permanently on the screen. #include <d3dx8.h> // from the DIRECTX8.1 sdk // dllfunction PaintD3DTriangle(); // draws a red/blue/green triangle in D3D mode DLLFUNC fixed PaintD3DTriangle (void) { // get the active D3D device LPDIRECT3DDEVICE8 pd3ddev = (LPDIRECT3DDEVICE8) a5dx->pd3ddev8; if (!pd3ddev) return 0; // define a suited vertex struct struct VERTEX_FLAT { float x,y,z; float rhw; D3DCOLOR color; }; #define D3DFVF_FLAT (D3DFVF_XYZRHW | D3DFVF_DIFFUSE) // define the three corner vertices VERTEX_FLAT v[3]; v[0].x = 10.0; v[0].y = 10.0; v[0].color = 0xFFFF0000; // the red corner v[1].x = 310.0; v[1].y = 10.0; v[1].color = 0xFF0000FF; // the blue corner v[2].x = 10.0; v[2].y = 310.0; v[2].color = 0xFF00FF00; // the green corner v[0].z = v[1].z = v[2].z = 0.0; // z buffer - paint over everything v[0].rhw = v[1].rhw = v[2].rhw = 1.0; // no perspective // begin a scene - needed before D3D draw operations pd3ddev->BeginScene(); // set some render and stage states (you have to set some more, normally) pd3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE); pd3ddev->SetTextureStageState(0,D3DTSS_COLORARG2,D3DTA_DIFFUSE); pd3ddev->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_SELECTARG2); // now draw the triangle pd3ddev->SetVertexShader(D3DFVF_FLAT); pd3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN,1,(LPVOID)v,sizeof(VERTEX_FLAT)); // do not forget to do a clean closing of the scene pd3ddev->EndScene(); return 0; } Note: Depending on the 3D hardware, sometimes A5 has to release and reallocate the Direct3D device when the video output is switched between window and fullscreen mode. If you use the pd3ddev8 for allocating an object, like a texture or a buffer, you have to release the object before switching video, and recreate it afterwards. Otherwise the device can't be released and you'll receive an Uninitialized Device error message. Particle functions DLL functions can also be used for particles, using the A4_PARTICLE struct defined in a5dll.h. They can be used the same way as C-Script defined particle functions. A pointer to the particle is the sole argument of a DLL particle function. Example: // examples for a particle effect function // dllfunction DLLEffect_Explo(particle); // dllfunction DLLPart_Alphafade(particle); // start the particle effect by // effect(DLLEffect_Explo,1000,my.x,nullvector); fixed *var_time = NULL; long func_alphafade = 0; // helper function: fades out a particle DLLFUNC fixed DLLPart_Alphafade(long particle) { if (!var_time || !particle) return 0; A4_PARTICLE* p = (A4_PARTICLE*) particle; p->alpha -= *var_time * 2; if (p->alpha <= 0) p->lifespan = 0; return 0; } // helper function: return a random float float random(float max) { return (float)(rand()*max)/(float)RAND_MAX; } // particle effect: generate a blue explosion DLLFUNC fixed DLLEffect_Explo(long particle) { if (!particle) return 0; // initialize time var and alphafade function (must only be done once) if (!var_time) var_time = (fixed *)a5dll_getwdlobj("time"); if (!func_alphafade) func_alphafade = a5dll_getscript("DLLPart_Alphafade"); A4_PARTICLE* p = (A4_PARTICLE*) particle; // initialize particle parameters p->flags |= EPF_STREAK|EPF_MOVE|ENF_FLARE|ENF_BRIGHT; p->vel_x = FLOAT2FIX(random(10) - 5); p->vel_y = FLOAT2FIX(random(10) - 5); p->vel_z = FLOAT2FIX(random(10) - 5); p->red = 0; p->green = 0; p->blue = INT2FIX(255); p->alpha = FLOAT2FIX(50 + random(50)); p->function = func_alphafade; return 0; } Sending information over the network The SDK can use A5's send and receive functions for sending user-defined messages in a multiplayer environment. For this, the SendPacket and ReveivePacket function pointers are available via the ENGINE_INTERFACE: typedef struct { byte *save_block;// pointer to block of variables for save/load (not used) int save_size; // size of block of variables for saving (not used) long (*Exec)(long n,long p1,long p2,long p3); // DLLLIB internal use only // only available in A5.51 or above - first packet byte must be 17 (0x11) for user defined packets void (*SendPacket)(long to,void *data,long size,long guaranteed); // the send function of the engine void (*ReceivePacket)(long from,void *data,long size); // user provided function } ENGINE_INTERFACE; SendPacket sends a user defined packed from the client to the server, or vice versa. Parameters: to - Identifier number for the client to receive the message. Set to 0 for sending to all clients. data - Data packet to be sent. First byte must be 17 (0x11) for identifying a user-defined packet. size - Size of the packet in bytes. guaranteed - set to 1 for TCP/IP mode, 0 for UDP mode. ReceivePacket can be set to a user provided void(long,void*,long) function that receives and interprets messages sent with SendPacket. Parameters: from ID Number of the sender. If at 0, the message was received from the server. data - Data packet to be sent. First byte is always 17 (0x11) for identifying a user-defined packet. size - Size of the packet in bytes. Note that the receive function should be very short and mainly just store the message, for not interfering the receive process. It must not send, open a file, render, or do anything time consuming. Programming a game in C++ Using the A4_ENTITY object (see below), a DLL can implement complex AI functions that would be harder to code in C-Script. Even the whole gameplay could be written in a DLL. The following example shows how to change entity parameters through a DLL function. // rolls the given entity by 180 degrees DLLFUNC fixed FlipUpsideDown(long entity) { if (!entity) return 0; // retrieve the pointer to the given entity A4_ENTITY *ent = (A4_ENTITY *)entity; // set the entity's roll angle to 180 degrees ent->roll = FLOAT2FIX(180); return 0; } This would be called by C-Script through FlipUpsideDown(my). For controlling entities totally through a DLL for instance, when you intend to write your whole game in C++ or Delphi, instead of C-Script C-Script dummy actions can be assigned to the entity, like this: var appdll_handle; dllfunction dll_entmain(entity); dllfunction dll_entevent(entity); function main() { // open the application DLL appdll_handle = dll_open("myapp.dll");. } action myent_event { dll_handle = appdll_handle; dll_entevent(my); // this DLL function handles all entity events } action myentity { my.event = myent_event; while(1) { dll_handle = appdll_handle; dll_entmain(my); // this DLL function controls the entity wait(1); } } DLL interface structures and special functions Interface structs are initialized at DLL startup for accessing essential engine variables and pointers. There are three such interfaces, which are defined in the a5dll.h: the WDL_INTERFACE a5wdl that contains C-Script access functions and he MY and YOU entity pointers, the ENGINE_INTERFACE a5eng that contains basic engine functions, and the DX_INTERFACE a5dx that contains pointers to all DirectX devices initialized by A5. Normally you'll only need the last one. For instance, a5dx>pd3ddev8 will get you the pointer to the Direct3D 8.1 device. Some utility functions are provided for manipulation of textures and entities: A4_TEX *a5dll_tex4ent(A4_ENTITY *entity,int frame,int texnum=0); This function returns the texture of a sprite, model or terrain entity. It can be used to directly access D3D textures (see example below). Frame is the frame or skin number, texnum the subtexture number if it is split into several subtextures. A4_ENTITY *a5dll_entnext(A4_ENTITY *entity); This function enumerates local entities, and can be used to access all entities in a level. If called with NULL, it returns a pointer to the first entity in the level. If called with a level entity pointer, it returns a pointer to the next level entity. If called with a pointer to the last entity or no entity at all, it returns NULL. Example for a function that uses DirectX 8.1 for painting the textures of model, sprite and terrain entities red: // dllfunction PaintEntitiesRed(); // paints the first mipmap of all sprite and model entities red DLLFUNC fixed PaintEntitiesRed(void) { // find the first entity in the level A4_ENTITY *ent = NULL; while (1) { // find the next entity ent = a5dll_entnext(ent); if (!ent) break; // we can not be sure that the entity texture exists - it could be purged A4_TEX *tex = a5dll_tex4ent(ent,0,0); if (!tex) continue; LPDIRECT3DTEXTURE8 dx8tex = (LPDIRECT3DTEXTURE8) tex->pd3dtex; if (!dx8tex) continue; // check the texture format D3DSURFACE_DESC ddsd; if (FAILED(dx8tex->GetLevelDesc(0,&ddsd))) continue; // lock the texture and retrieve a pointer to the surface D3DLOCKED_RECT d3dlr; if (FAILED(dx8tex->LockRect(0,&d3dlr,0,0))) continue; byte *pixels = (byte *)(d3dlr.pBits); // do we have a 16 bit or 32 bit format? if (ddsd.Format == D3DFMT_A8R8G8B8) for (unsigned y = 0; y < ddsd.Height; y++ ) { DWORD *target = (DWORD *)(pixels + y*d3dlr.Pitch); for (unsigned x = 0; x < ddsd.Width; x++ ) *target++ = 0xFFFF0000; // that's red in 8888 } else if (ddsd.Format == D3DFMT_A4R4G4B4) for (unsigned y = 0; y < ddsd.Height; y++ ) { WORD *target = (WORD *)(pixels + y*d3dlr.Pitch); for (unsigned x = 0; x < ddsd.Width; x++ ) *target++ = 0xFF00; // that's red in 4444 } else if (ddsd.Format == D3DFMT_A1R5G5B5) for (unsigned y = 0; y < ddsd.Height; y++ ) { WORD *target = (WORD *)(pixels + y*d3dlr.Pitch); for (unsigned x = 0; x < ddsd.Width; x++ ) *target++ = 0xFC00; // that's red in 1555 } else if (ddsd.Format == D3DFMT_R5G6B5) for (unsigned y = 0; y < ddsd.Height; y++ ) { WORD *target = (WORD *)(pixels + y*d3dlr.Pitch); for (unsigned x = 0; x < ddsd.Width; x++ ) *target++ = 0xF800; // that's red in 565 } // Unlock the surface again dx8tex->UnlockRect(0); } a5dll_errormessage("Entities are now red!"); return 0; } void a5dll_errormessage(char *text); This function pops up an Error #1527 message requester with the given text. It can be used to display diagnostic messages, or notify the user of wrong DLL calls, like with an invalid entity pointer. One final consideration.. svc_fill svc_create svc_remove svc_entsound 0x01 0x03 0x04 0x05 Short Entity_Index Short Identifier Short Entity_Index Short Entity_Index Short Sound_Index Scale(2000) Volume Long Sound_Handle Short Action_Index Short Number Position Start[3] Fixed Vel[3] Created entity with given index (TCP). Removed entity from server (TCP). Play an entity sound on the clients (UDP). svc_effect Generate a particle or beam effect on the clients (UDP). svc_info Send a sync value and the server time Long 0x11191218 Byte Protocol_Version to the clients (TCP). This is sent once a frame. Float Server_Time Float Frame_Time Send a variable to the client (TCP). Short Var_Index Short Var_Length Fixed Var[Var_Length] svc_var svc_string svc_skill Short String_Index String Text Short Entity_Index Short Struct_Offset Fixed Skill Short Entity_Index Short Struct_Offset Fixed Skill[3] Short Entity_Index Short Function_Index (Parameters see below) (Parameters see below) (Parameters see below) Send a string to the client (TCP). Send an entity skill to the client (TCP). Struct_Offset gives the byte offset of the skill in the A4_ENTITY struct. Send an entity vector skill to the client (TCP). Start the given function with the given MY entity on the client (TCP). Update entity parameters 1 (UDP). Update entity parameters 2 (UDP). Update entity parameters 3 (UDP). svc_skill3 svc_local svc_update1 svc_update2 svc_update3 0x40.0x7f Short Entity_Index 0x80.0xbf Short Entity_Index 0xc0.0xff Short Entity_Index For the 3 entity parameter update messages, bits 0.5 of the svc_update bytecode give the parameter combination to be sent or received, in the order given below. All parameters are sent through the UDP protocol. Parameter Update.Bit Arguments Remarks XYZ position position pan tilt roll 2.0 2.1 2.2 2.3 CPosition Pos[3] Angle Pan Angle Tilt Angle Roll Parameter Update.Bit Arguments Remarks Short Frame_Int Scale(1) Frame_Frc Short Nextframe Short Flags 8.23 String File_Name Short Scale[3] Scale(100) Ambient Scale(255) Albedo Byte Skin Scale(2000) Lightrange Scale(255) Red,Green,Blue Scale(100) Alpha Fixed U,V Frame number, tweening target tweening factor, flags1 type scale ambient albedo skin lightrange color alpha uv 2.5 1.0 1.1 1.3 1.4 1.2 3.0 3.1 3.2 3.3 Name of the mdl, wmb, pcx, etc. file XYZ scale*0.25 Skin number RBG color packed in 3 bytes UV offset or speed for entity textures For instance, the code sequence 0x83 0x07 0x00 0x80 0x00 0x00 0x00 0x01 0x00 0x80 0x01 0x00 0x80 0x00 updates position and pan angle (0x83 has bits 0 and 1 set) of entity No. 7 (0x07 0x00). The position uses the packed format and is set at coordinates x=1 (0x80 0x00 0x00), y=2 (0x00 0x01 0x00) and z=3 (0x80 0x01 0x00), and the pan angle is set at 180 degrees (0x80 0x00). The MDL5 model format Despite the engine uses model files with.MDL extension, it's internal MDL5 format differs from the Quake MDL format. normally, 16-bit 565 RGB or 16 bit 4444 ARGB: {} };; is either mdl_trivertxb_t or mdl_trivertxs_t, depending on whether the type is 0 or 2. In the MDL3 format the type is always 0. The beginning of the frames sizeof(mdl_triangle_t). MDL bones This is for future expansion of the MDL format, and not supported yet. Bones are a linked list of 3D vertices that are used for animation in the MDL. can be found in the.MDL file at offset The size of each frame is while mdl_trivertx_t sizeframe = 20 + (numverts+2) * sizeof(mdl_trivertx_t), baseframes = basetri + numtris The HMP5 terrain format A terrain is basically a rectangular mesh of height values with one or several surface textures. It is a simplified version of the GameStudio Model format, without all the data structures that are unnecessary for terrain. HMP file header Once the file header is read, all the other terrain parts can be found just by calculating their position in the file. Here is the format of the.HMP file header: typedef float vec3[3]; typedef struct { char version[4]; long nu1; vec3 scale; vec3 offset; long nu6; float ftrisize_x; float ftrisize_y; float fnumverts_x; long numskins ; long nu8,nu9; long numverts; long nu10; long numframes; long nu11; long flags; long nu12; } hmp_header; // // // // // // // // // // // // // // // // "HMP4" or "HMP5"; only the newer HMP5 format is described here not used heightpoint scale factors heightpoint offset not used triangle X size triangle Y size number of mesh coordinates in X direction number of textures not used total number of mesh coordinates not used number of frames not used always 0 not used The size of this header is 0x54 bytes (84). The "HMP4" format is used by the A5 engine prior to 5.230, while the new "HMP5" format is used by the A5 engine since version 5.230. The number of vertices in the rectangular mesh can be determined by int numverts_x = (int) fnumverts_x; int numverts_y = numverts/numverts_x; After the file header follow the textures and then the array of height values. HMP texture format The terrain surface textures are flat pictures. There can be more than one texture. By default, the first texture is the terrain skin, and the second texture is the detail map if it has a different size. Further textures are not used yet. You will find the first texture just after the model header, at offset baseskin = 0x54. There are numskins textures to read. The texture and pixel formats are the same as for MDL skins, and are described in detail in the MDL format description. HMP height values and Y position of the vertesx_t bboxmin,bboxmax; // bounding box of the frame see mdl description char name[16]; // name of the frame, used for animation hmp_trivertx_t height[numverts]; // array of height values } hmp_frame_t; >>IMAGE. SMH9151B Strap MC-E4013 2443BW Digital Mackie TT24 Powershot G11 Review VLF8126 C 702 37LG2000-ZA AEU Integrated-homelink-transciever W3301 AP140R-e1 EP-50 EWX14540W SX-218-K 66320KF-N 64I EPL-N2050 AA8XE SS-RXD8S T240MD NRX-3 BAR986HG SGH-A867 DTH8060 SCD-XE597 BAR938HG Expedition-2007 Suite 10 AKG 659 IC-RP1510 KDL-46W4220 AD18A1e09 Phone-MD4260 EUU6174 LAV4750 YH-999 Translator DSC-H7-B CJ110MV Lowrance X97 Concept 30 P92 Echo BC 2255 EX774N L-558 Reference Cruise MX2500 Es500 VVX 2000 2012NB Locator A1018S BCR 2000 S-locomotion 1 5 LE-26S81B Motorola A760 8410D GC3230 KG36VX13 105 X BDM750 Firmware Recorder 8 Aastra 8314 Navman F10 ZI720 9K MG15fxmsdm Rummikub Server E-660 Envoy-2004 R-631 Factor Digital DVD-P370 1830 PSS Iphone NV-SD440B X340N Km001 XVS650AL MEX-BT3600U 8 X Xperia X2 Magic Semi Auto MC240 AW2092F-1 Esam 4400 Guide RF267aars-XAA STA-1100 Deskjet 5652 CLP-320 M1712N Harmonyg-XT Processor DFC
http://www.ps2netdrivers.net/manual/conitec.3d.gamestudio.-.a4/
crawl-003
refinedweb
4,342
53.31
ArcGIS Runtime SDK for OS X provides an Objective-C API for developers that allows you to add mapping and GIS functionality to your Mac applications. The API leverages functionality provided by ArcGIS Online and ArcGIS Server services through the REST interface. Map layers or webmaps (comprising individual layers) are displayed in a map using the AGSMapView class. Each layer relies on map services from ArcGIS Server or other geospatial technology such as Bing, OpenStreetmap, WMS, and so on. You can also add Graphics on the map to display your own points or areas. The API is provided as a framework called ArcGIS. Classes and functions defined in this framework begin with the prefix AGS. This prefix acts as a namespace and prevents naming conflicts with classes defined in your application or other frameworks you use. You need to use a minimum of OS X 10.8 SDK to build your applications. Also, the applications you build will require a Mac running a minimum of OS X 10.8. If you're already using CocoaPods, setting up your project to use ArcGIS is really easy. Download the SDK from . Run the installer, this will install the ArcGIS framework under ${HOME}/Library/SDKs/ArcGIS/OSX. The ArcGIS framework depends upon the following frameworks and libraries. These need to be added to your XCode project as references - Set the project's Frameworks Search Paths setting to include ${HOME}/Library/SDKs/ArcGIS/OSX , and the Other Linker Flags setting to include the following entries: -ObjC -framework ArcGIS Finally, you must also add the ArcGIS.bundle file found under ${HOME}/Library/SDKs/ArcGIS/OSX.
https://developers.arcgis.com/macos/10-2/api-reference/
CC-MAIN-2018-30
refinedweb
270
56.45
Deploying and Managing Enterprise Apps Learn how to build XAML/C# camera and photos apps for Windows and Windows Phone 8.1. This session includes rich demos of the Windows.Media.Capture API and advanced image processing techniques, including HDR. Great presentation. I am developing a simple camera app for the 520 and I'm excited about the new Windows.Media.Capture namespace. I want to show the user a live preview, but I want to draw a circle on the screen that has a specific field of view (say, 12 degrees). Then they can put the subject directly in the circle. I believe WriteableBitmapEx will get me the circle I want, but I don't know how big to make it. Seems like I'd have to know the field of view of the lens and work from there. Do you know of any resources that might help with this? I've tried the forums, but the search capabilities aren't the best. Thanks in advance. I'm also a big fan of MVVM Light. I understand Laurent works at IdentityMine, too. Must be a good company to have both of you guys. Hi.Nice blog. I have a question that how do i implement the preview to Portrait and the capture image also Portrait ? i want the preview can Portrait full screen like system camera .(window phone 8.1) Hi. When i test the app its start the frontfaceing camera, when i take a pic or record a video. How can i change that?
https://channel9.msdn.com/Events/Build/2014/2-525
CC-MAIN-2019-22
refinedweb
256
75.5
22 January 2008 15:37 [Source: ICIS news] LONDON (ICIS news)--NYMEX light sweet crude futures recovered some of the losses posted on Monday and earlier on Tuesday after the US Federal Reserve cut interest rates by three quarters of a percentage point in a bid to restore confidence in the ?xml:namespace> ?xml:namespace> However, the emergency rate cut seemed to have little effect in reversing the overall downward trend in crude oil prices. By 14:30 GMT, February NYMEX crude was trading around $88.04/bbl, down $2.52/bbl from the Friday close of $90.57/bbl but up on earlier figures on Tuesday. Due to the holidays in the At the same time, March Brent crude on ICE Futures was trading around $86.84/bbl, down $0.67/bbl from the Monday close. The The oil markets have been fallen in tandem with global markets over fears that a Investment banking sources were expecting the Fed to cut interest rates in their official meeting next week by a further half a percentage point, followed by another half point cut at the end of March. Tony Dillon
http://www.icis.com/Articles/2008/01/22/9094888/nymex-crude-recovers-slightly-after-fed-rate-cut.html
CC-MAIN-2015-22
refinedweb
190
62.17
Implementing an Unordered List In order to implement an unordered list, we will construct what is commonly known as a linked list. Recall that we need to be sure that we can maintain the relative positioning of the items. However, there is no requirement that we maintain that positioning in contiguous memory. For example, consider the collection of items shown below. It appears that these values have been placed randomly. ![ Items not constrained in their physical placement](figures/random-items.png) If we can maintain some explicit information in each item, namely the location of the next item, then the relative position of each item can be expressed by simply following the link from one item to the next: ![ Relative positions maintained by explicit links](figures/explicit-links.png) It is important to note that the location of the first item of the list must be explicitly specified. Once we know where the first item is, the first item can tell us where the second is, and so on. The external reference is often referred to as the head of the list. Similarly, the last item needs to know that there is no next item. The Node Class The basic building block for the linked list implementation is the node. Each node object must hold at least two pieces of information. First, the node must contain the list item itself. We will call this the data field of the node. In addition, each node must hold a reference to the next node. Here we provide one simple Python implementation: class Node(object): def __init__(self, value): self.value = value self.next = None To construct a node, you need to supply the initial data value for the node. Evaluating the assignment statement below will yield a node object containing the value passed: >>> temp = Node(93) >>> temp.value 93 The special Python reference value None will play an important role in the Node class and later in the linked list itself. A reference to None will denote the fact that there is no next node. Note in the constructor that a node is initially created with next set to None. Since this is sometimes referred to as “grounding the node,” we will use the standard ground symbol to denote a reference that is referring to None. It is always a good idea to explicitly assign None to your initial next reference values. The Unordered List Class As we suggested above, the unordered list will be built from a collection of nodes, each linked to the next by explicit references. As long as we know where to find the first node (containing the first item), each item after that can be found by successively following the next links. With this in mind, the UnorderedList class must maintain a reference to the first node. Below we show the constructor. Note that each list object will maintain a single reference to the head of the list. class UnorderedList(object): def __init__(self): self.head = None Initially when we construct a list, there are no items. The assignment statement >>> mylist = UnorderedList() creates this linked list representation: As we discussed in the Node class, the special reference None will again be used to state that the head of the list does not refer to anything. Eventually, the example list given earlier will be represented by this linked list: The head of the list refers to the first node which contains the first item of the list. In turn, that node holds a reference to the next node (the next item) and so on. It is important to note that the list class itself does not contain any node objects. Instead it contains a single reference to only the first node in the linked structure. The is_empty method, shown below, simply checks to see if the head of the list is a reference to None. The result of the boolean expression self.head is None will only be true if there are no nodes in the linked list. Since a new list is empty, the constructor and the check for empty must be consistent with one another. This shows the advantage to using the reference None to denote the “end” of the linked structure. In Python, None can be compared to any reference. Two references are equal if they both refer to the same object. We will use this often in our remaining methods. def is_empty(self): return self.head is None So, how do we get items into our list? We need to implement the add method. However, before we can do that, we need to address the important question of where in the linked list to place the new item. Since this list is unordered, the specific location of the new item with respect to the other items already in the list is not important. The new item can go anywhere. With that in mind, it makes sense to place the new item in the easiest location possible. Recall that the linked list structure provides us with only one entry point, the head of the list. All of the other nodes can only be reached by accessing the first node and then following next links. This means that the easiest place to add the new node is right at the head, or beginning, of the list. In other words, we will make the new item the first item of the list and the existing items will need to be linked to this new first item so that they follow. The linked list shown above was built by calling the add method a number of times. >>> mylist.add(31) >>> mylist.add(77) >>> mylist.add(17) >>> mylist.add(93) >>> mylist.add(26) >>> mylist.add(54) Note that since 31 is the first item added to the list, it will eventually be the last node on the linked list as every other item is added ahead of it. Also, since 54 is the last item added, it will become the data value in the first node of the linked list. The add method is shown below. Each item of the list must reside in a node object. We create a new node within the method and place the item as its value. Then we complete the process by linking the new node into the existing structure. def add(self, item): temp = Node(item) temp.next = self.head self.head = temp This requires two steps as shown below. Step 1 (line 3) changes the next reference of the new node to refer to the old first node of the list. Now that the rest of the list has been properly attached to the new node, we can modify the head of the list to refer to the new node. ![ Adding a new node is a two-step process](figures/add-to-head.png) The order of the two steps described above is very important. What happens if the order of the steps is reversed? If the modification of the head of the list happens first, the result can be seen below. Since the head was the only external reference to the list nodes, all of the original nodes are lost and can no longer be accessed. ![ Result of reversing the order of the two steps](figures/wrong-order.png) The next methods that we will implement– size, search, and remove–are all based on a technique known as linked list traversal. Traversal refers to the process of systematically visiting each node. To do this we use an external reference that starts at the first node in the list. As we visit each node, we move the reference to the next node by “traversing” the next reference. To implement the size method, we need to traverse the linked list and keep a count of the number of nodes that occurred. Below we provide the Python code for counting the number of nodes in the list. The external reference is called current and is initialized to the head of the list in line 2. At the start of the process we have not seen any nodes so the count is set to . Lines 4–6 actually implement the traversal. As long as the current reference has not seen the end of the list ( None), we move current along to the next node via the assignment statement in line 6. Every time current moves to a new node, we add to count. Finally, count gets returned after the iteration stops. def size(self): current = self.head count = 0 while current is not None: count = count + 1 current = current.next return count Searching for a value in a linked list implementation of an unordered list also uses the traversal technique. As we visit each node in the linked list we will ask whether the data stored there matches the item we are looking for. In this case, however, we may not have to traverse all the way to the end of the list. In fact, if we do get to the end of the list, that means that the item we are looking for must not be present. Also, if we do find the item, there is no need to continue. Here is a possible implementation of search: def search(self, item): current = self.head while current is not None: if current.value == item: return True current = current.next return False The remove method requires two logical steps. First, we need to traverse the list looking for the item we want to remove. Once we find the item (recall that we assume it is present), we must remove it. The first step is very similar to search. Starting with an external reference set to the head of the list, we traverse the links until we discover the item we are looking for. Since we assume that item is present, we know that the iteration will stop before current gets to None. Once we have found the node to be removed, how do we remove it? One possibility would be to replace the value of the item with some marker that suggests that the item is no longer present. The problem with this approach is the number of nodes will no longer match the number of items. It would be much better to remove the item by removing the entire node. In order to remove the node containing the item, we need to modify the link in the previous node so that it refers to the node that comes after current. Unfortunately, there is no way to go backward in the linked list. Since current refers to the node ahead of the node where we would like to make the change, it is too late to make the necessary modification. The solution to this dilemma is to use two external references as we traverse down the linked list. current will behave just as it did before, marking the current location of the traverse. The new reference, which we will call previous, will always travel one node behind current. That way, when current stops at the node to be removed, previous will be referring to the proper place in the linked list for the modification. Here is an implementation of a complete remove method: def remove(self, item): current = self.head previous = None while True: if current.value == item: break previous, current = current, current.next if previous is None: self.head = current.next else: previous.next = current.next First we assign current and previous to the head of the list and None respectively. Then, on each iteration of our while loop, we break if current represents the node we wish to remove, and if not we update previous and current to current and current.next respectively. Again, the order of these two statements is crucial. previous must first be moved one node ahead to the location of current. At that point, current can be moved. Here we illustrate the movement of previous and current as they progress down the list looking for the node containing the value 17: ![ "previous" and "current" move down the list](figures/previous-current.png) Once the searching step of the remove has been completed, we need to remove the node from the linked list. If previous is None, we know that current is in fact the head of the list, so we remove that node by updating the head of the list to the subsequent node, thereby losing the reference to the original head node: In all other cases, we know that both previous and current are nodes in the list, so we can remove current by setting the next attribute of previous to the node after current in the list: ![ Removing an item from the middle of the list](figures/remove-from-middle.png) The remaining methods append, insert, index, and pop are left as exercises. Remember that each of these must take into account whether the change is taking place at the head of the list or someplace else. Also, insert, index, and pop require that we name the positions of the list. We will assume that position names are integers starting with 0.
https://bradfieldcs.com/algos/lists/implementing-an-unordered-list/
CC-MAIN-2018-26
refinedweb
2,195
72.05
28 July 2010 09:19 [Source: ICIS news] MOSCOW (ICIS)--Russia’s total production of polyethylene (PE), polystyrene (PS) and polyvinyl chloride (PVC) in the first six months of 2010 increased compared with the same period last year, while polypropylene (PP) output fell, the Russian Industry and Trade Ministry said in a statement released on Wednesday. ?xml:namespace> The country’s total PVC production in the first half of 2010 was up by 16.2% year on year at 315,300 tonnes due to stable operations at producers Sayanskhimplast and Kaustic Sterlitamak, the ministry said. PS output during the period totalled 146,700 tonnes, up 13.4% from the first six months of 2009, due to steady production rates at manufacturers Nizhnekamskneftekhim and Salavatnefteorgsintez, according to the statement. For more on polymers
http://www.icis.com/Articles/2010/07/28/9379874/russias-january-june-output-of-pe-ps-pvc-rises-pp.html
CC-MAIN-2015-11
refinedweb
132
59.13
Printable View I assume I made the same mistake as before. Is this in the right direction? Code: #include <iostream> using namespace std; int fib ( int n ); // Function reference. int main() { int sum_of_all_fibs = 0; // The sum will begin at zero, this will be the final output of all numbers // found to be modded by 5 or 3 and be less then 4,000,000. do { int n = 1; fib (n) == fib (++n); if (fib(n) % 3 == 0 || fib(n) % 5 == 0) { sum_of_all_fibs += fib(n); } } while ( sum_of_all_fibs < 4000000 ); } int fib ( int n ) { int fib = 0; int fib1 = 0; int fib2 = 1; int sum_of_all_fibs; fib = fib1 + fib2; fib1 = fib2; fib2 = sum_of_all_fibs; return sum_of_all_fibs; } To be honest, I wouldn't use a function for the fibonacci number here. At any given point during your loop you have the two previous fibonacci numbers and the next one is equal to their sum. Then it's a matter of shifting the previous one back into the previous previous variable, and moving the next one into the previous variable, ready for the next time around the loop. Then get your if statement in the right place, test the right variable, and loop up until the right ending condition. A recursive fibonacci function isn't just inefficient, it's diabolically inefficient at roughly O(2^(0.694n)). Even a value around 200 would take somewhere on the order of as much time as the age of the universe to calculate, on the worlds fastest PC. It simply cannot be used for this. The first thing that comes mind which is worse than that is Ackermann's function, which is saying a lot
http://cboard.cprogramming.com/cplusplus-programming/142332-fibonacci-sequence-2-print.html
CC-MAIN-2016-07
refinedweb
275
66.27
Building Java GUIs with Matisse: A Gentle Introduction, Page 2 Making It Work Close down the running application if it is still up. It's time to add some functionality to the buttons. The main trick left to demonstrate with Matisse is hooking up the buttons. The rest is simply filling in code, and because this will be a very long article if I go into all of the code in great detail, I will provide all of the code snippets and some brief descriptions, but won't go into enormous detail in this area. Suffice it to say that the backing code is fairly straightforward and should not be surprising to anyone who takes a little time to understand it. The Timer Thread One thing you will need for this app is a timer thread that, once the clock is started, keeps updating the timer label periodically with the elapsed time of the recording. You also need a few new attributes for this, so select JFlubberMainFrm.java in the editor, and then click on the Source view near the top of the edit window so that you can see the Java source. Then, add the following code right after the public class JFlubberMainFrm extends javax.swing.JFrame {: private Timer timer = null; private int labelNo = 0; private long currTime = 0L; private long startTime = 0L; class UpdateTimeTask extends TimerTask { public void run() { long millis = System.currentTimeMillis() - startTime; int seconds = (int)(millis/1000); int minutes = seconds/60; seconds = seconds % 60; timeLabel.setText(String.format("%d:%02d", minutes, seconds)); } } This code defines four attributes used to track the time and label number, and also a TimerTask that runs a thread that will be used later in the class to update the time label periodically once the start button is pressed. Note that this code uses the new Java 5 convenient text formatting. If you are still using Java 1.4, you will need to use a message formatter instead to get the minutes and seconds formatted nicely. After you have put in this code and saved it, you will probably see some missing class errors. Just right-click in the editor window and select Fix Imports to add in the required classes. For the TimerTask, select the java.util one rather than the swing one if asked by the Fix Imports wizard. Button Events Everything is now in place. You now can add some button event handlers: This is where my own lack of knowledge of Swing may show though. There are a lot of different events in Swing and I tend to stick with the ones I know that do what I want. Whether they are strictly speaking correct or not is another matter. In fact, this leads me to my one complaint about Matisse right now, compared with something like Java Studio Creator where you can double-click on a button and get a sensible default event generated for that button. In Matisse, you can't do this; you have to right-click and select the event you want, from a somewhat overwhelming list of options. For example, given a button, the default event I want is when someone clicks the button. In Java Studio Creator, a double-click gives me a handler for exactly this event, which is really nice and saves me time and worry. In Swing, for the button I have a choice of ActionPerformed, MouseClicked, MousePressed, MouseReleased and many, many others. I am sure there will be times I would want to use some of these other options, but by far the most common is someone clicking the button, so couldn't Matisse be made to select a logical default in this case? If it does do this already, I have not yet found the magic way to do it. Instead, for buttons I tend to stick with the MouseReleased event (sort of like the MouseUp from the apple way of event handling). In other words, the event is fired not when the button is pressed, but when the button is released after being pressed. This seems to work the best and most consistently. Knowing this, adding code to the MouseReleased event on the button is pretty easy: Start Button - Select the Start Button in the Design view of the form. - Right-click on the button, and select Events->Mouse->Mouse Released. - After you click on that option, the view should change to the code view and you should see a new event created for you that you can fill in the handler code. - Add the following event code into the new method (replace the TODO comment): - Save this and fix any import problems with the Fix Imports popup menu option. - Don't worry too much about the code above, but in a nutshell it stores the current time into the startTime attribute, and then creates the timer thread to update the timer label every 1/5 of a second. if(startTime == 0L) { startTime = evt.getWhen(); timer = new Timer(); timer.schedule(new UpdateTimeTask(), 200, 200); } You want to add similar handlers for the other buttons, so repeat the above steps to attach the code below to each of the buttons as named: Stop Button if(timer != null) { timer.cancel(); startTime = 0L; } Flub Button labelNo++; this.addLabel(Integer.toString(labelNo)); Note that this method uses a method called addLabel for convenience. You have not defined it yet, so define it in the class as: public void addLabel(String label) { long millis = System.currentTimeMillis() - startTime; double seconds = (double)millis / 1000; String labelList = jTextArea1.getText(); labelList = labelList + Double.toString(seconds) + "t" + Double.toString(seconds) + "t" + label + "n"; jTextArea1.setText(labelList); } Save Button You want to use this to put a filechooser up for the user to let them save the text from the text area: JFileChooser chooser = new JFileChooser(); int rVal = chooser.showSaveDialog(this); if(rVal == JFileChooser.APPROVE_OPTION) { File outputFile = chooser.getSelectedFile(); PrintWriter outputStream; try { outputStream = new PrintWriter(new BufferedWriter( new FileWriter(outputFile))); outputStream.print(this.jTextArea1.getText()); outputStream.close(); } catch(IOException ex) { ex.printStackTrace(); } } Clear Button This needs to set the text area to empty, and set the label count back to 0 (so that the labels start getting added from 1 again). this.jTextArea1.setText(""); this.labelNo = 0; Again, the above doesn't have a lot of explanation attached, so if you get confused as to what goes where, just take a look at the source code from the zip file included with this article and it should become apparent. Building and Distribution Once you have added this code, saved, and fixed any import problems (Fix Imports from the editor popup menu), select build main project from the IDE build menu. When this builds, you should notice that the IDE reports that it has already wrapped the application up into a jar file for you (called jFlubber.jar in my case) and it also says that you can run the application using java -jar jFlubber.jar (with appropriate path information to tell java where jFlubber.jar is). However, that might not be the case, especially if you take the jar file created out of the dist directory and run it from somewhere else on your machine. Instead, you may see the error: Exception in thread "main" java.lang.NoClassDefFoundError: org/jdesktop/layout/GroupLayout$Group If you see this, the reason is that the GroupLayout that Matisse uses is not part of the standard Java distro, and so when you try and run the jar file with a normal java distribution, the layout manager is not available. Unfortunately, the fix for this is a little ugly, and the only other real complaint I have about Matisse usage in NetBeans 5.0. One can imagine that this problem will be one that crops up for every Matisse-based GUI created, and how nice it would be to have a simple project property checkbox to say "include Matisse related classes in the distribution jar file", but if there is such an option, I have yet to find it. Instead, the fix isn't hard, but it's irritating. In a nutshell, you have to alter the ant script used to build the project and add the missing classes required. To do this: - In the top left hand pane, select the Files view. - Open the project nodes as necessary until you see the build.xml file, and then double-click to open it. - At the end, just before the </project> line, add the following code: <target name="-post-jar"> <jar update="true" destfile="${dist.jar}"> <zipfileset src="${libs.swing-layout.classpath}"/> </jar> </target> This defines a task that NetBeans calls automatically to roll the GroupLayout class into the jar file so that it will run anywhere. This is a useful thing to know for other such dependencies, without doubt, but if Matisse is going to be the way to create Java GUIs now, how much better it would be to make this step much easier with a project-level setting. Note that there is a lib folder that you can keep in the same place relative to the jar file that will also keep this working; however, most developers roll a single jar file for the java -jar type of distribution simply because it is much easier to distribute that way. Your mileage may vary. Perhaps I am way out of line for suggesting the rolling up of GroupLayout into the jar file; it's simply my preference (and it makes things run much better if you are calling the jar file in a different directory). After you make and save the change, do a Clean and Build from the Build menu; the whole thing should be rolled up with GroupLayout this time. Then, run java -jar jFlubber.jar again. The Result So, now you should be able to run your new jFlubber application. From the IDE, just click the run button or menu entry, or you can create a .bat file or .sh file depending what operating system you are using, and run the java -jar jFlubber.jar command that way. Either way you run it, the flubber application should be running just fine. Here is a screenshot of my version running in Ubuntu 5.10 Linux: Conclusion So, this little application is unlikely to win any awards, beauty contests, or just about anything else, but it does serve as a good introduction to Matisse development, and also fills a useful role in my podcasting production tools. I am certain this program could be vastly improved, which is why I stuck it out there under the GPL license, and I hope it will be useful either as an example or an actual application to others. Note also that it is a very simple application. It demonstrates only a fraction of what Matisse can do; furthermore, it doesn't even touch on the NetBeans Rich Client Platform (RCP) that will save an enormous amount of time for anyone doing more complex applications. Perhaps I will dive into the RCP in a future column, once I have got to know it better, but in the meantime I hope this example has been useful. If anyone wants to point out improvements in the way this application was written, please feel free to contact me. I am eager to learn more about Swing development now that there is finally a tool that makes it easy enough for me to be interested again. It's hard to believe that it has taken this long for a really good Swing GUI creation solution like this to come along, but I am very glad that it has. Further Reading/Resources - NetBeans 5.0 can be downloaded from. - A very useful visual guide to the Matisse layout cues is at. - More Matisse tutorials can be found at and. - For Rich Client Platform information:. - And also highly recommended, Roman Strobl's excellent flash demos:.. Page 2 of 2
http://www.developer.com/lang/article.php/10924_3589961_2/Building-Java-GUIs-with-Matisse-A-Gentle-Introduction.htm
CC-MAIN-2013-48
refinedweb
1,988
69.21
JDK 9/10/11: Side Effects From += on Java String JDK 9/10/11: Side Effects From += on Java String In this quick post, we take a look at a peculiar bug present in JDKs 9, 10, and 11 involving how the Java compiler interprets += on Java Strings. Join the DZone community and get the full member experience.Join For Free The question "Why does `array[i++%n] += i+" "` give different results in Java 8 and Java 10?" was posted earlier this week on StackOverflow.com. It points to a bug in the Java compiler that is present in JDK 9 and later, but is not present in JDK 8. As explained on the StackOverflow thread, Didier L provided a simple example of Java code that reproduces this issue. That is adapted in the code listing shown next. package dustin.examples.strings; import static java.lang.System.out; /** * Example demonstrating JDK-8204322 and adapted from Didier L's * original example (). */ public class StringConcatenationBug { static void didierLDemonstration() { final String[] array = {""}; array[generateArrayIndex()] += "a"; } static int generateArrayIndex() { out.println("Array Index Evaluated"); return 0; } public static void main(final String[] arguments) { didierLDemonstration(); } } Reading the code shown above, one would expect to see the string "Array Index Evaluated" displayed once if this class's main(String[]) function was executed. With JDK 8, that was the case, but since JDK 9, it has not been the case. The next screen snapshot demonstrates this. The examples shown in the screen snapshot show that when the class is compiled with javac's -source and -target flags set to " 8", the string is shown only once when the compiled class is executed. However, when javac's -source and -target flags are set to " 9", the string is shown twice when the compiled class is executed. This bug exists in JDK 9, JDK 10, and JDK 11. Olivier Grégoire has described this bug, "The issue seems to be limited to the string concatenation and assignment operator ( +=) with an expression with side effect(s) as the left operand." JDK-8204322 ["'+=' applied to String operands can provoke side effects"] has been written for this bug, has been resolved, and its resolution is targeted currently for JDK 11. The bug report describes the problem, "When using the += operator, it seems that javac duplicates the code before the +=." It also explains that code written like array[i++%n] += i + " "; is compiled effectively to code like array[i++%n] = array[i++%n] + i + " ";. Jan Lahoda's comment on the bug describes why it occurs. Aleksey Shipilev has requested that this fix be backported to JDK 10 and it appears that it will be via JDK-8204340. Additional background information regarding this bug can be found in the previously mentioned StackOverflow thread, in the related StackOverflow chat, and on the OpenJDK compiler-dev mailing list threads "Compiler bug about string concatenation" and "RFR: 8204322: '+=' applied to String operands can provoke side effects." Published at DZone with permission of Dustin Marx , 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/jdk-91011-side-effects-from-on-java-string?fromrel=true
CC-MAIN-2019-51
refinedweb
523
52.7
Connect to SQL Server in a BizTalk Services Project There are three overall steps to connect to the SQL Server database from a BizTalk Services project. Create an LOB Target for SQL Server. Important To create an LOB Target for SQL Server, you must be a member of the local Administrators group and have the System Administrator right on the on-premises SQL Server. Visual Studio must be opened with Administrative privileges to use BizTalk Adapter Service. Use the LOB Target Generate schema for the operation to be performed on the SQL Server application. Important These steps assume you have a Service Bus namespace. Install Azure BizTalk Services SDK lists the requirements. To add an LOB Target for SQL Server In Server Explorer, expand BizTalk Adapter Service, expand the Management URL, and then expand LOB Types. Right-click SQL and select Add SQL Target. The Add a Target wizard opens: In the Welcome window, select Next. In Connection Parameters, enter the following: Server: The server name or IP address of the SQL Server and optionally, the port number. If the port number is not entered, port 1433 is used. To use a different port, enter ComputerName:PortNumber. Instance: The name of the SQL Server instance. If no value is entered, the Default instance is used. Catalog: The name of the database. Advanced: Select this button to configure additional Uri Properties and any Binding Properties: > [!TIP] > <P>A single LOB Relay can be used with multiple LOB Targets. There are restrictions based on the security model. As a best practice, group the same security method in one LOB Relay. For example, use the same LOB Relay to host the LOB Targets that use Message Credential or Fixed Windows security type.</P> To create a new LOB Relay: <table> <colgroup> <col style="width: 50%" /> <col style="width: 50%" /> </colgroup> <tbody> <tr class="odd"> <td><p>Namespace</p></td> <td><p><strong>Required</strong>. Enter your Service Bus namespace. The namespace name is available in the <a href="">Azure classic portal</a>.</p></td> </tr> <tr class="even"> <td><p>Issuer Name</p></td> <td><p><strong>Required</strong>. A valid Service Bus Issuer Name is required.</p></td> </tr> <tr class="odd"> <td><p>Issuer Secret</p></td> <td><p><strong>Required</strong>. A valid Service Bus Issuer Secret key is required.</p></td> </tr> <tr class="even"> <td><p>Relay Path</p></td> <td><p><strong>Required</strong>. Enter the desired name of the relay path. For example, if you use chose the Fixed windows credential option for Runtime Security; you can enter something like <em>WindowsAuthRelay</em>.</p></td> </tr> <tr class="odd"> <td><p>Target Sub-path</p></td> <td><p><strong>Required</strong>. Enter a sub-path to make this target unique. For example, you can enter <em>GetOrder</em>.</p></td> </tr> <tr class="even"> <td><p>Target runtime URL</p></td> <td><p>This is automatically populated with the namespace name, relay path and target sub-path entered. If using the examples above, it is populated with something like:</p> <p></p></td> </tr> </tbody> </table> Select **Next**. 6. Summary shows your configured values. Select **Create**. 7. When complete, select **Finish**. The following activities occur in the background: - The LOB Target is created in Server Explorer. It can be disabled, started, and deleted. Its configuration can also be exported. - The LOB Target is created as an application in IIS. This application uses the Runtime for this specific LOB Target. [Runtime Components: BizTalk Adapter Service](hh689786\(v=azure.100\).md) describes the IIS components. To use the LOB Target Right-click anywhere on the BizTalk Service project design area, select Properties, and update the BizTalk Service URL property to include your BizTalk Services name. This is the name that you entered in Azure classic portal when creating the BizTalk Services. Set the security property for the relay endpoint: Right-click the relay endpoint in Server Explorer and select Properties. In the Properties grid, select the ellipsis (…) next to the Runtime Security property. In the Edit Security dialog box, select the security method you want to use, and enter their values. Select OK. Drag and drop the LOB Target onto the design area. Note the Entity Name property of the LOB Target. The default value of the property is Relay-Path_target-sub-path. Open the .config file for the LOB target, which typically has the RelayPath_target-sub-path.config naming convention. Enter the Service Bus issuer name and issuer secret, as shown: <tokenProvider> <sharedSecret issuerName="owner" issuerSecret="issuer_secret" /> </tokenProvider> Save changes to the config file. Once a LOB Target is configured and added to the design area, add a XML One-Way Bridge or a XML Request-Reply Bridge to be the source. Use Connector in the Toolbox to connect the bridge to the LOB Target, similar to the following: Create an XML One-Way Bridge and Create an XML Request-Reply Bridge provide more specific information on the XML bridge and any additional properties that must be configured. Tip The bridge uses the Relative Address property of the LOB Target to send messages to the on-premises LOB system. To generate the schema In the BizTalk Service project, in the Server Explorer, right click the LOB Target you created, and then select Add schemas to <project_name>. The Schema Generation dialog opens. Enter a file name prefix. This value is prefixed with all the schema files that are generated. You can also enter the folder name under which the schema is added in the Visual Studio Solution Explorer. The default value for the folder is LOB Schemas. Select a credential type to generate the schema, provided appropriate values for authentication, and then select OK. The schemas are added to the project under the folder name. See Also Connect to Oracle Database or eBusiness Suite in a BizTalk Services Project Connect to mySAP Business Suite in a BizTalk Services Project Connect to Siebel eBusiness Applications in a BizTalk Services Project PowerShell Cmdlets for the BizTalk Adapter Service Connect to LOB systems from a BizTalk Services Project
https://docs.microsoft.com/en-us/previous-versions/azure/hh689783(v=azure.100)
CC-MAIN-2019-22
refinedweb
1,017
57.77
> Q.1 > duke% export NAMESPACE=/home/adriano/NS > duke% factotum > duke% 9fs milagro > duke% 9 mount NS/milagro mil > factotoum ok, with/without secstore. > mount ok. When you run 9fs, you should be prompted for a user name and password to use. Are you being prompted? > duke% echo ciaociao > mil/usr/adriano/ciao > bash: mil/usr/adriano/ciao: Permissione denied try: echo hi | 9p write milagro/usr/adriano/ciao that will cut FUSE out of the loop, just to make things a little simpler. > Q.2 > > duke% 9p -a milagro -A main/archive > > Ok for all s, I see, read etc milagro's archive. > > How can I mount main/{archive,snapshot} on a duke's directory ? > In P9P doc I've not found how to issue a command like > "mount /srv/fossil /n/arc main/archive". > My mistake or feature intentionally not implemented (or not implemented > yet)? Just not implemented. It should be, it isn't. You can use this as a workaround: srv -a -A main/archive milagro milagro-dump 9 mount `namespace`/milagro-dump /dump > Q.3 > > All tests done using the raw char console (no X) > produce the expected network traffic. > > Under X + KDE there is a continuous, unsolicited, net activity > which stops dismounting the Plan9 file server (milagro) > or stopping X without dimounting milagro. > This is independent on the environment from which milagro has been > mounted (char console or X-KDE). > I tried all command sequences to have both milagro mounted and KDE > running, but the final behaviour is always the same. > > Where/what am I mistaking ? There is probably some KDE daemon running in the background that is excited about a new drive being mounted and is scanning it. ("Modern" X window managers like KDE and GNOME just do this sort of thing, ostensibly to make your life better, though that's rarely the effect.) You might try running lsof | grep mil/ to find out which programs are holding open references to milagro. You might also be able use "umount -f" to force an unmount. Russ
http://fixunix.com/plan9/46364-%5B9fans%5D-questions-about-freebsd-p9p.html
CC-MAIN-2015-11
refinedweb
341
64.3
Hi folks, here I am in this article going to explain Regular expression. How to form regular expression in Scala. What is Regular Expression: A regular expression is a string of characters and punctuation that represents a search pattern. Popularized by Perl and command-line utilities like Grep, regular expressions are a standard feature in the libraries of most programming languages including Scala. In Scala, we called it Scala Regex. The organization of Scala’s customary expressions depends on the Java class java.util.regex.Pattern. I suggest looking carefully at the Javadoc (Java Programming Interface Documentation) for java.util.regex.Pattern. if you are new to this kind of thing since Java (what’s the consequence of Scala) Standard expressions can be unique concerning the org you use with different dialects and tools. To reconstitute a string into a regular expression, we need to use the .r() method with the specified string. Let’s see through the example: import scala.util.matching.Regex val numberPassword: Regex = "[0-9]".r numberPassword.findFirstMatchIn("testpassword") match { case Some(_) => println("Password Is Valid.") case None => println("Password must contain a number.") } in the above example, the numberPattern is a Regex (regular expression) which we use to make sure a password contains a number. Suppose we are trying to find out the word from a statement. How to find that word in a statement in Scala there is a predefined method named findAllIn(). Let’s see by an example:- import scala.util.matching.Regex object RegularExpression { def main(args: Array[String]) { val matchingWord = "Scala".r val statement = "Scala is a Functinal Programming." println(matchingWord findFirstIn statement) } } Output: Some(Scala) Here, we have called the method .r() on the specified string to get an instance of the Regex class, to produce a pattern. The method findFirstIn() is used in the above code to find the first match of a regular expression. How to Form a Regular Expression: The following regular expression operators are supported in Scala and using these operators we can form any type of regular expression: 1.) Basic operator for Regex: Anchors — ^ and $ ^a matches any string that starts with a b$ matches a string that ends with b ^a b$ exact string match (starts and ends with a b) Quantifiers — * + ? and {} abc* matches a string that has ab followed by zero or more c abc+ matches a string that has ab followed by one or more c abc? matches a string that has ab followed by zero or one c abc{2} matches a string that has ab followed by 2 c abc{2,} matches a string that has ab followed by 2 or more c a(bc)* matches a string that has a followed by zero or more copies of the sequence bc a(bc)* matches a string that has a followed by zero or more copies of the sequence bc a(bc){2,5} matches a string that has a followed by 2 up to 5 copies of the sequence bc OR operator — | or [ ] a(b|c) matches a string that has a followed by b or c (and captures b or c) a[bc] same as previous, but without capturing b or c Character classes — \d \w \s and . \d matches a single character that is a digit \w matches a word character (alphanumeric character plus underscore) \s matches a whitespace character (includes tabs and line breaks) . matches any character \d, \w and \s also present their negation with \D, \W and \S respectively. 2.) Intermediate operator for Regex: Grouping and capturing — ( ) a(bc) parentheses create a capturing group with value bc a(?<foo>bc) using ?<foo> we put a name to the group This operator is very useful when we need to extract information from strings or data using your preferred programming language. Any multiple events captured by multiple groups will be exposed as a classical array: we will access their values specified using an index on the result of the match. Greedy and Lazy match: Quantifiers (* + {}) are greedy operators, so they extend the match through the given text. 3.) Advanced Operator for Regex: Boundaries — \b and \B \babc\b Performs a "whole words only" search pattern \b represents an anchor like a caret (it’s the same as $ and ^ ) matching position where one side is a word character (like \w) and the other side is not a word character (e.g. this string beginning may contain or a space character) Look-ahead and Look-behind — (?=) and (?<=) d(?=r) matches a d only if is followed by r, but r will not be part of the overall regex match (?<=r)d matches a d only if is preceded by an r, but r will not be part of the overall regex match Summary: As you noticed, the application areas of regex can be multiple and we can use regex for data validation, data contention, string parsing, and data scraping. Have fun and don’t forget to recommend the article if you liked it. For more blogs click here. References:
https://blog.knoldus.com/how-to-use-regular-expression-in-scala/
CC-MAIN-2022-21
refinedweb
842
59.33
1. Getting Started¶ 1.1. Loading a model and inspecting it¶ To begin with, cobrapy comes with bundled models for Salmonella and E. coli, as well as a “textbook” model of E. coli core metabolism. To load a test model, type In [1]: from __future__ import print_function import cobra import cobra.test # "ecoli" and "salmonella" are also valid arguments model = cobra.test.create_test_model("textbook") The reactions, metabolites, and genes attributes of the cobrapy model are a special type of list called a cobra.DictList, and each one is made up of cobra.Reaction, cobra.Metabolite and cobra.Gene objects respectively. In [2]: print(len(model.reactions)) print(len(model.metabolites)) print(len(model.genes)) 95 72 137 When using Jupyter notebook this type of information is rendered as a table. In [3]: model Out[3]: Just like a regular list, objects in the DictList can be retrieved by index. For example, to get the 30th reaction in the model (at index 29 because of 0-indexing): In [4]: model.reactions[29] Out[4]: Additionally, items can be retrieved by their id using the DictList.get_by_id() function. For example, to get the cytosolic atp metabolite object (the id is “atp_c”), we can do the following: In [5]: model.metabolites.get_by_id("atp_c") Out[5]: As an added bonus, users with an interactive shell such as IPython will be able to tab-complete to list elements inside a list. While this is not recommended behavior for most code because of the possibility for characters like “-” inside ids, this is very useful while in an interactive prompt: In [6]: model.reactions.EX_glc__D_e.bounds Out[6]: (-10.0, 1000.0) 1.2. Reactions¶ We will consider the reaction glucose 6-phosphate isomerase, which interconverts glucose 6-phosphate and fructose 6-phosphate. The reaction id for this reaction in our test model is PGI. In [7]: pgi = model.reactions.get_by_id("PGI") pgi Out[7]: We can view the full name and reaction catalyzed as strings In [8]: print(pgi.name) print(pgi.reaction) glucose-6-phosphate isomerase g6p_c <=> f6p_c We can also view reaction upper and lower bounds. Because the pgi.lower_bound < 0, and pgi.upper_bound > 0, pgi is reversible. In [9]: print(pgi.lower_bound, "< pgi <", pgi.upper_bound) print(pgi.reversibility) -1000.0 < pgi < 1000.0 True We can also ensure the reaction is mass balanced. This function will return elements which violate mass balance. If it comes back empty, then the reaction is mass balanced. In [10]: pgi.check_mass_balance() Out[10]: {} In order to add a metabolite, we pass in a dict with the metabolite object and its coefficient In [11]: pgi.add_metabolites({model.metabolites.get_by_id("h_c"): -1}) pgi.reaction Out[11]: 'g6p_c + h_c <=> f6p_c' The reaction is no longer mass balanced In [11]: pgi.check_mass_balance() Out[11]: {'H': -1.0, 'charge': -1.0} We can remove the metabolite, and the reaction will be balanced once again. In [12]: pgi.subtract_metabolites({model.metabolites.get_by_id("h_c"): -1}) print(pgi.reaction) print(pgi.check_mass_balance()) g6p_c <=> f6p_c {} It is also possible to build the reaction from a string. However, care must be taken when doing this to ensure reaction id’s match those in the model. The direction of the arrow is also used to update the upper and lower bounds. In [13]: pgi.reaction = "g6p_c --> f6p_c + h_c + green_eggs + ham" unknown metabolite 'green_eggs' created unknown metabolite 'ham' created In [14]: pgi.reaction Out[14]: 'g6p_c --> f6p_c + green_eggs + h_c + ham' In [15]: pgi.reaction = "g6p_c <=> f6p_c" pgi.reaction Out[15]: 'g6p_c <=> f6p_c' 1.3. Metabolites¶ We will consider cytosolic atp as our metabolite, which has the id "atp_c" in our test model. In [16]: atp = model.metabolites.get_by_id("atp_c") atp Out[16]: We can print out the metabolite name and compartment (cytosol in this case) directly as string. In [17]: print(atp.name) print(atp.compartment) ATP c We can see that ATP is a charged molecule in our model. In [18]: atp.charge Out[18]: -4 We can see the chemical formula for the metabolite as well. In [19]: print(atp.formula) C10H12N5O13P3 The reactions attribute gives a frozenset of all reactions using the given metabolite. We can use this to count the number of reactions which use atp. In [20]: len(atp.reactions) Out[20]: 13 A metabolite like glucose 6-phosphate will participate in fewer reactions. In [21]: model.metabolites.get_by_id("g6p_c").reactions Out[21]: frozenset({<Reaction G6PDH2r at 0x11b870c88>, <Reaction GLCpts at 0x11b870f98>, <Reaction PGI at 0x11b886a90>, <Reaction Biomass_Ecoli_core at 0x11b85a5f8>}) 1.4. Genes¶ The gene_reaction_rule is a boolean representation of the gene requirements for this reaction to be active as described in Schellenberger et al 2011 Nature Protocols 6(9):1290-307. The GPR is stored as the gene_reaction_rule for a Reaction object as a string. In [22]: gpr = pgi.gene_reaction_rule gpr Out[22]: 'b4025' Corresponding gene objects also exist. These objects are tracked by the reactions itself, as well as by the model In [23]: pgi.genes Out[23]: frozenset({<Gene b4025 at 0x11b844cc0>}) In [24]: pgi_gene = model.genes.get_by_id("b4025") pgi_gene Out[24]: Each gene keeps track of the reactions it catalyzes In [25]: pgi_gene.reactions Out[25]: frozenset({<Reaction PGI at 0x11b886a90>}) Altering the gene_reaction_rule will create new gene objects if necessary and update all relationships. In [26]: pgi.gene_reaction_rule = "(spam or eggs)" pgi.genes Out[26]: frozenset({<Gene spam at 0x11b850908>, <Gene eggs at 0x11b850eb8>}) In [27]: pgi_gene.reactions Out[27]: frozenset() Newly created genes are also added to the model In [28]: model.genes.get_by_id("spam") Out[28]: The delete_model_genes function will evaluate the GPR and set the upper and lower bounds to 0 if the reaction is knocked out. This function can preserve existing deletions or reset them using the cumulative_deletions flag. In [29]: cobra.manipulation.delete_model_genes( model, ["spam"], cumulative_deletions=True) print("after 1 KO: %4d < flux_PGI < %4d" % (pgi.lower_bound, pgi.upper_bound)) cobra.manipulation.delete_model_genes( model, ["eggs"], cumulative_deletions=True) print("after 2 KO: %4d < flux_PGI < %4d" % (pgi.lower_bound, pgi.upper_bound)) after 1 KO: -1000 < flux_PGI < 1000 after 2 KO: 0 < flux_PGI < 0 The undelete_model_genes can be used to reset a gene deletion In [30]: cobra.manipulation.undelete_model_genes(model) print(pgi.lower_bound, "< pgi <", pgi.upper_bound) -1000 < pgi < 1000 1.5. Making changes reversibly using models as contexts¶ Quite often, one wants to make small changes to a model and evaluate the impacts of these. For example, we may want to knock-out all reactions sequentially, and see what the impact of this is on the objective function. One way of doing this would be to create a new copy of the model before each knock-out with model.copy(). However, even with small models, this is a very slow approach as models are quite complex objects. Better then would be to do the knock-out, optimizing and then manually resetting the reaction bounds before proceeding with the next reaction. Since this is such a common scenario however, cobrapy allows us to use the model as a context, to have changes reverted automatically. In [31]: model = cobra.test.create_test_model('textbook') for reaction in model.reactions[:5]: with model as model: reaction.knock_out() model.optimize() print('%s blocked (bounds: %s), new growth rate %f' % (reaction.id, str(reaction.bounds), model.objective.value)) ACALD blocked (bounds: (0, 0)), new growth rate 0.873922 ACALDt blocked (bounds: (0, 0)), new growth rate 0.873922 ACKr blocked (bounds: (0, 0)), new growth rate 0.873922 ACONTa blocked (bounds: (0, 0)), new growth rate -0.000000 ACONTb blocked (bounds: (0, 0)), new growth rate -0.000000 If we look at those knocked reactions, see that their bounds have all been reverted. In [32]: [reaction.bounds for reaction in model.reactions[:5]] Out[32]: [(-1000.0, 1000.0), (-1000.0, 1000.0), (-1000.0, 1000.0), (-1000.0, 1000.0), (-1000.0, 1000.0)] Nested contexts are also supported In [33]: print('original objective: ', model.objective.expression) with model: model.objective = 'ATPM' print('print objective in first context:', model.objective.expression) with model: model.objective = 'ACALD' print('print objective in second context:', model.objective.expression) print('objective after exiting second context:', model.objective.expression) print('back to original objective:', model.objective.expression) original objective: -1.0*Biomass_Ecoli_core_reverse_2cdba + 1.0*Biomass_Ecoli_core print objective in first context: -1.0*ATPM_reverse_5b752 + 1.0*ATPM print objective in second context: 1.0*ACALD - 1.0*ACALD_reverse_fda2b objective after exiting second context: -1.0*ATPM_reverse_5b752 + 1.0*ATPM back to original objective: -1.0*Biomass_Ecoli_core_reverse_2cdba + 1.0*Biomass_Ecoli_core Most methods that modify the model are supported like this including adding and removing reactions and metabolites and setting the objective. Supported methods and functions mention this in the corresponding documentation. While it does not have any actual effect, for syntactic convenience it is also possible to refer to the model by a different name than outside the context. Such as In [34]: with model as inner: inner.reactions.PFK.knock_out
http://cobrapy.readthedocs.io/en/latest/getting_started.html
CC-MAIN-2017-47
refinedweb
1,478
52.36
Extension methods From Nemerle Homepage Intro This is one of C# 3.0 features, that we've been thinking about since a year or so. The basic idea is to allow users to extend existing classes with methods. One example where it is useful is a list class extending array class with ToList() method. Usage Extension methods need to be public and static. They can be polymorphic themselves, but the class that holds them cannot. You currently cannot place them in nested types. The first parameter of extension method is a class that is going to be extended, for example to extend the System.String class you use: namespace MyNamespace { class MyExtensionClass { public static Capitalize (this s : string) : string { s.Substring (0, 1).ToUpper () + s.Substring (1) // or whatever } } } Now in addition to regular: using MyNamespace; _ = MyExtensionClass.Capitalize (my_string) you can do: using MyNamespace; _ = my_string.Capitalize () The using part is necessary. So all it takes to turn a static method into extension method is a little this in front of the first parameter. The method could have other parameters, like: public static ChopLast (this s : string, k : int) : string { s.Substring (0, s.Length - k) } then the usage would be: _ = my_string.ChopLast (7) Polymorphic types In order to use extension method on generic types, like arrays, one need to define a generic method or non-generic method in generic class. For example: public static ToList[T] (this a : array [T]) : list [T] { // whatever } There are cases, when you need more than one type parameter, like: public static FoldLeft[A,B] (this a : array [A], ini : B, f : A * B -> B) : B { ... } We also can do specializations with extension methods, like: public static Sum (this a : array [int]) : int { ... }
http://nemerle.org/Extension_methods
crawl-001
refinedweb
291
65.93
What is a standard? Wikipedia says about Technical Standards: A technical standard is an established norm or requirement in regard to technical systems. It is usually a formal document that establishes uniform engineering or technical criteria, methods, processes and practices. OK, and what is a requirement? Wikipedia, as source for unlimited knowledge about everything, says about Requirement: A requirement is a singular documented physical and functional need that a particular design, product or process must be able to perform Summarized and applied to “testing”, this means for me that a testing standard formally describes the methods and processes necessary to provide a uniform testing service. When it comes to testing, the past has shown that project environments are so manifold and diverse, that it’s extremely hard to unify them and apply the same over-weight test approach to them all. Many people have accepted that fact and are doing the best they can think of that is necessary and helpful in their context. But some are afraid of the diversity and differences between testing projects and want to find the one way to rule them all with one ring, eh I mean standard. I’ve been in more discussions this past year (2015) regarding ISO 29119 than I even dreamed of when I first came across it, back in 2012. This post is not designed as a rant against the new ISO standard, I’ve done my share of that already this year. To be more precise, the goal of this post is to describe a testing standard that should really be the minimum process to all test projects you perform professionally and structured. I say that a project adheres to a standard, when it fulfills this set minimum. A project that does not follow this standard, is sub-standard. There is no need to fill out huge checklists of things that you shall do, don’t want to do, and have to justify why. Just don’t do it and you are sub-standard. And believe me, from working for years below standard, it really feels like that. If in your context there are special rules to follow, documents to produce that some other standard, law, federal agency, or whoever prescribe, those rules and documents belong to that other standard and don’t belong to the testing standard. It’s not useful that one standard cares for other standards to be fulfilled. If you can combine your efforts to fulfill both at the same time, excellent! If not, don’t blame it on the testing standard. Everything that is not described as part of the standard that is on top or extra, and depends on your project context or personal favors is nothing but that, an extra on top. It might improve the situation and quality in your special situation, but is not a must to comply with Testpappy’s International Testing Standard. The standard consists of 3 parts: Part 1 – Terminology: Some basic terms to know, when speaking about testing. Part 2 – Test Process: Activities a testing project consists of. Part 3 – Documentation: Stuff you should write down. In contrast to ISO 29119, I don’t see much use in test techniques being part of a standard. You cannot and don’t have to use all techniques in every project, sometimes the use of a well known test technique might result in testing the wrong things. Context is king when testing! I don’t say, test techniques are useless, au contraire, they are good tools for good testers and should be learned and practiced. But I don’t see them as part of a standard that describes a process. The usage of tools is also as important and is also not part of this or any other standard I know of. Tester: “But I followed test technique abc, because the standard describes it!” Stakeholder: “I don’t care, the program still sucks!” Not with my standard! There will be no part of the standard describing testing in a waterfall, V-model, SCRUM, Agile, DevOps approach or anything that will come up in the future. The testing process is and will be always the same, only the involvement of roles within the project life cycle differ. The sooner good and structured testing starts, the better. But context, availability of skills and resources, and many other factors can have a huge influence and impact here. As long as you test in your project, you can’t be that wrong. Part 1 – Terminology Most terms are project context specific. There are more people speaking about testing than just testers. The most important fact is, that you reach a common understanding, not shallow, of the terms you use in your context. Every testing training (with or without certification scheme) bring their own namespace of terms. Some of the terms and definitions are useful, some may not be the best or thought through. But all need to be understood to get the ideas presented and taught to you during the training. Most words have meanings given to them by the dictionary a long time ago and should not be reused, some words are made up and given a meaning in the context of the namespace to transport complicated ideas by simple terms. This part of the standard just wants to give you a set of basic terms, to distinguish roughly between some basic testing terms. Testing and Checking Testing: Intellectual process of learning about a product / feature / function by exploration and experimentation. It’s all about gaining new information about the system under test. Testing strongly follows the scientific method. Checking: Making evaluations by applying algorithmic rules to observations of the system that don’t bring new information other than, “it’s still working the way it was intended and did before”. Example: What most people call “automated tests” are actually checks. The testing happened beforehand and exact instructions are given to a machine what to do and how to evaluate the results. The machine will only say “yes, worked as expected”, or “no, did not work as expected”. (Hint: Don’t exaggerate using this term in contrast to testing. Most people, especially non-testers, don’t see the difference between testing and checking. It is an important difference to understand the value of individual tasks testers are actually doing, but as long as that is clear to all or not a problem, just go with “testing” even if it’s “checking”. “Checking” is a part of “testing”, so it’s not wrong to call it all just “testing”.) Functional and Non-functional Tests Functional Test: Testing related to a function or feature, if it doesn’t show any problems when using. Non-functional Test: Testing a part of your product, that is not directly functional related. e.g. operational tests are non-functional. Even if your application doesn’t fail over, it can still work correct most of the time. Performance, Load and Stress Tests Performance Test: You measure and monitor the reaction times of multiple parts of the system for your user. You monitor this over time and when changes are applied, and you can evaluate the individual results or trends as good or bad. This should be done on a special environment, that is used exclusively for performance tests, so that third-party influences can be excluded from the measurements. Load Test: You expect a certain amount of load onto your system in production. To know ahead if the system can handle the load, you apply this load to your product and monitor the performance for the single users and parts of the application. This should be done on a special environment which reflects the production environment to certain level. Stress Test: You want to know what your product can stand, so you raise the load onto the system and monitor the performance and system behavior. Once the system starts making errors or the performance is rated unbearable for the user, you have found a rough boundary for your system performance. Environment should be the same like that for load testing. An interesting result of a stress test is to see how your system reacts under stress. Is it simply getting slower, or does it start to produce errors?! Security Test: Everything that you do with your system under test that helps to understand the level of security built into the system. Namespaces usually consider of hundreds of words, but I don’t see much use for a standard to define them all. Use those words as you need them in your context and how you and your colleagues understand them. The most important aspect is that there is common, not shallow, understanding of all the terms used in your project context. Part 2 – Test Process What is a process? Again wikipedia helps: A business process is a collection of related, structured activities or tasks that produce a specific service … for a particular customer or customers. This part describes what activities and tasks you have to do in a testing project. It does not describe “testing” itself. Some of the tasks you won’t even experience as special tasks, because they come with the natural flow of a test project. (Overall) Test Strategy: Create an overall strategy how and when to include testing in your project, and who (which role or team) is testing to what extend in what part of the project. The test strategy should support the common goal to achieve a certain quality. This might even be given by the overall project management. Test Management: Testing is a project activity like anything else and should be managed at a certain level. Managing a testing effort consists of planning, segmentation/controlling, monitoring and reporting. Test Plan: Plan all your testing activities, skills and resources, as far as you can. In general, everything you create that should be delivered you should test to some degree – given by the context. And remember, it’s testing! You produce information and never know exactly what you’ll find, that will lead to additional testing. So better start to plan only on a high level and have only a rough idea what to do. Plan your functional and non-functional tests, special tests, performance and load tests, or plan for using automated scripts and tools. Detailed planning in the beginning might be a waste of time in many cases and is on your own risk. You and your stakeholders (should) have a certain quality expectation. Plan your tests accordingly to show that those expectations are met. Planning is a reoccurring activity that has to react to changes and additional information. Test Segmenting: This can be achieved by structuring and splitting the necessary testing in manageable bits. This can be test cases, checklists, charters, post-its, or any other sort of structure you want to apply in your context. In the sense of the standard it means that a manager or lead has a certain control over what the testers actually look at during test execution. Testing produces information that might lead to more testing necessary. You must also manage those additional bits. Test Monitoring: Monitor the progress of your testing activities. This informs further planning activities. Test Reporting: Based on strategy and plan, summarize your test results with the achieved information about the product under test. Focus your report on the valuable information for the stakeholders. Test Execution: The “Testing” activity itself consists of test design, preparation, execution and documentation. Those steps can be handled separately as the classical approach often suggests, or can be seen as interacting activities that best work together as the more modern approaches suggest. Test Design: Tests are like experiments and need to be designed. What are the prerequisites (e.g. state of the system, input data, etc.), what do you plan to do with the system under test to achieve what goal? Test Preparation: Prepare your test environment, the test data, tools and scripts, set up logging and monitoring. Test Execution and Documentation: The performance of the tests or experiments itself. The actual interaction with the system. Collect the results of your experiments and document them in the way prescribed by the project, which depends on the context how to re-use the documentation for other purposes than the original. If you think about testing on different scales, from being alone to testing in 50-people team, you will go through those activities sooner or later. And the project size and context will dictate the importance and approach to choose. But if you skip one of those steps, which is actually really hard, you are operating below standard. Part 3 – Documentation There is one basic rule defined by the standard: document only as much as you have to (prescribed e.g. by the non-testing influences of the project) but as much as is useful (for reporting, supporting your memory, later reuse). But do document and communicate! Test Strategy: The strategy should be usually a part of the overall project management documentation. If not, write down a separate one. It should also be presented to the team and stakeholders. Test Plan: The plan should go conform with the test strategy. Write down what you plan and keep it up-to-date. An outdated plan is a useless document. Better keep it to a minimum and up-date, than plan in detail and let it get deprecated quickly. Do you need special equipment, test environments, specially skilled people, write it down. And of course, the best plan is good for nothing if you just write it down and don’t tell anyone. Remember to share and communicate your plan! Test Execution: There are lots of ways to document test executions. There is – of course – only one minimum requirement to follow Testpappy’s International Testing Standard: do it! You can write down your planned tests way ahead in a more or less detailed way. Everything is fine from rough charters via long checklists, up to detailed test scripts (if you really want that). You made a plan, you know what is important for your stakeholders, why put that at risk to forget it during execution? During execution you can then decide to simply check off the performed steps as a bare minimum of documentation or take extensive notes of what you have done and observed, supported by screenshots and videos. Document something for the people who should do the testing to follow. If you are the one, why not write down your ideas, so you don’t forget them. If someone has to take over from you, there is a start. It must not be much according to the standard, but of course can be if you want. Nobody stops you from wasting your time. But a minimum to prove the testing that has been performed is mandatory for fulfilling the standard. Bug Reporting: This is a necessary part of a development project. And yes, bug reporting is a valuable skill for a tester. A bug report is a special piece of information and is collected and managed by a process involving more roles than just the tester. So besides the fact that bugs which are not fixed right away should be documented and even managed, the standard for testing doesn’t add any rules here. Setting up a bug life cycle and process is part of the overall project management (even if often the test lead is responsible for that process), it’s not necessary for testing. Testing can live without such a process. But you have to document the found bugs somehow as part of your notes. Test Reporting: Don’t report (only) by numbers. Testers are in the information business, and what other information business do you know that report by numbers? Your information should be valuable to the stakeholder, so treat it like that. The form of a test report depends of course on project, context, and size of testing. It can be a simple mail, an excel sheet, a fancy slide deck, or if necessary even a 100-page word-document; or everything in between. The one rule to follow is again, it should be written down somewhere and communicated to the stakeholders. Your stakeholders want to make an informed decision, so provide information in a relevant way! Reporting should happen throughout the whole project. But the standard prescribes the test completion report as the only mandatory. Every other reporting occasion is helpful for the project, but not mandatory by the standard. That’s all! – Disclaimer If you have a test project and you follow the steps prescribed by the standard, you have created a project that has a certain minimum aspect of quality and value, a good test project should have from a management perspective. It cannot be described by this or any standard that the test results you produce are what your stakeholders expect. This standard won’t prevent any bugs from showing up in production. And of course, following this standard – like any other standard – doesn’t prevent you from creating a product that sucks and nobody wants. If you don’t follow this standard, your test project can still be a success. If you follow this standard, your project can still fail. This standard does not describe how to actually test! Because my motto is, as long as bugs don’t adhere to a standard, neither do I when looking for them! If you think there is a term, an activity or task, or a document that is missing from this standard, please let me know, and I will think about adding it. 3 thoughts on “Testpappy’s International Testing Standard”
https://testpappy.wordpress.com/2015/12/27/testpappys-international-testing-standard/
CC-MAIN-2018-26
refinedweb
2,952
62.78
Compiling C on the Omega Since the Omega is a Linux computer, it supports C and C++ programs. By default, gcc, the C compiler, and g++, the C++ compiler are not installed. This article will explain the limitations of compiling C & C++ programs on the Omega, how to install and then use the compilers. Limitations There are two main limitations when compiling C & C++ programs with the Omega: the processing speed and availability of the headers of libraries. Processing Speed The Omega’s processor is optimized for low power consumption and low heat generation, which means that it’s definitely not as powerful as the average modern laptop. This means that compiling large programs will take some time, you’ll have to be patient. To use a library in your program, you need to include the header file in your code so that the compiler knows the declaration of the functions that you are using from that library. Then, when the compiler is linking the binary file of your program, it needs to be informed of the location of the library shared object, .sofile so the program knows where to look during runtime for the compiled definitions of the library functions used in the program. If the headers are not present, the compiler will not successfully compile the program, even if the library object is present. A Solution It is possible to overcome to two above-mentioned limitations by using the LEDE build system on your computer to cross-compile your program for the Omega. See the article on Cross Compilation for more details and instructions. Installing the Compiler The gcc compiler takes up quite a bit of space, so the first order of business is to configure the Omega to boot from external storage. The packages we need are not included in the Onion package repositories, so we’ll need to update the repositories that the opkg utility checks. Open up /etc/opkg/distfeeds.conf and uncomment the following lines: src/gz reboot_base and src/gz reboot_packages For more info on the package repos the Omega uses, take a look at our article on using opkg Once that’s done, we can proceed to install gcc and the make utility: opkg update opkg install gcc opkg install make Installing a Debugger If you will be running C & C++ programs, you’ll most likely want to debug a program at one point or another. Install the gdb to help in that endeavour: opkg update opkg install gdb There are many resources available online that provide guides on using GDB to debug programs. These two guides offer a good overview on using GDB and are a good place to start: Compiling a C Program Now that you have the compiler installed, let’s use it to compile a C program! Create a file on your Omega called helloworld.c and populate it with some C code: #include <stdio.h> int main() { printf("Hello World!\n"); printf("We're running a C program on the Omega2!\n"); return 0; } To compile the program, run the following command: gcc helloworld.c -o helloworld This will produce helloworld, an executable binary file that is the compiled version of your C code! Let’s run it: root@Omega-665D:~# ./helloworld Hello World! We're running a C program on the Omega2! Awesome! You’ve just compiled your very first C program on the Omega! A Example Program Take a look at our c-example repo on GitHub to find a C program and Makefile that can be compiled on your Omega. Connect to your Omega, install git, clone the c-example repo, and run make to compile your very own C program. The output of the compilation will be an executable binary called gpioRead. The program will read and print the input value on a user-specified GPIO pin once a second for 20 seconds. Run it with ./gpioRead! Compiling a C++ Program The gcc package we installed with opkg also includes g++, a C++ compiler, so we can compile C++ programs as well! The process is very similar to compiling a C program, just a few key differences. Let’s create a helloworld.cpp file on the Omega and populate it with the following code: #include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; cout << "Now we're running a C++ program on the Omega2" << endl; return 0; } Compile it with the following command: g++ helloworld.cpp -o helloworld2 This produces an executable binary file, helloworld2 that is the compiled version of your C++ code! Let’s run the binary: root@Omega-665D:~# ./helloworld2 Hello World! Now we're running a C++ program on the Omega2 Going Further The gcc and g++ compilers are really powerful and configurable. When used in conjunction with the make utility we installed, you will be able to create and compile a variety of C & C++ projects with little repetitive work. There are many resources available online on these topics, we recommend starting with the following to get an overview:
https://docs.onion.io/omega2-docs/c-compiler-on-omega.html
CC-MAIN-2017-43
refinedweb
843
61.36
Is there a default variable that can be used in the application that refers to the project using it as a recipe? Something like ${callingProjectKey} ? I have SQL merge recipes in the application that reference ${projectKey}_tablename which fail because the temporary project instance has not created the table in advance. e.g. MERGE INTO ${projectKey}_mytable as t USING (SELECT ID,blah) ... DSS doesn't provide directly the calling project's key as variable, you have to sniff it in the scenario, for example with the python code I suggested. That would indeed be a nice improvement. Hi, if the goal is to reuse tables that are "fixed", then you should probably replace ${projectKey} in their names by either a fixed value or by another variable that you define in the project. The easiest to get at the projectKey of the project from which the recipe is run, is to use the variable storing it for the scenario of the app-as-recipe, and put it as a project variable: - in the scenario, start by a Execute Python code step with from dataiku.scenario import Scenario calling_project_key = Scenario().get_all_variables().get('scenarioTriggerParam_projectKey', dataiku.default_project_key()) import dataiku p = dataiku.Project() vars = p.get_variables() vars["local"]["callingProjectKey"] = calling_project_key p.set_variables(vars) - in the project defining the app-as-recipe, add a variable called `callingProjectKey` with the projectKey as value, and use it in place of ${projectKey} in places where you want to access the same table Hi, Thanks for the reply. We may have a few project copies for testing and would have different tables for each. I can achieve the same by defining "calllingProjectKey" as a control setting in the application designer and then specifying the value in the parameter field when defining the recipe made from the application (is this the same as your example?). My question was whether DSS provided its own internally-set variable for the name of the calling project. If not, it would be a reasonable enhancement request. DSS doesn't provide directly the calling project's key as variable, you have to sniff it in the scenario, for example with the python code I suggested. That would indeed be a nice improvement.
https://community.dataiku.com/t5/Using-Dataiku/Applications-as-recipes-and-projectKey/td-p/14816
CC-MAIN-2021-43
refinedweb
367
61.56
30 June 2011 09:33 [Source: ICIS news] By Chow Bee Lin SINGAPORE (ICIS)--?xml:namespace> This is because of reduced domestic supply and improved demand for low density PE (LDPE) and linear low density PE (LLDPE), the sources added. The domestic production of PE will reduce significantly because several major producers in The demand for LDPE and LLDPE film grades is expected to be strong in August-December because production in the downstream greenhouse film application sector is expected be in full swing during this period, local distributors said. A stronger demand for LDPE and LLDPE will boost the buying interest for high density PE (HDPE), the distributors said. The weekly average prices of LDPE and LLDPE film grades fell by 9-11% from $1,665/tonne (€1,149/tonne) CFR (cost & freight) China and $1,375/tonne CFR China respectively in late April to $1,480/tonne CFR China and $1,240/tonne CFR China respectively in the week ending 24 June, according to ICIS. The weekly average prices of HDPE film grade fell by 7% to $1,300/tonne CFR China in the week ending 24 June, down by $100/tonne from early May, according to ICIS. Some resin producers in “The price scenario in the petrochemical sector will change if crude [prices] fall to below $90/bbl,” a regional PE producer said. Crude futures were traded at around $92/bbl on Wednesday, supported by a larger-than-expected fall in US crude stocks and expectations that Greek lawmakers will approve austerity measures to avoid a default on the country’s sovereign debts. ($1 = €0.69) Additional reporting by Lizzie Yu
http://www.icis.com/Articles/2011/06/30/9473856/chinas-pe-prices-expected-to-rebound-in-late-july.html
CC-MAIN-2014-15
refinedweb
274
51.72
Q about instanceof Kathy Cai Greenhorn Joined: Jan 13, 2004 Posts: 13 posted Feb 25, 2004 11:52:00 0 The following code is from Sierra&Bates book. It would not compile. The error message says �inconvertible types.� I donot know why one can not check whether t is an object of type String . Sorry I do not understand such fundamental stuff. import java.awt.*; class Ticker extends Component { public static void main (String [] args) { Ticker t = new Ticker(); boolean test = (t instanceof String); } } Edited by Corey McGlone: Added CODE tags [ February 25, 2004: Message edited by: Corey McGlone ] Corey McGlone Ranch Hand Joined: Dec 20, 2001 Posts: 3271 posted Feb 25, 2004 12:50:00 0 The whole point of the instanceof operator is to determine the "runtime type" of an object. This becomes an issue because, with inheritance, you can use a child object anywhere a parent is expected. Therefore, the following is legal: class Animal {} public class Cat extends Animal { public static void main(String[] args) { Animal a = new Cat(); } } You see, we are assigning an Animal reference to a Cat object. This is perfectly legal because a Cat "is a" Animal. However, a can not reference just any old class. For example, you can't reference a String object because a String "is not a" Animal. The following would give you a compiler error: Animal a = new String("This won't work."); You're getting an error message because you're testing to see if an object is of a type that it can't possibly be. There is no way that the object referenced by t could be a String object because String does not extend Ticker. In short, String "is not a" ticker. That's why you're getting the error message. I hope that helps, Corey P.S. I realize you're new to the forums, Kathy, but I would appreciate if you would insert "CODE" tags around your code when you post some. It helps retain the formatting which makes it much easier to read. You can check out this page for details about how to use UBB tags in your posts and there is also a series of buttons beneath "Instant UBB Code" that will help you insert proper tags. If you can put those tags in there to begin with, you not only reduce my workload (I won't have to edit your posts), but you'll also make it easier for other people to understand and respond to your posts. Thanks. [ February 25, 2004: Message edited by: Corey McGlone ] SCJP Tipline, etc. Kathy Cai Greenhorn Joined: Jan 13, 2004 Posts: 13 posted Feb 25, 2004 15:24:00 0 Corey, Thanks. I will start to use CODE" tags. Thank you for answering my question. But this time I did not get the point well.. Kathy Sindhur Sat Greenhorn Joined: Feb 23, 2004 Posts: 23 posted Feb 25, 2004 22:33:00 0 You need to know before hand that the operands used in the instanceof operator belong to the same class/class hierarchy/implement same interface somewhere up in the hierarchy but you want to test which class. Maybe this example clears the idea for you: class Vehicle{ } class FourWheeler extends Vehicle{ } class TwoWheeler extends Vehicle{ } class Suv extends FourWheeler{ } class SportsCar extends FourWheeler{ } class Mpv extends FourWheeler{ } public class CarShopping{ public static void main(String[] args){ Vehicle Corvette = new SportsCar(); Vehicle Hummer = new Suv(); if(Hummer instanceof FourWheeler) if(Hummer instanceof SportsCar) System.out.println("Hummer is a sports car. I dont want a sports car");//BTW I love corvetts else if(Hummer instanceof Suv) System.out.println("Hummer is a SUV. I love SUVs let me buy this"); //I wish!! } } Please ignore those comments I have been reading the book by Kaythy and Bert a lot these days and I am tired of driving my Mazda Protege. I hope that helps Sindhur. Corey McGlone Ranch Hand Joined: Dec 20, 2001 Posts: 3271 posted Feb 26, 2004 08:54:00 0 Originally posted by Kathy Cai:. If you look at the JLS, §15.20.2 Type Comparison Operator instanceof , you see the following text: "If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true." You see, you should NEVER have to test to see if an object referenced by a String object is really an Animal - you already know that it can't be. What would be the point of such a test? You might as well write "if (false)". Where this operator can come in very handy is in the case of overriding methods. Take, for example, the equals(Object) method defined in java.lang.Object . Let's look at an example: public class Animal { public int id; public boolean equals(Object o) // Overridden from Object { if ( o instanceof Animal ) { return id == ((Animal)o).id; } else { return false; } } } In this case, we've defined a class named Animal which has a member named "id." If any two animals have the same id, we consider them equal. In order to get them to compare that way, we need to override the equals method defined in java.lang.Object . However, that method takes an arbitrary Object as a parameter. Therefore, it would be quite possible to pass a String object to this method. In order to do the comparison, however, we need to get the value of the id member of the passed object. Object, however, doesn't define a member named id so we must first cast the object (o) as an Animal. However, before we do that cast (and risk a ClassCastException ), we should check to make sure that the object referenced by o really IS an Animal. Therefore, we first use the instanceof operator to ensure that our upcoming cast won't produce an exception. I hope that helps clear up the issue for you. If you're still confused or have other questions, please let me know. Corey Rashi Gulati Ranch Hand Joined: Jan 08, 2004 Posts: 44 posted Mar 01, 2004 22:20:00 0 Hi I came across this question Which of the following statements are true? 1) The instanceof operator can be used to determine if a reference is an instance of a class, but not an interface. 2) The instanceof operator can be used to determine if a reference is an instance of a particular primitive wrapper class 3) The instanceof operator will only determine if a reference is an instance of a class immediately above in the hierarchy but no further up the inheritance chain 4) The instanceof operator can be used to determine if one reference is of the same class as another reference thus According to me no option is correct, but to my surprise the answer is 2. Please Help Regards Rashi Corey McGlone Ranch Hand Joined: Dec 20, 2001 Posts: 3271 posted Mar 02, 2004 10:15:00 0 Why wouldn't number 2 be correct? This is an example of what #2 is saying: public void compare(Object o) { if ( o instanceof Integer ) { // o is a reference to a primitive wrapper } } That's really what that question is asking about. Is there something else that is confusing you about this? Sekhar Kadiyala Ranch Hand Joined: Feb 17, 2004 Posts: 170 posted Mar 02, 2004 16:00:00 0 For your program to compile you should change it to CODE import java.awt.*; class Ticker extends Component { public static void main (String [] args) { Ticker t = new Ticker(); boolean test = ((Object)t instanceof String); } } CODE As explained in the earlier posts, Compiler is smart enough to see the relation between the LHS and RHS operands. If it sees no relation can be established even during the run time, it won't let you get away with that and screw up your own code These are some of the great qualities of Java. PMP CSQA SCJP SCWCD SCBCD INS 21 INS 23 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. subject: Q about instanceof Similar Threads instanceof Problem instanceof question Short circuit operators Question from Ch 3 Self Test, Sierra/Bates Book instanceof example not compiling All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/244797/java-programmer-SCJP/certification/instanceof
CC-MAIN-2013-48
refinedweb
1,414
67.79
(Assignment) Linux word wonderful Q & A Contact: linuxmine@gmail.com Editor's note: Given the current development status of Linux in China, 90% of the questions can be answered in one sentence, this is the original intention of this article. Welcome to add your own "words", the original state after your provider. More detailed documentation, Please visit or Amendment Description: This FAQ is in the original "linux word wonderful Q & A" based on the 4/28/2006 version of the actual situation for this edition made small changes to make it more suitable for site users. Members of the Department if any errors were found, please inform, so that timely corrections; Also, if there is anything to add new content, also welcomed the letter informed. Thank you! (By JJCH) ---------- --------- Internet related articles 0001 changes the host name (bjchenxu) vi / etc / sysconfig / network, modify the HOSTNAME an act "HOSTNAME = host name" (without this line? then add this line right), then run the command "hostname host name." General also modify / etc / hosts file in the host name. In this way, whether you reboot, the host name is changed successfully. 0002 characters start systems to interface (do not start xwindow) (bjchenxu) vi / etc / inittab id: x: initdefault: x = 3: text mode; x = 5: graphically. 0003 Linux automatic updates problem Upgrade the system under Fedora: yum update packagename # upgrade package yum upgrade # upgrade the system all the prerequisite packages: configured the network and / etc / yum.conf and / etc / yum.repos.d / within the file, Reference edition essence - are each distribution area -Redhat/Fedora/CentOS- configuration management. Upgrade the software under Debian: apt-get update packagename apt-get upgrade Prerequisite: configured the network and / etc / apt / sources.list, refer to http:// home. 0004 windows partition under Linux to see the software (bjchenxu) Paragon.Ext2FS.Anywhere.3.0.rar and explore2fs-1.00-pre4.zip Schools Download: 0005 mount usage mount [-t file system format] [-o parameter] device name mount point -T common parameters vfat FAT32 ntfs NTFS iso9660 CD / ISO file -O common parameters between the use of multiple parameters "," separated. iocharset = utf8, or set the character encoding gb2312 umask = 0 allows ordinary users to access loop mounted iso file using the common device name / dev / hdaN, hdcN, period number N values of their look, the first primary partition as a second primary partition of 2, The first extended partition of 5, second 6, and so on. Mount point to any existing directory name, such as / mnt / cdrom. LINUX 0006 in vmware's local hard drive using FAT partitions (bjchenxu) FAT partition will be the local share, and then hung in VMWARE using SMBFS. You can put the following line / etc / fsta b,: / / Win_ip / D $ / mnt / d smbfs defaults, auto, username = win_name, password = win_pass, co depage = 936, iocharest = gb2312 0 0 One win_ip is the IP address of your windows; D $ is the inside of your windows shared D drive share name; / Mnt / d is to mount the partition to the linux directory; win_name and win_pass is your WINDOWS partition which can be read by the user, such as your administrator name and password. If you run the / etc / rc.d / init.d / netfs, when it will start automatically mount the partition. 0007.a delete the file named-a (bjchenxu) rm. /-a rm --a tell rm This is the last option, see getopt ls-i lists inum, and then find.-inum inum_of_thisfile-exec rm '()'; 0007.b delete a file named (bjchenxu) rm \ a 0007.c delete the name with the / and''document (bjchenxu) The character is a normal file system does not allow the characters, but may be generated in the file name, such as under unix NFS file system used in Mac systems 1. The solution, the NFS file system is not linked to the filter '/' character in the systems with a special file name to delete the file. 2. File name can also be wrong to remove the directory of other files, ls-id display the directory containing the file inum, umount the file system, clri clear the directory inum, fsck, mount, check your lost + found, rename the file in it. Preferably through WINDOWS FTP in the past you can delete any file name in the files! 0007.d remove invisible character with the name of the file (bjchenxu) Lists the file names and dump to a file: ls-l> del Then edit the contents of the file by adding rm command to delete the file content into the format: vi del [Rm-r ******* ] The file with execute permissions chmod + x del Implementation of the $. / Del 0007.e delete the file size to zero in the file (bjchenxu) rm-i `find. /-size 0` find. /-size 0-exec rm (); Or find. /-size 0 | xargs rm-f & Or for file in * # own custom file types to delete do if [!-s $ (file)] then rm $ (file) echo "rm $ file Success!" fi done 0008 redhat9 set wheel mouse (mc1011) Into the X, select the configuration of the mouse, select the wheel mouse (ps / 2) on it, If the mouse abnormalities, you can restart the computer. 0009 to install X window After installing the base system Debian: apt-get install x-window-system-core Redhat / Fedora installation CD: Select the upgrade installation, you can then select the appropriate package. 0010 Remove Linux partitions (bjchenxu) Under the Windows "disk management" in deleting it, or with other partitioning tool. 0011 How to Quit man (bjchenxu) Press q button 0012 does not compile the kernel, mount ntfs partitions present on the support of many distributions default ntfs partition can use to mount directly under the top mount. For Redhat / Fedora by default does not support ntfs, it may proceed as follows, 1. Uname-r, be the kernel version number; 2. Login search for "kernel-ntfs", download the corresponding kernel rpm; 2. Rpm-ivh download rpm package; 3. Mkdir / mnt / WinC 4. Mount-t ntfs / dev/hda1 / mnt / WinC 0013 tar sub-volume compression and consolidation (WongMokin, Waker) 500M per Case Volume tar sub-volume compression: tar cvzpf - somedir | split-d-b 500m multi-volume tar merger: cat x *> mytarfile.tar.gz 0014 when using grub retrieve forgotten the root password to be added 0015 to ctrl + alt + del Failure (bjchenxu) vi / etc / inittab The ca:: ctrlaltdel: / sbin / shutdown-t3-r now comment out this line, on it 0016 how to view the release name (hutuworm) cat / proc / version or cat / etc / issue 0017 rpm file in which (the Warriors) On the search, or rpm-qf file names are 0018 man's information saved as a text file (bjchenxu) To ls as an example: man ls> tcsh.txt 0019 using the existing two files, generate a new file (bjchenxu) 1. Remove the two documents and the set (keep a copy of the duplicate rows only) 2. Remove the intersection of the two files (leaving only exist in the two files in the file) 3. Remove the intersection, leaving the other line 1. Cat file1 file2 | sort | uniq 2. Cat file1 file2 | sort | uniq-d 3. Cat file1 file2 | sort | uniq-u 0020 set the com1 port, to com1 port via HyperTerminal log (bjchenxu) Recognizing the / sbin / agetty, edit / etc / inittab, add 7:2345: respawn: / sbin / agetty / dev/ttyS0 9600 9600bps is because the default router, usually in conjunction this rate can be set to 19200,38400,57600,115200 Modify / etc / securetty, add a line: ttyS0, to ensure the root user can log on reboot, you can unplug the mouse, keyboard display (starts to look better output) of the 0021 to delete all the files directory, including subdirectories (bjchenxu) $ Rm-rf directory name 0022 View System Information (bjchenxu) cat / proc / cpuinfo - CPU (ie vendor, Mhz, flags like mmx) cat / proc / interrupts - interrupt cat / proc / ioports - Device IO Port cat / proc / meminfo - memory information (ie mem used, free, swap size) cat / proc / partitions - all partitions of all equipment cat / proc / pci - PCI device information cat / proc / swaps - all the information Swap partition cat / proc / version - Linux version number of the equivalent of uname-r uname-a - look at the system kernel and other information 0023 removed redundant text file carriage return (bjchenxu) sed 's / ^ M / /' test.sh> back.sh, note that ^ M is knocking ctrl + v ctrl + m received or dos2unix filename 0024 X Desktop Switch (lnx3000) Prerequisite: Install a number of desktop systems, such as KDE & & GNOME Graphical login if you are logged on linux, then click on the login session (tasks) that can select gnome and kde. If you are a text log, then the implementation of switchdesk gnome or switchdesk kde, then you can enter startx gnome or kde. (Or vi ~ /. Xinitrc, add or modify into exec gnome-session or exec startkde, then sta rtx start X) 0025 generic sound card driver (lnx3000) ALSA OSS 0026 to change the Redhat / Fedora system language / character set changes / etc/sysconfig/i18n documents, such as LANG = "en_US", shows the English interface LANG = "zh_CN.UTF-8", shows Chinese language interface. Or LANG = "zh_CN.GB2312" UTF-8 recommended Another way: cp / etc/sysconfig/i18n $ HOME/.i18n Modify $ HOME/.i18n documents, such as LANG = "en_US", shows the English interface LANG = "zh_CN.UTF-8", shows Chinese language interface. This will only change the interface language of individuals, without affecting other users 0027 screen is set to 90 (bjchenxu) stty cols 90 0028 using the md5sum file (bjchenxu) md5sum isofile> hashfile, the md5sum files and hashfile contents of the file to verify the validity hash value Are the same md5sum-c hashfile An extract multiple zip files 0029 (bjchenxu) unzip "*", note the quotation marks can not be less 0030 View pdf file (bjchenxu) Recommended to use Acrobat reader for linux Schools Download: 0031 Find the file permission bits for the S (bjchenxu) find.-type f (-perm -04000-o-perm -02000)-exec ls-lg (); 0032 to support the Chinese character mode to Download zhcon-0.2.1.tar.gz $ Tar xvfz zhcon-0.2.1.tar.gz $ Cd zhcon-0.2.1 $. / Configure $ Make & & make install To use, run zhcon, would like to quit, run exit. 0033 Pop CD back to (beike) # Eject-t 0034 cd iso disc made of paper (MH) cp / dev / cdrom xxxx.iso 0035 Quick view boot hardware detection (mentally handicapped) dmesg | more 0036 view hard disk usage (bjchenxu) df-k to K as the unit shown df-h shows a more human unit, can be b, k, m, g, t.. 0037 view directory size (bjchenxu) du-sh dirname -S Display only a total of -H to K, M, G unit, to improve the readability of information. KB, MB, GB is 1024 for the conversion unit,-H 100 0 for the conversion unit. 0038 Find a file or delete the process being used (wwwzc) fuser filename fuser-k filename 0039 installation package to install rpm package: rpm-ivh aaa.rpm Install deb package: dpkg-i aaa.deb Install Source Package: tar xvfz aaa.tar.gz; cd aaa;. / Configure; make; make install (the premise: the compiler is installed and the necessary library files) 0040 character mode, set / delete environment variables (bjchenxu) established under bash: export the variable name = variable value to delete: unset variable names established under csh: setenv variable value of variable name to delete: unsetenv variable name 0041 ls how to see hidden files (ie. At the beginning of the file) (double fold of the pig) ls-a 0042 rpm file to install gone (bjchenxu) rpm-qpl name.rpm 0043 using src.rpm (bjchenxu) rpmbuild-rebuild name.src.rpm 0044 vim does not appear in the display colors or color (bjchenxu) First make sure to install the vim-enhanced package, and then, vi ~ /. Vimrc; If there are syntax on, the display color, syntax off, not display color. In addition, on the vi's syntax color, another point is the terminal type (the environment variable TERM) settings. For example usually set to xterm or xterm-color to use syntax color. Especially from the Linux remote login to Unix on the other 0045 linux real-time or time-sharing operating system (bjchenxu) Time-sharing 0046 make bzImage-j of the j is the mean (wind521) -J is mainly useful when your hardware resources, when larger, more affluent, you can use this to accelerate the speed of compilation, such as the-j 3 0047 Source package how many distributions do not now no longer self-generation of source code, please download and install on their own. 0048 to modify the system time (bjchenxu, laixi781211, hutuworm) date-s "2003-04-14 cst", cst refers to the time zone and time settings with date-s 18:10 The revised implementation of the clock-w wrote CMOS hwclock-systohc set the hardware clock to the current system time 0049 to mount on the boot partition under windows (bjchenxu) D-plate windows automatically linked to / mnt / d, and with vi to open / etc / fstab, add the following line / Dev/hda5 / mnt / WinD ntfs umask = 0, iocharset = utf8 0 0 Notice served by hand a / mnt / WinD directory & & system support ntfs. 0050 linux how to use so much memory (bjchenxu) In order to improve system performance and do not waste memory, linux and more memory to do cache, to improve the io speed 0051 / etc / fstab configuration items inside the final the last two numbers mean (lnx3000) The first is called fs_freq, used to determine which file systems need to perform dump operations, 0 is not required; The second is called fs_passno, a system reboot disk fsck program detects the sequence number 1 is the root file system, 2 is the other file system. fsck disk detected by serial number, 0 means that the file system is not being detected dump the implementation of ext2 file system backup operation detect and repair the file system fsck 0052 linux in the user's password must have a certain length, and in line with complexity (eapass) vi / etc / login.defs, change PASS_MIN_LEN 0053 linux in the translation software (bjchenxu, hutuworm) StarDict xdict dict the next console there is a tool, through the DICT protocol to dict.org UP 11 dictionaries, for example: dict RTFM 0054 not to display sleep (bjchenxu) setterm-blank 0 setterm-blank n (n for the waiting time) 0055 inquiry yesterday's date with dat (gadfly) date-date = 'yesterday' 0056 xwindow how to screenshot (bjchenxu) Ksnapshot or gnome-screenshot 0057 extract souvenir (bjchenx tar-jvxf some.bz unzip example.zip rar / unrar the general need to download and install additional tools for their Alien provided. tgz,. rpm,. slp and. deb compression format such as converting between: sEx provides almost all the visible compression format decompression interface: 0057-2 tar compression, decompression instance (platinum) Extract: x Compression: c For gz: z For bz2: j For display: v Extract examples gz file: tar xzvf xxx.tar.gz bz2 files: tar xjvf xxx.tar.bz2 Compression examples gz file: tar czvf xxx.tar.gz / path bz2 files: tar cjvf xxx.tar.bz2 / path 0058 in a multi-level directory to find a way files (Qinghai Lake) find / dir-name filename.ext du-a | grep filename.ext locate filename.ext 0059 not to ordinary users change their password (myxfc) [Root @ xin_fc etc] # chmod 511 / usr / bin / passwd They want normal user to change password [Root @ xin_fc etc] # chmod 4511 / usr / bin / passwd 0060 graphics card configuration (win_bigboy) To be determined 0061 0062 utf8 encoding on how to make bmp player and play list display Chinese correctly BMP Preferences - Plugins - Media-MPEG Audio plug-in - Preferences - heading select "Disable ID3V2 tags" and "non-UTF-8 ID3 converted into UTF-8" "usually cover title" Fill in the text box ID3 encoding GB2312 0063 Redhat9 play mp3 files in the native x mms can not play MP3, mp3 plug-in to install a package x mms-mp3-1.2.7-13.p.i386.rpm. 0064 add Chinese characters under the current Linux free Chinese fonts are good uming, ukai, fireflysung, Wen Quan Yi afraid of copyright issues involved can copy Windows under simsun.ttc, tahoma.ttf, tahomabd.ttf On the beautification of the various distribution methods are not the same situation, can refer to Linuxsir.org and other related forums. 0065 0066 using Wubi and Pinyin, location, etc. Chinese input method from the download fcitx installation, refer to the above specific method of documentation. 0067 in Linux how to extract the rar file to download and install rar for Linux, unrar xxx.rar 0068 how to add / remove rpm package yum is recommended to manage your system, automatically resolve package dependencies. 0069 characters under control volume (grub007 outer Lonely) Using aumix. In addition, the volume level to save oss, the steps are: 1, Adjust the volume with aumix volume for your satisfaction 2, with the root user to / usr / lib / oss under (oss the default installation directory) 3, execution. / Savemixer. / Mixer.map 4, ok, after oss open after the first step is to adjust your volume up. ps: read the README of the directory can be more useful information. 0070 using dd to do iso (grub007) dd if = / dev / cdrom of = / tmp / somename.iso 0071 removed a few days before everything (including the directory name and the directory file) (shally5) find.-ctime +3-exec rm-rf (); Or find. /-mtime +3-print | xargs rm-f-r 0072 where the user's crontab (hutuworm) / Var / spool / cron / user-name under the name of the file 0073 to run a program as different user (bjchenxu) su - username-c "/ path / to / command" Sometimes need to run the special status of the program, you can do to su 0074 How to empty a file (bjchenxu) echo> filename 0075 0076 How to back up Linux systems reference tar or use better business software. 0077 linux partition tools under the command mode of the tool: fdisk gnome graphical interface tool under: gparted kde GUI partitioning tool under: qparted 0078 / proc / sys / sem representatives of each mean? (Sakulagi) / Proc / sys / sem as follows 2503200032128 These 4 parameters were SE MMSL (each user has the maximum number of semaphore), SEMMNS (system maximum number of semaphore), SEMOPM (operations per semop system call number), SEMMNI (system maximum number of semaphore sets) 0079 Grub boot menu bigmem smp up all mean? (Lnx3000) smp: (symmetric multiple processor) symmetric multi-processor mode bigmem: support more than 1G of memory optimized kernel up: (Uni processor) single-processor mode 0080 Oracle of the installation process why the garbled? (Lnx3000) The installation process is now Oracle's support of the Chinese problem, use only English interface to install, Before the implementation of runinstaller, run: $ Export LANG = C $ Export LC_ALL = C 0081 linux file and directory under the color mean anything (sakulagi, mentally handicapped) Blue said the catalog; green for executable files; red compressed file; light blue indicates a link file; Gray said that other documents; red flashing that there is a problem linked documents; Yellow is the device file, including the block, char, fifo. With dircolors-p to see the default color settings, including a variety of colors and the "bold", underline, blinking and other definitions. 0082 to see how many activities httpd script (bjchenxu) Write the following script, chmod + x test_ http.sh with executable permissions, then run the terminal can #! / Bin / sh while (true) do pstree | grep "* [httpd] $" | sed 's /.*-([ 0-9] [0-9 ]*)*[ httpd] $ / 1 /' sleep 3 done 0083 How do I add a hard drive (nice) First, shut down, if the physical connection is IDE hard disk drive, pay attention to the Lord, from the disk set; if SCSI hard drive, pay attention to choose not to use the ID of a No.. Second, boot to check the hard disk has not been detected in linux dmesg | grep hd * (ide hard drive) dmesg | grep sd * (SCSI drives) Or less / var / log / dmesg If you do not detect your new hard drive, reboot, check the connections to see if there is bios did not recognize it to. 3, area you can use fdisk, Sfdisk or parted (GNU partitioning tool, linux under the partition magic) 4, format mkfs 5, modify fstab vi / etc / fstab 0084 linux partition under the label to see how ah (q1208c) e2label / dev / hdxn, where x = a, b, c, d ....; n = 1,2,3 ... 0085 Redhat9 after installation to add new language pack on the third disc are similar looking package ttfonts-zh_CN-2.12-1.noarch.rpm (Simplified Chinese) ttfonts-zh_TW-2.11-19.noarch.rpm (Traditional Chinese) Other similar 0086 terminal screenshots (tsgx) cat / dev / vcsN> screenshot of them, N said that the first N-terminal also can run script screen.log, record on-screen information to screen.log years. For a record to your exit end. This is also a good way of screenshots. This is the cookbook debian seen. Can be used in RH9 on. Not in the other systems tested. 0087 for a program to continue running after logout (NetDC, double eyelids pig) # Nohup program name & Or use the disown command can also be 0088 man command is not in the path, how to view the non-standard man files (bjchenxu) nroff-man / usr/man/man1/cscope.1 | more 0089 0090 edit / etc / inittab after the direct effect (bjchenxu) # Init q 0091 for linux consecutive orders, the wrong stop (bjchenxu) command1 & & command2 & & command3 0092 how to install grub to the mbr (bjchenxu, NetDC) Interactive mode in grub grub> root (hd0, 0) grub> setup (hd0) You can also use the repair mode # Grub-install / dev / hda To install grub. 0093 installation to write linux grub boot partition or the master boot sector (MBR) (bjchenxu) If you want to boot directly into a computer operating system writes MBR grub boot menu put, if the write linux boot partition is to use boot disk boot. Proposed write MBR, convenient point, As write MBR unsafe, how to explain that? Every once installed Windows, MBR will be revised once, we think there is unsafe it? 0094 how to boot multiple systems to be added, look at the Digest -> "Installing update" -> "boot" 0095 how the graphical interface and console (character interface) switch back and forth between (bjchenxu) a. graphical interface to the console: Ctr + Alt + Fn (n = 1,2,3,4,5,6). b. The switch between the console: Alt + Fn (n = 1,2,3,4,5,6). c. the console to the graphical interface: Alt + F7 0096 Linux commands see the essence of common areas 0098 reinstall windows cause linux does not direct reference to the essence of a solution area - Frequently Asked Questions 0099 Why is installed after the win2K LINUX slow (lnx3000, nice) Old problems, you can see in 2000 is not Linux's logical drive, but can not access? In Disk Management, the select the disk, right-click -> change the "drive name and path" -> "delete" on it, pay attention to not delete this site! 0100 1101 linux burn iso in the method (hutuworm) Method 1: Use xcdroast, select CD-ROM produced, select the ISO file, burn! See # 17 Method 2: Find the recorder command: cdrecord-scanbus Output: 0,0,0 0) 'ATAPI' 'CD-R/RW 8X4X32' '5. EZ 'Removable CD-ROM Burn the command: cdrecord-v speed = 8 dev = 0,0,0 hutuworm.iso Method 3: Use k3b can burn CD / DVD k3b Home: (K3b is a graphical interface, in fact, burn CD using the cdrecord, burn a DVD using a dvd + rw-tools http: / / Fy.chalmers.se / ~ appro / linux / DVD + RW /) 1102 how to do when the screen change to spend (double fold of the pig) When you are not careless cat, a text document, then the screen will become flowers, you can double-click "Enter" key, then hit "clear", then the screen will return to normal of the .... 1103 how to uninstall the rpm package that specific package name (diablocom) We all know the command to delete the package is rpm-e XXX, but when we do not know the exact spelling XXX when Can use rpm-q-a check of all installed packages or use the rpm-qa | grep xxxx check out the name. 1104 under linux using the memory to / tmp folder (yulc) In / etc / fstab to add a line: none / tmp tmpfs default 0 0 Or in / etc / rc.local add mount tmpfs / tmp-t tmpfs-o size = 128m Note: size = 128m that / tmp can be used most 128m Either way, as long as linux reboot, / tmp files all disappear under the List only directories using ls 1105 (yulc) ls-lF | grep ^ d ls-lF | grep / $ ls-F | grep / $ 1106 in the command line following the IP address of the machine, not get card information (yulc) ifconfig | grep "inet" | cut-c 0-36 | sed-e 's / [a-zA-Z:] / / g' hostname-i 1107 modified / etc / profile or $ HOME / .profile file to take effect immediately (peter333) # Source / etc / profile (or source. Profile) 1108 bg and fg the use of (bjchenxu) Enter ctrl + z, the current task is suspended and the suspension, and return the process number on the screen, this time with "bg% process number" put back the implementation of this process will, but with "fg% process ID" on allow this process to run into the foreground. In addition, job order to view the current process by bg 1109 ctrl + s and ctrl + q (bjchenxu) ctrl-s to suspend sending data to the terminal, the screen just as dead, able to use ctrl-q to resume 1110 catalog statistics script (bjchenxu) Save as total.sh, then total.sh absolute path, the directory path can be the size of statistical code: #! / Bin / sh du $ 1-max-depth = 1 | sort-n | awk '(printf "% 7.2fM ->% sn", $ 1 / 1024, $ 2)' | s ed 's :/.*/([^/]{ 1 ,})$: 1: g' 1111 grep process itself does not appear (bjchenxu) # Ps-aux | grep httpd | grep-v grep grep-v grep show you can cancel the implementation of the grep itself, this process,-v parameter is not displayed process name listed 1112 to delete the directory containing the file keywords (WongMokin) find / mnt / ebook /-type f-exec grep "enter keyword" ();-print-exec rm (); 1113 does not allow cron tasks in feedback information, check for 5 minutes in this case the message (WongMokin) 0-59/5 * * * * / usr / local / bin / fetchmail> / dev / null 2> & 1 1114 rpm in the current directory, extract the file (bjchenxu) cat kernel-ntfs-2.4.20-8.i686.rpm | rpm2cpio | pax-r 1115 merger of the two Postscript or to remove the manual directory apache all. En suffix name (bjchenxu) Access to the manual directory code: find. /-Regex .*. en | awk-F. '(Printf "mv% s.% s.% s.% s% s.% s.% sn", $ 1, $ 2, $ 3, $ 4, $ 1, $ 2, $ 3) '| sh Since 1117 to more than X (noclouds) startx by default display: 0.0 as the first X, by passing parameters to the Xserver can play a number of X: # Startx -: 1.0 # Startx -: 2.0 ... Then Ctrl-Alt-F7/F8 ... switch. 1118 for a program to continue running after logout (noclouds, bjchenxu) # Nohup command & 1119 to see Linux boot screen display information (bjchenxu) After the start command dmesg View 1120 so that vi does not ring (sakulagi) echo "set vb t_vb =">> ~ /. vimrc 1121 to fedora boot automatically login (dzho002) 1) rpm-ihv autologin-1.0.0-7mdk.i586 rpm 2) the establishment of file / etc / sysconfig / autologin Add a line in it. USER = username 1122 Redhat / Fedora configuration to what service to start (the outer Lonely, q1208c) Method 1 Run ntsysv or setup command, enter the menu for configuration 2 chkconfig-list display services chkconfig name on / off on / off "name" service 1123 Safely Remove linux (outer Lonely) Step 1 Dos to use fdisk / mbr or boot into the CD-ROM with win2000/xp Recovery Console, use the command fixmbr Step 2 format the linux partition to windows partition can be. 1124 with the grub boot into the text interface (outer Lonely) Into the grub, press a, enter a space 3 can be guided into the text interface, but does not modify the operation of the system level, only when the sub-effective. 1125 to test whether the patch to run properly, they will not be changes to the kernel (jiadingjun) patch-dry-run 1126 redhat and debian install to delete files on the usage (NetDC) Remove a package: rpm-e dpkg-r Display the contents of a package: rpm-qvl dpkg-c Show all installed packages: rpm-qvia dpkg-l Print a package of information: rpm-qpi dpkg-I Test package characteristics: rpm-Va debsums-a Test which package a file belongs to: rpm-qf dpkg-S Install new packages: rpm-Uvh dpkg-i 1127 how to make a new user for the first time after landing force change password (Cat) # Useradd-p "testuser; chage-d 0 testuser 1128 log maintenance tools logrotate (hotbox) In / etc / logrotate.conf configured, role: to define log file size or time scheduled, automatic compression log file 1129 Linux What is the default administrator (bjchenxu) root 1130 how to generate a fixed length (such as file length 1M) byte empty file, that is, the value of each byte are all 0 × 00 (sakulagi) dd if = / dev / zero of = / tmp / zero_file bs = 1024 count = 1024 1131 RedHat Linux in modified step (hutuworm) 1. Set your time zone: timeconfig Select Asia / Shanghai (GMT +8 China, if you are in the area) 2. With the standard time server calibration: ntpdate time.nist.gov Of course, if you are Li Ka-shing, you can watch with your own calibration: date-s STRING (STRING format see man date) 3. Write back to the hardware clock: hwclock-systohc 1132 Find the file and change the current directory extension (2002 summer) Change all. Ss file. Aa # Find. /-Name "*. ss"-exec rename. Ss. Aa '()'; 1133 patch use (※ Genius Sakuragi) Syntax is the patch [options] [originalfile] [patchfile] For example: patch-p [num] -P parameter determines whether to use read the source file name prefix directory information, does not provide-p parameters, then ignore all directory information,-p0 (or-p 0) that the use of all the path information,-p1 will ignore the first "/" before the directory, and so on. Such as / usr / src / Linux-2.4.16/Makefile such a file name, in the provision of-p3 parameters will be used linux-2.4.16/Makefil e as a patch file to be. For the earlier example of a Linux kernel source 2.4.16 update example, assume that source directory located at / usr / src / linux, then in the current directory is / usr / src use "patch-p0 1134 to file.txt in the 123 to 456 (hutuworm) Method 1 sed 's/123/456/g' file.txt> file.txt.new mv-f file.txt.new file.txt Method 2 vi file.txt Enter the command: :% S/123/456/g 1135 will be a partition formatted as ext3 journaling file system (hutuworm) mkfs-j / dev / hdaN 1136 Open Hard ATA66 (laixi781211) / Sbin / hdparm-d1-X68-c3-m16 / dev / hda 1137 view the current run-level (double fold of pig) runlevel 1138 view the current log status (double fold of pig) (1) who am i (2) whoami (3) id Note (1) with (2) the small difference between 1139 can not remove rpm-e to delete the package (wwwzc) 1, remove the package if you remove the package directory before rpm-e-noscripts 2, if the system in a package is installed twice (because of some anomalies caused by) rpm-e multi-installed-pkgs-allmatches 1140 how to customize the information displayed when users log on (jiadingjun) In the / etc directory delegated a text file named motd achieved, for example, create your own / etc / motd: $ Cat / etc / motd welcome to my server! Then, when the user logs on the system when this message appears: Last login: Thu Mar 23 15:45:43 from *.*.*.* welcome to my server! 1141 Root empty the Recycle Bin command file (dtedu) cd / var / .Trash-root rm-rf * 1142 in the Red Hat add Simsun.ttc font (bjchenxu) To Red Hat 9, for example, select the installation to install simplified Chinese, the first copy of a simsun.ttc to / usr / share / fon t / TrueType, renamed simsun.ttf; and then go to / usr / share / font / TrueType directory, run the tt mkfdir> fonts.dir command; then fonts.dir file with vi editor, to have simsun.ttf lines read as follows: simsun.ttf-misc-SimSun-medium-r-normal-0-0-0-0-c-0-ascii-0 simsun.ttf-misc-SimSun-medium-r-normal-0-0-0-0-c-0-iso10646-1 simsun.ttf-misc-SimSun-medium-r-normal-0-0-0-0-p-0-iso8859-15 simsun.ttf-misc-SimSun-medium-r-normal-0-0-0-0-p-0-iso8859-1 simsun.ttf-misc-SimSun-medium-r-normal-0-0-0-0-c-0-gb2312.1980-0 simsun.ttf-misc-SimSun-medium-r-normal-0-0-0-0-p-0-gb2312.1980-0 simsun.ttf-misc-SimSun-medium-r-normal-0-0-0-0-m-0-gb2312.1980-0 simsun.ttf-misc-SimSun-medium-r-normal-0-0-0-0-p-0-gbk-0 Then run $ Cat fonts.dir> fonts.scale 1143 Unicon and Zhcon differences and the role of (bjchenxu) Unicon is the core state of Chinese platform, based on the modified Linux FrameBuffer and Virtual Console (fbcon) Achieved. As the underlying implementation in the system, therefore, excellent compatibility, you can directly support the gpm mouse. However, relatively dangerous, a little flaw might endanger system security. Zhcon Chinese platform is the user state, a bit like UCDOS. How to uninstall 1144 to install tar format software (bjchenxu) Access to install the software source code directory, run make uninstall. If not, you can also look Makef ile documents, mainly the install part, find the tar format from which files are copied to any path, then go to the appropriate directory to delete. 1145 custom linux prompt (bjchenxu) In the bash prompt is in an environment variable $ PS1 through specified. With export $ PS1 view the current value of intuitive common prompt can be set to export PS1 = "[u @ h W] $". One representative of the user name u, h on behalf of the host name, W on behalf of the last layer of the current working directory, if an ordinary user $ gives the $, root user #. 1146 in the vi search for a word, the word to highlight it looks very uncomfortable, how can it get rid of (b jchenxu) In vi command mode, enter: nohlsearch on it. Also in ~ /. Vimrc write the following statement in there will be highlighted: set hlsearch With the following statements would not have highlighted: set nohlsearch 1147 how to find out the system all the *. cpp, *. h files (bjchenxu) With the find command on it. But if from the root directory to find a higher consumption of resources, use the following command to: find /-name "*. cpp"-o-name "*. h" 1148 to install Debian need a few disks enough? All have to download? (Bjchenxu) If you have a good network environment, download the first on it. Without the network environment is not recommended if D ebian, because Debian mainly relies on the network to update the software. 1149 Debian first CD Why are there two versions? debian-30r1-i386-binary-1.iso and debian- 30r1-i386-binary-1_NONUS.iso the download this? They differ? (Bjchenxu) As with "non-US" (not an American) software can not legally set up in the United States stored in the server. Previously, the reason is usually because the software contains a strict password encoding, and today, it is because the program uses the algorithm of U.S. patent protection. Everyone should access to "non-US" to be used for private purposes; but not the identity of the iso Only on the set up in the United States will only be useful mirror and suppliers. Other binary does not contain any of the CD "US-sensitive" (and the U.S. related) software, they and other kinds of binary-1 CD-ROM as the operation very well. Therefore, personal use or download debia n-30r1-i386-binary-1_NONUS.iso version. 1150 Why do I use the umount / mnt / cdrom command device is busy a time of such statements can not be u mount (bjchenxu) When using the umount must ensure that exit / mnt / cdrom this directory, exit the directory, you can use u mount / mnt / cdrom was. 1151 I am using a laptop computer, how can we left in the console shows how much power it now? (Bjchenxu) Use apm-m you can see how many minutes, the specific parameters can be man apm view. 1152 Why I entered the Linux terminal window, man is garbled a command out of it? (Bjchenxu) This is because your character set settings. Temporary solution you can use the export LANG = "en_US". To modify the words not always in / etc/sysconfig/i18n files which modify the LANG = "en_US" on it. Can do for a user, so that individuals can change the interface language, without affecting other users. Command as follows: # cp / Etc/sysconfig/i18n $ HOME/.i18n. Error 1153 when compiling the kernel, indicating "Too many open files", I ask how to deal with (bjchenxu) This is because the default file-max value (8096) is too small. To solve this problem, you can run the following command as root ( Or add them to / etc / rcS.d / * init script under): # Echo "65536"> / proc / sys / Finally enter the unpacked directory, run the install command. # Cd vmware-linux-tools #. / Install.pl 1154 1155 installed a Linux server, and want to compile the kernel, step by step down, GRUB also be added, and However, there is "kernel Panic: VFS: Unable to mount root fs on 0:00" error, how does that matter? (Bjchenxu) Under normal circumstances initrd the file on the desktop is not required, but the server has SCSI devices is necessary. There may have not had time to compile the kernel initrd the file, so there will be above error. Users can use the mkinitrd command to build a initrd.img file, and then joined the GRUB, reboot try. 1156 how to set up user login welcome message? (Bjchenxu) Modify / etc / motd file, fill it to write the text, it will enable users to log in via Telnet correct, the implementation of Shell before the corresponding message. motd is the "messages of the day", that is, the meaning of the day information. Entered, the administrator can write a number of issues requiring attention or notification to remind the official user. 1157 I downloaded the rcs5.7, with. / Configure & & make & & make install when the error is as follows:. / Conf. sh: testing permissions .... / conf.sh: This command should not be run with su peruser permissions. I used the root user login compiled installed, why is it so? (Bjchenx u) Some software were actually taken into account security and other reasons can not compile the root user. Then just compile with other users, to make install this step, if the software is installed on the user does not belong to compile the main directory, you need to use the su command to convert the root user and then implementation of the make install. 1158 I installed USBView failed, as follows: # rpm-ivh usbview-1.0-9.src.rpm wa rning: usbview-1.0-9.src.rpm: V3 DSAsignature: NOKEY, key IDab42a60e (bjchenxu) This line of code to install the failure is because your system is not installed on the appropriate key to verify signatures. To make the package by check, you can import Red Hat's public key to solve the specific way to run the following command in the Shell: # Rpm-import / usr / share / rhn / RPM-GPG-KEY (Case sensitive) 1159 How to prevent a critical file is modified? (Bjchenxu) In Linux, some configuration files is not allowed any person (including root) changes. In order to prevent being accidentally deleted or modified, you can set the file "can not modify the bit (immutable)". Command as follows: # Chattr + i / etc / fstab If you need to modify the file then use the following command: # Chattr-i / etc / fstab 1160 How to limit a user can start the process a few? (Bjchenxu) Ascertain what / etc / pam.d / login file, the existence of the following line: session required / lib / security / pam_limits.so Then edit / etc / security / limits.conf, in which the process can be set to limit the number of users, CPU utilization and memory utilization, such as hard nproc 20 refers to the limit of 20 processes, specifically to see man. 1161 How to limit the size of Shell command history? (Bjchenxu) By default, bash in the file $ HOME / .bash_history in the record store up to 500 commands. Sometimes, depending on the systems, the default number of records different. System, each user's home directory has a such a document. For system security, I strongly recommend that users limit the size of the file. Users can edit / etc / profile file, Modify one of the options below: HISTFILESIZE = 30 or HISTSIZE = 30 This will be recorded in order to reduce the number of Article 30. 1162 I want to show startup information retained in order to check the computer out the problem areas, how do I ask? (B jchenxu) Enter the following commands: # Dmesg> bootmessage This command will display the message at boot time redirect the output to a file bootmessage in. 1163 I would like to delete order records in the write-off, may I ask how? (Bjchenxu) Edit / etc / skel / .bash_logout file (did not create one), add the following lines: rm-f $ HOME / .bash_history In this way, the system when all users log off command will remove records. If only for a specific user, such as the root user settings, the user can only modify the $ home directory HOME / .bash_history file, the same line can be increased. 1164 1165 How to use ssh channel technology (bjchenxu) This article discusses all the machines are Linux operating system. For example, my machine is A, the middle server B, the target server is C. You can ssh from A to B, from B to ssh to C, but A can not be directly ssh to C. Now showing use ssh access technology to transfer files directly from A to C. 1. Ssh-L1234: C: 22 root @ B input B's password 2. Scp-P1234 filename root @ localhost: input C's password 1166 using the rpm command no response, how to solve (beginner photography) rm-rf / var / lib / rpm / __db .* 1167 to login to the same server send a message to all users (bjchenxu) 1) Enter the wall and Enter 2) Enter the message to be sent 3) The end of the press "Control-d" key, the message that is displayed in the user's control window Enter a short message 1168 to a single user (bjchenxu) 1) Enter write username, when the user name appears in multiple terminal, after the user name plus tty, to indicate in which tty of the user. 2) Enter the message to be sent. 3) The end of the press "Control-d" key, the message that the user's control window. 4) The party receiving a message, you can set whether to allow people to send messages to you. Instruction format is: mesg n [y] % Write liuxhello! Everybody, I'llcome. % User Control window displays a message: Message from liux on ttyp1 at 10:00 ... hello! Everybod y, I'llcome. EOF When using the CDE or OpenWindows window system, etc., each window is seen as a separate logon; more than once if the user is logged on the number of message sent directly to the control window. 1169 to send the file in the message to a single user (bjchenxu) If there is a long message to send to several users, with the papers: 1) Create a text message to send the file filename. 2) Enter write username % Cat> messagehello! Everybody, I'llcome. % Write liux % Users in more than window login, the message displayed in the control window Message from liux on ttyp1 at 1 0:00 ... hello! Everybody, I'llcome. EOF 1170 to the remote machine to send messages to all users (bjchenxu) Use rwall (to all the remote write) command also sends a message to all users of the network. rwall hostname file When using the CDE or OpenWindows window system, etc., each window is seen as a single login; If the user is logged on more than one message number sent directly to the control window. 1171 to all network users to send messages (bjchenxu) Send a message to all users of the network 1) Input rwall-n netgroup and Enter 2) Enter the message to be sent 3) The end of the press "Control-d" button, a message that the system for each user control window display, the following is a message to the network system administrator for each user group Eng examples: % Rwall-n EngSystem will be rebooted at 11:00. (Control-d) % User Control window message: Broadcast message from root on console ... System will be r ebooted at 11:00. EOF Note: You can also rwall hostname (hostname) command to the system to all users. 1172 I need to compile the kernel, where the kernel source? Most current releases are no longer with the default source, if required, free to download Can go download a copy of your favorite, the school has kernel image. ---------- --------- Network-related articles 2001 to apache's default character set into Chinese (bjchenxu) vi httpd.conf, find AddDefaultCharset ISO-8859-1 line apache version 1 .* If, instead AddDefaultCharset GB2312 If 2.0.1-2.0.52, to AddDefaultCharset off Then run / etc / init.d / httpd restart restart apache to take effect. Note: For 2.0.53 or later, do not modify any configuration, can support Chinese. 2002 change change ip address and MAC IP: New ip ifconfig eth0 Then edit / etc/sysconfig/network-scripts/ifcfg-eth0, modify ip Change MAC: ifconfig eth0 down ifconfig eth0 hw ether 00:06:61:6 A: 7B: 8B ifconfig eth0 up For each boot automatically change the above three commands can be added to / etc / init.d / network last 2003 Linux on the remote display from the Windows Desktop (lnx3000) Install rdesktop 2004 manually add the default gateway (bjchenxu) To root user, do: route add default gw gateway IP 1 vi / etc/sysconfig/network-scripts/ifcfg-eth0 change GATEWAY 2 / etc / init.d / network restart 2005 Linux use msn and QQ MSN: Install gaim or aMSN download QQ: Install LumaQQ or the eva, eva recommended to use KDE. 2006, 22 ports are run to identify the procedure (bjchenxu) lsof-i 2007 view of the machine's IP, gateway, dns (bjchenxu) IP: To root users log on, the implementation of ifconfig. Where eth0 is the first piece of card, lo is the default device Gateway: To root user login, do the netstat-rn, to 0.0.0.0 at the beginning of a line of Gateway shall be the default gateway can also check / etc / sysconfig / network file, which has the specified address! DNS: more / etc / resolv.conf, the content designated as follows: nameserver 202.112.144.30 nameserver 202.112.144.65 2008 Redhat ping command line to change the TTL value (cgweb, lnx) Method 1 (valid after reboot): # Sysctl-w net.ipv4.ip_default_ttl = N (N = 0 ~ 255), if N> 255, then ttl = 0 Method 2 (after restart invalid): # Echo N (N is 0 ~ 255)> / proc/sys/net/ipv4/ip_default_ttl 2009 Open LINUX-IP forwarding (houaq) Edit / etc / sysctl.conf, such as the net.ipv4.ip_forward = 0 Into net.ipv4.ip_forward = 1 After rebooting into force, with a sysctl-a view known 2010 mount the other windows machines on the LAN of the directory (bjchenxu) Install samba mount-t smbfs-o username = guest, password = guest / / machine / path / mnt / cdrom 2011 allowed | prohibited root login via SSH (Fun-FreeBSD) Modify the sshd_config: PermitRootLogin no | yes 2012 so that direct root telnet login (bjchenxu, platinum) Method 1: Edit / etc / pam.d / login, to remove auth required / lib / security / pam_securetty.so words Method 2: vi / etc / securetty Add pts / 0 pts / 1 ... 2013 2014 to automatically synchronize linux time (shunz) vi / etc / crontab Added: 00 0 1 * * root rdate-s time.nist.gov 2015 Linux reference Digest of online resources - Information Resources 2016 to change the sshd port (bjchenx) In / etc / ssh / sshd_config to add a line: Port 2222, / etc / init.d / sshd restart restart the daemon 2017 to change the telnet port (bjchenxu) The / etc / services file, telnet port number corresponding to 21 to the value you want, / etc / init.d / xinetd r estart restart the daemon 2018 terminal mode in question (sakulagi) export TERM = vt100 2019 copy HyperTerminal, LINUX in the procedure to connect the router and switches (alstone) minicom 2020 ssh can not come up to automatically disconnect (wind521, double eyelids pig) Modify your HOME directory. Bash_profile file, add export TMOUT = 1000000 (in seconds) And then run the source. Bash_profile 2021 What tools do intrusion detection (bjchenxu) snort 2022 Linux memory leak detection program under tools (bjchenxu) cchecker or efence library can 2023 linux how to monitor all the data card through the machine (bjchenxu) tcpdump or iptraf 2024 Why is the implementation of many root command said command not found (bjchenxu) Telnet you up, and then su into root of it, change your su command to change the format, should be su - root 2025 shut down the user's POP3 rights (tiansgx) The POP3 port closed on it. In the file / etc / services to find this line pop-3 110/tcp before this line add a '#', it commented on it. Play flash animation under the 2026 linux download ftp:// / UNIX / multimedia / flashplayer / install_flash_player_7_linux.tar.gz $ Tar zxf install_flash_player_7_linux.tar.gz $ Cd install_flash_player_7_linux $. / Flashplayer-installer Installed according to their own path to the browser settings, and then open the flash file to the browser. 2027 2028 server, how to prevent telnet (Zhiqiu leaf) The server must start the telnet service & & server firewall to allow telnet. 2029 to prevent anyone the wheel group. 2030 how to make the lynx browser to visit the Chinese website (Ghost_Vale) View Simplified Chinese website following changes to settings on Save options to disk: [X] Display and Character Set Display character set: [Chinese________________________] Assumed document character set (!): [Iso-8859-1______] CJK mode (!): [ON_] Then move to the bottom of the Accept Changes can be saved by pressing Enter the system of course you can to support Simplified Chinese 2031 network card activated, but unable to get online, how do? (Slock, double eyelids pig) traceroute, look in the end is that one is standing in the way of. 1.ping own 2.ping Gateway 3.ping DNS 4.traceroute DNS If all nslookup ping sina's address traceroute sina's address Basically you can know the result 2032 under the redhat9 with samba, win2000 can access, win98 can not access? (Squall2003) If it is necessary to modify the registry wind98: HKEY_LOCAL_MACHINE / system / correntcontrolset / services / Vxd / VNETSUP build a D value under: EnablePlainTextpasswd, key 1 2033 how to get the network card MAC address (bjchenxu, hutuworm) arp-a | awk '(print $ 4)' ifconfig eth0 | head -1 | awk '(print $ 5)' 2034 how to get the network card IP address bind multiple ip next card. Bind more than one network card ip to another method (hotbox) In / etc / sysconfig / network-scripts / create a file: ifcfg-ethX-rangeX ("X" for the card number) Content of the document: IPADDR_START = IPADDR_END = CLONENUM = 0 Can have 256 ip 2037 How to bind an ip two network cards (hutuworm) Assuming 192.168.0.88 is the 2039 linux arp table under the clear command (NetDC) # Arp-d-a (applies to bsd) for HOST in `arp | sed '/ Address / d' | awk '(print $ 1)'`; do arp-d $ HOST; done 2040 using the ntp protocol from the server synchronization time (NetDC) ntpdate NTP-SERVER cases: ntpdate 172.16.2.1 2041 host command usage (bjchenxu) host can be used to query domain name, it can get more information host-t mx example.com example.com can check out the MX records, and handle mail in the host name host-l example.com will return all registered under the example.com domain host-a example.com will display the host information for all domain names. 2042 immediately so that LINUX support for NAT (platinum) echo 1> / proc/sys/net/ipv4/ip_forward iptables-t nat-I POSTROUTING-j MASQUERADE 2043 2044 in ethX device, so that LINUX support network radio feature (the default is not supported) (platinum) ip route add 255.255.255.255 dev ethX 2045 Route Set Manual (NetDC) View the routing information: netstat-rn route-n Manually add a route: route add-net 192.168.0.0 netmask 255.255.255.0 gw 172.16.0.1 Manually delete a route: route del-net 192.168.0.0 netmask 255.255.255.0 gw 172.16.0.1 Well, following that important, let the system boot automatically enabled when the routing settings. Add a route in redhat, modify file / etc / sysconfig / static-routes any net 192.168.0.0 netmask 255.255.255.0 gw 172.16.0.1 Add a route in debian, Method 1: Modify / etc / network / interfaces Code: auto eth0 iface eth0 inet static address 172.16.3.222 netmask 255.255.0.0 network 172.16.0.0 broadcast 172.16.255.255 gateway 172.16.2.1 up route add-net 192.168.0.0 netmask 255.255.255.0 gw 172.16.0.1 down route del-net 192.168.0.0 netmask 255.255.255.0 gw 172.16.0.1 Method 2: In the / etc / network / if-up.d directory to create a simple script file, such as static-route $ ( I remember a $ symbol at the end, or else have a run-parts will come out to tell you something) script the simplest thousand million, Example: Code: #! / Bin / bash route add-net 192.168.0.0 netmask 255.255.255.0 gw 172.16.0.1 Hey, you can guess / etc / network / directory of the role of other directory instead. Found in the debian settings in this route in fact only its the configuration file with a relatively simple Yingyong it, you can always do more complex the application. 2046 using ssh to copy files (platinum) If A, B have the SSH service, now in A, SSH in 1, from A Copy B (push in the past) scp-rp / path / filename username @ remoteIP: / path 2, copied from B to A (pull over) scp-rp username @ remoteIP: / path / filename / path If one is not a LINUX system, you can use SecureFX software on WINDOWS 2047 samba3.0 Chinese display solutions to the problem (linuxzfp, jiadingjun) In the samba 3.0 configuration file (/ etc / samba / smb.conf) the [global] add the following two sentences: unix charset = cp936 Restart services service smb restart 2048 network card MAC address of the temporary modification method of closed network card: / sbin / ifconfig eth0 down Then change address: / sbin / ifconfig eth0 hw ether 00: AA: BB: CC: DD: EE Then start the network card: / sbin / ifconfig eth0 up 2049 conntrack table full treatment (cgweb) Configuration of iptables + squid while ago to do proxy server, has been working. Today I found on the console Jun 18 12:43:36 red-hat kernel: ip_conntrack: table full, dropping packet. Jun 18 12:49:51 red-hat kernel: ip_conntrack: table full, dropping packet. Jun 18 12:50:57 red-hat kernel: ip_conntrack: table full, dropping packet. Jun 18 12:57:38 red-hat kernel: ip_conntrack: table full, dropping packet. IP_conntrack that connection tracking database (conntrack database), on behalf of NAT machine to track the number of connections, connection tracking table can hold a variable number of records are being controlled, it may be the kernel of ip- sysctl function sets. Each track link table will occupy 350 bytes of kernel memory space, over time the space will fill up the default, then by default How much space? I redhat example in the memory when the machine 4096 64MB, 128MB memory is 8192, 256MB of memory is 16376, then will be able to / proc/sys/net/ipv4/ip_conntrac k_max in view, setting. For example: to 81920, you can use the following command: echo "81920"> / proc/sys/net/ipv4/ip_conntrack_max So setting is not saved, we must save after restart in / etc / sysctl.conf and Canada: net.ipv4.ip_conntract_max = 81920 After the change in accordance with this method, all normal, and if the full increase its value can be. Under the 2050 Linux how to use BT (atz0001) BitStorm azureus, 2051 Linux view the card's operating mode optical fiber (sakulagi) PCI-X slot on the motherboard to insert a 64-bit fiber card, in LINUX9.0 environment, to know that it is working in 64 bit mode, you can use getconf WORD_BIT 2052 online alternative way to update RHEL 1. Install the appropriate APT package: 2. Online Update apt-get update apt-get upgrade 2053 SOCKS5 start to stop working after a period of time. With the command ps auxw | grep socks5 look and found many SOCKS defunct process, why (bjchenxu) Mainly to patch the problem. If socks5-tar.gz version is not patched, you must take the next patch v1 .0-R11 version, reinstall, run the problem can be solved. 2054 to install the VMware WorkStation 4.0.5 Debian 3.0, the tips not found the hard disk, required SCSI drive. But I use the IDE hard disk, how does that do? (Bjchenxu) As the VMware partition of hard disk space the user into the virtual SCSI hard drives, and Debian install disk does not correspond to the driver, And install other Linux versions, some in the beginning will be loaded SCSI drive, so there is no problem. Users can modify the VMware configuration, to read analog IDE hard drive on it. 2055 how to get behind Linux Gateway, under the user directly clicks WIN32 FTP connection to download? (Platinum) modprobe ip_nat_ ftp 2056 Will the user's IP is dynamic, how to limit Squid in the same account at the same time, the number of line? ( bjchenxu) Such as restrictions on individual users can only open 12 HTTP connections, use the following method: acl all src 0.0.0.0/0.0.0.0 acl limit maxconn 12 acl localnet src 192.168.0.0/24 http_access deny localnet maxconn http_access allow localnet http_access deny all 2057 If I use a proxy server Squid proxy 192.168.1.0 in this segment, such as its IP is 192.16 8.1.1, I have some clients in the 192.168.2.0 the network segment, and how to set a proxy server to go through this? (Bjchenxu) If no transparent proxy, the proxy directly in the browser option in settings on it. Otherwise, the proxy server first, then hang a card on IP as 192.168.2.1, add the appropriate routing, and then modify the squid.conf file Squid listening address and port, etc., and finally set the client 192.168.2.0 segment The gateway 192.168.2.1, and then directly in the browser's proxy option in settings click on it. 2058 How to use netrc file for automatic FTP? (Bjchenxu) In their own home directory, create a permission for the 600, the suffix name. Netrc file, as follows: machine 172.168.15.1 login admin password admin This user login FTP server 172.168.15.1 each subsequent time, the system will help the user to the user name admin, Admin login password. This feature enables users to automatically FTP. For example, the user wants to 6:00 every day to 172.168 .15.1 Machine above was / admin directory files admin.txt, the following method can be done. Create a file ftp_cmd, reads as follows: cd admin get amin.txt bye Then use the crontab-e to set a timer task: 0 6 * * * ftp 172.168.15.1 <ftp_cmd 2059 How to get ipchains log? (Bjchenxu) When the user set the rules will be added-l parameter in / etc / messages which do record. But the proposal is still without a good, or the user's / etc / messages will become very large. 2060 How to not show other user's message? (Bjchenxu) Users can use the mesg n to send the message to yourself against others, in fact, forbidden to write their own terminal authority above. When people try to re-use write to send their own messages, the sender will see prompt as follows: write: user has messages disabled on pts / n 2061 minicom color display (double fold of the pig) minicom-s to serial port configuration, and then configured, minicom-o-c on -O that does not initialize the -C on that color on 2062 SELinux enabled the Apache configuration file httpd.conf which appear useless or modify the DocumentRoot 4 03 Forbidden error (arbor) # Chcon-u system_u-t httpd_sys_content_t-R website directory 2063 apache2 the log file location how to customize the directory (tomi) Edit httpd.conf inside ErrorLog / var / log / http / error_log <== This is the tube errorlog of CustomLog / var / log / http / access_log common <== This is the tube accesslog of 2064 whether to change eth0 promiscuous mode (wwy) Network card into promiscuous mode eth0: ifconfig eth0 promisc Close promiscuous mode: ifconfig eth0-promisc 2065 characters in the interface of ftp, download the entire folder (bjchenxu) 1. L ftp IP 2.> User username 3.> Mirror-c-parallel = number remotedir localdir 3a.> Help mirror 2066 how to make ssh only allow specified users log (xinyv, nice, wolfg, I love fishing) Method 1: In / etc / pam.d / sshd file to add auth required pam_listfile.so item = user sense = allow file = / etc / sshusers onerr = fail Then in the / etc files under the build sshusers, edit this file, allows the use of ssh service on your user name, you can re-start sshd service. Method 2: pam rules would also deny the written auth required pam_listfile.so item = user sense = deny file = / etc / sshusers onerr = s ucceed Method 3: In the sshd_config to set AllowUsers, formats such as AllowUsers abc Restart the sshd service, users can only a/b/c3 landing. 2067 in Linux How to bind IP address and hardware address (bjchenxu) You can edit an address corresponding file, which records the IP address and hardware address of the corresponding relationship, and then do "arp -F address corresponds to File. "If no corresponding address file is usually the next default file / etc / eth ers shall prevail. Address corresponding to the file format is as follows: 192.168.0.1 00:0 D: 61:27:58:93 192.168.0.2 00:40: F4: 2A: 2E: 5C 192.168.0.3 00:0 A: EB: 5E: BA: 8E 2068 known network hardware address of a machine, how to know its corresponding IP address (bjchenxu) In Linux, it is assumed to check "00:0 A: EB: 27:17: B9" a hardware address corresponding to IP addresses, you can use the following command: # Cat / proc / net / arp | grep 00:0 A: EB: 27:17: B9 192.168.2.54 0 × 1 0 × 6 00:0 A: EB: 27:17: B9 * eth2 In addition, you can also use the "arp-a" command queries: # Arp-a | grep 00:0 A: EB: 27:17: B9 (192.168.2.54) at 00:0 A: EB: 27:17: B9 [ether] on eth2 2069 based on Apache HTTPD or Sendmail service is suspended during startup, and how to solve this problem (bjchenxu) Encounter such problems, make sure that / etc / hosts file has the following line: 127.0.0.1 localhost.localdomain localhost 127.0.0.1 is the address of the network loop. 2070 how to make the Linux system does not respond to the ping (bjchenxu) For Linux on the ping did not respond, that is to ignore the Linux system I CMP package. Use the following command for this purpose: # Echo 1> / proc/sys/net/ipv4/icmp-echo-ignore-all To resume, the following commands available: # Echo 0> / proc/sys/net/ipv4/icmp-echo-ignore-all ---------- --------- Programming articles 3001 linux debug core files (bjchenxu) gdb : Error generated core dump of the executable. : Core dump file name, the default is the "core" 3002 gcc abc.c get a.out can not run (bjchenxu) . / A.out 3003 c + + compile-time error message that cout Why not defined (bjchenxu) After accession to include the header file using namespace std; 3004 generated new compiler gcc, use the standard connection library in / usr / local / lib under, but the connection using the default path is / usr / lib How do I add? (Except when the increase in per compile-L / usr / local / lib away) (Sakulagi, hutuworm) export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH: / usr / local / lib Write ~ /. Bash_profile inside. A simple way to increase: The / usr / local / lib added / etc / ld.so.conf, then run a ldconfig 3005 RH9 installation under the GCC (As Time Goes By, hutuworm) Choose one of three ways: (1) the use of CD to install on rpm CD-1: compat-gcc-7.3-2.96.118.i386.rpm CD-1: compat-gcc-c + +-7.3-2.96.118.i386.rpm CD-1: libgcc-3.2.2-5.i386.rpm CD-2: compat-gcc-g77-7.3-2.96.118.i386.rpm CD-2: compat-gcc-java-7.3-2.96.118.i386.rpm CD-2: compat-gcc-objc-7.3-2.96.118.i386.rpm CD-2: gcc-3.2.2-5.i386.rpm CD-2: gcc-c + +-3.2.2-5.i386.rpm CD-2: gcc-g77-3.2.2-5.i386.rpm CD-2: gcc-gnat-3.2.2-5.i386.rpm CD-2: gcc-java-3.2.2-5.i386.rpm CD-2: gcc-objc-3.2.2-5.i386.rpm Such encounter prompted: warning: gcc-3.2.2-5.i386.rpm: V3 DSA signature: MOKEY key ID db42a60e error: Failed dependencies: binutils> = 2.13.90.0.18-9 is needed by gcc-3.2.2-5 glibc-devel> = 2.3.2-11.9 is needed by gcc-3.2.2-5 ... To install glibc-devel package, and so on (2) The better way is to choose the X-window under the "Main Menu" ─ ─> "System Settings" ─ ─> "Add / Remove Applications" ─ ─> "development tools" in the gcc and install it (3) up2date gcc will automatically solve the dependency problem 3006 shell script, why not run (GOD_Father) First, the script permissions for executable # chmod + x test.sh Second, the script in a directory in the PATH environment variable, or direct execution #. / Test.sh 3007 See what process a file is read-write (bjweiqiong) lsof filename 3008 See what files a process opened (bjweiqiong) lsof-c process name lsof-p process ID 3009 lsof mean (bjweiqiong) list open files 3010 lsof use small whole (bjweiqiong) lsof abc.txt shows the process of opening files abc.txt lsof-i: 22 to know what program to run 22-port now lsof-c nsd nsd process is now open display file lsof-g gid gid ownership of the process shows the situation lsof + d / usr / local / display directory of files opened by the process lsof + D / usr / local / Ibid, but will search the directory of directories, a long time lsof-d 4 shows the process of using fd 4 lsof-i to demonstrate compliance with the conditions of the process conditions Syntax: lsof-i [46] [protocol] [@ hostname | hostaddr] [: service | port] 46 -> IPv4 or IPv6 protocol -> TCP or UDP hostname -> Internet host name hostaddr -> IPv4 Location service -> / etc / service in the service name (can be more than one) port -> port number (can be more than one) Examples: TCP: 25 - TCP and port 25 @ 1.2.3.4 - Internet IPv4 host address 1.2.3.4 tcp@ohaha.ks.edu.tw: ftp - TCP protocol host: ohaha.ks.edu.tw service name: ftp lsof-n do not convert the IP hostname, the default is not with-n parameter example: lsof-i tcp@ohaha.ks.edu.tw: ftp-n lsof-p 12 to see the process number 12 which documents the process of opening lsof + |-r [t] control lsof repeated execution, the default is 15s refresh -R, lsof will always keep the execution until the interrupt signal is received + R, lsof will always be executed until there are no files were shown examples: ftp connection constantly see the current situation: lsof-i tcp@ohaha.ks.edu.tw: ftp-r lsof-s list to open the file size, if not size, is left blank lsof-u username to UID, list open files ---------- --------- Classic books articles 4001 GNU / Linux Advanced Network Application Services Guide (bjchenxu) Mechanical Industry Press linuxaid site advantages: it all and concise, as are all the shortcomings of combat: For the lower version for redhat 6.2 4002 Linux Apache Web Server Administration Guide (Linux Apache Web Server Administration) ( bjchenxu) Charles Aulds Mashu Qi / Jin Yan Translation Publishing House Electronics Industry Benefits: I have not found the problem which this book on apache not discussed drawbacks: for 1.3.x, the latest for 2.0 .* The English version of the Chinese version When the 4003 Linux Kernel Scenario Analysis (bjchenxu) Maud parade / Hu Ximing, Zhejiang University Press Advantages: very thorough, and can not understand Disadvantages: or version problem, the kernel update too fast, but still required reading 4004 Unix environment for high-level programming (bjchenxu) Richard Stevens Machinery Industry Press Advantages: profound weaknesses: it is very difficult for beginners to understand, otherwise how is "Advanced Programming" mean? 4005 Programming Highlights-Microsoft preparing high-quality c program error-free tips (bjchenxu) Steve Maguire Electronic Industry Press Advantages: do not say, and the author is a senior Microsoft engineers Disadvantages: hard to find, out of 1994 4006 Understanding the Linux Kernel, 2nd Edition (hutuworm) Daniel P. Bovet & Marco Cesati O'Reilly Press, after reading this book, you will understand the circumstances under which Linux has the best performance, and how it challenges, in various environments to provide process scheduling, file access and memory management when excellent system response. On to the introduction by explaining the importance of each subject, and the kernel and the Unix operating system programmers and users familiar with the utilities call or link. 4007 UNIX Operating System Tutorial (English) (MH) Syed Mansoor Sarwar, etc. Machine Press features: easy to understand, focus on basic unix concepts and overall understanding of the way English review. Also: Mechanical Industry Press has published the Chinese version, the name of: UNIX Tutorial 4008 UNIX programming environment (mentally handicapped) Brian W. Kernighan, Rob Pike Xiang-Qun Chen, M. Machine Press features: simple and obvious, easy to understand on how to use UNIX and a variety of tools, a brief introduction Unix programming environment; contrast "U NIX high-level programming environment ", this book suitable for beginners. 4009 The Art of UNIX Programming (hutuworm) Eric Steven Raymond ~ esr / writings / taoup / html / Related Posts of (Assignment) Linux word wonderful Q & A
http://www.codeweblog.com/assignment-linux-word-wonderful-q-a/
CC-MAIN-2014-52
refinedweb
11,810
58.92
Remember when I ranted at length about how Apple was letting Microsoft take the lead in collaborative features as simple as screen sharing? Well, until they come to their senses and make Apple Remote Desktop (or the built-in VNC server) as simple to use as the Vista screen sharing feature, I decided to have a go at it myself. I wanted an approach that: - Let me share a Mac screen with anybody, on any platform - Required the least possible amount of software at either end (no complex servers and no funky clients to install) - Wasn't too sophisticated (the more features, the harder things are to use) - Would work remotely, provided you have direct Internet access And what comes with pretty much every OS on the planet? Well, a browser, of course. What about VNC? At first I considered setting up an HTML page on my Mac and have it serve the VNC Java applet, but the built-in Mac OS X VNC server is utterly brain-dead in terms of image encodings and crashed most of the applet versions I tried. Then I realized that Java applets aren't the best thing to ensure cross-platform support (modern Windows and Linux require you to find and download a JVM, which severely raises the bar and kills the "instant sharing" approach). Plus I started running across issues such as screen scaling (which not all VNC clients do properly, let alone the Java ones), pre-configuring the applets to do shared connections, etc., etc. Furthermore, trying another VNC server like OSXvnc would be cheating, since it requires extra software to be installed on the serving Mac. KISS Is Best As usual, taking down complexity a peg makes for a better solution. Browsers can render images, and images are readily obtainable on the Mac using the screencapture CLI command. I didn't need interactivity at all, so a solution that let me see a Mac's screen in a browser as an image was fine with me. All that remained was the refresh interval, and I settled on 10 seconds because it's a nice compromise between the pace of slideshow presentations and live demos (where you need to see some sort of mouse movement and interaction). Incidentally, people doing online/LAN-based presentations might want to take a look at Mouseposé - it helps people keep track of the cursor. So I decided to write a small Python script to serve screenshots via HTTP, taking some care to ensure that the screenshots were evenly spaced in time and that a bunch of simultaneous requests wouldn't result in undue load on the serving Mac and several nearly-identical screenshots being served to clients. What Your Audience Sees The end result looks like this: Can't be much simpler, huh? And the code (without any dependencies whatsoever, runnable on just about any Mac) is small enough to include verbatim right here, HTTP server and all. Code import os, socket, datetime, SimpleHTTPServer, SocketServer, StringIO IMAGE_PATH = '/tmp/screen.png' INTERVAL = 10 counter = 0; function update() { document.getElementById("screenshot"). <center> <img id="screenshot" src="/screen.png"><br><p class="info">Updated every %s seconds</p> </center> </body> </html>""" % (socket.gethostname(), INTERVAL * 1000, INTERVAL) class LocalRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """Custom HTTP Request Handler""" def send_head(self): """Common handler for GET and HEAD requests""" if self.path == "/": self.send_response(200) self.send_header("Content-type","text/html") self.end_headers() return StringIO.StringIO(formatPage()) if self.path[:11] == "/screen.png": try: screenCapture(IMAGE_PATH) f = open(IMAGE_PATH,'rb') self.send_response(200) self.send_header("Content-type","image/png") self.send_header("Content-Length", str(os.fstat(f.fileno()).st_size)) mtime = datetime.datetime.fromtimestamp(os.fstat(f.fileno()).st_mtime) self.send_header("Last-Modified", mtime.strftime(HTTP_DATE_FORMAT)) expires = mtime + datetime.timedelta(seconds=INTERVAL) self.send_header("Expires", expires.strftime(HTTP_DATE_FORMAT)) self.end_headers() return f except IOError: pass self.send_error(404, "File not found") return None if __name__=='__main__': screenCapture(IMAGE_PATH) httpd = SocketServer.TCPServer(('',2000),LocalRequestHandler) httpd.serve_forever() Usage To use this, just save the above as, say, present.py, type python present.py at the terminal prompt, and access your Mac via port 2000 like the URL you see above (hostname:2000). Obviously, you'll have to figure out and tell other people your IP address, open any firewalls, etc., etc. If you're a complete networking newbie, please don't ask me how to find your own IP address. Learn the basics first... Possible Enhancements And, of course, this can be enhanced in all sorts of ways: - Taking CLI parameters such as the port number, refresh interval and screen size - Auto-detecting the most useful interface (usually en0 or en1 in Macs) and outputting the IP address upon startup - It can be re-packaged as an application bundle - It can use PyObjC to perform the actual screenshot-taking and resizing - It can be modified to advertise itself on the LAN via Bonjour - HTTP handling can be improved a bit (dealing with HEAD and If-Modified-Since) - etc., etc. But as it is, it works just fine with my PCs and Macs (I have not tried IE, but I assume it will work), and might be just the thing for anyone wanting a very simple view-only screen sharing trick. The choice of port 2000 is entirely arbitrary, and my guess is that a more sensible default would be 8000, 8080, 8090, etc., since those are typically open in corporate firewalls in the outbound direction (i.e., you can share your screen with somebody behind one).
http://the.taoofmac.com/space/blog/2006/03/12
crawl-002
refinedweb
920
51.28
Hello, I'm having some problems with trying to get my random numbers to go in ascending order and descending order as well and trying to figure out how to get when I put in a number between 2 - 25 how to get the highest number out of the random pick as well as the lowest number out of the random pick. Can someone please help!?!?!?!?! I greatly appreciate it if someone could help me out on this! :) Below is my code I have so far... Thanks, ethompson #include <iostream> #include <time.h> #include <stdlib.h> using namespace std; void bubbleSort (int Rand[]); main() { cout<<"Data Searching and Sorting!!"<<endl<<endl; srand(time(0)); int Rand_Num; int Input; char ans; int cnt, inside, outside, Swapped, tmp; int high, low; do { cout << "How many numbers would you like to be generated (2 - 25): "; cin >> Input; if(Input >= 2 && Input <= 25) { cout<<"The "<<Input<<" numbers genterated are: "<<endl; for(int i = 0; i < Input; i++) { Rand_Num = (rand() % 47) + 1; cout <<Rand_Num<<endl; } } else cout<<"Sorry, that is invalid try again"<<endl; //______________________________________________________________________________ cout<<"The Highest Number is: "<<high<<endl<<endl<<endl; cout<<"The Lowest number is: "<<low<<endl<<endl<<endl; //______________________________________________________________________________ void bubbleSort(int Rand, 25); cout<< "After sorting, the list elements are: "<<endl; int i; for (i = 0; i<25; i++) cout<<Rand_Num<<" "; cout<<endl; cout<<"Want to pick again? "; cin>>ans; cout<<endl<<endl; } while((ans=='y') || (ans=='Y')); cin.get(); cin.get(); return 0; }
https://www.daniweb.com/programming/software-development/threads/49724/random-number-with-ascending-order-help
CC-MAIN-2021-21
refinedweb
245
67.08
Terraform Cloud estimates costs for many resources found in your Terraform configuration. It displays an hourly and monthly cost for each resource, and the monthly delta. It also totals the cost and delta of all estimable resources. In this tutorial, you will enable cost estimation then This tutorial assumes that you are familiar with Terraform Cloud and you have an existing test Terraform Cloud workspace configured with AWS access credentials. Do not apply this policy to a production workspace as it may impact your production environment. If you don’t, refer to the Create a Workspace tutorial and Set Up Workspace tutorial to learn more about Terraform Cloud and set up a Terraform Cloud workspace configured with AWS access credentials. Note: Terraform Cloud will not estimate cost on runs or applies targeted against a subset of resources. »Verify costs using policies To verify cost estimates using policies, you need to update your policy set and define your policy. Fork the example repository cost-estimation branch to review the final configuration. Add the following configuration to your sentinel.hcl file to declare your new policy in your policy set. policy "less-than-100-month" { enforcement_level = "soft-mandatory" } Then, create a new file named less-than-100-month.sentinel that contains the following policy configuration. import "tfrun" import "decimal" delta_monthly_cost = decimal.new(tfrun.cost_estimate.delta_monthly_cost) main = rule { delta_monthly_cost.less_than(100) } This policy uses the tfrun import to check that the new cost delta is no more than \$100. (A new t3.nano instance should cost well below that.) The decimal import is used for more accurate math when working with currency numbers. Finally, save the updated policy configurations to source control. Terraform Cloud will run both policies defined in the sentinel.hcl policy set. »Add an estimable Terraform configuration You will need a valid configuration with cost estimable resources. Add the following terraform configuration in a main.tf to your workspace repository. The Ubuntu ami provided in the sample configuration is for us-west-1. Refer to the Amazon EC2 AMI Locator to select a similar ami for your AWS region. resource "aws_instance" "basic" { ami = "ami-0ee1a20d6b0c6a347" instance_type = "t3.nano" } Then, save the updated configuration to source control and queue a run in Terraform Cloud. For a full list of supported resources in Terraform Cloud cost estimation, refer to the AWS, Azure, and Google Cloud Cost Estimation Documentation. »View cost estimate After queueing a new run, Terraform Cloud will estimate your resource cost, which it displays in a phase in the run UI. There you'll find the list of resources, their price details, and the list of un-estimated resources. You'll also find the totals so you can get a sense of the proposed overall monthly cost once the run is applied. Note: This is just an estimate; some resources don't have cost information available or have unpredictable usage-based pricing. Click "Discard run" to cancel the run. »Next steps Congrats — you've enabled cost estimation and used it in a policy check! This provides another tool to manage your infrastructure spending. To learn more about cost estimation, refer to the Cost Estimation documentation. If you would like to learn more about Terraform Cloud, refer to the following links. -.
https://learn.hashicorp.com/tutorials/terraform/cost-estimation?in=terraform/cloud-get-started
CC-MAIN-2020-45
refinedweb
540
58.18
17 July 2012 10:12 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The plant will produce 300,000 tonnes/year of monoammonium phosphate (MAP) and 300,000 tonnes/year of diammonium phosphate (DAP), the source said. The products will be supplied to the domestic market in the first year instead of being exported, because the company does not have enough time to prepare for exports before the low export tax window closes in September, the company source added. The company initially planned to start up the unit in January this year, but this was delayed to August because of weak demand, according to the source. MAP/DAP supply in Hubei province will increase after the start-up, but this is expected to have only limited effect on the market as downstream demand remains weak, a market player said. Yidu Xingfa is a subsidiary of Hubei Xingfa
http://www.icis.com/Articles/2012/07/17/9578605/chinas-yidu-xingfa-to-start-up-ammonium-phosphate-unit-in.html
CC-MAIN-2014-52
refinedweb
146
56.79
Creating trial apps for Windows Phone 8 July 21, 2014 Applies to: Windows Phone 8 and Windows Phone Silverlight 8.1 | Windows Phone OS 7.1 You can design and implement a trial mode of your app in the Windows Phone Store. Experience shows that users enjoy trying out new products and are much more likely to buy an app if they have been able to try it before buying. The Windows Phone app platform makes it easy for you to provide trial and full versions of your apps within a single XAP package. Users who want to buy an app they are trying out can seamlessly access the familiar Store purchase experience from within the trial app. There are no restrictions around how you design the trial experience for your app. You can determine the extent of functionality that you want to expose to your user, whether the trial mode is of a limited duration, or how you want to encourage your user to buy your app. You can also determine whether an app’s data and state are maintained if a user chooses to purchase a trial app. When you submit your trial mode app to the Store, check the Trial Application box and the Store client will display a Try option view on the app’s detail page. This topic contains the following sections. To implement a trial mode for your app you must define and implement how trial behavior differs from full mode behavior. To run in the correct mode when executed by a user, your code must determine whether the app is running with trial or with full execution rights. To provide a purchase path your code must launch the Store client. The trial/full state of a user’s execution rights for an app are maintained in a license. When a user tries your app, it is installed on their phone along with a license that grants them the right to try the app. Trial licenses do not expire but when a user purchases an app they have been trying a full license is downloaded. The full license replaces the trial license and grants full rights to the app. To determine whether the license in place at run time is trial or full execution rights, Windows Phone supplies methods that return true if the app is running under a trial license and false if the app has been purchased and is running under a full license. To allow a trial user to purchase your app Windows Phone supplies methods that open the Store client to the app’s purchase page. XNA Framework developers should use the GamerServices.Guide class to build your try and buy experience. Use the Guide.IsTrialMode property to get current license mode and the Guide.ShowMarketplace method to initiate the purchase experience. Windows Phone apps can use the XNA Framework methods described above or use the IsTrial() method to get current license state directly, and the Show() method of the MarketplaceDetailTask class to initiate the purchase experience. To understand the trade-offs between choices see the Trial mode testing overview section below. Determining trial state and navigation to the Store for purchase must be simulated by your code when you are testing or debugging your app. Methods for this functionality do not work in debug or testing mode because required licensing and Windows Phone Store ID properties are not created until after your app is complete and submitted. XNA Framework apps should always use the GamerServices.Guide class for these functions. This class has built in trial and purchase simulation features. For more information, see Simulating Trial Mode for Marketplace Content. Windows Phone apps can also use the GamerServices.Guide class or implement their own custom behavior. Using the GamerServices.Guide calls in a Windows Phone app may save some work simulating trial license state during debug and testing. Using the LicenseInformation.IsTrial and MarketplaceDetailTask.Show methods allows more opportunity to customize your trial testing and debugging methods. This section describes the best practices you should consider when you create a trial app. XNA apps should always use GamerServices.Guide class to implement trial mode. When setting the Guide.SimulateTrialMode flag to TRUE, always enclose it in an #if DEBUG/#endif statement. Check the IsTrial() state when your app loads or resumes. You can avoid some potential trial design flaws especially if you cache the IsTrial() state. Do not rely on usage time limited trials to protect your app’s value. Typically, it is best to protect the value of your full mode app by limiting trial access to key code paths. A user may uninstall and retry an app without restriction so a trial design that offers full mode behavior for a limited time provides only inconvenience as a barrier to reuse. Provide a way for users to buy your trial app before the end-of-trial. Make sure that you help users understand why they want to buy your app, perhaps, by implementing your trial limit at a point in the app where they will naturally want more. For example, let users experience the first level of game play and require them to purchase the app to play higher levels, retain points, or to connect to a gaming service.
http://msdn.microsoft.com/en-us/library/ff967558
CC-MAIN-2014-41
refinedweb
881
63.49
Back in March 2015, I was trying to relearn for loops and foreach loops in Java. By September, though, I was helping build out the automation framework for our Selenium WebDriver browser tests -- See Automate Amazon for a sample. And by January 2016, I thought I was really becoming an experienced developer, independently writing a framework to handle Rest APIs. All the extra work I was putting into learning to code was really paying off. Now, I feel like I don't know anything! We are switching from being an "Automation Department" to being a "Software Test Engineering" department, from just running browser tests to testing APIs and performance testing. I find myself experimenting with many languages and tools that are brand new to me... and one of them is the build management tool, Gradle. Maven and Gradle: Setting Dependencies As far as I knew, a build management tool was something you set up once at the start of the project to handle the dependencies, installing the tools you needed to create the framework, and then forgot about them. I was first introduced to Apache Maven during Alan Richardson's online course, Selenium 2 WebDriver with Java. Take a look at the first practice testing framework I designed back in July 2015. The pom.xml file has nothing but dependencies for the tools I am using. Pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns=" xmlns:xsi=" xsi:schemaLocation=" <modelVersion>4.0.0</modelVersion> <groupId>WebDriver_TheInternet_Advanced</groupId> <artifactId>WebDriver_TheInternet_Advanced</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.1.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.46.0</version> </dependency> </dependencies> </project> If you take a look at the poorly named project I created, InitialWebDriverSetup_GradleJunitChromeDriver, you can see that I am only using Gradle in this same way. It is just a quick way for the project to download other libraries I am using in the project. Take a look at the build.gradle file: Build.gradle group 'com.tmaher' version '1.0-SNAPSHOT' apply plugin: 'java' repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.11' compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '2.53.0' compile group: 'org.hamcrest', name: 'java-hamcrest', version: '2.0.0.0' } Gradle Tasks There is a lot more to Gradle than handling dependencies. When creating a Gradle project with IntelliJ, as I did in the blog post WebDriver development environment setup with IntelliJ, Gradle, Hamcrest, and ChromeDriver, you can see that there are many Gradle tasks that have been set up for us: These tasks were automatically created as soon as the Java plugin for Gradle was added to the build.java file. See Chapter 45: The Java Plugin of the free Gradle Users Guide. Gradle: Build Tasks: - assemble: Assembles all the archives in the project - build: Performs a full build of the project. - buildDependents: Performs a full build of the project and all projects which depend on it. - clean: Deletes the project build directory. - check: Performs all verification tasks in the project. - test: Runs the unit tests using JUnit or TestNG. public class TestClass { private WebDriver driver; @Test public void testFirefoxDriver() { driver = new FirefoxDriver(); . . . } @Test public void testChromeDriver() { . . . } @Test public void testIE11Driver() { . . . } @After public void closeBrowsers() throws Exception { driver.quit(); } } Running Tests through IntelliJ When I double-click on test: - Build.Gradle is reviewed: Since there isn't anything explicitly saying test { useTestNG() } it will use JUnit (3.8.x or 4.x). See Gradle Test configurations. - It searched for all the unit tests in src/test/java. Since it didn't see anything in the build.gradle file excluding any tests, it ran all the tests we marked @Test. - After the project is compiled, one by one, the browser tests are run. - A report is printed out. Testing started at 1:05 AM ... 1:05:14 AM: Executing external task 'test'... :compileJava UP-TO-DATE :processResources UP-TO-DATE :classes UP-TO-DATE :compileTestJava UP-TO-DATE :processTestResources UP-TO-DATE :testClasses UP-TO-DATE :test BUILD SUCCESSFUL Total time: 29.391 secs 1:05:43 AM: External task execution finished 'test'. Running Tests through the Command Line These tests can also be run in the Command Line Interface (CLI), within the Mac Terminal or the Windows Command Prompt. Go into the project folder and run the following from the command line: Mac Terminal: ./gradlew test Windows Command Prompt: gradlew.bat test This does the same exact thing as above, except it uses the Gradle Wrapper to execute the task called test. On the Windows environment, the wrapper is a batch file (*.bat) that runs Gradle. What is the Gradle Wrapper? From Chapter 5: The Gradle Wrapper of the Gradle Users Guide, Version 2.13 ". What Was Gradle, Again?It was created mainly by Hans Doctker ( LinkedIn, Twitter: @hans_d ) the CEO of the Gradle (formerly Gradleware) company. From Wikipedia's article on Gradle: "Gradle is an open source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven of declaring the project configuration. Gradle uses a directed acyclic graph ('DAG') to determine the order in which tasks can be run. "Gradle was designed for multi-project builds which can grow to be quite large, and supports incremental builds by intelligently determining which parts of the build tree are up-to-date, so that any task dependent upon those parts will not need to be re-executed. "The initial plugins are primarily focused around Java, Groovy and Scala development and deployment, but more languages and project workflows are on the roadmap". Gradle Links: - Documentation: Gradle Users Guide at - GitHub site, where you can view its source code, at - Free Class on Udacity: Gradle for Android and Java - The next Gradle Summit is June 23-24, 2016 in Palo Alto, CA. - The funniest page in the Gradle Summit site is How to Convince Your Boss to go to the summit. They even have a hard-sell form letter you can copy-and-paste. Breaking Open: Gradle: Interview with the author of Gradle Video Description: "Published on Oct 4, 2012: In our second episode of Breaking Open, Hans Dockter peels back the curtains on Gradle, the open source, general purpose, and platform agnostic build system he created to address the changing landscape and new demands of modern enterprise automation". Gradle Summit 2015 Keynote: Hans Dockter "It Used To Be Fun To Make Software" ... With the next blog post, we'll explore the free class offered on Udacity: Gradle for Android and Java. Until then, Happy Testing! -T.J. Maher Sr. QA Engineer, Fitbit-Boston // QA Engineer since Aug. 1996 // Automation developer for [ 1 ] year and still counting!
https://www.tjmaher.com/2016/06/a-quick-gradle-overview-setting.html
CC-MAIN-2022-21
refinedweb
1,150
57.77
These two very similar code have very different speed. I don't understand why. The first one is much slower (2min) than the second one (5s). from numpy import sqrt primes = [2] for i in range(3, 1000000): sq = int(sqrt(i)) aux = False for j in primes: if j>sq: aux = True elif i%j==0: break if aux: primes.append(i) def isPrime(p, primes): bound = numpy.sqrt(p) i = 0 while(primes[i] <= bound): if p % primes[i] == 0: return False i += 1 return True def compute_primes(bound): primes = [] primes.append(2) for n in range(3, bound): answer = isPrime(n, primes) if answer: primes.append(n) return primes compute_primes(1000000) The reason for performance difference is that first version doesn't break the inner loop when upper bound is reached where as the second one does. Let's say the both versions are checking if 11 is prime or not. First version will run the inner loop for all the smaller primes (2, 3, 5, 7) where as the second one will only check values smaller or equal than sqrt(11): (2, 3). If you change the first version to break when upper bound is reached they run roughly the same time: if j > sq: aux = True break
https://codedump.io/share/g3P1BSVXw2S6/1/two-very-similar-codes-to-generate-the-primes-under-n-but-very-different-cpu-time
CC-MAIN-2017-17
refinedweb
212
79.7
OCaml Labs Apr. The remainder of 2014 was thus spent polishing this nascent OPAM release into a solid base (both as a command-line tool and as a library) that we could use as the basis for documentation, testing and build infrastructure, all the while making sure that bigger OCaml projects continued to migrate over to it. Things have been busy; here are the highlights of this effort.. The goal of the blog is also to start bringing together the various components that form the OCaml Platform. These are designed to be modular tools (so that you can pick and choose which ones are necessary for your particular use of OCaml). There are more details available from the OCaml Workshop presentation at ICFP 2014 to ensure that binary packages remain up-to-date. We also contribute to the hardworking packagers on MacOS X, Debian, FreeBSD, NetBSD and OpenBSD where possible as well to ensure that binary builds are well rounded out. Richard Mortier also assembled The public Travis CI testing does come with some limitations, since it only checks that the latest package sets install, but not if any transitive dependencies fail due to interface changes. It also doesn't test all the optional dependency combinations due to the 50 minute time limit.AM" whether a particular feature or new syntax would break any existing code. This in turn provides an incentive for commercial users to provide representative samples of their code; for instance, the Jane Street Core releases in OPAM (with their very modular style) act as an open-source canary without needing access to any closed source code. in OPAM for earlier versions of the compiler that had Camlp4 built-in, and then used the OPAM constraint engine to compile it as an external tool for the newer compiler revisions. Then we just had to triage the bulk build logs to find build failures from packages that were missing a Camlp4 dependency, and. In the 2014 OCaml workshop presentation (abstract, slides, video), we mentioned the "module wall" for documentation and this attempts to fix it. To try it out, simply follow the directions in the README on that repository, or browse some samples of the current, default output of the tool. Please do bear in mind codoc and its constituent libraries are still under heavy development and are not feature operates, and how to quickly resolve any conflicts that may arise in the future. He took care to ensure it had a well-defined scope, is simple and self-contained, and (crucially) documents the current reality. The result of this work is circulating privately through all the existing volunteers for a first round of feedback, and will go live in the next few months as a living document that explains how our community operates. Assemblage One consequence of OCaml's age (close to twenty years old now) is that the tools built around the compiler have evolved fairly independently. While OPAM now handles the high-level package management, there is quite a complex ecosystem of other components that are complex for new users to get to grips with: OASIS, ocamlfind, ocamlbuild, and Merlin to name a few. Each of these components (while individually stable) have their own metadata and namespace formats, further compounding the lack of cohesion of the tools. Thomas Gazagnaire and Daniel Buenzli embarked on an effort to build an eDSL that unifies OCaml package descriptions, with the short-term aim of generating the support files required by the various support tools, and the long-term goal of being the integration point for the build, test and documentation generation lifecycle of an OCaml/OPAM package. This prototype, dubbed Assemblage has gone through several iterations and design discussions over the summer of 2014. Daniel has since been splitting out portions of it into the Bos OS interaction library. Assemblage is not released officially yet, but we are committed to resuming work on it this summer when Daniel visits again, with the intention of unifying much of our workflow through this tool. If you are interested in build and packaging systems, now is the time to make your opinion known! Core Compiler We also spent time in 2014 working on the core OCaml language and compiler, with our work primarily led by Jeremy Yallop and Leo White. These efforts were not looking to make any radical changes in the core language; instead, we generally opted for evolutionary changes that either polish rough edges in the language (such as open type and handler cases), or new features that fit into the ML style of building programs. A common criticism of OCaml is its lack of support for ad-hoc polymorphism. The classic example of this is OCaml's separate addition operators for integers ( +) and floating-point numbers ( +.). Another example is the need for type-specific printing functions ( print_int, print_string, etc.) rather than a single Taking inspiration from Scala's implicits and Modular Type Classes by Dreyer et al., Leo White designed a system for ad-hoc polymorphism in OCaml based on using modules as type-directed implicit parameters. The design not only supports implicit modules, but also implicit functors (that is, modules parameterised by other module types) to permit the expression of generic modular implicits in exactly the same way that functors are used to build abstract data structures.op Some of the early feedback on modular implicits from industrial users was interesting. Jane Street commented that although this would be a big usability leap, it would be dangerous to lose control over exactly what goes into the implicit environment (i.e. the programmer should always know what (a + b) represents by locally reasoning about the code). The current design thus follows the ML discipline of maintaining explicit control over the namespace, with any ambiguities in resolving an implicit module type resulting in a type error. Multicore In addition to ad-hoc polymorphism, support for parallel execution on multicore CPUs is undoubtedly the most common feature request for OCaml. This has been high on our list after improving tooling support, and Stephen Dolan and Leo White made solid progress in 2014 on the core runtime plumbing required. Stephen initially added thread-local support to the OCaml compiler. This design avoided the need to make the entire OCaml runtime preemptive (and thus a huge patch) by allocating thread-local state per core. We are now deep into the design and implementation of the programming abstractions built over these low-level primitives. One exciting aspect of our implementation is much of the scheduling logic for multicore OCaml can be written in (single-threaded) OCaml, making the design very flexible with respect to: (* Define a struct of callbacks (C function pointers) *) let handlers : [`handlers] structure typ = structure "handlers" let (--) s f = field handlers s (funptr f) let on_data = "on_data" -- (string @-> returning void) let on_start_tag = "on_start_tag" -- (string @-> string @-> returning void) let on_end_tag = "on_end_tag" -- (void @-> returning void) let on_dtd = "on_dtd" -- (string @-> returning void) let on_error = "on_error" -- (int @-> int @-> string @-> returning void) let () = seal handlers and then expose this via C functions: module Stubs(I : Cstubs_inverted.INTERNAL) = struct (* Expose the type 'struct handlers' to C. *) let () = I.structure handlers (* We expose just a single function to C. The first argument is a (pointer to a) struct of callbacks, and the second argument is a string representing a filename to parse. *) let () = I.internal "parse_xml" (ptr handlers @-> string @-> returning void) parse ende. We continued this bi-monthly tradition in 2014, with a regular attendance of 15-30 people, and even cross-pollinated communities with our local F# and Haskell colleagues. We rotated locations from the Cambridge Computer Laboratory to Citrix, Makespace, and the new Cambridge Postdoc Centre. We posted some for supporting the latest entry point of OpenGL 4.5 and OpenGL ES 3.1. Since the bindings are automatically generated from the OpenGL XML registry the work is not too involved but there's always the odd function signature you don't/can't handle automatically yet. and it felt like this could be the basis for adding interactivity and animation to Vg/Vz visualizations – js viz libraries simply rely on the support provided by the browser or SVG support but Vg/Vz strives for backend independence and clear separations of concern (up to which limit remains an open question). Unfortunately I couldn't bring it to a release and got a little bit lost in browser compatibility issues and trying to reconcile what browser and SDL give us in terms of functionality and way of operating, so that a maximum of client code can be shared among the supported platforms. But despite this non-release it still managed to be useful in some way, see the next point. Helped Jeremy and Leo to implement the rendering and interaction for their ICFP tutorial 2048 js_of_ocaml implementation. This featured the use of Gg, Vg, Useri and React and I was quite pleased with the result (despite some performance problems in certain browsers, but hey composable rendering and animation without a single assignement in client code). It's nice to see that all these pains at trying to design good APIs eventually fit together [...]. The most notable thing has been how well the MirageOS research work has melded with the core OCaml Labs efforts, since much of it has been constructing good quality OCaml libraries to plug holes in the ecosystem. It also served to make us use OPAM on a day-to-day basis for our own work, thus creating an effective feedback loop between open-source and research.: The entire core team is focussed on fusing together the individual tools that have been created last year into a cohesive OCaml Platform release that covers the lifecycle of documentation, testing and build. This is being managed by Amir Chaudhry. OPAM remains at the heart of this strategy, and Louis Gesbert and Thomas Gazagnaire have settled on the OPAM 1.3 roadmap (summary). Multicore: KC Sivaramakrishnan has joined the core OCaml Labs fulltime to drive the multicore work into a publically testable form. Leo White recently departed after many productive years in Cambridge to head into a career in industry (but still remains very much involved with OCaml development!). and wider community for a wonderfully enjoyable 2014 and start of 2015, and am very thankful to the funding and support from Jane Street, Citrix, British Telecom, RCUK, EPSRC, DARPA and the EU FP7 that made it all possible. As always, please feel free to contact any of us directly with questions, or reach out to me personally with any queries, concerns or bars of chocolate as encouragement. Dec 2013 This time last year in 2012, I had just announced the formation of a new group called OCaml Labs in the Cambridge Computer Lab that would combine research and community work towards the practical application of functional programming. An incredible year has absolutely flown by, and I've put together this post to summarise what's gone on, and point to our future directions for 2014. The theme of our group was not to be pure research, but rather a hybrid group that would take on some of the load of day-to-day OCaml maintenance from INRIA, as well as help grow the wider OCaml community. To this end, all of our projects have been highly collaborative, often involving colleagues from OCamlPro, INRIA, Jane Street, Lexifi and Citrix. This post covers progress in tooling, the compiler and language, community efforts, research projects and concludes with our priorities for 2014. Tooling At the start of 2013, OCaml was in the interesting position of being a mature decades-old language with a small, loyal community of industrial users who built mission critical applications using it. We had the opportunity to sit down with many of them at the OCaml Consortium meeting and prioritise where we started work. The answer came back clearly: while the compiler itself is legendary for its stability, the tooling around it (such as package management) was a pressing problem. OPAM Our solution to this tooling was centered around the OPAM package manager that OCamlPro released into beta just at the end of 2012, and had its first stable release in March 2013. OPAM differs from most system package managers by emphasising a flexible distributed workflow that uses version constraints to ensure incompatible libraries aren't mixed up (important for the statically-typed OCaml that is very careful about dependencies). Working closely with OCamlPro we developed a git-based workflow to make it possible for users (both individual or industrial) to easily build up their own package repositories and redistribute OCaml code, and started curating the package repository. The results have been satisfying: we started with an initial set of around 100 packages in OPAM (mostly imported by the 4 developers), and ended 2013 with 587 unique packages and 2000 individual versions, with contributions from 160 individuals. We now have a curated central package repository for anyone to submit their OCaml code, several third-party remotes are maintained (e.g. the Xen Project and Ocsigen). We also regularly receive releases of the Core libraries from Jane Street, and updates from sources as varied as Facebook, Coherent PDF, to the Frenetic SDN research. A notable contribution from OCamlPro during this time was to clarify the licensing on the package repository to be the liberal CC0, and also to pass ownership to the OCaml organization on GitHub, where it's now jointly maintained by OCaml Labs, OCamlPro and anyone else that wishes to contribute. A lens into global OCaml code It's been quite interesting just watching all the varied code fly into the repository, but stability quickly became a concern as the new packages piled up. OCaml compiles to native code on not just x86, but also PowerPC, Sparc and ARM CPUs. We kicked off various efforts into automated testing: firstly David Sheets built the OCamlot daemon that would schedule builds across all the exotic hardware. Later in the year, the Travis service launched support for testing from GitHub pull requests, and this became the front line of automated checking for all incoming new packages to OPAM. A major headache with automated testing is usually setting up the right build environment with external library dependencies, and so we added Docker support to make it easier to bulk-build packages for local developer use, with the results of builds available publically for anyone to help triage. Unfortunately fixing the bugs themselves is still a very manual process, so more volunteers are always welcome to help out! We're going to be really seeing the rewards from all this effort as OCaml 4.02 development proceeds, since we can now adopt a data-driven approach to changing language features instead of guessing how much third-party code will break. If your code is in OPAM, then it'll be tested as new features such as module aliases, injectivity and extension points show up. Better documentation The venerable OCamlDoc tool has done an admirable job for the last decade, but is increasingly showing its age due to a lack of support for cross-referencing across packages. We started working on this problem in the summer when Vincent Botbol visited us on an internship, expecting it to be a quick job to come up with something as good as Haskell's excellent Haddock online documentation. Instead, we ran into the "module wall": since OCaml makes it so easy to parameterise code over other modules, it makes it hard to generate static documentation without outputting hundreds of megabytes of HTML every time. After some hard work from Vincent and Leo, we've got a working prototype that lets you simply run opam install opam-doc && opam doc core async to generate package documentation. You can see the results for Mirage online, but expect to see this integrated into the main OCaml site for all OPAM packages as we work through polishing up the user interface. Turning OPAM into libraries The other behind-the-scenes effort for OPAM has been to keep the core command-line tool simple and stable, and to have it install OCaml libraries that can be interfaced with by other tools to do domain-specific tasks. Thomas Gazagnaire, Louis Gesbert and David Sheets have been steadily hacking away at this and we now have opamfu to run operations over all packages, and an easy-to-template opam2web that generates the live opam.ocaml.org website. This makes OPAM easier to deploy within other organizations that want to integrate it into their workflow. For example, the software section of the OCaml Labs website is regularly generated from a search of all OPAM packages tagged ocamllabs. We also used it to rewrite the entire OPAM repository in one epic diff to add external library dependencies via a command-line shim. OPAM-in-a-Box All of this effort is geared towards making it easier to maintain reusable local OPAM installations. After several requests from big universities to help out their teaching needs, we're putting together all the support needed to easily redistribute OPAM packages via an "OPAM-in-a-Box" command that uses Docker containers to let you clone and do lightweight modifications of OCaml installations. This will also be useful for anyone who'd like to run tutorials or teach OCaml, without having to rely on flaky network connectivity at conference venues: a problem we've suffered from too! Core Compiler Starting to work on a real compiler can often be a daunting prospect, and so one initiative we started this year is to host regular compiler hacking sessions where people could find a curated list of features to work on, with the regular developers at hand to help out when people get stuck, and free beer and pizza to oil the coding wheels. This has worked out well, with around 20 people showing up on average for the three we held, and several patches submitted upstream to OCaml. Gabriel Scherer and Damien Doligez have been helping this effort by tagging junior jobs in the OCaml Mantis bug tracker as they are filed. Syntax transformations and extension points Leo White started the year fresh out of completing his PhD with Alan Mycroft, and before he realized what he'd gotten himelf into was working with Alain Frisch on the future of syntax transformations in OCaml. We started off our first wg-camlp4 working group on the new lists.ocaml.org host, and a spirited discussion started that went on and on for several months. It ended with a very satisfying design for a simpler extension points mechanism which Leo presented at the OCaml 2013 workshop at ICFP, and is now merged into OCaml 4.02-trunk. Namespaces Not all of the working groups were quite as successful in coming to a conclusion as the Camlp4 one. On the Platform mailing list, Gabriel Scherer started a discussion on the design for namespaces in OCaml. The resulting discussion was useful in separating multiple concerns that were intermingled in the initial proposal, and Leo wrote a comprehensive blog post on a proposed namespace design. After further discussion at ICFP 2013 with Jacques Garrigue later in the year, it turns out adding support for module aliases would solve much of the cost associated with compiling large libraries such as Core, with no backwards compatibility issues. This solution has now been integrated into OCaml 4.02.0dev and is being tested with Core. Delving into the bug tracker Jeremy Yallop joined us in April, and he and Leo also leapt into the core compiler and started triaging issues on the OCaml bug tracker. This seems unglamorous in the beginning, but there rapidly turned out to be many fascinating threads that shed light on OCaml's design and implementation through seemingly harmless bugs. Here is a pick of some interesting threads through the year that we've been involved with: - An unexpected interaction between variance and GADTs that led to Jacques Garrigue's talk at OCaml 2013. - Type unsoundness by pattern matching lazy mutable values, thus shedding light on the precise semantics of the order of pattern matching. - Leo proposed an open types extension to allow abstract types to be declared open. You can try it via opam switch 4.00.1+open-types. - Designing the popular, but controversial record disambiguation feature in OCaml 4.01.0, and debating the right warnings needed to prevent programmer surprise. - Exposing a GADT representation for Bigarray. This is just a sample of some of the issues solved in Mantis; if you want to learn more about OCaml, it's well worth browsing through it to learn from over a decade of interesting discussions from all the developers. Thread-local storage runtime While OCamlPro was working on their reentrant OCaml runtime, we took a different tack by adding thread-local storage to the runtime instead, courtesy of Stephen Dolan. This is an important choice to make at the outset of adding multicore, so both approaches are warranted. The preemptive runtime adds a lot of code churn (due to adding a context parameter to most function calls) and takes up a register, whereas the thread-local storage approach we tried doesn't permit callbacks to different threads. Much of this work isn't interesting on its own, but forms the basis for a fully multicore runtime (with associated programming model) in 2014. Stay tuned! Ctypes One other complaint from the Consortium members was quite surprising: the difficulty of using the OCaml foreign function interface safely to interface with C code. Jeremy Yallop began working on the ctypes library that had the goal of eliminating the need to write any C code at all for the vast majority of foreign bindings. Instead, Ctypes lets you describe any C function call as an OCaml value, and provides various linkage options to invoke that function into C. The first option he implemented was a dlopen interface, which immediately brought us the same level of functionality as the Python or Haskell Ctypes equivalents. This early code was in itself startlingly useful and more pleasant to use than the raw FFI, and various folk (such as David Sheets' libsodium cryptography bindings) started adopting it. At this point, I happened to be struggling to write the Foreign Function Interface chapter of Real World OCaml without blowing through our page budget with a comprehensive explanation of the existing system. I decided to take a risk and write about Ctypes instead, since it let new users to the language have a far more productive experience to get started. Xavier Leroy pointed out some shortcomings of the library in his technical book review, most notably with the lack of an interface with C. The design of Ctypes fully supports alternate linking mechanisms than just dlopen though, and Jeremy has added automatic C stub generation support as well. This means that if you use Ctypes to build an OCaml binding in 2014, you can choose several mechanisms for the same source code to link to the external system. Jeremy even demonstrated a forking model at OCaml 2013 that protects the OCaml runtime from the C binding via process separation. The effort is paying off: Daniel Bünzli ported SDL2 using ctypes, and gave us extensive feedback about any missing corner cases, and the resulting bindings don't require any C code to be written. Jonathan Protzenko even used it to implement an OCaml controlle r for the Adafruit Raspberry Pi RGB LCD! Community Efforts Our community efforts were largely online, but we also hosted visitors over the year and regular face-to-face tutorials. Online at OCaml.org While the rest of the crew were hacking on OPAM and OCaml, Amir Chaudhry and Philippe Wang teamed up with Ashish Agarwal and Christophe Troestler to redesign and relaunch the OCaml website. Historically, OCaml's homepage has been the caml.inria.fr domain, and the ocaml.org effort was begun by Christophe and Ashish some years ago to modernize the web presence. The webpages were already rather large with complex scripting (for example, the 99 Problems page runs the OCaml code to autogenerate the output). Philippe developed a template DSL that made it easier to unify a lot of the templates around the website, and also a Markdown parser that we could link to as a library from the rest of the infrastructure without shelling out to Pandoc. Meanwhile, Amir designed a series of interactive wireframe sketches and gathered feedback on it from the community. A local design agency in Cambridge helped with visual look and feel, and finally at the end of the summer we began the migration to the new website, followed by a triumphant switchover in November to the design you see today. The domain isn't just limited to the website itself. Leo and I set up a SVN-to-Git mirror of the OCaml compiler Subversion repository on the GitHub OCaml organization, which is proving popular with developers. There is an ongoing effort to simplify the core compiler tree by splitting out some of the larger components, and so camlp4 is also now hosted on that organization, along with OASIS. We also administer several subdomains of ocaml.org, such as the mailing lists and the OPAM repository, and other services such as the OCaml Forge are currently migrating over. This was made significantly easier thanks to sponsorship from Rackspace Cloud (users of XenServer which is written in OCaml). They saw our struggles with managing physical machines and gave us developer accounts, and all of the ocaml.org infrastructure is now hosted on Rackspace. We're very grateful to their ongoing help! If you'd like to contribute to infrastructure help (for example, I'm experimenting with a GitLab mirror), then please join the infrastructure@lists.ocaml.org mailing list and share your thoughts. The website team also need help with adding content and international translations, so head over to the website issue tracker and start proposing improvements you'd like to see. Next steps for ocaml.org The floodgates requesting features opened up after the launch of the new look and feel. Pretty much everyone wanted deeper OPAM integration into the main website, for features such as: - Starring and reviewing packages - Integrating the opam-doc documentation with the metadata - Display test results and a compatibility matrix for non-x86 and non-Linux architectures. - Link to blog posts and tutorials about the package. Many of these features were part of the original wireframes but we're being careful to take a long-term view of how they should be create d and maintained.Rather than building all of this as a huge bloated opam2web extension, David Sheets (our resident relucant-to-admit-it web expert) has designed an overlay directory scheme that permits the overlaying of different metadata onto the website. This lets one particular feature (such as blog post aggregation) be handled separately from the others via Atom aggregators. Real World OCaml A big effort that took up most of the year for me was finishing and publishing an O'Reilly book called Real World OCaml with Yaron Minsky and Jason Hickey. Yaron describes how it all started in his blog post, but I learnt a lot from developing a book using the open commenting scheme that we developed just for this. In particular, the book ended up shining a bright light into dark language corners that we might otherwise not have explored in OCaml Labs. Two chapters of the book that I wasn't satisfied with were the objects and classes chapters, largely since neither Yaron nor Jason nor I had ever really used their full power in our own code. Luckily, Leo White decided to pick up the baton and champion these oft-maligned (but very powerful) features of OCaml, and the result is the clearest explanation of them that I've read yet. Meanwhile, Jeremy Yallop helped out with extensive review of the Foreign Function Interface chapter that used his ctypes library. Finally, Jeremie Dimino at Jane Street worked hard on adding several features to his utop toplevel that made it compelling enough to become our default recommendation for newcomers. All in all, we ended up closing over 2000 comments in the process of writing the book, and I'm very proud of the result (freely available online, but do buy a copy if you can to support it). Still, there's more I'd like to do in 2014 to improve the ease of using OCaml further. In particular, I removed a chapter on packaging and build systems since I wasn't happy with its quality, and both Thomas Gazagnaire and I intend to spend time in 2014 on improving this part of the ecosystem. Tutorials and Talks We had a lively presence at ICFP 2013 this year, with the third iteration of the OCaml 2013 held there, and Stephen Dolan presenting a paper in the main conference. I liveblogged the workshop as it happened, and all the talks we gave are linked from the program. The most exciting part of the conference for a lot of us were the two talks by Facebook on their use of OCaml: first for program analysis using Pfff and then to migrate their massive PHP codebase using an OCaml compiler. I also had the opportunity to participate in a panel at the Haskell Workshop on whether Haskell is too big to fail yet; lots of interesting perspectives on scaling another formerly academic language into the real world. Yaron Minsky and I have been giving tutorials on OCaml at ICFP for several years, but the release of Real World OCaml has made it significantly easier to give tutorials without the sort of labor intensity that it took in previous years (one memorable ICFP 2011 tutorial that we did took almost 2 hours to get everyone installed with OCaml. In ICFP 2013, it took us 15 minutes or so to get everyone started). Still, giving tutorials at ICFP is very much preaching to the choir, and so we've started speaking at more general-purpose events. Our first local effort was FPDays in Cambridge, where Jeremy Yallop and Amir Chaudhry ran the tutorial with help from Phillipe Wang, Leo White and David Sheets. The OCaml session there ended up being the biggest one in the entire two days, and Amir wrote up their experiences. One interesting change from our ICFP tutorial is that Jeremy used js_of_ocaml to teach OCaml via JavaScript by building a fun Monty Hall game. Visitors and Interns Since OCaml Labs is a normal group within the Cambridge Computer Lab, we often host academic visitors and interns who pass through. This year was certainly diverse, and we welcomed a range of colleagues: - Mathias Bourgoin has just finished his work on interfacing OCaml with GPUs, and gave us a seminar on how his SPOC tool works (also available in OPAM via a custom remote). - Benjamin Canou (now at OCamlPro) practised his OCaml 2013 talk on building high-level interfaces to JavaScript with OCaml by giving a departmental seminar. - Roberto Di Cosmo, who directs the IRILL organization on Free Software in Paris delivered a seminar on constraint solving for package systems that are as large-scale as Debian's. - Thomas Gazagnaire visited during the summer to help plot the Mirage 1.0 and OPAM 1.1 releases. He has also since joined OCaml Labs fulltime to work on Nymote. - Louis Gesbert from OCamlPro visited for 2 weeks in December and kicked off the inaugral OPAM developers summit (which was, admittedly, just 5 developers in the Kingston Arms, but all good things start in a pub, right?) - Jonathan Protzenko presented his PhD work on Mezzo (which is now merged into OPAM), and educated us on the vagaries of Windows support. - Gabriel Scherer from the Gallium INRIA group visited to discuss the direction of OPAM and various language feature discussions (such as namespaces). He didn't give a talk, but promises to do so next time! - Benoît Vaugon gave a seminar on his OCamlCC OCaml-to-C compiler, talked about porting OCaml to 8-bit PICs, and using GADTs to implement Printf properly. We were also visited several times by Wojciech Meyer from ARM, who was an OCaml developer who maintained (among other things) the ocamlbuild system and worked on DragonKit (an extensible LLVM-like compiler written in OCaml). Wojciech very sadly passed away on November 18th, and we all fondly remember his enthusiastic and intelligent contributions to our small Cambridge community. We also hosted visitors to live in Cambridge and work with us over the summer. In addition to Vincent Botbol (who worked on OPAM-doc as described earlier) we had the pleasure of having Daniel Bünzli and Xavier Clerc work here. Here's what they did in their own words. Xavier Clerc: OCamlJava Xavier Clerc took a break from his regular duties at INRIA to join us over the summer to work on OCaml-Java and adapt it to the latest JVM features. This is an incredibly important project to bridge OCaml with the huge Java community, and here's his report: After a four-month visit to the OCaml Labs dedicated to the OCaml-Java project, the time has come for an appraisal! The undertaken work can be split into two areas: improvements to code generation, and interaction between the OCaml & Java languages. Regarding code generation, several classical optimizations have been added to the compiler, for example loop unrolling, more aggressive unboxing, better handling of globals, or partial evaluation (at the bytecode level). A new tool, namely ocamljar, has been introduced allowing post-compilation optimizations. The underlying idea is that some optimizations cannot always be applied (e.g. depending whether multiple threads/programs will coexist), but enabling them through command-line flags would lead to recompilation and/or multiple installations of each library according to the set of chosen optimizations. It is thus far more easier to first build an executable jar file, and then modify it according to these optimizations. Furthermore, this workflow allows the ocamljar tool to take advantage of whole-program information for some optimizations. All these improvements, combined, often lead to a gain of roughly 1/3 in terms of execution time. Regarding language interoperability, there are actually two directions depending on whether you want to call OCaml code from Java, or want to call Java code from OCaml. For the first direction, a tool allows to generate Java source files from OCaml compiled interfaces, mapping the various constructs of the OCaml language to Java classes. It is then possible to call functions, and to manipulate instances of OCaml types in pure Java, still benefiting from the type safety provided by the OCaml language. In the other direction, an extension of the OCaml typer is provided allowing to create and manipulate Java instances directly from OCaml sources. This typer extension is indeed a thin layer upon the original OCaml typer, that is mainly responsible for encoding Java types into OCaml types. This encoding uses a number of advanced elements such as polymorphic variants, subtyping, variance annotations, phantom typing, and printf-hack, but the end-user does not have to be aware of this encoding. On the surface, the type of instances of the Java Object classes is java'lang'Object java_instance, and instances can be created by calling Java.make Object(). While still under heavy development, a working prototype is available, and bugs can be reported. Finally, I would like to thank the OCaml Labs for providing a great working environment. Daniel Bünzli: Typography and Visualisation Daniel joined us from Switzerland, and spent some time at Citrix before joining us in OCaml Labs. All of his software is now on OPAM, and is seeing ever-increasing adoption from the community. Released a first version of Vg [...] I'm especially happy about that as I wanted to use and work on these ideas since at least 2008. The project is a long term project and is certainly not finished yet but this is already a huge step. Adjusted and released a first version of Gg. While the module was already mostly written before my arrival to Cambridge, the development of Vg and Vz prompted me to make some changes to the module. [...] released Otfm, a module to decode OpenType fonts. This is a work in progress as not every OpenType table has built-in support for decoding yet. But since it is needed by Vg's PDF renderer I had to cut a release. It can however already be used to implement certain simple things like font kerning with Vg, this can be seen in action in the vechobinary installed by Vg. Started to work on Vz, a module for helping to map data to Vg images. This is really unfinished and is still considered to be at a design stage. There are a few things that are however well implemented like (human) perceptually meaningful color palettes and the small folding stat module ( Vz.Stat). However it quickly became evident that I needed to have more in the box w.r.t. text rendering in Vg/Otfm. Things like d3js entirely rely on the SVG/CSS support for text which makes it easy to e.g. align things (like tick labels on such drawings). If you can't rely on that you need ways of measuring rendered text. So I decided to suspend the work on Vz and put more energy in making a first good release of Vg. Vz still needs quite some design work, especially since it tries to be independent of Vg's backend and from the mechanism for user input. Spent some time figuring out a new "opam-friendly" release workflow in pkgopkg. One of my problem is that by designing in the small for programming in the large --- what a slogan --- the number of packages I'm publishing is growing (12 and still counting). This means that I need to scale horizontally maintenance-wise unhelped by the sad state of build systems for OCaml. I need tools that make the release process flawless, painless and up to my quality standards. This lead me to enhance and consolidate my old scattered distribution scripts in that repo, killing my dependencies on Oasis and ocamlfind along the way. (edited for brevity, see here) Daniel also left his bicycle here for future visitors to use, and the "Bünzli-bike" is available for our next visitor! (Louis Gesbert even donated lights, giving it a semblance of safety). Industrial Fellows Most of our regular funding bodies such as EPSRC or EU FP7 provide funding, but leave all the intellectual input to the academics. A compelling aspect of OCaml Labs has been how involved our industrial colleagues have been with the day-to-day problems that we solve. Both Jane Street and Citrix have senior staff regularly visiting our group and working alongside us as industrial fellows in the Computer Lab. - Mark Shinwell from Jane Street Europe has been working on improving the state of native debugging in OCaml, by adding extended DWARF debugging information to the compiler output. Mark is also a useful source of feedback about the forthcoming design of multicore, since he has daily insight into a huge production codebase at Jane Street (and can tell us about it without us requiring access!). - Dave Scott is the principal architect of XenServer at Citrix in Cambridge. This year has been transformative for that project, since Citrix open-sourced XenServer to GitHub and fully adopted OPAM into their workflow. Dave is the author of numerous libraries that have all been released to OPAM, and his colleagues Jon Ludlam and Euan Harris are also regular visitors who have also been contributors to the OPAM and Mirage ecosystems. Research Projects The other 100% of our time at the Labs is spent on research projects. When we started the group, I wanted to set up a feedback loop between local people using OCaml to build systems, with the folk developing OCaml itself. This has worked out particularly well with a couple of big research projects in the Lab. Mirage Mirage is a library operating system written in OCaml that compiles source code into specialised Xen microkernels, developed at the Cambridge Computer Lab, Citrix and the Horizon Digital Economy institute at Nottingham. This year saw several years of effort culminate in the first release of Mirage 1.0 as a self-hosting entity. While Mirage started off as a quick experiment into building specialised virtual appliances, it rapidly became useful to make into a real system for use in bigger research projects. You can learn more about Mirage here, or read the Communications of the ACM article that Dave Scott and I wrote to close out the year. This project is where the OCaml Labs "feedback loop" has been strongest. A typical Mirage application consists of around 50 libraries that are all installed via OPAM. These range from device drivers to protocol libraries for HTTP or DNS, to filesystems such as FAT32. Coordinating regular releases of all of these would be near impossible without using OPAM, and has also forced us to use our own tools daily, helping to sort out bugs more quickly. You can see the full list of libraries on the OCaml Labs software page. Mirage is also starting to share code with big projects such as XenServer now, and we have been working with Citrix engineers to help them to move to the Core library that Jane Street has released (and that is covered in Real World OCaml). Moving production codebases this large can take years, but OCaml Labs is turning out to be a good place to start unifying some of the bigger users of OCaml into one place. We're also now an official Xen Project incubator project, which helps us to validate functional programming to other Linux Foundation efforts. Nymote and User Centric Networking The release of Mirage 1.0 has put us on the road to simplifying embedded systems programming. The move to the centralized cloud has led to regular well-publicised privacy and security threats to the way we handle our digital infrastructure, and so Jon Crowcroft, Richard Mortier and I are leading an effort to build an alternative privacy-preserving infrastructure using embedded devices as part of the User Centric Networking project, in collaboration with a host of companies led by Technicolor Paris. This work also plays on the strong points of OCaml: it already has a fast ARM backend, and Mirage can easily be ported to the new Xen/ARM target as hardware becomes available. One of the most difficult aspects of programming on the "wide area" Internet are dealing with the lack of a distributed identity service that's fully secure. We published our thoughts on this at the USENIX Free and Open Communications on the Internet workhsop, and David Sheets is working towards a full implementation using Mirage. If you're interested in following this effort, Amir Chaudhry is blogging at the Nymote project website, where we'll talk about the components as they are released. Data Center Networking At the other extreme from embedded programming is datacenter networking, and we started the Network-as-a-Service research project with Imperial College and Nottingham. With the rapid rise of Software Defined Networking this year, we are investigating how application-specific customisation of network resources can build fast, better, cheaper infrasructure. OCaml is in a good position here: several other groups have built OpenFlow controllers in OCaml (most notably, the Frenetic Project), and Mirage is specifically designed to assemble such bespoke infrastructure. Another aspect we've been considering is how to solve the problem of optimal connectivity across nodes. TCP is increasingly considered harmful in high-through, high-density clusters, and George Parisis led the design of Trevi, which is a fountain-coding based alternative for storage networking. Meanwhile, Thomas Gazagnaire (who joined OCaml Labs in November), has been working on a branch-consistent data store called Irminsule which supports scalable data sharing and reconciliation using Mirage. Both of these systems will see implementations based on the research done this year. Higher Kinded Programming Jeremy Yallop and Leo White have been developing an approach that makes it possible to write programs with higher-kinded polymorphism (such as monadic functions that are polymorphic in the monad they use) without using functors. It's early days yet, but there's a library available on OPAM that implements the approach, and a draft paper that outlines the design. Priorities for 2014 This year has been a wild ride to get us up to speed, but we now have a solid sense of what to work on for 2014. We've decided on a high-level set of priorities led by the senior members of the group: - Multicore: Leo White will be leading efforts in putting an end-to-end multicore capable OCaml together. - Metaprogramming: Jeremy Yallop will direct the metaprogramming efforts, continuing with Ctypes and into macros and extension points. - Platform: Thomas Gazagnaire will continue to drive OPAM development towards becoming the first OCaml Platform. - Online: Amir Chaudhry will develop the online and community efforts that started in 2013. These are guidelines to choosing where to spend our time, but not excluding other work or day-to-day bugfixing. Our focus on collaboration with Jane Street, Citrix, Lexifi, OCamlPro and our existing colleagues will continue, as well as warmly welcoming new community members that wish to work with us on any of the projects, either via internships, studentships or good old-fashioned open source hacking. I appreciate the whole team's feedback in editing this long post into shape, the amazing professorial support from Jon Crowcroft, Ian Leslie and Alan Mycroft throughout the year, and of course the funding and support from Jane Street, Citrix, RCUK, EPSRC, DARPA and the EU FP7 that made all this possible. Roll on 2014, and please do get in touch with me with any queries! Jun 2013 The rain continues to plummet down relentlessly as "summer" starts in OCaml Labs. The most exciting news has been the public release of the Real World OCaml, which hit the front page of the usual news aggregators and generated huge interest! This (reminiscent of the Xen 1.0 release) promptly took down servers for a couple of hours, but we managed to minimise downtime in time for the Californians waking up. O'Reilly has also started selling PDF copies of the book under their Rough Cuts program. This gives you a copy of the final book when it's released too. Commenting is still open on the online version, so please do feel free to participate there if you have time. Systems Projects Mirage: Anil and Dave did the last of the sweeping build changes to make Mirage friendlier to use for beginners. Previously, we required a custom OPAM switch to build kernels, but now we use virtual packages to separate the choice of compiler and packages. This of course breaks all our documentation, but we're going to do a big sweep in July before OSCON with the new scheme. Vincent has also been burning through the core platform libraries, cleaning them up and adding documentation strings. He is also building a shared memory vchan driver that will make parallel-Mirage unikernels very easy to coordinate on the same host. The huge news from our friends at Citrix is the open-sourcing of XenServer, which is the popular Citrix product that embeds the OCaml XAPI cloud management stack. There are almost 100 major components released as part of this, several of which can be directly reused with Mirage. Mirage was always an ambitious project, but it's all coming together now thanks to bold moves such as this from Citrix! Signpost: We woke up to the excellent but slightly scary news that our USENIX FOCI paper was accepted. This now means that we get to present it in August at USENIX Security, but the team is now racing to pull together the prototypes into a complete system before the conference. Nothing like a deadline to focus the mind! We're also working on the camera-ready version of the paper, which we will share here when it's ready. Platform Projects OCamlot: David Sheets did an astounding job at pulling together a working continuous build system in a very short amount of time, and promptly managed to melt some of the older non-x86 machines in Anil's office. Once Anil sadly replaced them, the builder churned through a matrix of different compiler versions (4.0,4.1dev,4.2dev), architectures (x86, x86_64, ARM, PowerPC), and operating systems (Debian, Ubuntu, FreeBSD, OpenBSD to start with). There's a development URL, but the next step is to retire this and move it to a proper home at ocaml.org. Having continuous build for OPAM is really, really useful though, as it lets us vet pull requests on several architectures before merging them. It also let Anil repair OCaml on OpenBSD/macppc too, which is possibly the most obscure fix he's done in a while. The next steps with OCamlot are to take a shot at porting the core to Jenga, which is Jane Street's next-generation distributed build system. This should let us improve the fault-tolerance and logging aspects of it before putting it properly into production later in the summer. Ctypes: The May release brought with it a good chunk of feedback, so Jeremy spent time incorporating that and contributing to the Real World OCaml ctypes chapter. He also added support for garbage-collecting closures passed to C, and also very cool support for printing C types and values. Our friends at Citrix have started looking at ctypes, and Rob Hoes has already used it to write bindings to the Netlink Protocol Library Suite. OPAM-doc: Vincent Botbol got the documentation generator stable enough to pass the Core library through. This is particularly challenging since Core exercises pretty much every trick in the book when it comes to the use of the module system. However, Vincent successfully demonstrated the workflow of OPAM-doc at the end-of-month meeting, and is aiming to have a public release via OPAM in July (hopefully in time for the next beta release of Real World OCaml, which uses Core heavily). Visualisation libraries: Daniel Bünzli has been spending a few months based in Citrix, working on a foundational new declarative drawing library written in pure OCaml. The Vg is already quite functional despite still being in beta, and features a Javascript backend that renders to both SVG and Canvas in HTML5. That's not all though! He's also developing the Vz visualization library that uses Vg to assemble more complex scenes and graphs. Daniel's going to join us in OCaml Labs for the remainder of the summer, so we're looking forward to developing this more and using it on our various Platform projects such as OCamlot. Outreach Real World OCaml: As mentioned earlier, the beta release of RWO went splendidly, with a pleasing vibe that the book is what people expected. There were some interesting criticisms of the choice of Github authentication, but we've had over 6000 registered commentators despite this (and of course, we have plans brewing to tackle the identity problem). No beta release is perfect, of course, and our now-public commenting system has resulted in over 1500 issues being raised. Well, that's all of Yaron, Anil and Jason's free time gone for some time! OCaml.org: We're in the process of looking at the site as a whole and designing the workflow we'd like to have for growing and maintaining it. Some discussions have taken place about using Markdown in place of the current HTML snippets, which would make it easier for external contributors to get involved. In the meantime, Amir has converted the current site to Markdown format to see how this process would work in practice. You can see his experimenting and scripts in the temporary repo in the markdown-site/ folder. Philippe also showed off MPP at the internal meetings, and is stabilising it for a public release this summer (once it has been integrated into the ocaml.org workflow). This month also had a number of programming language gurus show up at the Lab for the Algebraic Effects and Handlers workshop organised by Sam Staton. Most of the group attended this, as we're all interested in how to encode effects for several of our projects (most notably Irminsule). We also enjoyed a visit by Benoît Vaugon, who gave a talk on his OCamlCC OCaml-to-C compiler, and also participated in a talk on OCAPIC. He also chatted with us about his alternative GADT-based implementation of Printf, which promises to both speed up and simplify the printer support in OCaml (and also relieve Mirage of another dependency on libc). Link roundup: - XenServer open-sourced! (Jun 25th) - Real World OCaml public beta now available. (Jun 17th) May 2013 May is exam time in Cambridge, and the corridors of the OCaml Labs resounded with the wailing of frantic students finishing their dissertations and preparing for exams. We welcomed Vincent Botbol to join us for a summer internship, and he started hacking on the new opam-doc right away. Anil, Thomas, Leo and Amir also visited Jane Street HQ in New York City, where we had a productive couple of days reviewing our projects and getting feedback from them about approaches to multicore and type system enhancements. Ashish Agarwal also organised a fun evening with the New York OCaml Users Group, where Anil and Thomas presented our plans for the nascent OCaml Platform. Systems Projects Mirage: This was a month of consolidation and bugfixing in Mirage. We've been settling into weekly meetings to coordinate the hacking between us and Citrix, and the minutes (1 2 3) may be useful if you want to catch up. The biggest bugbear is always the build system, and we've been exploring the use of Jenga as the eventual async-aware coordination and build system for running Mirage kernels. Dave made great progress with a message-switch that coordinates multiple kernels, and Balraj fixed several performance regressions in the TCP/IP stack by building unit tests that spawn millions of parallel TCP connections. Signpost: We took a break from building prototypes to submit a paper on the basic design to the USENIX Free and Open Communications (FOCI 2013) workshop. Haris and Heidi blazed a path on writing this paper, and we've got even more ideas rolling around about how to use DNSSEC to break the cloud deadlock. The ocaml-dns continues to grow features too. Platform Projects Ctypes: Jeremy announced the first release of a new foreign-function mechanism for OCaml that doesn't require you to write any C stubs at all! You can browse the source code and tutorial, and install it via OPAM. This is very much the first 0.1 release, and we have exciting future developments to turn this into a full-fledged replacement for the fast-but-rather-difficult-to-use-right OCaml FFI. OPAM-doc: Vincent Botbol started building on Leo's work on the new opam-doc tool. This is intended to replace the venerable ocamldoc with one that uses all the latest features of the compiler. In particular, it can use the new typed AST cmt output to avoid duplicating the compiler functionality, and can also build up a global package table to generate complete cross-references across an entire OPAM collection. OCamlot: David has been building up the libraries and tools needed for the continuous build infrastructure. This includes much-improved ocaml-github, bindings, which are now being used to power the Real World OCaml site as well as well as OCamlot. In addition, he's got an interesting collection of regular expressions to automatically triage common failures from OPAM (such as missing external dependencies), that should help reduce the manual burden of getting thousands of tests results dumped on the small OPAM team. Compiler Projects OCaml-Java: Xavier Clerc has been hacking away at his next-generation OCaml-Java backend (using many new features in JDK7). He's released a preview of the bindings to Java concurrency, and is looking for feedback on it. Performance profiling: Mark Shinwell has been hacking on improving the integration of the runtime with perf. This should give us the hooks to reliably track where memory was allocated. His branch isn't going to land in OCaml 4.1, but should be available as an OPAM switch for people to easily try out when it's more stable. Outreach OCaml.org: Philippe and Amir have been putting their heads together with Christophe and Ashish to turn the ocaml.org build pipeline into something a little more structured. Philippe is building a template processor for this purpose. The OCaml site is a more complicated than the average site due to our desire to embed js_of_ocaml interactive toplevels throughout the tutorials, and also to have active OPAM integration throughout the site to make it easier for newcomers to sample the language. The design of a handful of pages are also now available to preview, if you don't mind some manual git cloning. The best way to do this is to clone the temporary repo onto your local machine and look in the new-design/_site directory. There are examples of the home page, 100 lines of OCaml page and several others. Since we're just getting started with applying these changes the site isn't clicky (yet). For some extra fun, try resizing your browser window and see how the pages reflow to suit smaller (mobile) screens! Real World OCaml: Anil, Yaron and Jason continue to work hard on getting a release out of the door. We shipped a final alpha6 this month that is chapter-complete, and have been preparing for a big public June release of the book. Thousands of comments have been received and closed already, making this an unusually active (but incredibly useful) ongoing review process. Leo and Jeremy also contributed portions of text for the Objects and FFI chapters in alpha6, and join Stephen Weeks as external contributors to the book. Meanwhile, Leo himself has recovered from the elation of being granted his PhD, to the harsh reality of having to finish corrections. He has been forced by his colleagues to stop hacking on OCaml and submit his final thesis. Rumours are that he will reemerge in June after delivering his SAS 2013 talk on using an implication-algebra generalisation of logic programming to concisely analyse OpenMP programs for parallisation opportunities. This month's talk was courtesy of Mathias Bourgoin, who visited from France and gave a talk on his PhD work on GPU processing. His tool, SPOC has been released onto OPAM and is a set of easy-to-use tools for generating CUDA and OpenCL code, and also a camlp4 extension to write external kernels directly in OCaml. Thanks for visiting, Mathias! Apr 2013 It's been a heads-down month of hacking at the Labs for April, as the group have settled into their projects and are concentrating on getting code out. We did take the opportunity to redesign the project pages as the active projects grew. We welcomed Euan Harris as a new visitor, and he has begun work on a distributed actor library in the vein of Erlang's OTP. The prolific Daniel Bünzli also joined us for the summer to work on his Vg visualisation library. He's based out of the Citrix offices, and is also contributing to the Xen project. Platform projects OPAM: The project has entered a bug fixing stage after its release, and the package set has steadily grown via external contributors. David Sheets has been hacking away on the automated OCamlot bot, and we released improved Github API bindings. We're aiming to get OCamlot live and running in May, so stay tuned! There is a steadily growing collection of odd ARM and PowerPC devices in Anil's desk that will generally make it easier to test your OCaml code in unusual environments. OCaml.org redesign: Progress on the website continues and we're now working on the actual HTML/CSS from the earlier mockups. We'll be publishing these in a fork of the website repository, so do feel free to create issues there with your comments. Philippe has begun the MPP templating tool to glue together all the website scripts more coherently. Discussions about this take place on the infrastructure mailing list, which is open to all. The monthly OCaml get togethers in the Cambridge Makespace are also really fun. This month saw around 30 people wander through the doors, and work through the latest excerpts of Real World OCaml. And around midnight, Jeremy and Leo competed to find more and more obscure bugs in the corners of the OCaml type system... You can track the subsequent meetups via the NonDysFunctional Meetup group, which includes functional programmers from around the Cambridgeshire area. Jon and Anil also attended the Yahoo Hackday in London, where Jon met a giant robot and started SSL bindings, and Anil experimented with js_of_ocaml LocalStorage for Irminsule. Systems projects Mirage: We've finally got a release date for the first preview of Mirage, which will be at O'Reilly OSCON this July! Pulling together the release is a big endeavour, and the team has started weekly calls to work through the project. The minutes for these are online, so you can browse them to catch up. There's also a slightly scary checklist of all the libraries that need to be released before July, so the team has its work cut out for it! The Xen group also announced that it is joining the Linux Foundation, and the press release gave Mirage a prominent mention as one of the key recent developments in Xen. Irminsule: Thomas now has a full implementation of the git file format in his cagit repository, and the interfaces for Irminsule's branch-consistent model are coming together. He gave a demo to the Mirage team, with discussion notes available. Compiler projects Multicore and Concurrency: Stephen Dolan's made great progress on bringing up a multicore runtime using thread-local storage, which results in a surprisingly compact diff to the OCaml runtime. We're now moving onto the higher-level bindings to use the parallel runtimes effectively from within OCaml. We also began a wg-parallel working group in order to start figuring out the evolution of the Lwt and Async concurrency libraries. libffi: Jeremy got frustrated by the difficulty of writing safe C bindings, and started the ctypes library, which offers a pure OCaml solution. This even includes managing callbacks across the OCaml/C divide, and uses libffi under the hood to remain efficient and platform-independent. There is the exciting possibility about hooking this library with the compile-time metaprogramming to eliminate all performance cost, so we're going to spend some time on this project to make it a well-documented alternative to the existing C FFI. The OCaml Labs talk series continued with a visit from Francois Pottier ad Jonathan Protzenko from the INRIA Gallium research team. Jonathan presented their Mezzo language, which places emphasis on aliasing and controlled access to mutation. This is of particular interest to several of our systems projects that do not require the full power of OCaml to build low-level systems components, and Raphael, Alan, Leo and Anil had productive discussions about how we could try Mezzo out when it's released. Link roundup: - Xen and MirageOS to join Linux Foundation (Apr 14th) - OCaml Hacking/Meetup Session (Apr 18th) - OSCon Mirage talk selected. (Apr 21st) Mar 2013 The OCaml Labs hackers continue to arrive, with David Sheets arriving from sunny San Francisco, and Xavier Clerc visiting from the less-sunny INRIA in France. David's done great work on several OCaml libraries such as Cohttp and on WebGL, and he's diving straight into a first release of OCamlot before starting his PhD later in the year. Xavier will work on releasing his OCaml Java 2.0 rewrite this summer, which takes advantage of all the latest JDK features for non-Java languages. A new research grant has also been awarded to Jon Crowcroft. The Hub of All Things is a £1.2m multi-disciplinary project funded by the RCUK Digital Economy Programme and led by Irene Ng in Warwick. HAT aims to create a home platform, under the user's control, where a market to exchange their personal data for new products and personalised services could exist. The Cambridge piece of this work will use Mirage for embedded systems programming, and Signpost, to enable devices to connect and communicate with each-other across the edge network. Platform projects OPAM: OPAM, the popular OCaml Package Manager, recently had its 1.0 release! OPAM has been in development for just over a year, and this is a significant milestone for the project. The OPAM package repository has had over 500 issues, closed over 400 pull requests and now contains over 450 packages (and more than twice that number if you consider that multiple versions are available). This kind of user adoption is a fantastic sign for the OCaml community. We're very happy to be using OPAM as a key piece of the upcoming OCaml Platform and the continuous integration and test system. OCaml.org redesign: Amir extended the Balsamiq mockups into more realistic static site designs that can be found on the wiki. We're building on the theme we began with the OCaml Logo, but also including the full functionality we want for the revamped site. The samples should give people an idea of the colour schemes and images we'll be using, and feedback is very welcome. Next, we're creating the HTML/CSS templates we need to make these mockups a reality. OCamlot: Within hours of getting off the plane, David was already getting well into the OCaml-based test tool and working on the pieces we need to get to a usable first version. The OCamlot workflow was last described in Amir's Balsamiq mockups in case you want to catch up. This work is made all the more important as Jane Street continues to demonstrate their strong commitment to open-source by sending in OPAM pull requests every week for new releases of their libraries. The testing for these releases is currently handled manually and we're really looking forward to having them dealt with automatically! Systems projects Mirage: There is much preparation ongoing for the big xen.org incubation, which has now been approved by the Xen community board. Vincent's work on Mirari is going very well, and he's updated the Mirage installation instructions to use Mirari instead of the manual process required before. Anil and Mort also attended and presented the ASPLOS 2013 paper in Houston. For the curious, Ben's Beans is the only good coffee we could find suitable for a European in Texas. Irminsule: Now that the core of Mirage is heading for release, the team is turning their attention to the storage and distributed programming challenge. Thomas and Anil have been working on a new policy-free, branch-consistent storage layer that exposed a raw git-like universe to Mirage applications. We're working on as part of the Trilogy2 that's investigating how to improve the reliability of congested datacenters. Signposts: Heidi gave an excellent talk about Signpost and the benefits it can offer internet users today (see right). This was one of a set of talks that took place in the Computer Lab, organised by Alan Mycroft, on open software and open hardware with speakers such as Jon 'maddog' Hall of Linux International. There was fairly unanimous agreement that Heidi's slides were better than Anil's. Compiler projects Multicore: Once the dreaded ICFP deadline was out of the way, Stephen, Leo, Raphael and Anil put their heads together to start architecting the support for parallel multicore support in the OCaml runtime. A key part of the design space is to maintain the sequential performance and simplicity of the existing runtime, but still make it easy to extend shared memory onto different cores. We'll have more details on this shortly when early prototypes are done and some benchmarks run. Namespaces: Leo's also been extremely busy in the platform mailing list, which has been the location for the discussion of namespaces. A few hundred emails have been exchanged on this topic and Leo has summarised the discussion and made proposals in his blog post about OCaml namespaces. Although this is a complex issue, aspects of namespaces will be important to the work on the OCaml Platform so we look forward to the outcome of these discussions. Link roundup: - OPAM 1.0 Released! (Mar 14th) - Wireframe demos for OCaml.org (Mar 14th) - Adding namespaces to OCaml (Mar 10th) Feb 2013 Two new people joined the core team at Cambridge: Jeremy Yallop and Philippe Wang! Jeremy has extensive expertise with meta-programming and generic programming, and is initially looking at the camlp4 redesign. Philippe has been taking on the challenge of running OCaml well on restricted embedded systems, which will also have knock-on benefits to x86 compilation with the same optimisations. Xavier Clerc also joined us for a day in advance of his visit in April, with much interest in his Argot project and the upcoming redesign of OCaml.org. Two new research grants have been awarded that are relevant to the OCaml Labs mission: - Network-as-a-Service is a 3-year grant to solve pressing problems in "Big Data" processing, and will enable us to continue to develop MirageOS and the use of OCaml and functional programming in this space. We're going to be collaborating with Imperial and Nottingham on this, with the Cambridge efforts led by Andrew Moore, Jon Crowcroft and Anil Madhavapeddy. - Rigorous Engineering of Mainstream Systems asks how we can use rigorous maths to improve the quality of mainstream computer systems. It is led by Peter Sewell at Cambridge, and most of the tools (including Ott and Lem) are written in OCaml and will benefit from the ongoing work at OCaml Labs. Platform projects OPAM: We've been working hard on an OPAM 1.0 release, and Thomas and Anil have been sweeping through the package tree to stabilise the repository via automated builds. We also had a brilliant visit from Roberto Di Cosmo from PPS, who has contributed extensively to the open-source community over the years. He gave a talk on the challenges of handling large-scale versioning of packages from a mathematical perspective (particularly applied to Debian), which is very useful input for the ongoing OPAM work. Mailing lists: A new opengl@lists.ocaml.org was set up for those interested in OpenGL and WebGL on OCaml, and discussion so far has covered LabGL on the Raspberry Pi. There are also still plans to begin working groups for build systems and parallelism but will be announced in due course once the preparatory work has been completed. Real World OCaml: The book is now on alpha3, where Part 1 is nearly complete. New sections on installation and a more expanded prologue have also been included in this version. Redesign: As part of the redesign work, and to showcase the kind of additional functionality we'd like to create, Amir put together a set of screencasts that talk though a wireframe demo of the new site. These short videos covered elements of design, the new documentation system and an overview of how the continuous integration system would work. You can read more and experience the clickable demo via Amir's blog post. Systems and compiler projects Mirage: Anil gave two tech talks about Mirage this month at Citrix and Microsoft Research, as practise talks for ASPLOS 2013. Mirage itself is nearing a release, and Vincent Bernardoff has joined the Citrix engineering team to help drive it to release. He's been primarily focussed on the build frontend (dubbed Mirari) to make Mirage applications easier to compile out-of-the-box. camlp4 redesign: There has been more discussion about the future of camlp4 and Leo posted another summary on his thoughts for an alternative apporach to quotations. Link roundup: - An alternative to camlp4 - Part 2 (Feb 5th) Jan 2013 There's a lot of interest in the work we're doing, and the number of collaborative projects is increasing fast. We held the first monthly meeting in the Computer Lab, where Anil provided an overview of the research work that OCaml Labs is starting. An interesting theme of the discussion that followed was related to undergraduate teaching and how things like the OCaml Platform and infrastructure would make it easier for students to get to grips with programming. For the evening after the meeting, Amir set up an informal OCaml hacking/tutorial session in Cambridge. Around 15 eager people attended the event in Makespace (a community workshop), with most of them being new to the language. Anil introduced Real World OCaml and shared the introductory chapters while Thomas provided help with OPAM. This turned out to be a great test of the installation process for newcomers to OCaml, as well as the book's instructions. A number of issues came to light, partly related to a perfect storm of package issues, which everyone is keen to improve. Despite these problems, attendees were very positive and were keen to see more gatherings like this in future. When Amir asked for feedback, pretty much everyone commented on how great the pizza was. Platform projects OCaml Labs also hosted its first visitor this month as Thomas Gazagnaire, the CTO of OCamlPro, spent three weeks in Cambridge. Much effort was put into preparing Mirage for release, discussions about parallelism and the OCaml Platform, and anything where OPAM is a crucial component. Worth noting is that (at time of writing) the opam-repository has now become the overall most forked OCaml project on Github. The Platform mailing list has also been formed for discussion regarding the OCaml Platform. Anyone interested in the discussions about the platform, which will include development on OPAM, should join this list. Part of the Platform work involves creating a new design for OCaml.org, which also kicked-off this week. Amir will keep people updated about progress via updates to the OCL website, Infrastructure mailing list and also by posting things to the OCaml.org Github wiki. The current stage of work involves thinking of the types of pages OCaml.org requires, in order to refine the templates we need. As part of this, we also commissioned a new logo for OCaml and although it's still under development, you can see the latest draft on the OCaml.org wiki. Please send any feedback directly to Amir. The Real World OCaml book website was released as a limited alpha earlier in the month, with the aim of getting early feedback and comments. Each paragraph of the online book has commenting functionality, using Github issues as a backend. This means that each comment made on the book website creates a new issue on Github, which authors/commenters can track and discuss before editing the content. So far there have been over 250 comments on the alpha, with half them being dealt with already. A new EU project also kicked-off called Trilogy 2, which builds on the award-winning work from the original Trilogy project. OnApp (a member of Trilogy 2), will be providing the cloud Infrastructure for ocaml.org, and Thomas and Anil will be expanding the Mirage project into distributed computing under this umbrella. As befits an EU project, it kicked off with an especially nice dinner at Christ's College... Systems research Mirage: This was formally proposed as an incubated Xen.org project and the proposal was put forward for community review. There were many positive comments on the Xen mailing lists (along the lines of "Mirage is cool stuff") and voting is currently underway by eligible members of the Xen community. Assuming a positive outcome, incubation would give the Mirage project greater visibility and access to resources. This would accelerate progress towards an alpha release in Q1/Q2 this year. In addition to this, a proposal for an OSCON talk was also submitted and the camera-ready version of the ASPLOS paper is now available. Illuminate: A related research topic where Mirage could be useful is in embedded systems and the Internet of Things. One specific use case is the Illuminate Project, where Mirage can be used to create appliances running on the ARM microcontrollers alongside an LED lighting network. Such a lighting system is now deployed in large parts of the Computer Laboratory and will form an excellent test-bed to explore these ideas further. Signpost:: Signpost is also achieving greater outreach with Jon Crowcroft discussing such technologies at a meeting in Dagstul on Decentralized Systems for Privacy Preservation. Cambridge also hosted Eric Schmidt from Google, where he is the Humanitas Visiting Professor in Media for 2013. Eric delivered a talk on the future of conflict, combat and intervention. Anil and Jon got an opportunity to discuss Signposts with him for 20 minutes, which was an interesting clash of opinions (we want decentralised identity, Google want it all to go through them). Either way, we're even more motivated to get the Signpost tech out to the big bad world as soon as possible. Meanwhile, Haris found his identical twin brother in St Johns Masters Lodge... Compiler projects Several mailing lists are in progress for various community-driven projects. The first of these is a working group on the future of syntax extensions in OCaml (wg-camlp4). This group is chaired by Alain Frisch and Leo White and has generated a great deal of discussion in the last two weeks. Leo is summarising his thoughts in a series of blog posts as he goes. Further working groups on parallelism in OCaml and build systems are under discussion and will be announced in due course. As well as all the research and development activity we've also been recruiting. We've had several rounds of interviews and made a number of offers so hopefully we'll be announcing new members of the OCaml Labs team in the coming months. In addition, we'd also like to mention that Leo successfully defended his PhD Thesis in January. Finally, we'd like to welcome a new honorary member of OCaml Labs, Nathan Scott, born on 30th January. Congratulations Dave! Link roundup: - An alternative to camlp4 - Part 1 (Jan 23rd) Dec 2012 OCaml Labs kicked-off with an internal meeting of the Cambridge-based members, who battled endless snow to make it to the meeting. There are over 20 people involved just within the building and over 30 including those outside the University. We welcomed a few new members, including Leo White (Postdoc), Raphael Proust (PhD student) and Stephen Dolan (PhD student). At this initial gathering Anil talked over some of the projects that were already taking place in the Lab, as well as the new work that would be supported by OCaml Labs. Significant progress was made on the research side too. Mirage has had a flurry of new releases as we prepare for a first public release, and we're in the final stages of being officially incubated as a xen.org project. Signpost is also taking shape, mainly due to the addition of DNSSEC to the ocaml-dns implementation. There's been industrial interest in the applications of Signpost and the team is pursuing these for more use cases. We also began work on a new website for the Real World OCaml. We took inspiration from our friends who wrote Real World Haskell, and the site will have commenting functionality so that people can suggest improvements before the book is finalised. As part of this, we also worked with a design firm to begin creating a new logo for the OCaml language. The logo will be placed into the public domain for use by anyone. Last, but certainly not least, Ashish put the new ocaml.org website live, to much electronic applause. A great way to end 2012! Nov 2012 OCaml Labs finally opened its doors with announcements from Yaron and Anil! Although much of the remainder of November was spent on administration and wiring up machines for the forthcoming test cluster, we also celebrated the acceptance of a paper on Mirage to ASPLOS 2013. We also had a very productive visit from OCamlPro. Fabrice, Thomas and Pierre came over to discuss the new OPAM package manager and the plans for building an OCaml Platform in 2013. This was in preparation for the subsequent Consortium meeting of the industrial board of OCaml, where Anil was able to present (and get approved) an overview of what ocaml.org would become. You can see the slides of his talk online. An interesting thing to note is just how broad the set of OCaml language users are: right the way from formal methods, to systems projects, and even web developers. Since the Consortium meeting, the infrastructure behind ocaml.org is being built out and there's already been helpful input via the infrastructure mailing list. A continuous build system has been put together for internal testing, with support from Citrix, and OPAM itself continues to mature and grow in popularity.
http://www.cl.cam.ac.uk/projects/ocamllabs/news/
CC-MAIN-2015-27
refinedweb
13,647
57.2
Unity 2019.3 Beta (Concluded) Accédez en avant-première aux fonctionnalités de la prochaine version complète.Télécharger Unity 2019.3b Améliorations d'Unity 2019.3 La dernière version bêta du TECH cycle 2019, Unity 2019.3b, est présentée ici avec de nombreuses nouvelles fonctionnalités, des améliorations et une interface entièrement revisitée. Optez pour la version bêta et découvrez le nouveau système d'entrée, le post-traitement dans le pipeline de rendu universel (anciennement LWRP), les mises à jour physiques, les temps d'itération plus courts dans l'éditeur et le premier aperçu du tracing de rayons dans Unity.Téléchargez la version bêta 2019.3 IU de l'éditeur optimisée : nouvelles icônes et polices, retour visuel, etc. L'IU de l'Éditeur mise à jour comprend des icônes uniformes et une prise en charge intégrale de la haute résolution DPI. Elle propose également une nouvelle police (Inter), plus lisible et qui s'adapte facilement à de multiples IU et types d'affichage. Nous avons également ajouté un retour visuel au contrôle de survol pour améliorer la convivialité et la réactivité de l'IU. Nouveau système d'entrée (aperçu) Cette version du nouveau système d'entrée est plus puissante, flexible et configurable que le gestionnaire d'entrées classique. Essayez-le et dites-nous ce que vous en pensez sur le forum ! Tracing de rayons dans le pipeline de rendu HD (aperçu) L'API DXR (fonctionnalité expérimentale) du package HDRP cible les applications destinées aux secteurs de l'ingénierie et de l'architecture. Certaines des implémentations incluses sont des ombres directionnelles et de zones, des illuminations globales, des réflexions et des transparences. L'Éditeur Unity propose des Raytracing Shaders et des Raytracing Acceleration Structures avec l'API pour créer/développer/mettre à jour les structures et les propriétés de répartition/liaison des shaders. Mise à jour du pipeline de rendu universel (anciennement pipeline de rendu léger) Le pipeline de rendu universel cible les appareils bas de gamme, mais peut également être utilisé dans le cadre de productions à plus grande échelle. Il propose désormais des effets de post-traitement. Nouvelles options d'entrée en mode lecture Ces options vous permettent de désactiver le rechargement de domaine et/ou de scène à partir du processus Entrer en mode lecture en l'absence de changement de code. Cela accélère considérablement la création de prototypes et l'itération. Mises à jour d'Animation Rigging Vous pouvez désormais prévisualiser vos effets Animation Rigging et vos images clés dans Timeline pour une itération plus rapide et pour tirer parti des outils Timeline. Bénéficiez ainsi de puissants flux de production d’animation multi-pistes en couches. Les animateurs peuvent désormais mixer plusieurs clips avec des squelettes animés pour créer des animations uniques. Boostez votre équipe avec Unity Accelerator The Unity Accelerator is a local network proxy and cache service that speeds up iteration times for two major scenarios – source code download through Collaborate and asset pipeline importing. This improved workflow will substantially reduce the time spent waiting for routine blockers, getting you and your team back to doing what is important: creating! Unity Accelerator est un outil autonome, maintenant disponible en téléchargement sous OSX, Windows et Linux. Pour en savoir plus, lisez cet article de blog. Tentez de remporter un GPU NVIDIA GeForce™RTX 2080 En participant à la version bêta de 2019.3, vous avez une chance de remporter l’un des quatre GPU offerts en partenariat avec NVIDIA. Pour participer, il vous suffit d'identifier et de signaler au moins un bug unique pendant le TECH cycle 2019.3b et d'ajouter « #Beta2019Win_NVIDIA » dans la description du rapport (la « Proposition »). La participation au concours débute à 00h01 le 27 août et la période d'envoi des propositions prend fin à 23h59 le 28 octobre 2019. Pas d'achat nécessaire. Ne s'applique pas là où la loi l'interdit. Veuillez consulter les conditions générales officielles. Les gagnants seront prévenus directement. Qu'attendre d'une bêta ? Comme avec n'importe quel programme bêta, vous aurez un accès rapide aux nouvelles fonctionnalités et serez en mesure d'aider dans les dernières étapes de leur développement. Cela signifie que vous aurez probablement l'impression que Unity est moins stable qu'une version finale. La phase de bêta commence une fois que toutes les principales caractéristiques prévues ont été incluses et qu'une base de référence de qualité a été établie. Plusieurs versions bêta seront disponibles durant cette phase et la qualité s'améliorera à chaque version. Newsletter bêta testeur Inscrivez-vous et recevez des actualités sur la bêta, ainsi que des conseils pour être un testeur efficace. Notes de version Unity 2019.3.0f5 Known Issues in 2019.3.0f5 Ads: Verified and default Ads package for 2019.3 should be 3.3.1 instead of 2.0.8 (1206332) Animation: Animator.Update CPU time spikes when multiple animations are playing (1184690) Asset Importers: OnPostprocessTexture isn't always called (1210674) Global Illumination: Crash on SpookyHash::Short when continually interrupting auto-generating light (1205313) Graphics - General: Crash on UnityEditor.Handles.Internal_FinishDrawingCamera when moving around Scene view with baked Occlusion Culling (1205699) IAP: Disabling and re-enabling IAP in services window throws multiple errors about failing to find assemblies (1193774) IMGUI: Major IMGUI performance regression in 2019.3.0a11 when compared to 2019.3.0a10 (1206495) IMGUI: [TreeCreator] NullReferenceException on modifying properties of "Tree" components when "Branch Material" is set to any material (1206697) MacOS: Bug reporter crashes on Mac when machine is connected to the internet (1181697) MacOS: Realtime shadows are broken on OpenGL/ES3/Metal/Vulkan in Shadowmask mode (1206092) MacOS: [Metal][RealtimeGI] Baked albedo colors are different from the shaded colors after baking GI (1183273) Mobile: [Android] Application crashes on start when Minify is set to Proguard in the player settings (1204992) Mobile: [Android] Loading assets from AssetBundles takes significantly more time when the project is built as an AAB (1153358) Particles: Fixed crash when using ParticleSystem.SetParticles and system uses a Size module. (1197761) Fixed in 2019.3.0f6. Physics: Parts of Cloth Mesh disappear when entering Play mode (1174475) Scene Management: Prefab variant's Scripts are missing fields when upgrading to Unity 2019.3.0a12 and above (1208775) Scripting: "UnityEngine.dll" doesn't automatically reference its individual DLLs preventing project compilation (1205367) New 2019.3.0f5 Entries since 2019.3.0f4 Fixes 2D: Fixed crash when stopping a preview of a Material animation for a TilemapRenderer2D set to Individual Mode. (1191109) 2D: Fixed TilemapRenderer showing normal maps of other Tiles when displaying Tiles with Sprites without normal maps. (1185586) 2D: Improve performance of SpriteEditorWindow when applying changes for new Sprites created. (1201297) AI: Fixed crash in NavMeshManager on IL2CPP builds. (1175557) This is a change to a 2019.3.0a10 change, not seen in any released version, and will not be mentioned in final notes. Android: AndroidExternalToolsSettings.sdkRootPath setting does not throw InvalidOperationException when set from -executeMethod or InitializeOnLoad methods anymore (1205401) This has been backported and will not be mentioned in final notes. Android: Bundletool 0.7.2 in 2019.2 causes Build & Run failure when running App Bundle Android 4.x device (1189570) This is a change to a 2019.3.0b12 change, not seen in any released version, and will not be mentioned in final notes. Android: Fix poor physics performance on ARM64 on certain devices with power mode disabled. (1186295) This has already been backported to older releases and will not be mentioned in final notes. Animation: Fixed crash on Android when reading serialised animation data. (1197792) Asset Bundles: Fix assertion when building multiple scene asset bundles with data analytics enabled. (1203242) Asset Import: Fixed issue where setting EditorCurveBinding.type to a custom component binds to "MonoBehavior" instead of the derived class. (1201584) Pipeline: AssetDatabase performance improvements (1149051) This has been backported and will not be mentioned in final notes. Asset Pipeline: Improved empty assetdatabase refresh performance (1171344) This has been backported and will not be mentioned in final notes. Asset Pipeline: Improved ImportAsset performance, which solves slow prefab editing experience (1203186) Audio: Fix accessing AudioReverbFilter.lfReference / .hfReference from scripts. (1199970) Audio: Fix accessing certain problematic clips in the editor when the selected platform is WebGL. (1201868) This is a change to a 2019.3.0a10 change, not seen in any released version, and will not be mentioned in final notes. Audio: Fixed editor crash on SoundManager::FlushDisposedSounds when importing audio files through asset database v1 (1198006) This is a change to a 2019.3.0 change, not seen in any released version, and will not be mentioned in final notes. DX12: Fixed CommandBuffer.DrawProcedural to work with various topology types when using DX12. (1190099) Editor: Adds entitlement to request camera access in macOS editor (1202032) This has been backported and will not be mentioned in final notes. Editor: Corrected adding prefabs to hierarchy in first position. (1197793) This has been backported and will not be mentioned in final notes. Editor: External Script Editor "Open by file extension" option is not working (1198526) This has already been backported to older releases and will not be mentioned in final notes. Editor: Fix collab related 401s after waking a computer up from sleep. (1209678) Editor: Fix logging errors from background thread crashes the editor when "Error Pause" is enabled (1173657) Editor: Fix null deref in SettingProvider. (1206985) This is a change to a 2019.3.0f4 change, not seen in any released version, and will not be mentioned in final notes. Editor: Fixed an issue where the rotate handle was not accepting input whenever the Handles matrix was not identity. (1201134) This is a change to a 2019.3.0b1 change, not seen in any released version, and will not be mentioned in final notes. Editor: Fixed an issue where Unity crashes when copying text with Unicode emojis. (1201331) Editor: Fixed memory leaking of wintermute shaderloader. (1015837) This has been backported and will not be mentioned in final notes. Editor: Fixed performance issue with editor elements in the inspector. (1203050) Editor: Fixed should not be capturing when there is a hotcontrol logs appear when changing property values after removing search query (1183232) Editor: Fixed vertical lines for sub-scenes in the scene hierarchy (1201408) This has been backported and will not be mentioned in final notes. Editor: [SRP] objects are drawn at 0, 0, 0 position, rotation and scale when Shading mode is set to 'Wireframe' - SRP batcher (1204671) This has been backported and will not be mentioned in final notes. GI: Fix lightmapping errors when painting holes on terrain. (1202457) This is a change to a 2019.3.0b9 change, not seen in any released version, and will not be mentioned in final notes. Graphics: Android: Fix Adreno 5XX Vulkan crash with Render texture 8xAA without depth buffer (1089111) Graphics: Dynamic Array index out of bounds assert. (1178205) Graphics: ECS RenderMeshSystemV2 has substantial amount of memory leak (1151798) This has been backported and will not be mentioned in final notes. Graphics: Editor crashes when calling Shader.WarmUpAllShaders() with one or more GPU Instanced Materials on OpenGL (1201344) This is a change to a 2019.3.0 change, not seen in any released version, and will not be mentioned in final notes. Graphics: Fixed issues loading meshes and shaders authored in 17.4 in to later versions of Unity. (1195750) This has already been backported to older releases and will not be mentioned in final notes. Graphics: Prefer dLDR HDR encoding over RGBM for HDR cubemaps on mobile platforms when ASTC format is selected as override in TextureImporter. (1198678) IL2CPP: Allow the IOControlCode.KeepAliveValues option to work properly on POSIX platforms. (1198796) This has already been backported to older releases and will not be mentioned in final notes. IL2CPP: Correct the behavior of network interface detection code on iOS. (1191670) This has already been backported to older releases and will not be mentioned in final notes. IL2CPP: Correct the behavior of the MulticastOption constructor when the localAddress argument is not provided. (1199942) IL2CPP: Handle calls to open delegates on instance methods of value types properly. (1191419) IL2CPP: Improve the performance of job methods on Microsoft platforms. (1196765) IL2CPP: Marshal.SizeOf computes correct values for structs containing structs. (1201175) IMGUI: Fixed 'On Demand Remap' foldout icon click (1186889) This is a change to a 2019.3.0a7 change, not seen in any released version, and will not be mentioned in final notes. iOS: Add support for iPad 7th generation (1196002) iOS: Added a check to see if the app needs and could safely be cleaned up (case 1145982) (1145982) This has been backported and will not be mentioned in final notes. iOS: Crash on CreateCppStringFromNSString when entering Emoji as max character. (1198204) This has been backported and will not be mentioned in final notes. Linux: Fix the "Build" button for iOS platform on Linux. (1188590) Package Manager: Transforms - Fix crashes caused by disposing of default-constructed TransformAccessArrays (1148324) (1148324) This has been backported and will not be mentioned in final notes. Particles: Fixed crash when destroying a culled Particle System that has a Stop Action. (1206498) This is a change to a 2019.3.0b8 change, not seen in any released version, and will not be mentioned in final notes. Physics: Fix inaccurate collision detection with Terrain, following from the wrong tesselation order being used (1200526) This is a change to a 2019.3.0a5 change, not seen in any released version, and will not be mentioned in final notes. Player: Fixed crash when accessing input devices during application quit. (1193017) Prefabs: Fixed Editor crash when applying joint dependency override after the rigidbody is removed. (1163986) Profiler: Fixed an Editor crash in the GetProfilerThreadID() on exit. (1202746) This has been backported and will not be mentioned in final notes. Profiler: Fixed an error when saving Unity Profiler captures to an invalid path (1204481) This has been backported and will not be mentioned in final notes. Profiler: Fixed an issue where an assembly prefix makes reading the Profiler harder. (1182855) Profiler: Fixed an issue with the Current Frame toggle where it only worked the first time it was pressed. (1204973) This is a change to a 2019.3.0b11 change, not seen in any released version, and will not be mentioned in final notes. Profiler: Fixed an issue with the Target Selection drop-down menu where it would get stuck on Autoconnected Player when it failed to connect to a Player. (1193777) This has already been backported to older releases and will not be mentioned in final notes. Scripting: Editor: Fix a number of bugs with single quote usage in namespace parser (1188570) Scripting: Fix crash due to random memory corruption. (1204409) Scripting: Fixed Reimporting project causes "Assembly for asmdef File will not be compiled, because it has no scripts associated with it" (1185386) This has been backported and will not be mentioned in final notes. Serialization: Performance optimization for prefab merging/creation. (1203377) This has been backported and will not be mentioned in final notes. Terrain: Fix IgnoreMasterTextureLimit handling for rendertextures and CopyTexture_Region (1148582) This has already been backported to older releases and will not be mentioned in final notes. Terrain: Fix issue where rendering terrain with VR active would cause Unity to crash. (1204666) This has been backported and will not be mentioned in final notes. UI: Fixed EventSystem not being created when an EventSystem prefab was loaded but not in the scene. (1200002) This has already been backported to older releases and will not be mentioned in final notes. UI: Fixing issue where a near clipping plane of zero wouldn't trigger graphics (1196850) This is a change to a 2019.3.0a3 change, not seen in any released version, and will not be mentioned in final notes. UI Elements: Support @2x file naming convention with url() function in USS files. Video: Asset bundles which include VideoClip have different CRC values when built from a different directory (1152507) Web: Fix UploadHandlerFile properties contentType and progress. (1197177) This has been backported and will not be mentioned in final notes. WebGL: Disabled unnecessary default canvas event for "on drag" WebGL (case 1206214) (1190839) This has been backported and will not be mentioned in final notes. XR: Update Oculus Plugin to 1.1.4 API Changes - 2D: Added: Add SortingGroup.UpdateAllSortingGroups to allow users to immediately update SortingGroups instead of waiting for LateUpdate (1202432) Preview of Final 2019.3.0f5 Release Notes System Requirements Changes For running Unity games - iOS: minimum version incremented to 10.0 (from 9.0).)) Asset Bundles: Fix assertion when building multiple scene asset bundles with data analytics enabled. (1203242) Asset Import: AnimationClip fileIds generated from a Model imported before Unity 3.2 now conserve their file IDs and references when opened in a 2019.1+ Project.: Clearing mapping of bones of avatar should not lead to re-automapping on apply. (1142768) the Delete tag was erroneously appearing on Assets when importing or updating them. (1179668) Asset Import: Fixed an issue with the Sketchup importer where some Scenes were generating empty Meshes during import. (1155424) Asset Import: Fixed issue where setting EditorCurveBinding.type to a custom component binds to "MonoBehavior" instead of the derived class. (1201584) Import: The Plugin Importer no longer changes the meta file while opening a Project. (1145258) Asset) CommandBuffer.DrawProcedural to work with various topology types when using DX12. (1190099) Editor: Ctrl + F now sets focus on the Search field in the Settings window. (1169717): first menu item opens unrelated window (1198618) Editor: fix for an invalid memory access iwhen querying for a deleted texture with DX12 mode (1138909)) in the Scene View Camera could cause the Move tool to render incorrectly. (1144461) Editor: Fixed an issue where hotkeys with special keys were not accelerated properly. (1182428)) Null Reference Exceptions occurring when previewing textures during Asset import. (1135750) Editor: Fixed crash when having a list of types containing SerializeReference (1187296) EditorApplication.hierarchyChangednot being fired when changes were made to GameObject hierarchy via scripts (1200758) Editor: Fixes an issue where EditorTools could not accept Event commands before the SceneView interprets them. (1151523):) issues with grabpass shader on Vulkan API (1187465) Graphics: Fixed SetPixels/GetPixels when using SRGB formats. (1179921, 1179990): Graphics package to 7.1.6 Graphics: Updated default SRP packages and templates to version 7.1.5: Handle calls to open delegates on instance methods of value types properly. (1191419) IL2CPP: Handle out marshaling of StringBuilder arguments for p/invoke. (1162547) IL2CPP: Improve the performance of job methods on Microsoft platforms. (11967: Add support for iPad 7th generation (1196002) iOS: Directory plugins which are not supported iOS plugins (.framework or .bundle) are now properly copied to the Xcode project (1129771) iOS: Fixed Airplay crash/assert on display connection. (1173096)): Adding iPod Touch 7th Generation to the iOS.DeviceGeneration API. (1185468) that prevented creating a project on an SMB shared network. (1172278).: Execute the Stop Action even if a system goes offscreen (1167771): Improve roll correction when disabling the Enable Roll option (1081596) Particles: Make each system in the Particle System pop-out window wider, to accomodate the ensure content is visible. (1184253) Particles: Prevent crash if trying to use some modules without initializing them (1187445)))) Physics: Make sure all the physics public API setters only call SetDirty when the serialised properties were actually changed (1172914):) high frequency rescaling of the frame count label in the Profiler toolbar (1181367) Profiler: Fixed the Audio Profiler view state restoring (1183981): Editor: Fix a number of bugs with single quote usage in namespace parser (1188570) Scripting: Fix AssemblyUpdater incorrectly removing assembly references when the only reference to the assembly was from an attribute (at assembly level). (1175254) Scripting: Fix crash due to random memory corruption. (1204409) ScreenCapture.CaptureScreenshot not working properly with Physical cameras when superSize > 1 (1192257)) when Terrain details density is low even when target strength has the highest value. (1157402) shader picking pass for SRP. (1176497))) an issue where overflowing text was not clipped correctly in text fields with labels. UI Elements: Fixed an issue with List View where changing DisplayStyle to None and then to Flex made some items invisible. (1181499) UI Elements: Fixed issues with UIElements group transform and stencil clipping (1197094, 1197896)) selected asset state stuck in "updating" when reconnecting to VCS (1175534): Asset bundles which include VideoClip have different CRC values when built from a different directory (1152507) Video: Fix for movies with multiple video tracks on Windows (1196384) OnApplicationPause events when using HolographicPauseOnTrackingLoss. (1192322). API Changes 2D: Added: Add SortingGroup.UpdateAllSortingGroups to allow users to immediately update SortingGroups instead of waiting for LateUpdate (1202432) enum to ModelImporterMaterialImportMode.ImportViaMaterialDescription. Asset:: Changed: Moved RenderingThreadingMode toTime which API to GameObject and Component classes that do not allocate in the editor when the component does not exist Scripting: Added: Added 'PlatformSpecificOpenFileAtLine' to: com.unity.xr.oculus@1.1.2 verified XR: Removed Vuforia built-in functionality from the Editor. Moved to package. XR: The following built-in XR platform packages have been deprecated: - "com.unity.xr.googlevr.android" - "com.unity.xr.googlevr.ios" - "com.unity.xr.oculus.android" - "com.unity.xr.oculus.standalone" - "com.unity.xr.openvr.standalone" - "com.unity.xr.windowsmr.metro" - "com.ptc.vuforia.engine" Please refer to this link <> for more information. Improvements 2D: 2D verified packages update "com.unity.2d.animation": "3.0.8" "com.unity.2d.path": "2.0.4", "com.unity.2d.pixel-perfect": "2.0.3", "com.unity.2d.psdimporter": "2.0.7", "com.unity.2d.spriteshape": "3.0.7" (1197018): Android: When "Installed with Unity (recommended)" is selected in Editor Tools Preferences window, display the path where the tool should be located. Android: Custom UnityPlayerActivity implementations can now modify the command line arguments passed to Unity during startup..). Editor: Special Thanks to beta users Editor: The context menu Copy command now works on disabled Text, Float, and Color fields. (1180207) Editor: Updated ProBuilder to 4.1.2.: Frame debugger now works even if graphics jobs are enabled (except for direct graphics jobs) (1182399) Graphics: Graphics: Mesh scripting API improvements. Added non-alloc overload of GetVertexAttributes. Added NativeArray overloads of Mesh.SetFoo. Added T[] and List<T>: Reduced the Editor's. Physics: Reduce the number of calls to Transform-Dispatch system (shown as "TransformChangedDispatch" in profiler) per Physics2D.Simulate call. (1185425): Improved icons for the validity of Define Constraints in the Asmdef Importer Inspector.: Improved performance of picking operations (1194971)": Abiltiy to save and restore Particle System state data, making it possible to save a snapshot of an entire Particle System at a point in time. A use case for this is for efficient rewind support, by saving periodic keyframes of the particle state, to avoid full resimulations. working as Mute works.: 44796c9d3c2c 6 raisons pour lesquelles vous devriez rejoindre le programme bêta - Accédez en avant-première aux dernières fonctionnalités - Testez la compatibilité de vos projets - Rejoignez une communauté d'experts Unity - Tentez votre chance pour gagner des récompenses - Montrez vos compétences - Influencer le futur de Unity
https://unity3d.com/fr/unity/beta/2019.3
CC-MAIN-2020-10
refinedweb
3,825
55.34
Here is a listing of C++ questions and puzzles on “Linkage” along with answers, explanations and/or solutions: 1. How any types of linkage are there in c++? a) 1 b) 2 c) 3 d) 4 View Answer Explanation:There are three types of linkage in c++. They are internal linkage, external linkage and no linkage. 2. To use internal linkage we have to use which keyword? a) static b) extern c) static or extern d) none of the mentioned View Answer Explanation:None. 3. Which one is used to refer to program elements in any translation units? a) internal linkage b) external linkage c) no linkage d) none of the mentioned View Answer Explanation:In the external linkage, it is used to refer to identifiers in various programs. 4. What will be the output of these two programs? 1. #ifndef Exercise_H #define Exercise_H int num = 842; #endif 2. #include <iostream> #include "exe.h" using namespace std; int main(int argc, char * argv[] ) { cout << number++; return 0; } a) 842 b) 843 c) compile time error d) none of the mentioned View Answer Explanation:In this program, we have created a header file and linked that into the source program and we are post incrementing that because of that it is printed as 842. Output: $ g++ link.cpp $ a.out 842 5. What is the defualt type oof linkage that are available for identifires? a) internal b) external c) no linkage d) none of the mentioned View Answer Explanation:None. 6. To use external linkage we have to use which keyword? a) static b) extern c) const d) none of the mentioned View Answer Explanation:extern keyword is used to represent identifiers from other programs. 7. Which is used to use a function from one source file to another? a) code b) declaration c) prototype d) none of the mentioned View Answer Explanation:By defining a function’s prototype in another file means, we can inherit all the features from the source function. 8. What is the use of no linkage? a) make the entity visible to other programs b) make the entity visible to other blocks in the same program. c) make the entity visible only to that block++.
http://www.sanfoundry.com/c-plus-plus-puzzles-linkage/
CC-MAIN-2017-17
refinedweb
369
64.2
Last week, Cynthia Thomas joined us for #CodeLive. We worked to refactor a bit of Apex code that clones cases. We refactored away from a Visualforce Controller to an @AuraEnabled Apex class, and built an LWC user interface for it. Missed the stream? We missed you too! Unfortunately, due to a technical glitch, there’s no recording this week. (Software is hard, lets go write software!) But never fear, we’ve vanquished webinar gremlins to the fixed bugs: section of the release notes, so next week’s stream will be recorded! Remember to register for future CodeLive streams here. Our use case It’s a bit of an unorthodox use case, but one that’s probably more common than you might think. Cynthia’s org allows customers to submit cases via email. Inside, Salesforce Email2Case creates a case from the incoming email. To the business, a case represents a single, actionable bit of work — for instance, ‘Annual Maintenance Check: Refrigeration Unit 1.’ Fortunately for the business, most customers have multiple refrigeration units. Unfortunately for the Email2Case setup, that means customers often email in a request for ‘Annual Maintenance Check for all my refrigeration units.’ The discrepancy between what constitutes a case can be handled in a number of ways, but for the stream, we decided to provide Salesforce users the ability to clone the incoming cases and edit their details. Converting our Visualforce Controller Apex to a Lightning Web Components-compatible Apex class was simple enough — we were able to reuse the cloning logic. In fact, we could have refactored the existing Visualforce controller in place, but for clarity we started with a net-new class and ended up with this: @AuraEnabled public static List<Id> createCaseClones(Integer numberOfClonesToMake, Id caseIdToClone){ Case toBeCloned = [Select ID FROM Case where ID =: caseIdToClone]; list<Case> clonedCases = new List<Case>(); for (Integer i=0; i < numberOfClonesToMake; i++){ Case newClonedCase = new Case(); newClonedCase = toBeCloned.clone(); newClonedCase.parentId = caseIdToClone; clonedCases.add(newClonedCase); } insert clonedCases; Set<Id> theIds = new Map<id, Case>(clonedCases).keyset(); return new List<Id>(theIds); } A single static method accepts the number of clones to make and the original case ID. It then clones the case the appropriate number of times. Our only change from the original code is in the addition of the parentId field. Populating this field allows each cloned case to relate back to the original case created by the customer. What’s important to note here is that the conversion from a Visualforce interface to a Lightning Web Components interface did not require a change in our actual cloning logic. The UI Our UI for this code has to do two things. First, we need to provide an interface for the user to specify the number of clones to make and a button to trigger their creation. Secondly, once our code has created the clones, we need a concise and easy way for the user to make appropriate edits to each individual clone. That way each clone represents an actionable, specific set of work items. We chose to build our UI in Lightning Web Components, because, well, they’re a lot of fun to develop. We also chose to mix custom and base components together to really deliver our UI in a quick and standard-look-and-feel. Context Our Lightning web component needs to understand its context so that, for instance, it knows what the current record id is. To do that we specified that the component can only be used on Record Detail Pages by adding a target to the component’s .js-meta.xml file. <targets> <target>lightning__RecordPage</target> </targets> We also added an @api decorated property, called recordId. Together with the @api decorator, they allow the Lightning Web Components framework to automatically populate the recordId property with the ID of the current record. With our recordId sorted, we can move on to handling our user input. Building user inputs with base components Our component’s UI is built entirely with base components. Looking at the code below, you can see a Lightning Card provides the shape of the UI. The card’s actions slot holds a Lightning Layout with layout items consisting of Lightning-input and a lightning-button. This is what the code for the card and card’s header with actions looks like: <lightning-card <div slot="actions"> <lightning-layout <lightning-layout-item <div> <lightning-input <div> <lightning-button label="Make Clones" onclick={handleButtonPress} ></lightning-button> </div> </lightning-layout-item> </lightning-layout> </div> ... Note, how there’s an onchange handler on the lightning-input. This is how we update our controller code whenever the user changes the number of clones’ text field. Likewise, there’s an onclick handler assigned to the lightning-button. This allows us to attach logic to the user’s interaction with the button. Calling our Apex method Let’s look at how we call our Apex controller method from JavaScript: handleCloneCountChange(event) { this.numberOfClonesToMake = event.target.value; } handleButtonPress(event) { this.validateUserInput(); // guard if (this.numberOfClonesToMake !== 0) { createCaseClones({ numberOfClonesToMake: this.numberOfClonesToMake, caseIdToClone: this.recordId }) .then(result => { this.clonedCaseIds = result; this.displayClonedCases = true; this.error = undefined; }) .catch(error => { this.error = error; this.cloneCaseIds = undefined; this.displayClonedCases = false; }); } } Our first function handles whenever the user changes the value of our number of clones to make input field. You’ll notice it accepts a parameter, event, whose target.value property gives us the user input. Our second function is where things get interesting. Because we’re dealing with user input when the button is pressed, the first thing we do is validate the input numbers. In our case, this is a simple validation that the user has entered a number between 1 and 30. Once our user input is sorted, this code imperatively — or on-demand — calls a server side Apex method. How? Well at the top of our component, we added this line: import createCaseClones from "@salesforce/apex/LWCCaseController.createCaseClones"; This import statement ties the LWCCaseController.createCaseClones method (on the right side of the from keyword) to the JavaScript object we named createCaseClones. (on the left side of the from keyword). Note, we could have named our JavaScript object anything, but keeping the method names identical helps make sense of the code. Now that we have a JavaScript object, createCaseClones, we can execute it simply by calling it. If our method accepted no parameters, it’d be as simple as calling createCaseClones(), but since we do have parameters to pass in, we create a JSON object to hold them. It’s important to note that the keys in this JSON object must match the variable names in your Apex method. Promises Apex methods that we import are promise-enabled. This means two things: 1. They’re asynchronous. 2. We can tell the system to do some work, whenever the data returns. We do that with a .then() method call. In our case, we’re using a fat-arrow function to accept the result — which is passed in by the system when .then() is called — and setting our client-side variable this.clonedCaseIds equal to the result. Since our Apex code returns a List<Id> we know the result will be a List (Array) of IDs. When things go as planned, the .then() method is called whenever the asynchronous work completes. However, when things go less than planned, the .catch() block is called. In our case, we’re capturing the error message(s) and making sure we don’t show any results. We could, however, retry the call or send a toast. The sky’s the limit here. Promises give us flow control for our asynchronous work. With our code setup to call Apex, which creates the clones and returns the IDs, we can now build the UI to display the new cases. This is where components in general — and the Lightning base components — really shine. Inside our template file, we put this code: <template if:true={displayClonedCases}> <lightning-layout <template for:each={clonedCaseIds} for: <lightning-layout-item</lightning-record-form> </div> </lightning-layout-item> </template> </lightning-layout> </template> While this might look like quite a bit, it’s really just three elements: - A sub-template that uses the if:truedirective to conditionally show our newly cloned cases. - A second sub-template that iterates over our collection of new case IDs. - A Lightning Record Form base component. This base component needs only the record’s object name, its Id and an array of fields to show. With just a handful of lines of code, we’ve defined a conditional UI displaying an editable form for each record that’s dynamically built from a list of fields. The base components and template directives allowed us to leverage platform functionality without writing any client or server side code to handle retrieving and modifying the record’s data! Here’s what the final UI looks like in use. This week’s CodeLive had some technical gremlins, but hey, that’s how you know it’s live! We took a data-driven use case for mass cloning case records and built a lovely (I’m biased) LWC user interface on top. We built with base components and we squeaked by in just under an hour! We put together a trailmix, along with this blog post to make sure those of you who couldn’t join in, could still benefit from the content. Take the Trailmix here. Earlier this week, Salesforce Wizard Brian Kwong and I converted a public-facing Visualforce page into an LWC Lightning App — that recap will be coming soon. In the meantime, sign up for the next #CodeLive stream this #Codetober on October 24, where I will be reviewing code with Ryan Headley from Salesforce.org.
https://developer.salesforce.com/blogs/2019/10/codelive-refactoring-data-driven-apps
CC-MAIN-2021-39
refinedweb
1,622
56.45